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 { _compile, _compileFile, _typecheck, _typecheckFile, _parseAST, _writeAST, _format, _formatFile, _walkAST, _getNodesOfType, _filterImports } from "agency-lang/stdlib-lib/agency.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/agency.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/agency.agency")) {
    return;
  }
  __ctx.globals.markInitialized("stdlib/agency.agency");
}
__registerGlobalsInit("stdlib/agency.agency", __initializeGlobals);
async function __registerTopLevelCallbacks(__ctx) {
  __ctx.topLevelCallbacks = [];
}
__functionRefReviver.registry = __toolRegistry;
const CompiledProgram = z.object({ "moduleId": z.string() });
const SourceLocation = z.object({ "line": z.number(), "col": z.number(), "start": z.number(), "end": z.number() });
const TypeCheckDiagnostic = z.object({ "severity": z.string(), "message": z.string(), "loc": z.union([SourceLocation, z.null()]), "variableName": z.union([z.string(), z.null()]), "expectedType": z.union([z.string(), z.null()]), "actualType": z.union([z.string(), z.null()]) });
const TypeCheckReport = z.object({ "errors": z.array(TypeCheckDiagnostic), "warnings": z.array(TypeCheckDiagnostic) });
async function __compile_impl(source) {
  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/agency.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["source"] = source;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/agency.agency", scopeName: "compile", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("source" in __overrides) {
      source = __overrides["source"];
      __stack.args["source"] = source;
    }
  }
  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: "compile",
            args: {
              source
            },
            isBuiltin: false,
            moduleId: "stdlib/agency.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __tryCall(async () => await __call(_compile, {
          type: "positional",
          args: [__stack.args.source]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "compile",
          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 compile threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "compile",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "compile",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "compile",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const compile = __AgencyFunction.create({
  name: "compile",
  module: "stdlib/agency.agency",
  fn: __compile_impl,
  params: [{
    name: "source",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "compile",
    description: `Compile Agency source code. Returns a CompiledProgram on success, or a failure with compilation errors. Only standard library (std::) imports are allowed in the compiled code.
  @param source - Agency source code as a string`,
    schema: z.object({ "source": z.string() })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __run_impl(compiled, node, args = __UNSET, wallClock = __UNSET, memory = __UNSET, ipcPayload = __UNSET, stdout = __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/agency.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["compiled"] = compiled;
  __stack.args["node"] = node;
  __stack.args["args"] = args === __UNSET ? {} : args;
  __stack.args["wallClock"] = wallClock === __UNSET ? 6e4 : wallClock;
  __stack.args["memory"] = memory === __UNSET ? 536870912 : memory;
  __stack.args["ipcPayload"] = ipcPayload === __UNSET ? 104857600 : ipcPayload;
  __stack.args["stdout"] = stdout === __UNSET ? 1048576 : stdout;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/agency.agency", scopeName: "run", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("compiled" in __overrides) {
      compiled = __overrides["compiled"];
      __stack.args["compiled"] = compiled;
    }
    if ("node" in __overrides) {
      node = __overrides["node"];
      __stack.args["node"] = node;
    }
    if ("args" in __overrides) {
      args = __overrides["args"];
      __stack.args["args"] = args;
    }
    if ("wallClock" in __overrides) {
      wallClock = __overrides["wallClock"];
      __stack.args["wallClock"] = wallClock;
    }
    if ("memory" in __overrides) {
      memory = __overrides["memory"];
      __stack.args["memory"] = memory;
    }
    if ("ipcPayload" in __overrides) {
      ipcPayload = __overrides["ipcPayload"];
      __stack.args["ipcPayload"] = ipcPayload;
    }
    if ("stdout" in __overrides) {
      stdout = __overrides["stdout"];
      __stack.args["stdout"] = stdout;
    }
  }
  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: "run",
            args: {
              compiled,
              node,
              args,
              wallClock,
              memory,
              ipcPayload,
              stdout
            },
            isBuiltin: false,
            moduleId: "stdlib/agency.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::run", `Running agent-generated code in subprocess`, {
            "moduleId": __stack.args.compiled.moduleId,
            "node": __stack.args.node,
            "args": __stack.args.args,
            "limits": {
              "wallClock": __stack.args.wallClock,
              "memory": __stack.args.memory,
              "ipcPayload": __stack.args.ipcPayload,
              "stdout": __stack.args.stdout
            }
          }, "std::agency", __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/agency.agency", scopeName: "run", 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(_run, {
          type: "positional",
          args: [__stack.args.compiled, __stack.args.node, __stack.args.args, __stack.args.wallClock, __stack.args.memory, __stack.args.ipcPayload, __stack.args.stdout]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "run",
          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 run threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "run",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "run",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "run",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const run = __AgencyFunction.create({
  name: "run",
  module: "stdlib/agency.agency",
  fn: __run_impl,
  params: [{
    name: "compiled",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "node",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "args",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "wallClock",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "memory",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "ipcPayload",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "stdout",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "run",
    description: `Execute a compiled Agency program in a subprocess. The parent's handler chain extends to the subprocess \u2014 subprocess interrupts must be approved by both subprocess and parent handlers. Returns the subprocess node's result on success.

  Resource limits clamp the subprocess: it is killed and a limit_exceeded failure is returned if it exceeds wallClock, memory, ipcPayload, or stdout.

  @param compiled - A CompiledProgram from compile()
  @param node - Which exported node to run
  @param args - Arguments to pass to the node (defaults to no args)
  @param wallClock - Max wall-clock time before SIGKILL (default 60s, max 1h)
  @param memory - Max V8 heap size (default 512mb, max 4gb)
  @param ipcPayload - Max single IPC message size (default 100mb, max 1gb)
  @param stdout - Max combined stdout+stderr bytes (default 1mb, max 100mb)`,
    schema: z.object({ "compiled": CompiledProgram, "node": z.string(), "args": z.record(z.string(), z.any()).nullable().describe("Default: {}"), "wallClock": z.number().nullable().describe("Default: 60s"), "memory": z.number().nullable().describe("Default: 512mb"), "ipcPayload": z.number().nullable().describe("Default: 100mb"), "stdout": z.number().nullable().describe("Default: 1mb") })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __runFile_impl(dir, filename, node, args = __UNSET, wallClock = __UNSET, memory = __UNSET, ipcPayload = __UNSET, stdout = __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/agency.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["dir"] = dir;
  __stack.args["filename"] = filename;
  __stack.args["node"] = node;
  __stack.args["args"] = args === __UNSET ? {} : args;
  __stack.args["wallClock"] = wallClock === __UNSET ? 6e4 : wallClock;
  __stack.args["memory"] = memory === __UNSET ? 536870912 : memory;
  __stack.args["ipcPayload"] = ipcPayload === __UNSET ? 104857600 : ipcPayload;
  __stack.args["stdout"] = stdout === __UNSET ? 1048576 : stdout;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/agency.agency", scopeName: "runFile", 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 ("filename" in __overrides) {
      filename = __overrides["filename"];
      __stack.args["filename"] = filename;
    }
    if ("node" in __overrides) {
      node = __overrides["node"];
      __stack.args["node"] = node;
    }
    if ("args" in __overrides) {
      args = __overrides["args"];
      __stack.args["args"] = args;
    }
    if ("wallClock" in __overrides) {
      wallClock = __overrides["wallClock"];
      __stack.args["wallClock"] = wallClock;
    }
    if ("memory" in __overrides) {
      memory = __overrides["memory"];
      __stack.args["memory"] = memory;
    }
    if ("ipcPayload" in __overrides) {
      ipcPayload = __overrides["ipcPayload"];
      __stack.args["ipcPayload"] = ipcPayload;
    }
    if ("stdout" in __overrides) {
      stdout = __overrides["stdout"];
      __stack.args["stdout"] = stdout;
    }
  }
  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: "runFile",
            args: {
              dir,
              filename,
              node,
              args,
              wallClock,
              memory,
              ipcPayload,
              stdout
            },
            isBuiltin: false,
            moduleId: "stdlib/agency.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.compileResult = await __tryCall(async () => await __call(_compileFile, {
          type: "positional",
          args: [__stack.args.dir, __stack.args.filename]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "runFile",
          args: __stack.args
        });
      });
      await runner.ifElse(2, [
        {
          condition: async () => await isFailure(__stack.locals.compileResult),
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __functionCompleted = true;
              runner3.halt(__stack.locals.compileResult);
              return;
            });
          }
        }
      ]);
      await runner.step(3, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __call(run, {
          type: "named",
          positionalArgs: [],
          namedArgs: {
            compiled: __stack.locals.compileResult.value,
            node: __stack.args.node,
            args: __stack.args.args,
            wallClock: __stack.args.wallClock,
            memory: __stack.args.memory,
            ipcPayload: __stack.args.ipcPayload,
            stdout: __stack.args.stdout
          }
        }));
        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 runFile threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "runFile",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "runFile",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "runFile",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const runFile = __AgencyFunction.create({
  name: "runFile",
  module: "stdlib/agency.agency",
  fn: __runFile_impl,
  params: [{
    name: "dir",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "filename",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "node",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "args",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "wallClock",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "memory",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "ipcPayload",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "stdout",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "runFile",
    description: `Compile and execute an Agency file in a subprocess. The file is read from dir/filename and compiled with the same stdlib-only import restrictions as compile() before being handed to run() \u2014 so the subprocess code can only call into the Agency standard library, not local files, npm packages, or Node modules.

  The dir argument is the sandbox boundary: filename cannot escape it via absolute paths or .. segments (and symlinks are followed and re-checked). dir is required (no default) so the caller must consciously specify the sandbox.

  Use partial application to bind dir to a sandbox directory once, then pass only filename + node at the call site, e.g. const safeRun = runFile.bind(dir: "/safe/dir").

  Resource limits clamp the subprocess: see run() for the full list of caps.

  @param dir - The sandbox directory. filename is resolved against this and must stay inside it.
  @param filename - The agency file to compile and run, resolved relative to dir
  @param node - Which exported node to run
  @param args - Arguments to pass to the node (defaults to no args)
  @param wallClock - Max wall-clock time before SIGKILL (default 60s, max 1h)
  @param memory - Max V8 heap size (default 512mb, max 4gb)
  @param ipcPayload - Max single IPC message size (default 100mb, max 1gb)
  @param stdout - Max combined stdout+stderr bytes (default 1mb, max 100mb)`,
    schema: z.object({ "dir": z.string(), "filename": z.string(), "node": z.string(), "args": z.record(z.string(), z.any()).nullable().describe("Default: {}"), "wallClock": z.number().nullable().describe("Default: 60s"), "memory": z.number().nullable().describe("Default: 512mb"), "ipcPayload": z.number().nullable().describe("Default: 100mb"), "stdout": z.number().nullable().describe("Default: 1mb") })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __typecheck_impl(source) {
  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/agency.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["source"] = source;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/agency.agency", scopeName: "typecheck", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("source" in __overrides) {
      source = __overrides["source"];
      __stack.args["source"] = source;
    }
  }
  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: "typecheck",
            args: {
              source
            },
            isBuiltin: false,
            moduleId: "stdlib/agency.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __tryCall(async () => await __call(_typecheck, {
          type: "positional",
          args: [__stack.args.source]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "typecheck",
          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 typecheck threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "typecheck",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "typecheck",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "typecheck",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const typecheck = __AgencyFunction.create({
  name: "typecheck",
  module: "stdlib/agency.agency",
  fn: __typecheck_impl,
  params: [{
    name: "source",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "typecheck",
    description: `Type-check Agency source code without compiling or running it. Returns a TypeCheckReport with separate \`errors\` and \`warnings\` arrays \u2014 a successful Result with a non-empty \`errors\` array means the type-checker ran and found problems. A failure Result means the type-checker could not run at all (parse error or unresolved import).

  Unlike compile(), this does NOT restrict imports \u2014 type-checking is read-only and does not execute code. Note that std:: and pkg:: imports resolve normally, but relative imports (./foo.agency) cannot be resolved when calling typecheck() with a source string, since there is no on-disk location to resolve them against. Use typecheckFile() for source that contains relative imports.

  @param source - Agency source code as a string`,
    schema: z.object({ "source": z.string() })
  },
  safe: false,
  exported: true
}, __toolRegistry);
const FilterImportsResult = z.object({ "source": z.string(), "filtered": z.boolean() });
async function __parseAST_impl(source) {
  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/agency.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["source"] = source;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/agency.agency", scopeName: "parseAST", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("source" in __overrides) {
      source = __overrides["source"];
      __stack.args["source"] = source;
    }
  }
  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: "parseAST",
            args: {
              source
            },
            isBuiltin: false,
            moduleId: "stdlib/agency.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __tryCall(async () => await __call(_parseAST, {
          type: "positional",
          args: [__stack.args.source]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "parseAST",
          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 parseAST threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "parseAST",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "parseAST",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "parseAST",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const parseAST = __AgencyFunction.create({
  name: "parseAST",
  module: "stdlib/agency.agency",
  fn: __parseAST_impl,
  params: [{
    name: "source",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "parseAST",
    description: `Parse Agency source code into an abstract syntax tree. Returns the raw AST as a JSON-serializable object on success, or a failure with the parse error message.

  The AST shape is the parser output with \`applyTemplate: false, lower: false\`, which matches what the formatter consumes \u2014 so an AST round-tripped through writeAST() / format() produces canonical Agency source.

  @param source - Agency source code as a string`,
    schema: z.object({ "source": z.string() })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __writeAST_impl(ast, dir, filename, overwrite = __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/agency.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["ast"] = ast;
  __stack.args["dir"] = dir;
  __stack.args["filename"] = filename;
  __stack.args["overwrite"] = overwrite === __UNSET ? true : overwrite;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/agency.agency", scopeName: "writeAST", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("ast" in __overrides) {
      ast = __overrides["ast"];
      __stack.args["ast"] = ast;
    }
    if ("dir" in __overrides) {
      dir = __overrides["dir"];
      __stack.args["dir"] = dir;
    }
    if ("filename" in __overrides) {
      filename = __overrides["filename"];
      __stack.args["filename"] = filename;
    }
    if ("overwrite" in __overrides) {
      overwrite = __overrides["overwrite"];
      __stack.args["overwrite"] = overwrite;
    }
  }
  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: "writeAST",
            args: {
              ast,
              dir,
              filename,
              overwrite
            },
            isBuiltin: false,
            moduleId: "stdlib/agency.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::write", `Are you sure you want to write this file?`, {
            "dir": __stack.args.dir,
            "filename": __stack.args.filename,
            "overwrite": __stack.args.overwrite
          }, "std::agency", __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/agency.agency", scopeName: "writeAST", 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(_writeAST, {
          type: "positional",
          args: [__stack.args.ast, __stack.args.dir, __stack.args.filename, __stack.args.overwrite]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "writeAST",
          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 writeAST threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "writeAST",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "writeAST",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "writeAST",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const writeAST = __AgencyFunction.create({
  name: "writeAST",
  module: "stdlib/agency.agency",
  fn: __writeAST_impl,
  params: [{
    name: "ast",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "dir",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "filename",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "overwrite",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "writeAST",
    description: `Format an AST as Agency source and write it to dir/filename. The AST is typically obtained from parseAST() and optionally transformed before being written.

  The output is canonical formatter output: comments are preserved (they live in the AST as nodes), but whitespace and formatting are normalized to the AgencyGenerator's style \u2014 the same style produced by \`pnpm run fmt\`.

  The dir argument is the sandbox boundary: filename cannot escape it via absolute paths or .. segments (symlinks on existing files are followed and re-checked).

  @param ast - The AST to write (typically from parseAST)
  @param dir - The sandbox directory
  @param filename - The agency file to write, resolved relative to dir
  @param overwrite - If false, fail when the file already exists (default true)`,
    schema: z.object({ "ast": z.any(), "dir": z.string(), "filename": z.string(), "overwrite": z.boolean().nullable().describe("Default: true") })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __format_impl(source) {
  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/agency.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["source"] = source;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/agency.agency", scopeName: "format", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("source" in __overrides) {
      source = __overrides["source"];
      __stack.args["source"] = source;
    }
  }
  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: "format",
            args: {
              source
            },
            isBuiltin: false,
            moduleId: "stdlib/agency.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __tryCall(async () => await __call(_format, {
          type: "positional",
          args: [__stack.args.source]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "format",
          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 format threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "format",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "format",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "format",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const format = __AgencyFunction.create({
  name: "format",
  module: "stdlib/agency.agency",
  fn: __format_impl,
  params: [{
    name: "source",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "format",
    description: `Format Agency source code using the standard Agency formatter (the same one used by \`pnpm run fmt\`). Returns the formatted source on success, or a failure with a parse error.

  Comments are preserved. Whitespace and formatting are canonicalized \u2014 this is a lossy transformation for whitespace but not for semantics or comments.

  @param source - Agency source code as a string`,
    schema: z.object({ "source": z.string() })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __formatFile_impl(dir, filename) {
  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/agency.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["dir"] = dir;
  __stack.args["filename"] = filename;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/agency.agency", scopeName: "formatFile", 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 ("filename" in __overrides) {
      filename = __overrides["filename"];
      __stack.args["filename"] = filename;
    }
  }
  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: "formatFile",
            args: {
              dir,
              filename
            },
            isBuiltin: false,
            moduleId: "stdlib/agency.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::write", `Are you sure you want to format this file in place?`, {
            "dir": __stack.args.dir,
            "filename": __stack.args.filename
          }, "std::agency", __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/agency.agency", scopeName: "formatFile", 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(_formatFile, {
          type: "positional",
          args: [__stack.args.dir, __stack.args.filename]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "formatFile",
          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 formatFile threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "formatFile",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "formatFile",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "formatFile",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const formatFile = __AgencyFunction.create({
  name: "formatFile",
  module: "stdlib/agency.agency",
  fn: __formatFile_impl,
  params: [{
    name: "dir",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "filename",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "formatFile",
    description: `Format an Agency file in place. Reads dir/filename, formats it with the standard Agency formatter, and writes the result back to the same path. If the file is already formatted, no write occurs (mtime is preserved).

  The dir argument is the sandbox boundary: filename cannot escape it via absolute paths or .. segments (symlinks are followed and re-checked). Both the read and the write happen inside the same interrupt \u2014 approving the interrupt approves both.

  Returns success(true) on a successful format (whether or not a write was needed), or a failure if parsing or I/O fails.

  @param dir - The sandbox directory. filename is resolved against this and must stay inside it.
  @param filename - The agency file to format, resolved relative to dir`,
    schema: z.object({ "dir": z.string(), "filename": z.string() })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __walkAST_impl(ast, visitor) {
  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/agency.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["ast"] = ast;
  __stack.args["visitor"] = visitor;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/agency.agency", scopeName: "walkAST", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("ast" in __overrides) {
      ast = __overrides["ast"];
      __stack.args["ast"] = ast;
    }
    if ("visitor" in __overrides) {
      visitor = __overrides["visitor"];
      __stack.args["visitor"] = visitor;
    }
  }
  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: "walkAST",
            args: {
              ast,
              visitor
            },
            isBuiltin: false,
            moduleId: "stdlib/agency.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __self.__retryable = false;
        __stack.locals.result = await __call(_walkAST, {
          type: "positional",
          args: [__stack.args.ast]
        });
        if (hasInterrupts(__stack.locals.result)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__stack.locals.result);
          return;
        }
      });
      await runner.loop(2, __stack.locals.result.visits, async (visit, _, runner2) => {
        await runner2.step(0, async (runner3) => {
          const __funcResult = await __call(__stack.args.visitor, {
            type: "positional",
            args: [visit.node, visit.ancestors]
          });
          if (hasInterrupts(__funcResult)) {
            await getRuntimeContext().ctx.pendingPromises.awaitAll();
            runner3.halt(__funcResult);
            return;
          }
        });
      });
      await runner.step(3, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(__stack.locals.result.clone);
        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 walkAST threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "walkAST",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "walkAST",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "walkAST",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const walkAST = __AgencyFunction.create({
  name: "walkAST",
  module: "stdlib/agency.agency",
  fn: __walkAST_impl,
  params: [{
    name: "ast",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "visitor",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "walkAST",
    description: `Walk every node in a deep-cloned copy of the AST, invoking the visitor with each (node, ancestors) pair. The visitor may mutate the node in place; mutations land in the returned AST. The original AST passed in is never modified.

  Iteration order is pre-order: a node is visited before its children. The set of nodes to visit is determined upfront \u2014 if the visitor adds new children (e.g. by appending to a function's body), those new children will NOT be visited on this walk. Similarly, if the visitor replaces a child reference (e.g. node.body = [newNode]), the visitor will still be called on the OLD body's nodes (which are already in the buffered visit list). To re-walk a transformed AST, call walkAST again.

  The ancestors array lists every enclosing node from the root outward (excluding \`node\` itself). For nodes inside a block argument (e.g. inside \`map(arr) as x { ... }\`), the block argument appears in ancestors as a node with \`type: "blockArgument"\`.

  @param ast - The AST to walk (typically from parseAST)
  @param visitor - Called once per node as visitor(node, ancestors). Return value is ignored.`,
    schema: z.object({ "ast": z.any() })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __getNodesOfType_impl(source, types) {
  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/agency.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["source"] = source;
  __stack.args["types"] = types;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/agency.agency", scopeName: "getNodesOfType", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("source" in __overrides) {
      source = __overrides["source"];
      __stack.args["source"] = source;
    }
    if ("types" in __overrides) {
      types = __overrides["types"];
      __stack.args["types"] = types;
    }
  }
  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: "getNodesOfType",
            args: {
              source,
              types
            },
            isBuiltin: false,
            moduleId: "stdlib/agency.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __tryCall(async () => await __call(_getNodesOfType, {
          type: "positional",
          args: [__stack.args.source, __stack.args.types]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "getNodesOfType",
          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 getNodesOfType threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "getNodesOfType",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "getNodesOfType",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "getNodesOfType",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const getNodesOfType = __AgencyFunction.create({
  name: "getNodesOfType",
  module: "stdlib/agency.agency",
  fn: __getNodesOfType_impl,
  params: [{
    name: "source",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "types",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "getNodesOfType",
    description: `Parse Agency source code and return all AST nodes whose \`type\` field matches any of the provided types. Walks the entire tree (not just top-level), so e.g. getNodesOfType(src, ["functionCall"]) returns every function call anywhere in the program.

  The returned nodes are references into a freshly-parsed AST; safe to mutate, but mutations do not write back to disk. Use writeAST() with the parsed AST to persist changes.

  @param source - Agency source code as a string
  @param types - List of AST type strings to match (e.g. ["function", "graphNode"])`,
    schema: z.object({ "source": z.string(), "types": z.array(z.string()) })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __getImports_impl(source) {
  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/agency.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["source"] = source;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/agency.agency", scopeName: "getImports", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("source" in __overrides) {
      source = __overrides["source"];
      __stack.args["source"] = source;
    }
  }
  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: "getImports",
            args: {
              source
            },
            isBuiltin: false,
            moduleId: "stdlib/agency.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __call(getNodesOfType, {
          type: "positional",
          args: [__stack.args.source, [`importStatement`]]
        }));
        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 getImports threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "getImports",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "getImports",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "getImports",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const getImports = __AgencyFunction.create({
  name: "getImports",
  module: "stdlib/agency.agency",
  fn: __getImports_impl,
  params: [{
    name: "source",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "getImports",
    description: `Return all import statements in the source (i.e. \`import { x } from "..."\`).

  @param source - Agency source code as a string`,
    schema: z.object({ "source": z.string() })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __getFunctions_impl(source) {
  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/agency.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["source"] = source;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/agency.agency", scopeName: "getFunctions", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("source" in __overrides) {
      source = __overrides["source"];
      __stack.args["source"] = source;
    }
  }
  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: "getFunctions",
            args: {
              source
            },
            isBuiltin: false,
            moduleId: "stdlib/agency.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __call(getNodesOfType, {
          type: "positional",
          args: [__stack.args.source, [`function`]]
        }));
        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 getFunctions threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "getFunctions",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "getFunctions",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "getFunctions",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const getFunctions = __AgencyFunction.create({
  name: "getFunctions",
  module: "stdlib/agency.agency",
  fn: __getFunctions_impl,
  params: [{
    name: "source",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "getFunctions",
    description: `Return all function definitions (\`def foo(...) { ... }\`) in the source.

  @param source - Agency source code as a string`,
    schema: z.object({ "source": z.string() })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __getGraphNodes_impl(source) {
  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/agency.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["source"] = source;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/agency.agency", scopeName: "getGraphNodes", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("source" in __overrides) {
      source = __overrides["source"];
      __stack.args["source"] = source;
    }
  }
  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: "getGraphNodes",
            args: {
              source
            },
            isBuiltin: false,
            moduleId: "stdlib/agency.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __call(getNodesOfType, {
          type: "positional",
          args: [__stack.args.source, [`graphNode`]]
        }));
        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 getGraphNodes threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "getGraphNodes",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "getGraphNodes",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "getGraphNodes",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const getGraphNodes = __AgencyFunction.create({
  name: "getGraphNodes",
  module: "stdlib/agency.agency",
  fn: __getGraphNodes_impl,
  params: [{
    name: "source",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "getGraphNodes",
    description: `Return all graph node definitions (\`node main() { ... }\`) in the source. Note: "graph nodes" here means Agency's \`node\` declarations, not generic AST nodes \u2014 see getNodesOfType for the latter.

  @param source - Agency source code as a string`,
    schema: z.object({ "source": z.string() })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __filterImports_impl(source, allowedPackages = __UNSET, excludedPackages = __UNSET, allowKinds = __UNSET, excludeKinds = __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/agency.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["source"] = source;
  __stack.args["allowedPackages"] = allowedPackages === __UNSET ? [] : allowedPackages;
  __stack.args["excludedPackages"] = excludedPackages === __UNSET ? [] : excludedPackages;
  __stack.args["allowKinds"] = allowKinds === __UNSET ? [] : allowKinds;
  __stack.args["excludeKinds"] = excludeKinds === __UNSET ? [] : excludeKinds;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/agency.agency", scopeName: "filterImports", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("source" in __overrides) {
      source = __overrides["source"];
      __stack.args["source"] = source;
    }
    if ("allowedPackages" in __overrides) {
      allowedPackages = __overrides["allowedPackages"];
      __stack.args["allowedPackages"] = allowedPackages;
    }
    if ("excludedPackages" in __overrides) {
      excludedPackages = __overrides["excludedPackages"];
      __stack.args["excludedPackages"] = excludedPackages;
    }
    if ("allowKinds" in __overrides) {
      allowKinds = __overrides["allowKinds"];
      __stack.args["allowKinds"] = allowKinds;
    }
    if ("excludeKinds" in __overrides) {
      excludeKinds = __overrides["excludeKinds"];
      __stack.args["excludeKinds"] = excludeKinds;
    }
  }
  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: "filterImports",
            args: {
              source,
              allowedPackages,
              excludedPackages,
              allowKinds,
              excludeKinds
            },
            isBuiltin: false,
            moduleId: "stdlib/agency.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __tryCall(async () => await __call(_filterImports, {
          type: "positional",
          args: [__stack.args.source, __stack.args.allowedPackages, __stack.args.excludedPackages, __stack.args.allowKinds, __stack.args.excludeKinds]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "filterImports",
          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 filterImports threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "filterImports",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "filterImports",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "filterImports",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const filterImports = __AgencyFunction.create({
  name: "filterImports",
  module: "stdlib/agency.agency",
  fn: __filterImports_impl,
  params: [{
    name: "source",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "allowedPackages",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "excludedPackages",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "allowKinds",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "excludeKinds",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "filterImports",
    description: `Parse Agency source, drop imports that fail the policy, and return the resulting source plus a flag indicating whether anything was dropped.

  Imports are classified by \`kind\`:
    - "stdlib" \u2014 \`std::*\` (e.g. \`std::shell\`)
    - "pkg"    \u2014 \`pkg::*\` (e.g. \`pkg::wikipedia\`)
    - "local"  \u2014 relative or absolute file paths (e.g. \`./util.agency\`)
    - "node"   \u2014 bare specifiers resolved by Node (e.g. \`fs\`, \`child_process\`)

  Policy:
    - \`allowedPackages\` / \`excludedPackages\` are glob patterns (picomatch syntax) matched against the raw import path string.
    - \`allowKinds\` / \`excludeKinds\` accept the kind strings above.
    - Exclude rules always win: if a path matches anything in \`excludedPackages\` or \`excludeKinds\`, it is dropped.
    - When all four lists are empty, every import is allowed (default-allow).
    - When at least one allow list is non-empty, an import must match an allowed kind OR an allowed package glob (union across the two axes). Note that allowKinds=["stdlib"] is still a restriction even with the package lists empty \u2014 only stdlib passes.

  The returned source is regenerated via the Agency formatter, so whitespace and formatting are canonicalized. Comments are preserved (see writeAST docstring for details).

  @param source - Agency source code as a string
  @param allowedPackages - Glob patterns; matched imports are allowed (subject to excludes)
  @param excludedPackages - Glob patterns; matched imports are dropped
  @param allowKinds - Kind strings ("stdlib" | "pkg" | "local" | "node") to allow
  @param excludeKinds - Kind strings to drop`,
    schema: z.object({ "source": z.string(), "allowedPackages": z.array(z.string()).nullable().describe("Default: []"), "excludedPackages": z.array(z.string()).nullable().describe("Default: []"), "allowKinds": z.array(z.string()).nullable().describe("Default: []"), "excludeKinds": z.array(z.string()).nullable().describe("Default: []") })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __typecheckFile_impl(dir, filename) {
  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/agency.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["dir"] = dir;
  __stack.args["filename"] = filename;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/agency.agency", scopeName: "typecheckFile", 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 ("filename" in __overrides) {
      filename = __overrides["filename"];
      __stack.args["filename"] = filename;
    }
  }
  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: "typecheckFile",
            args: {
              dir,
              filename
            },
            isBuiltin: false,
            moduleId: "stdlib/agency.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::read", `Are you sure you want to read this file?`, {
            "dir": __stack.args.dir,
            "filename": __stack.args.filename
          }, "std::agency", __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/agency.agency", scopeName: "typecheckFile", 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(_typecheckFile, {
          type: "positional",
          args: [__stack.args.dir, __stack.args.filename]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "typecheckFile",
          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 typecheckFile threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "typecheckFile",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "typecheckFile",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "typecheckFile",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const typecheckFile = __AgencyFunction.create({
  name: "typecheckFile",
  module: "stdlib/agency.agency",
  fn: __typecheckFile_impl,
  params: [{
    name: "dir",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "filename",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "typecheckFile",
    description: `Type-check an Agency file on disk. The file is read from dir/filename, and relative imports inside the file are resolved against the file's directory.

  The dir argument is the sandbox boundary for the entry file: filename cannot escape it via absolute paths or .. segments (and symlinks are followed and re-checked). Note that transitive imports from the entry file are NOT confined to dir \u2014 type-checking is read-only, so the sandbox only governs which file the caller can ask to be type-checked.

  Use partial application to bind dir once, e.g. const tc = typecheckFile.partial(dir: "/safe/dir").

  Returns a TypeCheckReport with \`errors\` and \`warnings\` arrays on success; returns a failure when the file cannot be read, the sandbox is violated, or the source cannot be parsed.

  @param dir - The sandbox directory. filename is resolved against this and must stay inside it.
  @param filename - The agency file to type-check, resolved relative to dir`,
    schema: z.object({ "dir": z.string(), "filename": z.string() })
  },
  safe: false,
  exported: true
}, __toolRegistry);
var stdin_default = graph;
const __sourceMap = { "stdlib/agency.agency:compile": { "1": { "line": 32, "col": 2 } }, "stdlib/agency.agency:run": { "1": { "line": 57, "col": 2 }, "2": { "line": 64, "col": 2 } }, "stdlib/agency.agency:runFile": { "1": { "line": 95, "col": 2 }, "2": { "line": 96, "col": 2 }, "3": { "line": 99, "col": 2 }, "2.0": { "line": 97, "col": 4 } }, "stdlib/agency.agency:typecheck": { "1": { "line": 118, "col": 2 } }, "stdlib/agency.agency:parseAST": { "1": { "line": 134, "col": 2 } }, "stdlib/agency.agency:writeAST": { "1": { "line": 155, "col": 2 }, "2": { "line": 160, "col": 2 } }, "stdlib/agency.agency:format": { "1": { "line": 171, "col": 2 } }, "stdlib/agency.agency:formatFile": { "1": { "line": 185, "col": 2 }, "2": { "line": 189, "col": 2 } }, "stdlib/agency.agency:walkAST": { "1": { "line": 203, "col": 2 }, "2": { "line": 204, "col": 2 }, "3": { "line": 207, "col": 2 }, "2.0": { "line": 205, "col": 4 } }, "stdlib/agency.agency:getNodesOfType": { "1": { "line": 219, "col": 2 } }, "stdlib/agency.agency:getImports": { "1": { "line": 228, "col": 2 } }, "stdlib/agency.agency:getFunctions": { "1": { "line": 237, "col": 2 } }, "stdlib/agency.agency:getGraphNodes": { "1": { "line": 246, "col": 2 } }, "stdlib/agency.agency:filterImports": { "1": { "line": 280, "col": 2 } }, "stdlib/agency.agency:typecheckFile": { "1": { "line": 296, "col": 2 }, "2": { "line": 300, "col": 2 } } };
export {
  __getCheckpoints,
  __setDebugger,
  __setLLMClient,
  __setTraceFile,
  __sourceMap,
  __toolRegistry,
  approve,
  compile,
  stdin_default as default,
  filterImports,
  format,
  formatFile,
  getFunctions,
  getGraphNodes,
  getImports,
  getNodesOfType,
  hasInterrupts,
  interrupt,
  isDebugger,
  isInterrupt,
  parseAST,
  reject,
  respondToInterrupts,
  rewindFrom,
  run,
  runFile,
  typecheck,
  typecheckFile,
  walkAST,
  writeAST
};
