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 { _ls, _grep, _glob, _stat, _exists, _which, _exec, _bash } from "agency-lang/stdlib-lib/shell.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,
  isRejected,
  isApproved,
  interruptWithHandlers,
  respondToInterrupts as _respondToInterrupts,
  rewindFrom as _rewindFrom,
  RestoreSignal,
  GuardExceededError,
  __registerGlobalsInit,
  failure,
  isFailure,
  __tryCall,
  AgencyFunction as __AgencyFunction,
  UNSET as __UNSET,
  __call,
  __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/shell.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/shell.agency")) {
    return;
  }
  __ctx.globals.markInitialized("stdlib/shell.agency");
}
__registerGlobalsInit("stdlib/shell.agency", __initializeGlobals);
async function __registerTopLevelCallbacks(__ctx) {
  __ctx.topLevelCallbacks = [];
}
__functionRefReviver.registry = __toolRegistry;
const ExecResult = z.object({ "stdout": z.string(), "stderr": z.string(), "exitCode": z.number() });
async function __exec_impl(command, args = __UNSET, cwd = __UNSET, timeout = __UNSET, stdin = __UNSET, allowedExecutables = __UNSET, blockedCommands = __UNSET, allowedPaths = __UNSET) {
  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/shell.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["command"] = command;
  __stack.args["args"] = args === __UNSET ? [] : args;
  __stack.args["cwd"] = cwd === __UNSET ? `` : cwd;
  __stack.args["timeout"] = timeout === __UNSET ? 0 : timeout;
  __stack.args["stdin"] = stdin === __UNSET ? `` : stdin;
  __stack.args["allowedExecutables"] = allowedExecutables === __UNSET ? [] : allowedExecutables;
  __stack.args["blockedCommands"] = blockedCommands === __UNSET ? [] : blockedCommands;
  __stack.args["allowedPaths"] = allowedPaths === __UNSET ? [] : allowedPaths;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/shell.agency", scopeName: "exec", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("command" in __overrides) {
      command = __overrides["command"];
      __stack.args["command"] = command;
    }
    if ("args" in __overrides) {
      args = __overrides["args"];
      __stack.args["args"] = args;
    }
    if ("cwd" in __overrides) {
      cwd = __overrides["cwd"];
      __stack.args["cwd"] = cwd;
    }
    if ("timeout" in __overrides) {
      timeout = __overrides["timeout"];
      __stack.args["timeout"] = timeout;
    }
    if ("stdin" in __overrides) {
      stdin = __overrides["stdin"];
      __stack.args["stdin"] = stdin;
    }
    if ("allowedExecutables" in __overrides) {
      allowedExecutables = __overrides["allowedExecutables"];
      __stack.args["allowedExecutables"] = allowedExecutables;
    }
    if ("blockedCommands" in __overrides) {
      blockedCommands = __overrides["blockedCommands"];
      __stack.args["blockedCommands"] = blockedCommands;
    }
    if ("allowedPaths" in __overrides) {
      allowedPaths = __overrides["allowedPaths"];
      __stack.args["allowedPaths"] = allowedPaths;
    }
  }
  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: "exec",
            args: {
              command,
              args,
              cwd,
              timeout,
              stdin,
              allowedExecutables,
              blockedCommands,
              allowedPaths
            },
            isBuiltin: false,
            moduleId: "stdlib/shell.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
      });
      await runner.step(2, async (runner2) => {
        __stack.locals.subcommand = ``;
      });
      await runner.ifElse(3, [
        {
          condition: async () => __stack.args.args.length > 0,
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __stack.locals.subcommand = __stack.args.args[0];
            });
          }
        }
      ]);
      await runner.step(4, async (runner2) => {
        const __response = getRuntimeContext().ctx.getInterruptResponse(__self.__interruptId_4);
        if (__response) {
          if (__response.type === "approve") {
          } else if (__response.type === "reject") {
            runner2.halt(failure("interrupt rejected", { retryable: false, checkpoint: getRuntimeContext().ctx.getResultCheckpoint() }));
            return;
          }
        } else {
          const __handlerResult = await interruptWithHandlers("std::exec", `Are you sure you want to run this command?`, {
            "command": __stack.args.command,
            "args": __stack.args.args,
            "subcommand": __stack.locals.subcommand,
            "cwd": __stack.args.cwd,
            "timeout": __stack.args.timeout,
            "stdin": __stack.args.stdin
          }, "std::shell", __ctx, __stateStack());
          if (isRejected(__handlerResult)) {
            runner2.halt(failure(__handlerResult.value ?? "interrupt rejected", { retryable: false, checkpoint: getRuntimeContext().ctx.checkpoints.get(__resultCheckpointId) }));
            return;
          }
          if (!isApproved(__handlerResult)) {
            __self.__interruptId_4 = __handlerResult[0].interruptId;
            const __checkpointId = getRuntimeContext().ctx.checkpoints.create(__stateStack(), __ctx, { moduleId: "stdlib/shell.agency", scopeName: "exec", stepPath: "4" });
            __handlerResult[0].checkpointId = __checkpointId;
            __handlerResult[0].checkpoint = getRuntimeContext().ctx.checkpoints.get(__checkpointId);
            runner2.halt(__handlerResult);
            return;
          }
        }
      });
      await runner.step(5, async (runner2) => {
        __self.__retryable = false;
        __functionCompleted = true;
        runner2.halt(await __call(_exec, {
          type: "positional",
          args: [__stack.args.command, __stack.args.args, __stack.args.cwd, __stack.args.timeout, __stack.args.stdin, {
            "allowedExecutables": __stack.args.allowedExecutables,
            "blockedCommands": __stack.args.blockedCommands,
            "allowedPaths": __stack.args.allowedPaths
          }]
        }));
        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 exec threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "exec",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "exec",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "exec",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const exec = __AgencyFunction.create({
  name: "exec",
  module: "stdlib/shell.agency",
  fn: __exec_impl,
  params: [{
    name: "command",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "args",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "cwd",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "timeout",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "stdin",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "allowedExecutables",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "blockedCommands",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "allowedPaths",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "exec",
    description: `Run an executable directly with an array of arguments, bypassing the shell. This is safer than bash() because arguments are passed directly to the process without shell interpretation, preventing command injection. Use this when you have a known command and structured arguments. Pass cwd to change the working directory, timeout in milliseconds to enforce a time limit (e.g. timeout: 30s), and stdin to feed input to the command. Set allowedExecutables to restrict which executables can be run. Set blockedCommands to reject specific executables. Set allowedPaths to require \`cwd\` to live under one of those prefixes.

  @param command - The executable to run
  @param args - Array of arguments to pass
  @param cwd - Working directory for the command
  @param timeout - Time limit in milliseconds (e.g. 30s)
  @param stdin - Input to feed to the command
  @param allowedExecutables - Only allow running these executables (allow-list)
  @param blockedCommands - Block running these executables
  @param allowedPaths - Only allow cwd values under these path prefixes`,
    schema: z.object({ "command": z.string(), "args": z.array(z.string()).nullable().describe("Default: []"), "cwd": z.string().nullable().describe("Default: "), "timeout": z.number().nullable().describe("Default: 0"), "stdin": z.string().nullable().describe("Default: "), "allowedExecutables": z.array(z.string()).nullable().describe("Default: []"), "blockedCommands": z.array(z.string()).nullable().describe("Default: []"), "allowedPaths": z.array(z.string()).nullable().describe("Default: []") })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __bash_impl(command, cwd = __UNSET, timeout = __UNSET, stdin = __UNSET, blockedCommands = __UNSET, allowedPaths = __UNSET) {
  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/shell.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["command"] = command;
  __stack.args["cwd"] = cwd === __UNSET ? `` : cwd;
  __stack.args["timeout"] = timeout === __UNSET ? 0 : timeout;
  __stack.args["stdin"] = stdin === __UNSET ? `` : stdin;
  __stack.args["blockedCommands"] = blockedCommands === __UNSET ? [] : blockedCommands;
  __stack.args["allowedPaths"] = allowedPaths === __UNSET ? [] : allowedPaths;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/shell.agency", scopeName: "bash", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("command" in __overrides) {
      command = __overrides["command"];
      __stack.args["command"] = command;
    }
    if ("cwd" in __overrides) {
      cwd = __overrides["cwd"];
      __stack.args["cwd"] = cwd;
    }
    if ("timeout" in __overrides) {
      timeout = __overrides["timeout"];
      __stack.args["timeout"] = timeout;
    }
    if ("stdin" in __overrides) {
      stdin = __overrides["stdin"];
      __stack.args["stdin"] = stdin;
    }
    if ("blockedCommands" in __overrides) {
      blockedCommands = __overrides["blockedCommands"];
      __stack.args["blockedCommands"] = blockedCommands;
    }
    if ("allowedPaths" in __overrides) {
      allowedPaths = __overrides["allowedPaths"];
      __stack.args["allowedPaths"] = allowedPaths;
    }
  }
  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: "bash",
            args: {
              command,
              cwd,
              timeout,
              stdin,
              blockedCommands,
              allowedPaths
            },
            isBuiltin: false,
            moduleId: "stdlib/shell.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        const __response = getRuntimeContext().ctx.getInterruptResponse(__self.__interruptId_1);
        if (__response) {
          if (__response.type === "approve") {
          } else if (__response.type === "reject") {
            runner2.halt(failure("interrupt rejected", { retryable: false, checkpoint: getRuntimeContext().ctx.getResultCheckpoint() }));
            return;
          }
        } else {
          const __handlerResult = await interruptWithHandlers("std::bash", `Are you sure you want to run this shell command?`, {
            "command": __stack.args.command,
            "cwd": __stack.args.cwd,
            "timeout": __stack.args.timeout,
            "stdin": __stack.args.stdin
          }, "std::shell", __ctx, __stateStack());
          if (isRejected(__handlerResult)) {
            runner2.halt(failure(__handlerResult.value ?? "interrupt rejected", { retryable: false, checkpoint: getRuntimeContext().ctx.checkpoints.get(__resultCheckpointId) }));
            return;
          }
          if (!isApproved(__handlerResult)) {
            __self.__interruptId_1 = __handlerResult[0].interruptId;
            const __checkpointId = getRuntimeContext().ctx.checkpoints.create(__stateStack(), __ctx, { moduleId: "stdlib/shell.agency", scopeName: "bash", stepPath: "1" });
            __handlerResult[0].checkpointId = __checkpointId;
            __handlerResult[0].checkpoint = getRuntimeContext().ctx.checkpoints.get(__checkpointId);
            runner2.halt(__handlerResult);
            return;
          }
        }
      });
      await runner.step(2, async (runner2) => {
        __self.__retryable = false;
        __functionCompleted = true;
        runner2.halt(await __call(_bash, {
          type: "positional",
          args: [__stack.args.command, __stack.args.cwd, __stack.args.timeout, __stack.args.stdin, {
            "blockedCommands": __stack.args.blockedCommands,
            "allowedPaths": __stack.args.allowedPaths
          }]
        }));
        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 bash threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "bash",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "bash",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "bash",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const bash = __AgencyFunction.create({
  name: "bash",
  module: "stdlib/shell.agency",
  fn: __bash_impl,
  params: [{
    name: "command",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "cwd",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "timeout",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "stdin",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "blockedCommands",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "allowedPaths",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "bash",
    description: `Run a shell command string via sh -c and return its stdout, stderr, and exit code. The command is interpreted by the shell, so pipes, redirects, globbing, and other shell features work. However, this means interpolated values are subject to shell interpretation -- use exec() instead when passing untrusted or dynamic arguments. Pass cwd to change the working directory, timeout in milliseconds to enforce a time limit (e.g. timeout: 30s), and stdin to feed input to the command. Set blockedCommands to reject commands that start with specific strings. Set allowedPaths to require \`cwd\` to live under one of those prefixes; bash() cannot meaningfully restrict the shell string itself, so prefer exec() when capability narrowing matters.

  @param command - The shell command to run
  @param cwd - Working directory for the command
  @param timeout - Time limit in milliseconds (e.g. 30s)
  @param stdin - Input to feed to the command
  @param blockedCommands - Block commands that start with these strings
  @param allowedPaths - Only allow cwd values under these path prefixes`,
    schema: z.object({ "command": z.string(), "cwd": z.string().nullable().describe("Default: "), "timeout": z.number().nullable().describe("Default: 0"), "stdin": z.string().nullable().describe("Default: "), "blockedCommands": z.array(z.string()).nullable().describe("Default: []"), "allowedPaths": z.array(z.string()).nullable().describe("Default: []") })
  },
  safe: false,
  exported: true
}, __toolRegistry);
const LsEntry = z.object({ "name": z.string(), "path": z.string(), "type": z.union([z.literal("file"), z.literal("dir"), z.literal("symlink"), z.literal("other")]), "size": z.number() });
async function __ls_impl(dir = __UNSET, recursive = __UNSET, allowedPaths = __UNSET) {
  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/shell.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["dir"] = dir === __UNSET ? `.` : dir;
  __stack.args["recursive"] = recursive === __UNSET ? false : recursive;
  __stack.args["allowedPaths"] = allowedPaths === __UNSET ? [] : allowedPaths;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/shell.agency", scopeName: "ls", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("dir" in __overrides) {
      dir = __overrides["dir"];
      __stack.args["dir"] = dir;
    }
    if ("recursive" in __overrides) {
      recursive = __overrides["recursive"];
      __stack.args["recursive"] = recursive;
    }
    if ("allowedPaths" in __overrides) {
      allowedPaths = __overrides["allowedPaths"];
      __stack.args["allowedPaths"] = allowedPaths;
    }
  }
  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: "ls",
            args: {
              dir,
              recursive,
              allowedPaths
            },
            isBuiltin: false,
            moduleId: "stdlib/shell.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        const __response = getRuntimeContext().ctx.getInterruptResponse(__self.__interruptId_1);
        if (__response) {
          if (__response.type === "approve") {
          } else if (__response.type === "reject") {
            runner2.halt(failure("interrupt rejected", { retryable: false, checkpoint: getRuntimeContext().ctx.getResultCheckpoint() }));
            return;
          }
        } else {
          const __handlerResult = await interruptWithHandlers("std::ls", `Are you sure you want to list this directory?`, {
            "dir": __stack.args.dir,
            "recursive": __stack.args.recursive
          }, "std::shell", __ctx, __stateStack());
          if (isRejected(__handlerResult)) {
            runner2.halt(failure(__handlerResult.value ?? "interrupt rejected", { retryable: false, checkpoint: getRuntimeContext().ctx.checkpoints.get(__resultCheckpointId) }));
            return;
          }
          if (!isApproved(__handlerResult)) {
            __self.__interruptId_1 = __handlerResult[0].interruptId;
            const __checkpointId = getRuntimeContext().ctx.checkpoints.create(__stateStack(), __ctx, { moduleId: "stdlib/shell.agency", scopeName: "ls", stepPath: "1" });
            __handlerResult[0].checkpointId = __checkpointId;
            __handlerResult[0].checkpoint = getRuntimeContext().ctx.checkpoints.get(__checkpointId);
            runner2.halt(__handlerResult);
            return;
          }
        }
      });
      await runner.step(2, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __tryCall(async () => await __call(_ls, {
          type: "positional",
          args: [__stack.args.dir, __stack.args.recursive, __stack.args.allowedPaths]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "ls",
          args: __stack.args
        }));
        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 ls threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "ls",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "ls",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "ls",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const ls = __AgencyFunction.create({
  name: "ls",
  module: "stdlib/shell.agency",
  fn: __ls_impl,
  params: [{
    name: "dir",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "recursive",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "allowedPaths",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "ls",
    description: `List entries in a directory. Each entry includes name, path, type ("file", "dir", "symlink", "other"), and size. Set recursive to true to walk subdirectories. Fails if the directory cannot be read (missing, not a directory, permission denied). Set allowedPaths to restrict which directories may be listed.

  Relative \`dir\` is resolved against the calling Agency module's directory (same policy as \`read\`/\`write\`/\`glob\`/\`grep\`), and returned \`path\` values are relative to \`dir\` \u2014 so results compose with \`read(path, dir)\` directly.

  Returns every entry under \`dir\` \u2014 large recursive listings can balloon. Narrow \`dir\`, set \`recursive: false\`, or use \`glob\` with a more specific pattern when you only need a subset.

  @param dir - The directory to list (relative paths resolve against the module directory)
  @param recursive - Whether to walk subdirectories
  @param allowedPaths - Only allow listing directories under these prefixes`,
    schema: z.object({ "dir": z.string().nullable().describe("Default: ."), "recursive": z.boolean().nullable().describe("Default: false"), "allowedPaths": z.array(z.string()).nullable().describe("Default: []") })
  },
  safe: false,
  exported: true
}, __toolRegistry);
const GrepMatch = z.object({ "file": z.string(), "line": z.number(), "text": z.string() });
async function __grep_impl(pattern, dir = __UNSET, flags = __UNSET, maxResults = __UNSET, allowedPaths = __UNSET) {
  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/shell.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["pattern"] = pattern;
  __stack.args["dir"] = dir === __UNSET ? `.` : dir;
  __stack.args["flags"] = flags === __UNSET ? `` : flags;
  __stack.args["maxResults"] = maxResults === __UNSET ? 200 : maxResults;
  __stack.args["allowedPaths"] = allowedPaths === __UNSET ? [] : allowedPaths;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/shell.agency", scopeName: "grep", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("pattern" in __overrides) {
      pattern = __overrides["pattern"];
      __stack.args["pattern"] = pattern;
    }
    if ("dir" in __overrides) {
      dir = __overrides["dir"];
      __stack.args["dir"] = dir;
    }
    if ("flags" in __overrides) {
      flags = __overrides["flags"];
      __stack.args["flags"] = flags;
    }
    if ("maxResults" in __overrides) {
      maxResults = __overrides["maxResults"];
      __stack.args["maxResults"] = maxResults;
    }
    if ("allowedPaths" in __overrides) {
      allowedPaths = __overrides["allowedPaths"];
      __stack.args["allowedPaths"] = allowedPaths;
    }
  }
  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: "grep",
            args: {
              pattern,
              dir,
              flags,
              maxResults,
              allowedPaths
            },
            isBuiltin: false,
            moduleId: "stdlib/shell.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        const __response = getRuntimeContext().ctx.getInterruptResponse(__self.__interruptId_1);
        if (__response) {
          if (__response.type === "approve") {
          } else if (__response.type === "reject") {
            runner2.halt(failure("interrupt rejected", { retryable: false, checkpoint: getRuntimeContext().ctx.getResultCheckpoint() }));
            return;
          }
        } else {
          const __handlerResult = await interruptWithHandlers("std::grep", `Are you sure you want to search files with grep?`, {
            "pattern": __stack.args.pattern,
            "dir": __stack.args.dir,
            "flags": __stack.args.flags,
            "maxResults": __stack.args.maxResults
          }, "std::shell", __ctx, __stateStack());
          if (isRejected(__handlerResult)) {
            runner2.halt(failure(__handlerResult.value ?? "interrupt rejected", { retryable: false, checkpoint: getRuntimeContext().ctx.checkpoints.get(__resultCheckpointId) }));
            return;
          }
          if (!isApproved(__handlerResult)) {
            __self.__interruptId_1 = __handlerResult[0].interruptId;
            const __checkpointId = getRuntimeContext().ctx.checkpoints.create(__stateStack(), __ctx, { moduleId: "stdlib/shell.agency", scopeName: "grep", stepPath: "1" });
            __handlerResult[0].checkpointId = __checkpointId;
            __handlerResult[0].checkpoint = getRuntimeContext().ctx.checkpoints.get(__checkpointId);
            runner2.halt(__handlerResult);
            return;
          }
        }
      });
      await runner.step(2, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __tryCall(async () => await __call(_grep, {
          type: "positional",
          args: [__stack.args.pattern, __stack.args.dir, __stack.args.flags, __stack.args.maxResults, __stack.args.allowedPaths]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "grep",
          args: __stack.args
        }));
        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 grep threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "grep",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "grep",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "grep",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const grep = __AgencyFunction.create({
  name: "grep",
  module: "stdlib/shell.agency",
  fn: __grep_impl,
  params: [{
    name: "pattern",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "dir",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "flags",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "maxResults",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "allowedPaths",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "grep",
    description: `Search for a regex pattern in files under a directory. Returns matches with file path, line number, and matched line. Skips node_modules, .git, dist, build. Stops at maxResults. Fails if the pattern is not a valid regex or the directory cannot be read. Set allowedPaths to restrict which directories may be searched.

  Relative \`dir\` is resolved against the calling Agency module's directory (same policy as \`read\`/\`write\`/\`glob\`/\`ls\`), and returned \`file\` values are relative to \`dir\` \u2014 so results compose with \`read(file, dir)\` directly.

  Returns at most \`maxResults\` matches (default 200). If you suspect matches were truncated, narrow \`dir\` or refine \`pattern\`.

  @param pattern - The regex pattern to search for
  @param dir - The directory to search in (relative paths resolve against the module directory)
  @param flags - Regex flags
  @param maxResults - Maximum number of results to return
  @param allowedPaths - Only allow searching under these path prefixes`,
    schema: z.object({ "pattern": z.string(), "dir": z.string().nullable().describe("Default: ."), "flags": z.string().nullable().describe("Default: "), "maxResults": z.number().nullable().describe("Default: 200"), "allowedPaths": z.array(z.string()).nullable().describe("Default: []") })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __glob_impl(pattern, dir = __UNSET, maxResults = __UNSET, allowedPaths = __UNSET) {
  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/shell.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["pattern"] = pattern;
  __stack.args["dir"] = dir === __UNSET ? `.` : dir;
  __stack.args["maxResults"] = maxResults === __UNSET ? 500 : maxResults;
  __stack.args["allowedPaths"] = allowedPaths === __UNSET ? [] : allowedPaths;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/shell.agency", scopeName: "glob", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("pattern" in __overrides) {
      pattern = __overrides["pattern"];
      __stack.args["pattern"] = pattern;
    }
    if ("dir" in __overrides) {
      dir = __overrides["dir"];
      __stack.args["dir"] = dir;
    }
    if ("maxResults" in __overrides) {
      maxResults = __overrides["maxResults"];
      __stack.args["maxResults"] = maxResults;
    }
    if ("allowedPaths" in __overrides) {
      allowedPaths = __overrides["allowedPaths"];
      __stack.args["allowedPaths"] = allowedPaths;
    }
  }
  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: "glob",
            args: {
              pattern,
              dir,
              maxResults,
              allowedPaths
            },
            isBuiltin: false,
            moduleId: "stdlib/shell.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        const __response = getRuntimeContext().ctx.getInterruptResponse(__self.__interruptId_1);
        if (__response) {
          if (__response.type === "approve") {
          } else if (__response.type === "reject") {
            runner2.halt(failure("interrupt rejected", { retryable: false, checkpoint: getRuntimeContext().ctx.getResultCheckpoint() }));
            return;
          }
        } else {
          const __handlerResult = await interruptWithHandlers("std::glob", `Are you sure you want to glob files?`, {
            "pattern": __stack.args.pattern,
            "dir": __stack.args.dir,
            "maxResults": __stack.args.maxResults
          }, "std::shell", __ctx, __stateStack());
          if (isRejected(__handlerResult)) {
            runner2.halt(failure(__handlerResult.value ?? "interrupt rejected", { retryable: false, checkpoint: getRuntimeContext().ctx.checkpoints.get(__resultCheckpointId) }));
            return;
          }
          if (!isApproved(__handlerResult)) {
            __self.__interruptId_1 = __handlerResult[0].interruptId;
            const __checkpointId = getRuntimeContext().ctx.checkpoints.create(__stateStack(), __ctx, { moduleId: "stdlib/shell.agency", scopeName: "glob", stepPath: "1" });
            __handlerResult[0].checkpointId = __checkpointId;
            __handlerResult[0].checkpoint = getRuntimeContext().ctx.checkpoints.get(__checkpointId);
            runner2.halt(__handlerResult);
            return;
          }
        }
      });
      await runner.step(2, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __tryCall(async () => await __call(_glob, {
          type: "positional",
          args: [__stack.args.pattern, __stack.args.dir, __stack.args.maxResults, __stack.args.allowedPaths]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "glob",
          args: __stack.args
        }));
        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 glob threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "glob",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "glob",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "glob",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const glob = __AgencyFunction.create({
  name: "glob",
  module: "stdlib/shell.agency",
  fn: __glob_impl,
  params: [{
    name: "pattern",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "dir",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "maxResults",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "allowedPaths",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "glob",
    description: `Find files whose paths match a glob pattern (e.g. "src/**/*.ts"). Stops at maxResults. Fails if the pattern is not valid glob syntax or the directory cannot be read. Set allowedPaths to restrict which directories may be searched.

  Relative \`dir\` is resolved against the calling Agency module's directory (same policy as \`read\`/\`write\`/\`ls\`/\`grep\`), and returned paths are relative to \`dir\` \u2014 so results compose with \`read(path, dir)\` directly.

  Returns at most \`maxResults\` paths (default 500). If you suspect matches were truncated, narrow \`dir\` or tighten the glob.

  @param pattern - The glob pattern to match
  @param dir - The directory to search in (relative paths resolve against the module directory)
  @param maxResults - Maximum number of results to return
  @param allowedPaths - Only allow searching under these path prefixes`,
    schema: z.object({ "pattern": z.string(), "dir": z.string().nullable().describe("Default: ."), "maxResults": z.number().nullable().describe("Default: 500"), "allowedPaths": z.array(z.string()).nullable().describe("Default: []") })
  },
  safe: false,
  exported: true
}, __toolRegistry);
const StatInfo = z.object({ "exists": z.boolean(), "type": z.union([z.literal("file"), z.literal("dir"), z.literal("symlink"), z.literal("other"), z.literal("missing")]), "size": z.number(), "modifiedMs": z.number() });
async function __stat_impl(filename, dir = __UNSET, allowedPaths = __UNSET) {
  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/shell.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["filename"] = filename;
  __stack.args["dir"] = dir === __UNSET ? `` : dir;
  __stack.args["allowedPaths"] = allowedPaths === __UNSET ? [] : allowedPaths;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/shell.agency", scopeName: "stat", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("filename" in __overrides) {
      filename = __overrides["filename"];
      __stack.args["filename"] = filename;
    }
    if ("dir" in __overrides) {
      dir = __overrides["dir"];
      __stack.args["dir"] = dir;
    }
    if ("allowedPaths" in __overrides) {
      allowedPaths = __overrides["allowedPaths"];
      __stack.args["allowedPaths"] = allowedPaths;
    }
  }
  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: "stat",
            args: {
              filename,
              dir,
              allowedPaths
            },
            isBuiltin: false,
            moduleId: "stdlib/shell.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __call(_stat, {
          type: "positional",
          args: [__stack.args.filename, __stack.args.dir, __stack.args.allowedPaths]
        }));
        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 stat threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "stat",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "stat",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "stat",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const stat = __AgencyFunction.create({
  name: "stat",
  module: "stdlib/shell.agency",
  fn: __stat_impl,
  params: [{
    name: "filename",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "dir",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "allowedPaths",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "stat",
    description: `Return metadata about a filesystem entry: whether it exists, its type ("file", "dir", "symlink", "other", or "missing" if absent), size in bytes, and mtime in ms. Set allowedPaths to restrict which paths may be stat-ed.

  Pass \`dir\` to resolve \`filename\` against a directory the same way \`read\`/\`write\`/\`edit\` do (filename must be relative, cannot escape \`dir\`, and \`dir\` itself resolves against the calling module's directory). When \`dir\` is left empty, filename is resolved against the process cwd and absolute paths are accepted \u2014 the legacy behavior.

  @param filename - The path to stat
  @param dir - Optional directory to resolve \`filename\` against (default: process cwd, absolute paths allowed)
  @param allowedPaths - Only allow paths under these prefixes`,
    schema: z.object({ "filename": z.string(), "dir": z.string().nullable().describe("Default: "), "allowedPaths": z.array(z.string()).nullable().describe("Default: []") })
  },
  safe: true,
  exported: true
}, __toolRegistry);
async function __exists_impl(filename, dir = __UNSET, allowedPaths = __UNSET) {
  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/shell.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["filename"] = filename;
  __stack.args["dir"] = dir === __UNSET ? `` : dir;
  __stack.args["allowedPaths"] = allowedPaths === __UNSET ? [] : allowedPaths;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/shell.agency", scopeName: "exists", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("filename" in __overrides) {
      filename = __overrides["filename"];
      __stack.args["filename"] = filename;
    }
    if ("dir" in __overrides) {
      dir = __overrides["dir"];
      __stack.args["dir"] = dir;
    }
    if ("allowedPaths" in __overrides) {
      allowedPaths = __overrides["allowedPaths"];
      __stack.args["allowedPaths"] = allowedPaths;
    }
  }
  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: "exists",
            args: {
              filename,
              dir,
              allowedPaths
            },
            isBuiltin: false,
            moduleId: "stdlib/shell.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __call(_exists, {
          type: "positional",
          args: [__stack.args.filename, __stack.args.dir, __stack.args.allowedPaths]
        }));
        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 exists threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "exists",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "exists",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "exists",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const exists = __AgencyFunction.create({
  name: "exists",
  module: "stdlib/shell.agency",
  fn: __exists_impl,
  params: [{
    name: "filename",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "dir",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "allowedPaths",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "exists",
    description: `Return true if a file or directory exists at the given path. Set allowedPaths to restrict which paths may be probed; probing outside the allow-list raises an error rather than silently returning false.

  Pass \`dir\` to resolve \`filename\` against a directory the same way \`read\`/\`write\`/\`edit\` do (filename must be relative, cannot escape \`dir\`, and \`dir\` itself resolves against the calling module's directory). When \`dir\` is left empty, filename is resolved against the process cwd and absolute paths are accepted \u2014 the legacy behavior.

  @param filename - The path to check
  @param dir - Optional directory to resolve \`filename\` against (default: process cwd, absolute paths allowed)
  @param allowedPaths - Only allow paths under these prefixes`,
    schema: z.object({ "filename": z.string(), "dir": z.string().nullable().describe("Default: "), "allowedPaths": z.array(z.string()).nullable().describe("Default: []") })
  },
  safe: true,
  exported: true
}, __toolRegistry);
async function __which_impl(command) {
  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/shell.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["command"] = command;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/shell.agency", scopeName: "which", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("command" in __overrides) {
      command = __overrides["command"];
      __stack.args["command"] = command;
    }
  }
  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: "which",
            args: {
              command
            },
            isBuiltin: false,
            moduleId: "stdlib/shell.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __call(_which, {
          type: "positional",
          args: [__stack.args.command]
        }));
        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 which threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "which",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "which",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "which",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const which = __AgencyFunction.create({
  name: "which",
  module: "stdlib/shell.agency",
  fn: __which_impl,
  params: [{
    name: "command",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "which",
    description: `Locate an executable in PATH and return its absolute path. Returns an empty string if the command is not found. On Windows, also tries PATHEXT extensions.`,
    schema: z.object({ "command": z.string() })
  },
  safe: true,
  exported: true
}, __toolRegistry);
var stdin_default = graph;
const __sourceMap = { "stdlib/shell.agency:exec": { "2": { "line": 44, "col": 2 }, "3": { "line": 45, "col": 2 }, "4": { "line": 48, "col": 2 }, "5": { "line": 57, "col": 2 }, "3.0": { "line": 46, "col": 4 } }, "stdlib/shell.agency:bash": { "1": { "line": 89, "col": 2 }, "2": { "line": 96, "col": 2 } }, "stdlib/shell.agency:ls": { "1": { "line": 127, "col": 2 }, "2": { "line": 132, "col": 2 } }, "stdlib/shell.agency:grep": { "1": { "line": 161, "col": 2 }, "2": { "line": 168, "col": 2 } }, "stdlib/shell.agency:glob": { "1": { "line": 189, "col": 2 }, "2": { "line": 195, "col": 2 } }, "stdlib/shell.agency:stat": { "1": { "line": 215, "col": 2 } }, "stdlib/shell.agency:exists": { "1": { "line": 228, "col": 2 } }, "stdlib/shell.agency:which": { "1": { "line": 235, "col": 2 } } };
export {
  __getCheckpoints,
  __setDebugger,
  __setLLMClient,
  __setTraceFile,
  __sourceMap,
  __toolRegistry,
  approve,
  bash,
  stdin_default as default,
  exec,
  exists,
  glob,
  grep,
  hasInterrupts,
  interrupt,
  isDebugger,
  isInterrupt,
  ls,
  reject,
  respondToInterrupts,
  rewindFrom,
  stat,
  which
};
