import { print, printJSON, parseJSON, input, sleep, round, read, write, readImage, notify, range, mostCommon, keys, values, entries, emit, callback } from "agency-lang/stdlib/index.js";
import { fileURLToPath } from "url";
import __process from "process";
import { z } from "agency-lang/zod";
import { nanoid } from "agency-lang";
import path from "path";
import {
  RuntimeContext,
  Runner,
  setupFunction,
  callHook,
  checkpoint as __checkpoint_impl,
  getCheckpoint as __getCheckpoint_impl,
  restore as __restore_impl,
  _run as __runtime_run_impl,
  interrupt,
  isInterrupt,
  hasInterrupts,
  isDebugger,
  respondToInterrupts as _respondToInterrupts,
  rewindFrom as _rewindFrom,
  RestoreSignal,
  GuardExceededError,
  __registerGlobalsInit,
  failure,
  isFailure,
  AgencyFunction as __AgencyFunction,
  __call,
  __callMethod,
  __stateStack,
  getRuntimeContext,
  agencyStore,
  functionRefReviver as __functionRefReviver,
  DeterministicClient as __DeterministicClient,
  createLogger as __createLogger
} from "agency-lang/runtime";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const __cwd = __process.cwd();
const getDirname = () => __dirname;
const __globalCtx = new RuntimeContext({
  statelogConfig: {
    host: "https://statelog.adit.io",
    apiKey: __process.env["STATELOG_API_KEY"] || "",
    projectId: "agency-lang",
    debugMode: false,
    observability: true,
    logFile: "statelog.log"
  },
  smoltalkDefaults: {
    openAiApiKey: __process.env["OPENAI_API_KEY"] || "",
    googleApiKey: __process.env["GEMINI_API_KEY"] || "",
    model: "gpt-4o-mini",
    logLevel: "warn",
    statelog: {
      host: "https://statelog.adit.io",
      projectId: "smoltalk",
      apiKey: __process.env["STATELOG_SMOLTALK_API_KEY"] || "",
      traceId: nanoid()
    }
  },
  dirname: __dirname,
  logLevel: "info",
  traceConfig: {
    program: "stdlib/array.agency"
  }
});
const graph = __globalCtx.graph;
function approve(value) {
  return { type: "approve", value };
}
function reject(value) {
  return { type: "reject", value };
}
function propagate() {
  return { type: "propagate" };
}
const respondToInterrupts = (interrupts, responses, opts) => _respondToInterrupts({ ctx: __globalCtx, interrupts, responses, overrides: opts?.overrides, metadata: opts?.metadata, registerTopLevelCallbacks: __registerTopLevelCallbacks, moduleDir: __dirname });
const rewindFrom = (checkpoint2, overrides, opts) => _rewindFrom({ ctx: __globalCtx, checkpoint: checkpoint2, overrides, metadata: opts?.metadata, registerTopLevelCallbacks: __registerTopLevelCallbacks, moduleDir: __dirname });
const __setDebugger = (dbg) => {
  __globalCtx.debuggerState = dbg;
};
const __setTraceFile = (filePath) => {
  __globalCtx.traceConfig.traceFile = filePath;
};
const __setLLMClient = (client) => {
  __globalCtx.setLLMClient(client);
};
const __getCheckpoints = () => __globalCtx.checkpoints;
if (__process.env.AGENCY_LLM_MOCKS) {
  __globalCtx.setLLMClient(
    new __DeterministicClient(JSON.parse(__process.env.AGENCY_LLM_MOCKS))
  );
}
const __toolRegistry = __functionRefReviver.registry ??= {};
function __registerTool(value, _aliasName) {
  if (__AgencyFunction.isAgencyFunction(value)) {
    __toolRegistry[`${value.module}:${value.name}`] = value;
  }
}
const checkpoint = __AgencyFunction.create({ name: "checkpoint", module: "__runtime", fn: __checkpoint_impl, params: [], toolDefinition: null }, __toolRegistry);
const getCheckpoint = __AgencyFunction.create({ name: "getCheckpoint", module: "__runtime", fn: __getCheckpoint_impl, params: [{ name: "checkpointId", hasDefault: false, defaultValue: void 0, variadic: false }], toolDefinition: null }, __toolRegistry);
const restore = __AgencyFunction.create({ name: "restore", module: "__runtime", fn: __restore_impl, params: [{ name: "checkpointIdOrCheckpoint", hasDefault: false, defaultValue: void 0, variadic: false }, { name: "options", hasDefault: false, defaultValue: void 0, variadic: false }], toolDefinition: null }, __toolRegistry);
const _run = __AgencyFunction.create({ name: "_run", module: "__runtime", fn: __runtime_run_impl, params: [{ name: "compiled", hasDefault: false, defaultValue: void 0, variadic: false }, { name: "node", hasDefault: false, defaultValue: void 0, variadic: false }, { name: "args", hasDefault: false, defaultValue: void 0, variadic: false }, { name: "wallClock", hasDefault: false, defaultValue: void 0, variadic: false }, { name: "memory", hasDefault: false, defaultValue: void 0, variadic: false }, { name: "ipcPayload", hasDefault: false, defaultValue: void 0, variadic: false }, { name: "stdout", hasDefault: false, defaultValue: void 0, variadic: false }], toolDefinition: null }, __toolRegistry);
function setLLMClient(client) {
  __globalCtx.setLLMClient(client);
}
function registerTools(tools) {
  for (const tool of tools) {
    if (__AgencyFunction.isAgencyFunction(tool)) {
      __toolRegistry[`${tool.module}:${tool.name}`] = tool;
    }
  }
}
__registerTool(print);
__registerTool(printJSON);
__registerTool(parseJSON);
__registerTool(input);
__registerTool(sleep);
__registerTool(round);
__registerTool(read);
__registerTool(write);
__registerTool(readImage);
__registerTool(notify);
__registerTool(range);
__registerTool(mostCommon);
__registerTool(keys);
__registerTool(values);
__registerTool(entries);
__registerTool(emit);
__registerTool(callback);
async function __initializeGlobals(__ctx) {
  if (__ctx.globals.isInitialized("stdlib/array.agency")) {
    return;
  }
  __ctx.globals.markInitialized("stdlib/array.agency");
}
__registerGlobalsInit("stdlib/array.agency", __initializeGlobals);
async function __registerTopLevelCallbacks(__ctx) {
  __ctx.topLevelCallbacks = [];
}
__functionRefReviver.registry = __toolRegistry;
async function __map_impl(arr, func) {
  const __setupData = setupFunction();
  const __stack = __setupData.stack;
  const __step = __setupData.step;
  const __self = __setupData.self;
  const __ctx = getRuntimeContext().ctx;
  let __forked;
  let __functionCompleted = false;
  if (!__ctx.globals.isInitialized("stdlib/array.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["arr"] = arr;
  __stack.args["func"] = func;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/array.agency", scopeName: "map", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("arr" in __overrides) {
      arr = __overrides["arr"];
      __stack.args["arr"] = arr;
    }
    if ("func" in __overrides) {
      func = __overrides["func"];
      __stack.args["func"] = func;
    }
  }
  try {
    await agencyStore.run({
      ...getRuntimeContext(),
      ctx: __ctx,
      stack: __setupData.stateStack,
      threads: __setupData.threads
    }, async () => {
      await runner.hook(0, async () => {
        await callHook({
          name: "onFunctionStart",
          data: {
            functionName: "map",
            args: {
              arr,
              func
            },
            isBuiltin: false,
            moduleId: "stdlib/array.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.newArr = [];
      });
      await runner.loop(2, __stack.args.arr, async (item, _, runner2) => {
        await runner2.step(0, async (runner3) => {
          await __callMethod(__stack.locals.newArr, "push", {
            type: "positional",
            args: [await __call(__stack.args.func, {
              type: "positional",
              args: [item]
            })]
          });
        });
      });
      await runner.step(3, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(__stack.locals.newArr);
        return;
      });
    });
    if (runner.halted) {
      if (isFailure(runner.haltResult)) {
        runner.haltResult.retryable = runner.haltResult.retryable && __self.__retryable;
      }
      return runner.haltResult;
    }
  } catch (__error) {
    if (__error instanceof RestoreSignal) {
      throw __error;
    }
    if (__error instanceof GuardExceededError) {
      throw __error;
    }
    {
      const __errMsg = __error instanceof Error ? __error.message : String(__error);
      const __errStack = __error instanceof Error && __error.stack ? __error.stack : "";
      const __log = __createLogger(__ctx.logLevel);
      __log.error("Function map threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "map",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "map",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "map",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const map = __AgencyFunction.create({
  name: "map",
  module: "stdlib/array.agency",
  fn: __map_impl,
  params: [{
    name: "arr",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "func",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "map",
    description: `Map a function over an array, returning a new array of results.

  @param arr - The array to map over
  @param func - The function to apply to each element`,
    schema: z.object({ "arr": z.array(z.any()) })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __filter_impl(arr, func) {
  const __setupData = setupFunction();
  const __stack = __setupData.stack;
  const __step = __setupData.step;
  const __self = __setupData.self;
  const __ctx = getRuntimeContext().ctx;
  let __forked;
  let __functionCompleted = false;
  if (!__ctx.globals.isInitialized("stdlib/array.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["arr"] = arr;
  __stack.args["func"] = func;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/array.agency", scopeName: "filter", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("arr" in __overrides) {
      arr = __overrides["arr"];
      __stack.args["arr"] = arr;
    }
    if ("func" in __overrides) {
      func = __overrides["func"];
      __stack.args["func"] = func;
    }
  }
  try {
    await agencyStore.run({
      ...getRuntimeContext(),
      ctx: __ctx,
      stack: __setupData.stateStack,
      threads: __setupData.threads
    }, async () => {
      await runner.hook(0, async () => {
        await callHook({
          name: "onFunctionStart",
          data: {
            functionName: "filter",
            args: {
              arr,
              func
            },
            isBuiltin: false,
            moduleId: "stdlib/array.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.result = [];
      });
      await runner.loop(2, __stack.args.arr, async (item, _, runner2) => {
        await runner2.ifElse(0, [
          {
            condition: async () => await __call(__stack.args.func, {
              type: "positional",
              args: [item]
            }),
            body: async (runner3) => {
              await runner3.step(0, async (runner4) => {
                await __callMethod(__stack.locals.result, "push", {
                  type: "positional",
                  args: [item]
                });
              });
            }
          }
        ]);
      });
      await runner.step(3, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(__stack.locals.result);
        return;
      });
    });
    if (runner.halted) {
      if (isFailure(runner.haltResult)) {
        runner.haltResult.retryable = runner.haltResult.retryable && __self.__retryable;
      }
      return runner.haltResult;
    }
  } catch (__error) {
    if (__error instanceof RestoreSignal) {
      throw __error;
    }
    if (__error instanceof GuardExceededError) {
      throw __error;
    }
    {
      const __errMsg = __error instanceof Error ? __error.message : String(__error);
      const __errStack = __error instanceof Error && __error.stack ? __error.stack : "";
      const __log = __createLogger(__ctx.logLevel);
      __log.error("Function filter threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "filter",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "filter",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "filter",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const filter = __AgencyFunction.create({
  name: "filter",
  module: "stdlib/array.agency",
  fn: __filter_impl,
  params: [{
    name: "arr",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "func",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "filter",
    description: `Return a new array containing only the elements for which the function returns true.

  @param arr - The array to filter
  @param func - The function that returns true for elements to keep`,
    schema: z.object({ "arr": z.array(z.any()) })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __exclude_impl(arr, func) {
  const __setupData = setupFunction();
  const __stack = __setupData.stack;
  const __step = __setupData.step;
  const __self = __setupData.self;
  const __ctx = getRuntimeContext().ctx;
  let __forked;
  let __functionCompleted = false;
  if (!__ctx.globals.isInitialized("stdlib/array.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["arr"] = arr;
  __stack.args["func"] = func;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/array.agency", scopeName: "exclude", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("arr" in __overrides) {
      arr = __overrides["arr"];
      __stack.args["arr"] = arr;
    }
    if ("func" in __overrides) {
      func = __overrides["func"];
      __stack.args["func"] = func;
    }
  }
  try {
    await agencyStore.run({
      ...getRuntimeContext(),
      ctx: __ctx,
      stack: __setupData.stateStack,
      threads: __setupData.threads
    }, async () => {
      await runner.hook(0, async () => {
        await callHook({
          name: "onFunctionStart",
          data: {
            functionName: "exclude",
            args: {
              arr,
              func
            },
            isBuiltin: false,
            moduleId: "stdlib/array.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.result = [];
      });
      await runner.loop(2, __stack.args.arr, async (item, _, runner2) => {
        await runner2.ifElse(0, [
          {
            condition: async () => await __call(__stack.args.func, {
              type: "positional",
              args: [item]
            }) === false,
            body: async (runner3) => {
              await runner3.step(0, async (runner4) => {
                await __callMethod(__stack.locals.result, "push", {
                  type: "positional",
                  args: [item]
                });
              });
            }
          }
        ]);
      });
      await runner.step(3, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(__stack.locals.result);
        return;
      });
    });
    if (runner.halted) {
      if (isFailure(runner.haltResult)) {
        runner.haltResult.retryable = runner.haltResult.retryable && __self.__retryable;
      }
      return runner.haltResult;
    }
  } catch (__error) {
    if (__error instanceof RestoreSignal) {
      throw __error;
    }
    if (__error instanceof GuardExceededError) {
      throw __error;
    }
    {
      const __errMsg = __error instanceof Error ? __error.message : String(__error);
      const __errStack = __error instanceof Error && __error.stack ? __error.stack : "";
      const __log = __createLogger(__ctx.logLevel);
      __log.error("Function exclude threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "exclude",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "exclude",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "exclude",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const exclude = __AgencyFunction.create({
  name: "exclude",
  module: "stdlib/array.agency",
  fn: __exclude_impl,
  params: [{
    name: "arr",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "func",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "exclude",
    description: `Return a new array excluding elements for which the function returns true. Inverse of filter.

  @param arr - The array to filter
  @param func - The function that returns true for elements to exclude`,
    schema: z.object({ "arr": z.array(z.any()) })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __find_impl(arr, func) {
  const __setupData = setupFunction();
  const __stack = __setupData.stack;
  const __step = __setupData.step;
  const __self = __setupData.self;
  const __ctx = getRuntimeContext().ctx;
  let __forked;
  let __functionCompleted = false;
  if (!__ctx.globals.isInitialized("stdlib/array.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["arr"] = arr;
  __stack.args["func"] = func;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/array.agency", scopeName: "find", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("arr" in __overrides) {
      arr = __overrides["arr"];
      __stack.args["arr"] = arr;
    }
    if ("func" in __overrides) {
      func = __overrides["func"];
      __stack.args["func"] = func;
    }
  }
  try {
    await agencyStore.run({
      ...getRuntimeContext(),
      ctx: __ctx,
      stack: __setupData.stateStack,
      threads: __setupData.threads
    }, async () => {
      await runner.hook(0, async () => {
        await callHook({
          name: "onFunctionStart",
          data: {
            functionName: "find",
            args: {
              arr,
              func
            },
            isBuiltin: false,
            moduleId: "stdlib/array.agency"
          }
        });
      });
      await runner.loop(1, __stack.args.arr, async (item, _, runner2) => {
        await runner2.ifElse(0, [
          {
            condition: async () => await __call(__stack.args.func, {
              type: "positional",
              args: [item]
            }),
            body: async (runner3) => {
              await runner3.step(0, async (runner4) => {
                __functionCompleted = true;
                runner4.halt(item);
                return;
              });
            }
          }
        ]);
      });
      await runner.step(2, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(null);
        return;
      });
    });
    if (runner.halted) {
      if (isFailure(runner.haltResult)) {
        runner.haltResult.retryable = runner.haltResult.retryable && __self.__retryable;
      }
      return runner.haltResult;
    }
  } catch (__error) {
    if (__error instanceof RestoreSignal) {
      throw __error;
    }
    if (__error instanceof GuardExceededError) {
      throw __error;
    }
    {
      const __errMsg = __error instanceof Error ? __error.message : String(__error);
      const __errStack = __error instanceof Error && __error.stack ? __error.stack : "";
      const __log = __createLogger(__ctx.logLevel);
      __log.error("Function find threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "find",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "find",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "find",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const find = __AgencyFunction.create({
  name: "find",
  module: "stdlib/array.agency",
  fn: __find_impl,
  params: [{
    name: "arr",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "func",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "find",
    description: `Return the first element for which the function returns true, or null if none match.

  @param arr - The array to search
  @param func - The function that returns true for the desired element`,
    schema: z.object({ "arr": z.array(z.any()) })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __findIndex_impl(arr, func) {
  const __setupData = setupFunction();
  const __stack = __setupData.stack;
  const __step = __setupData.step;
  const __self = __setupData.self;
  const __ctx = getRuntimeContext().ctx;
  let __forked;
  let __functionCompleted = false;
  if (!__ctx.globals.isInitialized("stdlib/array.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["arr"] = arr;
  __stack.args["func"] = func;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/array.agency", scopeName: "findIndex", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("arr" in __overrides) {
      arr = __overrides["arr"];
      __stack.args["arr"] = arr;
    }
    if ("func" in __overrides) {
      func = __overrides["func"];
      __stack.args["func"] = func;
    }
  }
  try {
    await agencyStore.run({
      ...getRuntimeContext(),
      ctx: __ctx,
      stack: __setupData.stateStack,
      threads: __setupData.threads
    }, async () => {
      await runner.hook(0, async () => {
        await callHook({
          name: "onFunctionStart",
          data: {
            functionName: "findIndex",
            args: {
              arr,
              func
            },
            isBuiltin: false,
            moduleId: "stdlib/array.agency"
          }
        });
      });
      await runner.loop(1, __stack.args.arr, async (item, index, runner2) => {
        await runner2.ifElse(0, [
          {
            condition: async () => await __call(__stack.args.func, {
              type: "positional",
              args: [item]
            }),
            body: async (runner3) => {
              await runner3.step(0, async (runner4) => {
                __functionCompleted = true;
                runner4.halt(index);
                return;
              });
            }
          }
        ]);
      });
      await runner.step(2, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(-1);
        return;
      });
    });
    if (runner.halted) {
      if (isFailure(runner.haltResult)) {
        runner.haltResult.retryable = runner.haltResult.retryable && __self.__retryable;
      }
      return runner.haltResult;
    }
  } catch (__error) {
    if (__error instanceof RestoreSignal) {
      throw __error;
    }
    if (__error instanceof GuardExceededError) {
      throw __error;
    }
    {
      const __errMsg = __error instanceof Error ? __error.message : String(__error);
      const __errStack = __error instanceof Error && __error.stack ? __error.stack : "";
      const __log = __createLogger(__ctx.logLevel);
      __log.error("Function findIndex threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "findIndex",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "findIndex",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "findIndex",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const findIndex = __AgencyFunction.create({
  name: "findIndex",
  module: "stdlib/array.agency",
  fn: __findIndex_impl,
  params: [{
    name: "arr",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "func",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "findIndex",
    description: `Return the index of the first element for which the function returns true, or -1 if none match.

  @param arr - The array to search
  @param func - The function that returns true for the desired element`,
    schema: z.object({ "arr": z.array(z.any()) })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __reduce_impl(arr, initial, func) {
  const __setupData = setupFunction();
  const __stack = __setupData.stack;
  const __step = __setupData.step;
  const __self = __setupData.self;
  const __ctx = getRuntimeContext().ctx;
  let __forked;
  let __functionCompleted = false;
  if (!__ctx.globals.isInitialized("stdlib/array.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["arr"] = arr;
  __stack.args["initial"] = initial;
  __stack.args["func"] = func;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/array.agency", scopeName: "reduce", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("arr" in __overrides) {
      arr = __overrides["arr"];
      __stack.args["arr"] = arr;
    }
    if ("initial" in __overrides) {
      initial = __overrides["initial"];
      __stack.args["initial"] = initial;
    }
    if ("func" in __overrides) {
      func = __overrides["func"];
      __stack.args["func"] = func;
    }
  }
  try {
    await agencyStore.run({
      ...getRuntimeContext(),
      ctx: __ctx,
      stack: __setupData.stateStack,
      threads: __setupData.threads
    }, async () => {
      await runner.hook(0, async () => {
        await callHook({
          name: "onFunctionStart",
          data: {
            functionName: "reduce",
            args: {
              arr,
              initial,
              func
            },
            isBuiltin: false,
            moduleId: "stdlib/array.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.acc = __stack.args.initial;
      });
      await runner.loop(2, __stack.args.arr, async (item, _, runner2) => {
        await runner2.step(0, async (runner3) => {
          __stack.locals.acc = await __call(__stack.args.func, {
            type: "positional",
            args: [__stack.locals.acc, item]
          });
          if (hasInterrupts(__stack.locals.acc)) {
            await getRuntimeContext().ctx.pendingPromises.awaitAll();
            runner3.halt(__stack.locals.acc);
            return;
          }
        });
      });
      await runner.step(3, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(__stack.locals.acc);
        return;
      });
    });
    if (runner.halted) {
      if (isFailure(runner.haltResult)) {
        runner.haltResult.retryable = runner.haltResult.retryable && __self.__retryable;
      }
      return runner.haltResult;
    }
  } catch (__error) {
    if (__error instanceof RestoreSignal) {
      throw __error;
    }
    if (__error instanceof GuardExceededError) {
      throw __error;
    }
    {
      const __errMsg = __error instanceof Error ? __error.message : String(__error);
      const __errStack = __error instanceof Error && __error.stack ? __error.stack : "";
      const __log = __createLogger(__ctx.logLevel);
      __log.error("Function reduce threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "reduce",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "reduce",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "reduce",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const reduce = __AgencyFunction.create({
  name: "reduce",
  module: "stdlib/array.agency",
  fn: __reduce_impl,
  params: [{
    name: "arr",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "initial",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "func",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "reduce",
    description: `Reduce an array to a single value by applying a function to an accumulator and each element.

  @param arr - The array to reduce
  @param initial - The initial accumulator value
  @param func - The reducer function receiving (accumulator, element)`,
    schema: z.object({ "arr": z.array(z.any()), "initial": z.any() })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __flatMap_impl(arr, func) {
  const __setupData = setupFunction();
  const __stack = __setupData.stack;
  const __step = __setupData.step;
  const __self = __setupData.self;
  const __ctx = getRuntimeContext().ctx;
  let __forked;
  let __functionCompleted = false;
  if (!__ctx.globals.isInitialized("stdlib/array.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["arr"] = arr;
  __stack.args["func"] = func;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/array.agency", scopeName: "flatMap", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("arr" in __overrides) {
      arr = __overrides["arr"];
      __stack.args["arr"] = arr;
    }
    if ("func" in __overrides) {
      func = __overrides["func"];
      __stack.args["func"] = func;
    }
  }
  try {
    await agencyStore.run({
      ...getRuntimeContext(),
      ctx: __ctx,
      stack: __setupData.stateStack,
      threads: __setupData.threads
    }, async () => {
      await runner.hook(0, async () => {
        await callHook({
          name: "onFunctionStart",
          data: {
            functionName: "flatMap",
            args: {
              arr,
              func
            },
            isBuiltin: false,
            moduleId: "stdlib/array.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.result = [];
      });
      await runner.loop(2, __stack.args.arr, async (item, _, runner2) => {
        await runner2.step(0, async (runner3) => {
          __stack.locals.mapped = await __call(__stack.args.func, {
            type: "positional",
            args: [item]
          });
          if (hasInterrupts(__stack.locals.mapped)) {
            await getRuntimeContext().ctx.pendingPromises.awaitAll();
            runner3.halt(__stack.locals.mapped);
            return;
          }
        });
        await runner2.loop(1, __stack.locals.mapped, async (sub, _2, runner3) => {
          await runner3.step(0, async (runner4) => {
            await __callMethod(__stack.locals.result, "push", {
              type: "positional",
              args: [sub]
            });
          });
        });
      });
      await runner.step(3, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(__stack.locals.result);
        return;
      });
    });
    if (runner.halted) {
      if (isFailure(runner.haltResult)) {
        runner.haltResult.retryable = runner.haltResult.retryable && __self.__retryable;
      }
      return runner.haltResult;
    }
  } catch (__error) {
    if (__error instanceof RestoreSignal) {
      throw __error;
    }
    if (__error instanceof GuardExceededError) {
      throw __error;
    }
    {
      const __errMsg = __error instanceof Error ? __error.message : String(__error);
      const __errStack = __error instanceof Error && __error.stack ? __error.stack : "";
      const __log = __createLogger(__ctx.logLevel);
      __log.error("Function flatMap threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "flatMap",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "flatMap",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "flatMap",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const flatMap = __AgencyFunction.create({
  name: "flatMap",
  module: "stdlib/array.agency",
  fn: __flatMap_impl,
  params: [{
    name: "arr",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "func",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "flatMap",
    description: `Map a function over an array and flatten the results by one level.

  @param arr - The array to map over
  @param func - The function to apply to each element`,
    schema: z.object({ "arr": z.array(z.any()) })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __every_impl(arr, func) {
  const __setupData = setupFunction();
  const __stack = __setupData.stack;
  const __step = __setupData.step;
  const __self = __setupData.self;
  const __ctx = getRuntimeContext().ctx;
  let __forked;
  let __functionCompleted = false;
  if (!__ctx.globals.isInitialized("stdlib/array.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["arr"] = arr;
  __stack.args["func"] = func;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/array.agency", scopeName: "every", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("arr" in __overrides) {
      arr = __overrides["arr"];
      __stack.args["arr"] = arr;
    }
    if ("func" in __overrides) {
      func = __overrides["func"];
      __stack.args["func"] = func;
    }
  }
  try {
    await agencyStore.run({
      ...getRuntimeContext(),
      ctx: __ctx,
      stack: __setupData.stateStack,
      threads: __setupData.threads
    }, async () => {
      await runner.hook(0, async () => {
        await callHook({
          name: "onFunctionStart",
          data: {
            functionName: "every",
            args: {
              arr,
              func
            },
            isBuiltin: false,
            moduleId: "stdlib/array.agency"
          }
        });
      });
      await runner.loop(1, __stack.args.arr, async (item, _, runner2) => {
        await runner2.ifElse(0, [
          {
            condition: async () => await __call(__stack.args.func, {
              type: "positional",
              args: [item]
            }) === false,
            body: async (runner3) => {
              await runner3.step(0, async (runner4) => {
                __functionCompleted = true;
                runner4.halt(false);
                return;
              });
            }
          }
        ]);
      });
      await runner.step(2, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(true);
        return;
      });
    });
    if (runner.halted) {
      if (isFailure(runner.haltResult)) {
        runner.haltResult.retryable = runner.haltResult.retryable && __self.__retryable;
      }
      return runner.haltResult;
    }
  } catch (__error) {
    if (__error instanceof RestoreSignal) {
      throw __error;
    }
    if (__error instanceof GuardExceededError) {
      throw __error;
    }
    {
      const __errMsg = __error instanceof Error ? __error.message : String(__error);
      const __errStack = __error instanceof Error && __error.stack ? __error.stack : "";
      const __log = __createLogger(__ctx.logLevel);
      __log.error("Function every threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "every",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "every",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "every",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const every = __AgencyFunction.create({
  name: "every",
  module: "stdlib/array.agency",
  fn: __every_impl,
  params: [{
    name: "arr",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "func",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "every",
    description: `Return true if the function returns true for every element in the array.

  @param arr - The array to test
  @param func - The predicate function`,
    schema: z.object({ "arr": z.array(z.any()) })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __some_impl(arr, func) {
  const __setupData = setupFunction();
  const __stack = __setupData.stack;
  const __step = __setupData.step;
  const __self = __setupData.self;
  const __ctx = getRuntimeContext().ctx;
  let __forked;
  let __functionCompleted = false;
  if (!__ctx.globals.isInitialized("stdlib/array.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["arr"] = arr;
  __stack.args["func"] = func;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/array.agency", scopeName: "some", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("arr" in __overrides) {
      arr = __overrides["arr"];
      __stack.args["arr"] = arr;
    }
    if ("func" in __overrides) {
      func = __overrides["func"];
      __stack.args["func"] = func;
    }
  }
  try {
    await agencyStore.run({
      ...getRuntimeContext(),
      ctx: __ctx,
      stack: __setupData.stateStack,
      threads: __setupData.threads
    }, async () => {
      await runner.hook(0, async () => {
        await callHook({
          name: "onFunctionStart",
          data: {
            functionName: "some",
            args: {
              arr,
              func
            },
            isBuiltin: false,
            moduleId: "stdlib/array.agency"
          }
        });
      });
      await runner.loop(1, __stack.args.arr, async (item, _, runner2) => {
        await runner2.ifElse(0, [
          {
            condition: async () => await __call(__stack.args.func, {
              type: "positional",
              args: [item]
            }),
            body: async (runner3) => {
              await runner3.step(0, async (runner4) => {
                __functionCompleted = true;
                runner4.halt(true);
                return;
              });
            }
          }
        ]);
      });
      await runner.step(2, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(false);
        return;
      });
    });
    if (runner.halted) {
      if (isFailure(runner.haltResult)) {
        runner.haltResult.retryable = runner.haltResult.retryable && __self.__retryable;
      }
      return runner.haltResult;
    }
  } catch (__error) {
    if (__error instanceof RestoreSignal) {
      throw __error;
    }
    if (__error instanceof GuardExceededError) {
      throw __error;
    }
    {
      const __errMsg = __error instanceof Error ? __error.message : String(__error);
      const __errStack = __error instanceof Error && __error.stack ? __error.stack : "";
      const __log = __createLogger(__ctx.logLevel);
      __log.error("Function some threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "some",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "some",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "some",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const some = __AgencyFunction.create({
  name: "some",
  module: "stdlib/array.agency",
  fn: __some_impl,
  params: [{
    name: "arr",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "func",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "some",
    description: `Return true if the function returns true for at least one element in the array.

  @param arr - The array to test
  @param func - The predicate function`,
    schema: z.object({ "arr": z.array(z.any()) })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __count_impl(arr, func) {
  const __setupData = setupFunction();
  const __stack = __setupData.stack;
  const __step = __setupData.step;
  const __self = __setupData.self;
  const __ctx = getRuntimeContext().ctx;
  let __forked;
  let __functionCompleted = false;
  if (!__ctx.globals.isInitialized("stdlib/array.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["arr"] = arr;
  __stack.args["func"] = func;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/array.agency", scopeName: "count", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("arr" in __overrides) {
      arr = __overrides["arr"];
      __stack.args["arr"] = arr;
    }
    if ("func" in __overrides) {
      func = __overrides["func"];
      __stack.args["func"] = func;
    }
  }
  try {
    await agencyStore.run({
      ...getRuntimeContext(),
      ctx: __ctx,
      stack: __setupData.stateStack,
      threads: __setupData.threads
    }, async () => {
      await runner.hook(0, async () => {
        await callHook({
          name: "onFunctionStart",
          data: {
            functionName: "count",
            args: {
              arr,
              func
            },
            isBuiltin: false,
            moduleId: "stdlib/array.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.n = 0;
      });
      await runner.loop(2, __stack.args.arr, async (item, _, runner2) => {
        await runner2.ifElse(0, [
          {
            condition: async () => await __call(__stack.args.func, {
              type: "positional",
              args: [item]
            }),
            body: async (runner3) => {
              await runner3.step(0, async (runner4) => {
                __stack.locals.n = __stack.locals.n + 1;
              });
            }
          }
        ]);
      });
      await runner.step(3, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(__stack.locals.n);
        return;
      });
    });
    if (runner.halted) {
      if (isFailure(runner.haltResult)) {
        runner.haltResult.retryable = runner.haltResult.retryable && __self.__retryable;
      }
      return runner.haltResult;
    }
  } catch (__error) {
    if (__error instanceof RestoreSignal) {
      throw __error;
    }
    if (__error instanceof GuardExceededError) {
      throw __error;
    }
    {
      const __errMsg = __error instanceof Error ? __error.message : String(__error);
      const __errStack = __error instanceof Error && __error.stack ? __error.stack : "";
      const __log = __createLogger(__ctx.logLevel);
      __log.error("Function count threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "count",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "count",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "count",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const count = __AgencyFunction.create({
  name: "count",
  module: "stdlib/array.agency",
  fn: __count_impl,
  params: [{
    name: "arr",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "func",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "count",
    description: `Count the number of elements in the array for which the function returns true.

  @param arr - The array to count in
  @param func - The predicate function`,
    schema: z.object({ "arr": z.array(z.any()) })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __sortBy_impl(arr, func) {
  const __setupData = setupFunction();
  const __stack = __setupData.stack;
  const __step = __setupData.step;
  const __self = __setupData.self;
  const __ctx = getRuntimeContext().ctx;
  let __forked;
  let __functionCompleted = false;
  if (!__ctx.globals.isInitialized("stdlib/array.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["arr"] = arr;
  __stack.args["func"] = func;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/array.agency", scopeName: "sortBy", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("arr" in __overrides) {
      arr = __overrides["arr"];
      __stack.args["arr"] = arr;
    }
    if ("func" in __overrides) {
      func = __overrides["func"];
      __stack.args["func"] = func;
    }
  }
  try {
    await agencyStore.run({
      ...getRuntimeContext(),
      ctx: __ctx,
      stack: __setupData.stateStack,
      threads: __setupData.threads
    }, async () => {
      await runner.hook(0, async () => {
        await callHook({
          name: "onFunctionStart",
          data: {
            functionName: "sortBy",
            args: {
              arr,
              func
            },
            isBuiltin: false,
            moduleId: "stdlib/array.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.result = [];
      });
      await runner.loop(2, __stack.args.arr, async (item, _, runner2) => {
        await runner2.step(0, async (runner3) => {
          await __callMethod(__stack.locals.result, "push", {
            type: "positional",
            args: [item]
          });
        });
      });
      await runner.step(3, async (runner2) => {
        __stack.locals.i = 0;
      });
      await runner.whileLoop(4, async () => __stack.locals.i < __stack.locals.result.length, async (runner2) => {
        await runner2.step(0, async (runner3) => {
          __stack.locals.j = __stack.locals.i + 1;
        });
        await runner2.whileLoop(1, async () => __stack.locals.j < __stack.locals.result.length, async (runner3) => {
          await runner3.ifElse(0, [
            {
              condition: async () => await __call(__stack.args.func, {
                type: "positional",
                args: [__stack.locals.result[__stack.locals.j]]
              }) < await __call(__stack.args.func, {
                type: "positional",
                args: [__stack.locals.result[__stack.locals.i]]
              }),
              body: async (runner4) => {
                await runner4.step(0, async (runner5) => {
                  __stack.locals.temp = __stack.locals.result[__stack.locals.i];
                });
                await runner4.step(1, async (runner5) => {
                  __stack.locals.result[__stack.locals.i] = __stack.locals.result[__stack.locals.j];
                });
                await runner4.step(2, async (runner5) => {
                  __stack.locals.result[__stack.locals.j] = __stack.locals.temp;
                });
              }
            }
          ]);
          await runner3.step(1, async (runner4) => {
            __stack.locals.j = __stack.locals.j + 1;
          });
        });
        await runner2.step(2, async (runner3) => {
          __stack.locals.i = __stack.locals.i + 1;
        });
      });
      await runner.step(5, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(__stack.locals.result);
        return;
      });
    });
    if (runner.halted) {
      if (isFailure(runner.haltResult)) {
        runner.haltResult.retryable = runner.haltResult.retryable && __self.__retryable;
      }
      return runner.haltResult;
    }
  } catch (__error) {
    if (__error instanceof RestoreSignal) {
      throw __error;
    }
    if (__error instanceof GuardExceededError) {
      throw __error;
    }
    {
      const __errMsg = __error instanceof Error ? __error.message : String(__error);
      const __errStack = __error instanceof Error && __error.stack ? __error.stack : "";
      const __log = __createLogger(__ctx.logLevel);
      __log.error("Function sortBy threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "sortBy",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "sortBy",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "sortBy",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const sortBy = __AgencyFunction.create({
  name: "sortBy",
  module: "stdlib/array.agency",
  fn: __sortBy_impl,
  params: [{
    name: "arr",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "func",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "sortBy",
    description: `Return a new array sorted by the values returned by the function, in ascending order.

  @param arr - The array to sort
  @param func - The function returning the sort key for each element`,
    schema: z.object({ "arr": z.array(z.any()) })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __unique_impl(arr, func) {
  const __setupData = setupFunction();
  const __stack = __setupData.stack;
  const __step = __setupData.step;
  const __self = __setupData.self;
  const __ctx = getRuntimeContext().ctx;
  let __forked;
  let __functionCompleted = false;
  if (!__ctx.globals.isInitialized("stdlib/array.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["arr"] = arr;
  __stack.args["func"] = func;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/array.agency", scopeName: "unique", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("arr" in __overrides) {
      arr = __overrides["arr"];
      __stack.args["arr"] = arr;
    }
    if ("func" in __overrides) {
      func = __overrides["func"];
      __stack.args["func"] = func;
    }
  }
  try {
    await agencyStore.run({
      ...getRuntimeContext(),
      ctx: __ctx,
      stack: __setupData.stateStack,
      threads: __setupData.threads
    }, async () => {
      await runner.hook(0, async () => {
        await callHook({
          name: "onFunctionStart",
          data: {
            functionName: "unique",
            args: {
              arr,
              func
            },
            isBuiltin: false,
            moduleId: "stdlib/array.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.result = [];
      });
      await runner.step(2, async (runner2) => {
        __stack.locals.seen = [];
      });
      await runner.loop(3, __stack.args.arr, async (item, _, runner2) => {
        await runner2.step(0, async (runner3) => {
          __stack.locals.key = await __call(__stack.args.func, {
            type: "positional",
            args: [item]
          });
          if (hasInterrupts(__stack.locals.key)) {
            await getRuntimeContext().ctx.pendingPromises.awaitAll();
            runner3.halt(__stack.locals.key);
            return;
          }
        });
        await runner2.step(1, async (runner3) => {
          __stack.locals.found = false;
        });
        await runner2.loop(2, __stack.locals.seen, async (s, _2, runner3) => {
          await runner3.ifElse(0, [
            {
              condition: async () => s === __stack.locals.key,
              body: async (runner4) => {
                await runner4.step(0, async (runner5) => {
                  __stack.locals.found = true;
                });
              }
            }
          ]);
        });
        await runner2.ifElse(3, [
          {
            condition: async () => __stack.locals.found === false,
            body: async (runner3) => {
              await runner3.step(0, async (runner4) => {
                await __callMethod(__stack.locals.result, "push", {
                  type: "positional",
                  args: [item]
                });
              });
              await runner3.step(1, async (runner4) => {
                await __callMethod(__stack.locals.seen, "push", {
                  type: "positional",
                  args: [__stack.locals.key]
                });
              });
            }
          }
        ]);
      });
      await runner.step(4, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(__stack.locals.result);
        return;
      });
    });
    if (runner.halted) {
      if (isFailure(runner.haltResult)) {
        runner.haltResult.retryable = runner.haltResult.retryable && __self.__retryable;
      }
      return runner.haltResult;
    }
  } catch (__error) {
    if (__error instanceof RestoreSignal) {
      throw __error;
    }
    if (__error instanceof GuardExceededError) {
      throw __error;
    }
    {
      const __errMsg = __error instanceof Error ? __error.message : String(__error);
      const __errStack = __error instanceof Error && __error.stack ? __error.stack : "";
      const __log = __createLogger(__ctx.logLevel);
      __log.error("Function unique threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "unique",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "unique",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "unique",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const unique = __AgencyFunction.create({
  name: "unique",
  module: "stdlib/array.agency",
  fn: __unique_impl,
  params: [{
    name: "arr",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "func",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "unique",
    description: `Return a new array with duplicate elements removed, using the function to determine the identity of each element.

  @param arr - The array to deduplicate
  @param func - The function returning the identity key for each element`,
    schema: z.object({ "arr": z.array(z.any()) })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __groupBy_impl(arr, func) {
  const __setupData = setupFunction();
  const __stack = __setupData.stack;
  const __step = __setupData.step;
  const __self = __setupData.self;
  const __ctx = getRuntimeContext().ctx;
  let __forked;
  let __functionCompleted = false;
  if (!__ctx.globals.isInitialized("stdlib/array.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["arr"] = arr;
  __stack.args["func"] = func;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/array.agency", scopeName: "groupBy", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("arr" in __overrides) {
      arr = __overrides["arr"];
      __stack.args["arr"] = arr;
    }
    if ("func" in __overrides) {
      func = __overrides["func"];
      __stack.args["func"] = func;
    }
  }
  try {
    await agencyStore.run({
      ...getRuntimeContext(),
      ctx: __ctx,
      stack: __setupData.stateStack,
      threads: __setupData.threads
    }, async () => {
      await runner.hook(0, async () => {
        await callHook({
          name: "onFunctionStart",
          data: {
            functionName: "groupBy",
            args: {
              arr,
              func
            },
            isBuiltin: false,
            moduleId: "stdlib/array.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.groups = {};
      });
      await runner.loop(2, __stack.args.arr, async (item, _, runner2) => {
        await runner2.step(0, async (runner3) => {
          __stack.locals.key = await __call(__stack.args.func, {
            type: "positional",
            args: [item]
          });
          if (hasInterrupts(__stack.locals.key)) {
            await getRuntimeContext().ctx.pendingPromises.awaitAll();
            runner3.halt(__stack.locals.key);
            return;
          }
        });
        await runner2.step(1, async (runner3) => {
          __stack.locals.groups[__stack.locals.key] ??= [];
        });
        await runner2.step(2, async (runner3) => {
          await __callMethod(__stack.locals.groups[__stack.locals.key], "push", {
            type: "positional",
            args: [item]
          });
        });
      });
      await runner.step(3, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(__stack.locals.groups);
        return;
      });
    });
    if (runner.halted) {
      if (isFailure(runner.haltResult)) {
        runner.haltResult.retryable = runner.haltResult.retryable && __self.__retryable;
      }
      return runner.haltResult;
    }
  } catch (__error) {
    if (__error instanceof RestoreSignal) {
      throw __error;
    }
    if (__error instanceof GuardExceededError) {
      throw __error;
    }
    {
      const __errMsg = __error instanceof Error ? __error.message : String(__error);
      const __errStack = __error instanceof Error && __error.stack ? __error.stack : "";
      const __log = __createLogger(__ctx.logLevel);
      __log.error("Function groupBy threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "groupBy",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "groupBy",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "groupBy",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const groupBy = __AgencyFunction.create({
  name: "groupBy",
  module: "stdlib/array.agency",
  fn: __groupBy_impl,
  params: [{
    name: "arr",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "func",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "groupBy",
    description: `Group elements of an array by the value returned by the function. Returns an object where keys are group names and values are arrays of elements.

  @param arr - The array to group
  @param func - The function returning the group key for each element`,
    schema: z.object({ "arr": z.array(z.any()) })
  },
  safe: false,
  exported: true
}, __toolRegistry);
var stdin_default = graph;
const __sourceMap = { "stdlib/array.agency:map": { "1": { "line": 7, "col": 2 }, "2": { "line": 8, "col": 2 }, "3": { "line": 11, "col": 2 }, "2.0": { "line": 9, "col": 4 } }, "stdlib/array.agency:filter": { "1": { "line": 21, "col": 2 }, "2": { "line": 22, "col": 2 }, "3": { "line": 27, "col": 2 }, "2.0.0": { "line": 24, "col": 6 }, "2.0": { "line": 23, "col": 4 } }, "stdlib/array.agency:exclude": { "1": { "line": 37, "col": 2 }, "2": { "line": 38, "col": 2 }, "3": { "line": 43, "col": 2 }, "2.0.0": { "line": 40, "col": 6 }, "2.0": { "line": 39, "col": 4 } }, "stdlib/array.agency:find": { "1": { "line": 53, "col": 2 }, "2": { "line": 58, "col": 2 }, "1.0.0": { "line": 55, "col": 6 }, "1.0": { "line": 54, "col": 4 } }, "stdlib/array.agency:findIndex": { "1": { "line": 68, "col": 2 }, "2": { "line": 73, "col": 2 }, "1.0.0": { "line": 70, "col": 6 }, "1.0": { "line": 69, "col": 4 } }, "stdlib/array.agency:reduce": { "1": { "line": 84, "col": 2 }, "2": { "line": 85, "col": 2 }, "3": { "line": 88, "col": 2 }, "2.0": { "line": 86, "col": 4 } }, "stdlib/array.agency:flatMap": { "1": { "line": 98, "col": 2 }, "2": { "line": 99, "col": 2 }, "3": { "line": 105, "col": 2 }, "2.0": { "line": 100, "col": 4 }, "2.1.0": { "line": 102, "col": 6 }, "2.1": { "line": 101, "col": 4 } }, "stdlib/array.agency:every": { "1": { "line": 115, "col": 2 }, "2": { "line": 120, "col": 2 }, "1.0.0": { "line": 117, "col": 6 }, "1.0": { "line": 116, "col": 4 } }, "stdlib/array.agency:some": { "1": { "line": 130, "col": 2 }, "2": { "line": 135, "col": 2 }, "1.0.0": { "line": 132, "col": 6 }, "1.0": { "line": 131, "col": 4 } }, "stdlib/array.agency:count": { "1": { "line": 145, "col": 2 }, "2": { "line": 146, "col": 2 }, "3": { "line": 151, "col": 2 }, "2.0.0": { "line": 148, "col": 6 }, "2.0": { "line": 147, "col": 4 } }, "stdlib/array.agency:sortBy": { "1": { "line": 161, "col": 2 }, "2": { "line": 162, "col": 2 }, "3": { "line": 165, "col": 2 }, "4": { "line": 166, "col": 2 }, "5": { "line": 178, "col": 2 }, "2.0": { "line": 163, "col": 4 }, "4.0": { "line": 167, "col": 4 }, "4.1.0.0": { "line": 170, "col": 8 }, "4.1.0.1": { "line": 171, "col": 8 }, "4.1.0.2": { "line": 172, "col": 8 }, "4.1.0": { "line": 169, "col": 6 }, "4.1.1": { "line": 174, "col": 6 }, "4.1": { "line": 168, "col": 4 }, "4.2": { "line": 176, "col": 4 } }, "stdlib/array.agency:unique": { "1": { "line": 188, "col": 2 }, "2": { "line": 189, "col": 2 }, "3": { "line": 190, "col": 2 }, "4": { "line": 203, "col": 2 }, "3.0": { "line": 191, "col": 4 }, "3.1": { "line": 192, "col": 4 }, "3.2.0.0": { "line": 195, "col": 8 }, "3.2.0": { "line": 194, "col": 6 }, "3.2": { "line": 193, "col": 4 }, "3.3.0": { "line": 199, "col": 6 }, "3.3.1": { "line": 200, "col": 6 }, "3.3": { "line": 198, "col": 4 } }, "stdlib/array.agency:groupBy": { "1": { "line": 213, "col": 2 }, "2": { "line": 214, "col": 2 }, "3": { "line": 219, "col": 2 }, "2.0": { "line": 215, "col": 4 }, "2.2": { "line": 217, "col": 4 } } };
export {
  __getCheckpoints,
  __setDebugger,
  __setLLMClient,
  __setTraceFile,
  __sourceMap,
  __toolRegistry,
  approve,
  count,
  stdin_default as default,
  every,
  exclude,
  filter,
  find,
  findIndex,
  flatMap,
  groupBy,
  hasInterrupts,
  interrupt,
  isDebugger,
  isInterrupt,
  map,
  reduce,
  reject,
  respondToInterrupts,
  rewindFrom,
  some,
  sortBy,
  unique
};
