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 { _multiedit, _applyPatch, _mkdir, _copy, _move, _remove, _printDiff } from "agency-lang/stdlib-lib/fs.js";
import { bash, glob, ls, grep } from "agency-lang/stdlib/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,
  __readStatic,
  __registerGlobalsInit,
  failure,
  isFailure,
  __tryCall,
  AgencyFunction as __AgencyFunction,
  UNSET as __UNSET,
  __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/fs.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);
__registerTool(bash);
__registerTool(glob);
__registerTool(ls);
__registerTool(grep);
async function __initializeGlobals(__ctx) {
  if (__ctx.globals.isInitialized("stdlib/fs.agency")) {
    return;
  }
  __ctx.globals.markInitialized("stdlib/fs.agency");
}
__registerGlobalsInit("stdlib/fs.agency", __initializeGlobals);
async function __registerTopLevelCallbacks(__ctx) {
  __ctx.topLevelCallbacks = [];
}
__functionRefReviver.registry = __toolRegistry;
const Edit = z.object({ "oldText": z.string(), "newText": z.string(), "replaceAll": z.boolean() });
const EditResult = z.object({ "replacements": z.number(), "path": z.string(), "edits": z.number() });
async function __edit_impl(filename, edits, dir = __UNSET, printDiff2 = __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/fs.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["filename"] = filename;
  __stack.args["edits"] = edits;
  __stack.args["dir"] = dir === __UNSET ? `.` : dir;
  __stack.args["printDiff"] = printDiff2 === __UNSET ? false : printDiff2;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/fs.agency", scopeName: "edit", 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 ("edits" in __overrides) {
      edits = __overrides["edits"];
      __stack.args["edits"] = edits;
    }
    if ("dir" in __overrides) {
      dir = __overrides["dir"];
      __stack.args["dir"] = dir;
    }
    if ("printDiff" in __overrides) {
      printDiff2 = __overrides["printDiff"];
      __stack.args["printDiff"] = printDiff2;
    }
  }
  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: "edit",
            args: {
              filename,
              edits,
              dir,
              printDiff: printDiff2
            },
            isBuiltin: false,
            moduleId: "stdlib/fs.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::edit", `Are you sure you want to apply these edits?`, {
            "dir": __stack.args.dir,
            "filename": __stack.args.filename,
            "edits": __stack.args.edits,
            "printDiff": __stack.args.printDiff
          }, "std::fs", __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/fs.agency", scopeName: "edit", 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(_multiedit, {
          type: "positional",
          args: [__stack.args.dir, __stack.args.filename, __stack.args.edits, __stack.args.printDiff]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "edit",
          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 edit threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "edit",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "edit",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "edit",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const edit = __AgencyFunction.create({
  name: "edit",
  module: "stdlib/fs.agency",
  fn: __edit_impl,
  params: [{
    name: "filename",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "edits",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "dir",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "printDiff",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "edit",
    description: `Edit a single file by applying one or more text replacements atomically. Each edit has \`oldText\`, \`newText\`, and \`replaceAll\`. Every edit's \`oldText\` must match a unique, non-overlapping region of the original file (matches are looked up against the file as it stands when the edit runs, after earlier edits). Set \`replaceAll: true\` on an edit to replace every occurrence. When any edit fails, nothing is written.

  Prefer one \`edit\` call with multiple entries over many \`edit\` calls. Keep each \`oldText\` as small as possible while still being unique \u2014 do not pad with unchanged context just to connect distant changes; instead, split them into separate entries in the same \`edits\` array.

  @param filename - The file to edit
  @param edits - Array of edit objects with oldText, newText, replaceAll
  @param dir - The directory to resolve the filename against (defaults to ".")
  @param printDiff - When true, print a colored diff to stdout after the edit applies`,
    schema: z.object({ "filename": z.string(), "edits": z.array(Edit), "dir": z.string().nullable().describe("Default: ."), "printDiff": z.boolean().nullable().describe("Default: false") })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __printDiff_impl(oldText, newText) {
  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/fs.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["oldText"] = oldText;
  __stack.args["newText"] = newText;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/fs.agency", scopeName: "printDiff", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("oldText" in __overrides) {
      oldText = __overrides["oldText"];
      __stack.args["oldText"] = oldText;
    }
    if ("newText" in __overrides) {
      newText = __overrides["newText"];
      __stack.args["newText"] = newText;
    }
  }
  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: "printDiff",
            args: {
              oldText,
              newText
            },
            isBuiltin: false,
            moduleId: "stdlib/fs.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        const __funcResult = await __call(_printDiff, {
          type: "positional",
          args: [__stack.args.oldText, __stack.args.newText]
        });
        if (hasInterrupts(__funcResult)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__funcResult);
          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 printDiff threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "printDiff",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "printDiff",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "printDiff",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const printDiff = __AgencyFunction.create({
  name: "printDiff",
  module: "stdlib/fs.agency",
  fn: __printDiff_impl,
  params: [{
    name: "oldText",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "newText",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "printDiff",
    description: `Print a colored, line-based diff of \`oldText\` vs \`newText\` to stdout.
  Deletions are shown in red with a \`-\` prefix, insertions in green
  with a \`+\` prefix, unchanged context is dimmed. Useful for showing
  what an edit actually changed before / after committing it.

  @param oldText - The original text
  @param newText - The replacement text`,
    schema: z.object({ "oldText": z.string(), "newText": z.string() })
  },
  safe: true,
  exported: true
}, __toolRegistry);
const PatchResult = z.object({ "applied": z.number(), "files": z.array(z.string()) });
async function __applyPatch_impl(patch, 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/fs.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["patch"] = patch;
  __stack.args["allowedPaths"] = allowedPaths === __UNSET ? [] : allowedPaths;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/fs.agency", scopeName: "applyPatch", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("patch" in __overrides) {
      patch = __overrides["patch"];
      __stack.args["patch"] = patch;
    }
    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: "applyPatch",
            args: {
              patch,
              allowedPaths
            },
            isBuiltin: false,
            moduleId: "stdlib/fs.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::applyPatch", `Are you sure you want to apply this patch?`, {
            "patch": __stack.args.patch
          }, "std::fs", __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/fs.agency", scopeName: "applyPatch", 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(_applyPatch, {
          type: "positional",
          args: [__stack.args.patch, __stack.args.allowedPaths]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "applyPatch",
          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 applyPatch threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "applyPatch",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "applyPatch",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "applyPatch",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const applyPatch = __AgencyFunction.create({
  name: "applyPatch",
  module: "stdlib/fs.agency",
  fn: __applyPatch_impl,
  params: [{
    name: "patch",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "allowedPaths",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "applyPatch",
    description: `Apply a unified diff to the working tree. Supports file creation (--- /dev/null), line additions, deletions, and context. Fails on a malformed diff or on a context-line mismatch against the current file contents. Set allowedPaths to restrict which path prefixes can be touched by the patch.

  @param patch - The unified diff to apply
  @param allowedPaths - Only allow patches that touch files under these prefixes`,
    schema: z.object({ "patch": z.string(), "allowedPaths": z.array(z.string()).nullable().describe("Default: []") })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __mkdir_impl(dir, 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/fs.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["dir"] = dir;
  __stack.args["allowedPaths"] = allowedPaths === __UNSET ? [] : allowedPaths;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/fs.agency", scopeName: "mkdir", 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 ("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: "mkdir",
            args: {
              dir,
              allowedPaths
            },
            isBuiltin: false,
            moduleId: "stdlib/fs.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::mkdir", `Are you sure you want to create this directory?`, {
            "dir": __stack.args.dir
          }, "std::fs", __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/fs.agency", scopeName: "mkdir", 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(_mkdir, {
          type: "positional",
          args: [__stack.args.dir, __stack.args.allowedPaths]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "mkdir",
          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 mkdir threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "mkdir",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "mkdir",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "mkdir",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const mkdir = __AgencyFunction.create({
  name: "mkdir",
  module: "stdlib/fs.agency",
  fn: __mkdir_impl,
  params: [{
    name: "dir",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "allowedPaths",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "mkdir",
    description: `Create a directory, including any missing parent directories. Idempotent: succeeds if the directory already exists. Fails if a non-directory entry already occupies the path, or on permission errors. Set allowedPaths to restrict which path prefixes are permitted.

  @param dir - The directory to create
  @param allowedPaths - Only allow paths starting with these prefixes`,
    schema: z.object({ "dir": z.string(), "allowedPaths": z.array(z.string()).nullable().describe("Default: []") })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __copy_impl(src, dest, 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/fs.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["src"] = src;
  __stack.args["dest"] = dest;
  __stack.args["allowedPaths"] = allowedPaths === __UNSET ? [] : allowedPaths;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/fs.agency", scopeName: "copy", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("src" in __overrides) {
      src = __overrides["src"];
      __stack.args["src"] = src;
    }
    if ("dest" in __overrides) {
      dest = __overrides["dest"];
      __stack.args["dest"] = dest;
    }
    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: "copy",
            args: {
              src,
              dest,
              allowedPaths
            },
            isBuiltin: false,
            moduleId: "stdlib/fs.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::copy", `Are you sure you want to copy this file or directory?`, {
            "src": __stack.args.src,
            "dest": __stack.args.dest
          }, "std::fs", __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/fs.agency", scopeName: "copy", 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(_copy, {
          type: "positional",
          args: [__stack.args.src, __stack.args.dest, __stack.args.allowedPaths]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "copy",
          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 copy threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "copy",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "copy",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "copy",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const copy = __AgencyFunction.create({
  name: "copy",
  module: "stdlib/fs.agency",
  fn: __copy_impl,
  params: [{
    name: "src",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "dest",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "allowedPaths",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "copy",
    description: `Copy a file or directory. Directories are copied recursively. Fails if src does not exist or dest cannot be written. Set allowedPaths to restrict which path prefixes are permitted.

  @param src - The source path
  @param dest - The destination path
  @param allowedPaths - Only allow paths starting with these prefixes`,
    schema: z.object({ "src": z.string(), "dest": z.string(), "allowedPaths": z.array(z.string()).nullable().describe("Default: []") })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __move_impl(src, dest, 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/fs.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["src"] = src;
  __stack.args["dest"] = dest;
  __stack.args["allowedPaths"] = allowedPaths === __UNSET ? [] : allowedPaths;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/fs.agency", scopeName: "move", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("src" in __overrides) {
      src = __overrides["src"];
      __stack.args["src"] = src;
    }
    if ("dest" in __overrides) {
      dest = __overrides["dest"];
      __stack.args["dest"] = dest;
    }
    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: "move",
            args: {
              src,
              dest,
              allowedPaths
            },
            isBuiltin: false,
            moduleId: "stdlib/fs.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::move", `Are you sure you want to move this file or directory?`, {
            "src": __stack.args.src,
            "dest": __stack.args.dest
          }, "std::fs", __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/fs.agency", scopeName: "move", 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(_move, {
          type: "positional",
          args: [__stack.args.src, __stack.args.dest, __stack.args.allowedPaths]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "move",
          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 move threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "move",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "move",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "move",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const move = __AgencyFunction.create({
  name: "move",
  module: "stdlib/fs.agency",
  fn: __move_impl,
  params: [{
    name: "src",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "dest",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "allowedPaths",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "move",
    description: `Move or rename a file or directory. Falls back to copy+remove if src and dest are on different filesystems. Fails if src does not exist. Set allowedPaths to restrict which path prefixes are permitted.

  @param src - The source path
  @param dest - The destination path
  @param allowedPaths - Only allow paths starting with these prefixes`,
    schema: z.object({ "src": z.string(), "dest": z.string(), "allowedPaths": z.array(z.string()).nullable().describe("Default: []") })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __remove_impl(target, 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/fs.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["target"] = target;
  __stack.args["allowedPaths"] = allowedPaths === __UNSET ? [] : allowedPaths;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/fs.agency", scopeName: "remove", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("target" in __overrides) {
      target = __overrides["target"];
      __stack.args["target"] = target;
    }
    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: "remove",
            args: {
              target,
              allowedPaths
            },
            isBuiltin: false,
            moduleId: "stdlib/fs.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::remove", `Are you sure you want to delete this file or directory? This cannot be undone.`, {
            "target": __stack.args.target
          }, "std::fs", __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/fs.agency", scopeName: "remove", 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(_remove, {
          type: "positional",
          args: [__stack.args.target, __stack.args.allowedPaths]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "remove",
          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 remove threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "remove",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "remove",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "remove",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const remove = __AgencyFunction.create({
  name: "remove",
  module: "stdlib/fs.agency",
  fn: __remove_impl,
  params: [{
    name: "target",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "allowedPaths",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "remove",
    description: `Delete a file or directory. Directories are removed recursively. Does not fail if the target does not exist. Set allowedPaths to restrict which path prefixes are permitted.

  @param target - The path to delete
  @param allowedPaths - Only allow paths starting with these prefixes`,
    schema: z.object({ "target": z.string(), "allowedPaths": z.array(z.string()).nullable().describe("Default: []") })
  },
  safe: false,
  exported: true
}, __toolRegistry);
const Workspace = z.object({ "read": z.any(), "write": z.any(), "edit": z.any(), "ls": z.any(), "glob": z.any(), "grep": z.any(), "bash": z.any(), "tools": z.array(z.any()) });
async function __openDir_impl(dir, 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/fs.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["dir"] = dir;
  __stack.args["allowedPaths"] = allowedPaths === __UNSET ? [] : allowedPaths;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/fs.agency", scopeName: "openDir", 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 ("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: "openDir",
            args: {
              dir,
              allowedPaths
            },
            isBuiltin: false,
            moduleId: "stdlib/fs.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.ap = [__stack.args.dir];
      });
      await runner.ifElse(2, [
        {
          condition: async () => __stack.args.allowedPaths.length > 0,
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __stack.locals.ap = __stack.args.allowedPaths;
            });
          }
        }
      ]);
      await runner.step(3, async (runner2) => {
        __stack.locals.read_ = await __callMethod(__readStatic(read, "read", ""), "partial", {
          type: "named",
          positionalArgs: [],
          namedArgs: {
            dir: __stack.args.dir
          }
        });
      });
      await runner.step(4, async (runner2) => {
        __stack.locals.write_ = await __callMethod(__readStatic(write, "write", ""), "partial", {
          type: "named",
          positionalArgs: [],
          namedArgs: {
            dir: __stack.args.dir
          }
        });
      });
      await runner.step(5, async (runner2) => {
        __stack.locals.edit_ = await __callMethod(edit, "partial", {
          type: "named",
          positionalArgs: [],
          namedArgs: {
            dir: __stack.args.dir
          }
        });
      });
      await runner.step(6, async (runner2) => {
        __stack.locals.ls_ = await __callMethod(__readStatic(ls, "ls", ""), "partial", {
          type: "named",
          positionalArgs: [],
          namedArgs: {
            dir: __stack.args.dir,
            allowedPaths: __stack.locals.ap
          }
        });
      });
      await runner.step(7, async (runner2) => {
        __stack.locals.glob_ = await __callMethod(__readStatic(glob, "glob", ""), "partial", {
          type: "named",
          positionalArgs: [],
          namedArgs: {
            dir: __stack.args.dir,
            allowedPaths: __stack.locals.ap
          }
        });
      });
      await runner.step(8, async (runner2) => {
        __stack.locals.grep_ = await __callMethod(__readStatic(grep, "grep", ""), "partial", {
          type: "named",
          positionalArgs: [],
          namedArgs: {
            dir: __stack.args.dir,
            allowedPaths: __stack.locals.ap
          }
        });
      });
      await runner.step(9, async (runner2) => {
        __stack.locals.bash_ = await __callMethod(__readStatic(bash, "bash", ""), "partial", {
          type: "named",
          positionalArgs: [],
          namedArgs: {
            cwd: __stack.args.dir
          }
        });
      });
      await runner.step(10, async (runner2) => {
        __functionCompleted = true;
        runner2.halt({
          "read": __stack.locals.read_,
          "write": __stack.locals.write_,
          "edit": __stack.locals.edit_,
          "ls": __stack.locals.ls_,
          "glob": __stack.locals.glob_,
          "grep": __stack.locals.grep_,
          "bash": __stack.locals.bash_,
          "tools": [__stack.locals.read_, __stack.locals.write_, __stack.locals.edit_, __stack.locals.ls_, __stack.locals.glob_, __stack.locals.grep_, __stack.locals.bash_]
        });
        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 openDir threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "openDir",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "openDir",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "openDir",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const openDir = __AgencyFunction.create({
  name: "openDir",
  module: "stdlib/fs.agency",
  fn: __openDir_impl,
  params: [{
    name: "dir",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "allowedPaths",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "openDir",
    description: `Build a Workspace anchored at \`dir\` \u2014 a bundle of file-system tools
  (\`read\`, \`write\`, \`edit\`, \`ls\`, \`glob\`, \`grep\`, \`bash\`) that all
  resolve filenames (or \`cwd\` for \`bash\`) against \`dir\` and its
  subtree. Designed to be handed to an LLM as a coherent surface:
  instead of giving the model a dozen tools that each take a \`dir\`
  arg, give it the bundle's members so they only have to think about
  the filename. The bundle also exposes a \`tools\` array containing
  every member in order, so you can splat it into a tools list:
  \`tools: [...workspace.tools, otherTool]\`.

  Each bundle member is constructed via \`.partial(dir: dir)\`, so \`dir\`
  is captured at \`openDir\` time. To re-anchor an agent to a new
  directory, call \`openDir(newDir)\` again and use the new bundle.

  Defense-in-depth sandboxing: \`allowedPaths\` is bound on \`ls\`,
  \`glob\`, and \`grep\`. It defaults to \`[dir]\` so those tools refuse to
  operate outside the anchor directory unless you explicitly pass a
  broader allow-list. Relative entries in \`allowedPaths\` resolve
  against the same directory as \`dir\` (the calling module's
  directory), matching how \`ls\`/\`glob\`/\`grep\` already resolve \`dir\`.

  \`bash\` is NOT sandboxed by \`allowedPaths\`: that argument only
  validates \`cwd\`, while the shell command itself can read or write
  anywhere the process can reach. \`bash\` is included in the bundle
  for convenience (its \`cwd\` is pinned to \`dir\`), but treat it as
  unsandboxed \u2014 gate it with user approval or \`blockedCommands\` if
  you care about confinement. \`read\`/\`write\`/\`edit\` do not accept
  \`allowedPaths\` but are already confined to \`dir\` by \`resolvePath\`,
  which rejects absolute filenames and \`..\` escapes.

  @param dir - The directory to anchor every bundled tool against
  @param allowedPaths - Sandbox roots bound on ls/glob/grep.
    Defaults to \`[dir]\` when empty. Relative entries resolve against
    the same base as \`dir\`.`,
    schema: z.object({ "dir": z.string(), "allowedPaths": z.array(z.string()).nullable().describe("Default: []") })
  },
  safe: false,
  exported: true
}, __toolRegistry);
var stdin_default = graph;
const __sourceMap = { "stdlib/fs.agency:edit": { "1": { "line": 26, "col": 2 }, "2": { "line": 33, "col": 2 } }, "stdlib/fs.agency:printDiff": { "1": { "line": 46, "col": 2 } }, "stdlib/fs.agency:applyPatch": { "1": { "line": 61, "col": 2 }, "2": { "line": 65, "col": 2 } }, "stdlib/fs.agency:mkdir": { "1": { "line": 75, "col": 2 }, "2": { "line": 79, "col": 2 } }, "stdlib/fs.agency:copy": { "1": { "line": 90, "col": 2 }, "2": { "line": 95, "col": 2 } }, "stdlib/fs.agency:move": { "1": { "line": 106, "col": 2 }, "2": { "line": 111, "col": 2 } }, "stdlib/fs.agency:remove": { "1": { "line": 121, "col": 2 }, "2": { "line": 125, "col": 2 } }, "stdlib/fs.agency:openDir": { "1": { "line": 191, "col": 2 }, "2": { "line": 192, "col": 2 }, "3": { "line": 195, "col": 2 }, "4": { "line": 196, "col": 2 }, "5": { "line": 197, "col": 2 }, "6": { "line": 198, "col": 2 }, "7": { "line": 199, "col": 2 }, "8": { "line": 200, "col": 2 }, "9": { "line": 201, "col": 2 }, "10": { "line": 202, "col": 2 }, "2.0": { "line": 193, "col": 4 } } };
export {
  Workspace,
  __getCheckpoints,
  __setDebugger,
  __setLLMClient,
  __setTraceFile,
  __sourceMap,
  __toolRegistry,
  applyPatch,
  approve,
  copy,
  stdin_default as default,
  edit,
  hasInterrupts,
  interrupt,
  isDebugger,
  isInterrupt,
  mkdir,
  move,
  openDir,
  printDiff,
  reject,
  remove,
  respondToInterrupts,
  rewindFrom
};
