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 { route } from "agency-lang/stdlib/agent.js";
import { clearMessages, pushMessage, repl } from "agency-lang/stdlib/cli.js";
import { today } from "agency-lang/stdlib/date.js";
import { box, render } from "agency-lang/stdlib/layout.js";
import { cliPolicyHandler, ScopedRuleFields } from "agency-lang/stdlib/policy.js";
import { exists } from "agency-lang/stdlib/shell.js";
import { highlight } from "agency-lang/stdlib/syntax.js";
import { cwd, env } from "agency-lang/stdlib/system.js";
import { getCost } from "agency-lang/stdlib/thread.js";
import { codeSysPrompt, codeTools } from "./code.js";
import { figs, title } from "./images/images.js";
import { researchSysPrompt, researchTools } from "./research.js";
import { fileURLToPath } from "url";
import __process from "process";
import { z } from "agency-lang/zod";
import { color, nanoid } from "agency-lang";
import path from "path";
import {
  RuntimeContext,
  ThreadStore,
  Runner,
  setupNode,
  setupFunction,
  runNode,
  callHook,
  checkpoint as __checkpoint_impl,
  getCheckpoint as __getCheckpoint_impl,
  restore as __restore_impl,
  _run as __runtime_run_impl,
  interrupt,
  isInterrupt,
  hasInterrupts,
  isDebugger,
  respondToInterrupts as _respondToInterrupts,
  rewindFrom as _rewindFrom,
  RestoreSignal,
  GuardExceededError,
  __readStatic,
  __registerGlobalsInit,
  failure,
  isFailure,
  AgencyFunction as __AgencyFunction,
  __call,
  __callMethod,
  __threads,
  __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: "dist/lib/agents/agency-agent/agent.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(route);
__registerTool(clearMessages);
__registerTool(pushMessage);
__registerTool(repl);
__registerTool(today);
__registerTool(box);
__registerTool(render);
__registerTool(cliPolicyHandler);
__registerTool(ScopedRuleFields);
__registerTool(exists);
__registerTool(highlight);
__registerTool(cwd);
__registerTool(env);
__registerTool(getCost);
__registerTool(codeSysPrompt);
__registerTool(codeTools);
__registerTool(figs);
__registerTool(title);
__registerTool(researchSysPrompt);
__registerTool(researchTools);
async function __initializeGlobals(__ctx) {
  if (__ctx.globals.isInitialized("dist/lib/agents/agency-agent/agent.agency")) {
    return;
  }
  __ctx.globals.markInitialized("dist/lib/agents/agency-agent/agent.agency");
  __ctx.globals.set("dist/lib/agents/agency-agent/agent.agency", "AGENT_DEBUG", await __call(env, {
    type: "positional",
    args: [`AGENT_DEBUG`]
  }) === `1`);
  __ctx.globals.set("dist/lib/agents/agency-agent/agent.agency", "POLICY_FILE", `policy.json`);
  __ctx.globals.set("dist/lib/agents/agency-agent/agent.agency", "HISTORY_FILE", `history`);
  __ctx.globals.set("dist/lib/agents/agency-agent/agent.agency", "ALWAYS_FIELDS", {
    "std::read": [{
      "field": `dir`,
      "matchSubpaths": true
    }],
    "std::write": [{
      "field": `dir`,
      "matchSubpaths": true
    }],
    "std::edit": [{
      "field": `dir`,
      "matchSubpaths": true
    }],
    "std::ls": [{
      "field": `dir`,
      "matchSubpaths": true
    }],
    "std::glob": [{
      "field": `dir`,
      "matchSubpaths": true
    }],
    "std::grep": [{
      "field": `dir`,
      "matchSubpaths": true
    }],
    "std::copy": [{
      "field": `src`,
      "matchSubpaths": true
    }, {
      "field": `dest`,
      "matchSubpaths": true
    }],
    "std::move": [{
      "field": `src`,
      "matchSubpaths": true
    }, {
      "field": `dest`,
      "matchSubpaths": true
    }],
    "std::exec": [{
      "field": `command`,
      "matchSubpaths": false
    }, {
      "field": `subcommand`,
      "matchSubpaths": false
    }]
  });
  __ctx.globals.set("dist/lib/agents/agency-agent/agent.agency", "_context", ``);
}
__registerGlobalsInit("dist/lib/agents/agency-agent/agent.agency", __initializeGlobals);
async function __registerTopLevelCallbacks(__ctx) {
  __ctx.topLevelCallbacks = [];
  await __call(callback, {
    type: "positional",
    args: [`onToolCallStart`, __cb_top_0]
  });
  await __call(callback, {
    type: "positional",
    args: [`onToolCallEnd`, __cb_top_1]
  });
}
__functionRefReviver.registry = __toolRegistry;
async function ____cb_top_0_impl(data) {
  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("dist/lib/agents/agency-agent/agent.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["data"] = data;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "dist/lib/agents/agency-agent/agent.agency", scopeName: "__cb_top_0", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("data" in __overrides) {
      data = __overrides["data"];
      __stack.args["data"] = data;
    }
  }
  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: "__cb_top_0",
            args: {
              data
            },
            isBuiltin: false,
            moduleId: "dist/lib/agents/agency-agent/agent.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
      });
      await runner.step(2, async (runner2) => {
        __self.__retryable = false;
        const __funcResult = await __call(pushMessage, {
          type: "positional",
          args: [await __callMethod(color, "yellow", {
            type: "positional",
            args: [`\u23FA ${__stack.args.data.toolName}(${await __call(formatArgs, {
              type: "positional",
              args: [__stack.args.data.args]
            })})`]
          })]
        });
        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 __cb_top_0 threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "__cb_top_0",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "__cb_top_0",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "__cb_top_0",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const __cb_top_0 = __AgencyFunction.create({
  name: "__cb_top_0",
  module: "dist/lib/agents/agency-agent/agent.agency",
  fn: ____cb_top_0_impl,
  params: [{
    name: "data",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "__cb_top_0",
    description: "No description provided.",
    schema: z.object({ "data": z.any() })
  },
  safe: false,
  exported: false
}, __toolRegistry);
async function ____cb_top_1_impl(data) {
  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("dist/lib/agents/agency-agent/agent.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["data"] = data;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "dist/lib/agents/agency-agent/agent.agency", scopeName: "__cb_top_1", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("data" in __overrides) {
      data = __overrides["data"];
      __stack.args["data"] = data;
    }
  }
  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: "__cb_top_1",
            args: {
              data
            },
            isBuiltin: false,
            moduleId: "dist/lib/agents/agency-agent/agent.agency"
          }
        });
      });
      await runner.ifElse(1, [
        {
          condition: async () => getRuntimeContext().ctx.globals.get("dist/lib/agents/agency-agent/agent.agency", "AGENT_DEBUG"),
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __self.__retryable = false;
              const __funcResult = await __call(pushMessage, {
                type: "positional",
                args: [await __callMethod(color, "yellow", {
                  type: "positional",
                  args: [`tool return: ${__stack.args.data.toolName} -> ${await __callMethod(JSON, "stringify", {
                    type: "positional",
                    args: [__stack.args.data.result]
                  })} ${__stack.args.data.timeTaken}ms`]
                })]
              });
              if (hasInterrupts(__funcResult)) {
                await getRuntimeContext().ctx.pendingPromises.awaitAll();
                runner3.halt(__funcResult);
                return;
              }
            });
          }
        }
      ]);
      await runner.step(2, async (runner2) => {
        __self.__retryable = false;
      });
    });
    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 __cb_top_1 threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "__cb_top_1",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "__cb_top_1",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "__cb_top_1",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const __cb_top_1 = __AgencyFunction.create({
  name: "__cb_top_1",
  module: "dist/lib/agents/agency-agent/agent.agency",
  fn: ____cb_top_1_impl,
  params: [{
    name: "data",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "__cb_top_1",
    description: "No description provided.",
    schema: z.object({ "data": z.any() })
  },
  safe: false,
  exported: false
}, __toolRegistry);
async function __truncate_impl(str, maxLength) {
  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("dist/lib/agents/agency-agent/agent.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["str"] = str;
  __stack.args["maxLength"] = maxLength;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "dist/lib/agents/agency-agent/agent.agency", scopeName: "truncate", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("str" in __overrides) {
      str = __overrides["str"];
      __stack.args["str"] = str;
    }
    if ("maxLength" in __overrides) {
      maxLength = __overrides["maxLength"];
      __stack.args["maxLength"] = maxLength;
    }
  }
  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: "truncate",
            args: {
              str,
              maxLength
            },
            isBuiltin: false,
            moduleId: "dist/lib/agents/agency-agent/agent.agency"
          }
        });
      });
      await runner.ifElse(1, [
        {
          condition: async () => __stack.args.str.length <= __stack.args.maxLength,
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __functionCompleted = true;
              runner3.halt(__stack.args.str);
              return;
            });
          }
        }
      ]);
      await runner.step(2, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __callMethod(__stack.args.str, "slice", {
          type: "positional",
          args: [0, __stack.args.maxLength]
        }) + `...`);
        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 truncate threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "truncate",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "truncate",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "truncate",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const truncate = __AgencyFunction.create({
  name: "truncate",
  module: "dist/lib/agents/agency-agent/agent.agency",
  fn: __truncate_impl,
  params: [{
    name: "str",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "maxLength",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "truncate",
    description: "No description provided.",
    schema: z.object({ "str": z.string(), "maxLength": z.number() })
  },
  safe: false,
  exported: false
}, __toolRegistry);
async function __formatArgs_impl(args) {
  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("dist/lib/agents/agency-agent/agent.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["args"] = args;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "dist/lib/agents/agency-agent/agent.agency", scopeName: "formatArgs", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("args" in __overrides) {
      args = __overrides["args"];
      __stack.args["args"] = args;
    }
  }
  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: "formatArgs",
            args: {
              args
            },
            isBuiltin: false,
            moduleId: "dist/lib/agents/agency-agent/agent.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.parts = [];
      });
      await runner.loop(2, __stack.args.args, async (key, _, runner2) => {
        await runner2.step(0, async (runner3) => {
          __stack.locals.value = __stack.args.args[key];
        });
        await runner2.step(1, async (runner3) => {
          await __callMethod(__stack.locals.parts, "push", {
            type: "positional",
            args: [`${key}: ${await __call(truncate, {
              type: "positional",
              args: [await __callMethod(JSON, "stringify", {
                type: "positional",
                args: [__stack.locals.value]
              }), 50]
            })}`]
          });
        });
      });
      await runner.step(3, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __callMethod(__stack.locals.parts, "join", {
          type: "positional",
          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 formatArgs threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "formatArgs",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "formatArgs",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "formatArgs",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const formatArgs = __AgencyFunction.create({
  name: "formatArgs",
  module: "dist/lib/agents/agency-agent/agent.agency",
  fn: __formatArgs_impl,
  params: [{
    name: "args",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "formatArgs",
    description: "No description provided.",
    schema: z.object({ "args": z.record(z.string(), z.any()) })
  },
  safe: false,
  exported: false
}, __toolRegistry);
async function __policyDir_impl() {
  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("dist/lib/agents/agency-agent/agent.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "dist/lib/agents/agency-agent/agent.agency", scopeName: "policyDir", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
  }
  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: "policyDir",
            args: {},
            isBuiltin: false,
            moduleId: "dist/lib/agents/agency-agent/agent.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.home = await __call(env, {
          type: "positional",
          args: [`HOME`]
        });
        if (hasInterrupts(__stack.locals.home)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__stack.locals.home);
          return;
        }
      });
      await runner.ifElse(2, [
        {
          condition: async () => __stack.locals.home === null,
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __functionCompleted = true;
              runner3.halt(`./.agency-agent`);
              return;
            });
          }
        }
      ]);
      await runner.step(3, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(`${__stack.locals.home}/.agency-agent`);
        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 policyDir threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "policyDir",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "policyDir",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "policyDir",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const policyDir = __AgencyFunction.create({
  name: "policyDir",
  module: "dist/lib/agents/agency-agent/agent.agency",
  fn: __policyDir_impl,
  params: [],
  toolDefinition: {
    name: "policyDir",
    description: "No description provided.",
    schema: z.object({})
  },
  safe: false,
  exported: false
}, __toolRegistry);
async function __policyPath_impl() {
  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("dist/lib/agents/agency-agent/agent.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "dist/lib/agents/agency-agent/agent.agency", scopeName: "policyPath", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
  }
  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: "policyPath",
            args: {},
            isBuiltin: false,
            moduleId: "dist/lib/agents/agency-agent/agent.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(`${await __call(policyDir, {
          type: "positional",
          args: []
        })}/${getRuntimeContext().ctx.globals.get("dist/lib/agents/agency-agent/agent.agency", "POLICY_FILE")}`);
        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 policyPath threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "policyPath",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "policyPath",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "policyPath",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const policyPath = __AgencyFunction.create({
  name: "policyPath",
  module: "dist/lib/agents/agency-agent/agent.agency",
  fn: __policyPath_impl,
  params: [],
  toolDefinition: {
    name: "policyPath",
    description: "No description provided.",
    schema: z.object({})
  },
  safe: false,
  exported: false
}, __toolRegistry);
async function __historyPath_impl() {
  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("dist/lib/agents/agency-agent/agent.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "dist/lib/agents/agency-agent/agent.agency", scopeName: "historyPath", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
  }
  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: "historyPath",
            args: {},
            isBuiltin: false,
            moduleId: "dist/lib/agents/agency-agent/agent.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(`${await __call(policyDir, {
          type: "positional",
          args: []
        })}/${getRuntimeContext().ctx.globals.get("dist/lib/agents/agency-agent/agent.agency", "HISTORY_FILE")}`);
        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 historyPath threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "historyPath",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "historyPath",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "historyPath",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const historyPath = __AgencyFunction.create({
  name: "historyPath",
  module: "dist/lib/agents/agency-agent/agent.agency",
  fn: __historyPath_impl,
  params: [],
  toolDefinition: {
    name: "historyPath",
    description: "No description provided.",
    schema: z.object({})
  },
  safe: false,
  exported: false
}, __toolRegistry);
async function __loadAgentsMd_impl(dir) {
  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("dist/lib/agents/agency-agent/agent.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["dir"] = dir;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "dist/lib/agents/agency-agent/agent.agency", scopeName: "loadAgentsMd", 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;
    }
  }
  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: "loadAgentsMd",
            args: {
              dir
            },
            isBuiltin: false,
            moduleId: "dist/lib/agents/agency-agent/agent.agency"
          }
        });
      });
      await runner.ifElse(1, [
        {
          condition: async () => !await __call(exists, {
            type: "positional",
            args: [`AGENTS.md`, __stack.args.dir]
          }),
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __functionCompleted = true;
              runner3.halt(``);
              return;
            });
          }
        }
      ]);
      await runner.handle(2, async (__data) => approve(), async (runner2) => {
        await runner2.step(0, async (runner3) => {
          __self.__retryable = false;
          __stack.locals.result = await __call(read, {
            type: "positional",
            args: [`AGENTS.md`, __stack.args.dir]
          });
          if (hasInterrupts(__stack.locals.result)) {
            await getRuntimeContext().ctx.pendingPromises.awaitAll();
            runner3.halt(__stack.locals.result);
            return;
          }
        });
      });
      await runner.step(3, async (runner2) => {
        __self.__retryable = false;
      });
      await runner.ifElse(4, [
        {
          condition: async () => await isFailure(__stack.locals.result),
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __functionCompleted = true;
              runner3.halt(``);
              return;
            });
          }
        }
      ]);
      await runner.step(5, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(`

<project_context>
${__stack.locals.result.value}
</project_context>`);
        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 loadAgentsMd threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "loadAgentsMd",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "loadAgentsMd",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "loadAgentsMd",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const loadAgentsMd = __AgencyFunction.create({
  name: "loadAgentsMd",
  module: "dist/lib/agents/agency-agent/agent.agency",
  fn: __loadAgentsMd_impl,
  params: [{
    name: "dir",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "loadAgentsMd",
    description: `Read \`AGENTS.md\` from \`dir\` if it exists and return it wrapped in a
  <project_context> block ready to splice into a system prompt. Returns
  an empty string if there is no AGENTS.md or it cannot be read. The
  read is auto-approved \u2014 the user implicitly opted in to scanning the
  project directory by running the agent there.`,
    schema: z.object({ "dir": z.string() })
  },
  safe: false,
  exported: false
}, __toolRegistry);
async function ___runTurn_impl(msg) {
  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("dist/lib/agents/agency-agent/agent.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["msg"] = msg;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "dist/lib/agents/agency-agent/agent.agency", scopeName: "_runTurn", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("msg" in __overrides) {
      msg = __overrides["msg"];
      __stack.args["msg"] = msg;
    }
  }
  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: "_runTurn",
            args: {
              msg
            },
            isBuiltin: false,
            moduleId: "dist/lib/agents/agency-agent/agent.agency"
          }
        });
      });
      await runner.ifElse(1, [
        {
          condition: async () => __stack.args.msg === ``,
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __functionCompleted = true;
              runner3.halt(true);
              return;
            });
          }
        }
      ]);
      await runner.ifElse(2, [
        {
          condition: async () => __stack.args.msg === `/exit` || __stack.args.msg === `/quit`,
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __functionCompleted = true;
              runner3.halt(false);
              return;
            });
          }
        }
      ]);
      await runner.ifElse(3, [
        {
          condition: async () => __stack.args.msg === `/clear`,
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __self.__retryable = false;
              const __funcResult = await __call(clearMessages, {
                type: "positional",
                args: []
              });
              if (hasInterrupts(__funcResult)) {
                await getRuntimeContext().ctx.pendingPromises.awaitAll();
                runner3.halt(__funcResult);
                return;
              }
            });
            await runner2.step(1, async (runner3) => {
              __functionCompleted = true;
              runner3.halt(true);
              return;
            });
          }
        }
      ]);
      await runner.step(4, async (runner2) => {
        __self.__retryable = false;
      });
      await runner.ifElse(5, [
        {
          condition: async () => __stack.args.msg === `/help`,
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __self.__retryable = false;
              const __funcResult = await __call(pushMessage, {
                type: "positional",
                args: [`Commands: /exit, /clear, /help`]
              });
              if (hasInterrupts(__funcResult)) {
                await getRuntimeContext().ctx.pendingPromises.awaitAll();
                runner3.halt(__funcResult);
                return;
              }
            });
            await runner2.step(1, async (runner3) => {
              __functionCompleted = true;
              runner3.halt(true);
              return;
            });
          }
        }
      ]);
      await runner.step(6, async (runner2) => {
        __self.__retryable = false;
      });
      await runner.step(7, async (runner2) => {
        __self.__retryable = false;
        __stack.locals.reply = await __call(route, {
          type: "positional",
          args: [{
            "start": `code`,
            "agents": {
              "code": {
                "systemPrompt": __readStatic(codeSysPrompt, "codeSysPrompt", "/Users/adityabhargava/agency-lang/packages/agency-lang/dist/lib/agents/agency-agent/code.agency"),
                "tools": __readStatic(codeTools, "codeTools", "/Users/adityabhargava/agency-lang/packages/agency-lang/dist/lib/agents/agency-agent/code.agency"),
                "memory": true
              },
              "research": {
                "systemPrompt": __readStatic(researchSysPrompt, "researchSysPrompt", "/Users/adityabhargava/agency-lang/packages/agency-lang/dist/lib/agents/agency-agent/research.agency"),
                "tools": __readStatic(researchTools, "researchTools", "/Users/adityabhargava/agency-lang/packages/agency-lang/dist/lib/agents/agency-agent/research.agency"),
                "memory": true
              }
            },
            "maxHops": 3,
            "context": getRuntimeContext().ctx.globals.get("dist/lib/agents/agency-agent/agent.agency", "_context")
          }, __stack.args.msg]
        });
        if (hasInterrupts(__stack.locals.reply)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__stack.locals.reply);
          return;
        }
      });
      await runner.step(8, async (runner2) => {
        __self.__retryable = false;
        const __funcResult = await __call(pushMessage, {
          type: "positional",
          args: [await __call(highlight, {
            type: "named",
            positionalArgs: [`${__stack.locals.reply}
`],
            namedArgs: {
              language: `markdown`
            }
          })]
        });
        if (hasInterrupts(__funcResult)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__funcResult);
          return;
        }
      });
      await runner.step(9, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(true);
        return;
      });
    });
    if (runner.halted) {
      if (isFailure(runner.haltResult)) {
        runner.haltResult.retryable = runner.haltResult.retryable && __self.__retryable;
      }
      return runner.haltResult;
    }
  } catch (__error) {
    if (__error instanceof RestoreSignal) {
      throw __error;
    }
    if (__error instanceof GuardExceededError) {
      throw __error;
    }
    {
      const __errMsg = __error instanceof Error ? __error.message : String(__error);
      const __errStack = __error instanceof Error && __error.stack ? __error.stack : "";
      const __log = __createLogger(__ctx.logLevel);
      __log.error("Function _runTurn threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "_runTurn",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "_runTurn",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "_runTurn",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const _runTurn = __AgencyFunction.create({
  name: "_runTurn",
  module: "dist/lib/agents/agency-agent/agent.agency",
  fn: ___runTurn_impl,
  params: [{
    name: "msg",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "_runTurn",
    description: "No description provided.",
    schema: z.object({ "msg": z.string() })
  },
  safe: false,
  exported: false
}, __toolRegistry);
async function __roundedCost_impl() {
  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("dist/lib/agents/agency-agent/agent.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "dist/lib/agents/agency-agent/agent.agency", scopeName: "roundedCost", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
  }
  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: "roundedCost",
            args: {},
            isBuiltin: false,
            moduleId: "dist/lib/agents/agency-agent/agent.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(`$${await __callMethod(await await __call(getCost, {
          type: "positional",
          args: []
        }), "toFixed", {
          type: "positional",
          args: [4]
        })}`);
        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 roundedCost threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "roundedCost",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "roundedCost",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "roundedCost",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const roundedCost = __AgencyFunction.create({
  name: "roundedCost",
  module: "dist/lib/agents/agency-agent/agent.agency",
  fn: __roundedCost_impl,
  params: [],
  toolDefinition: {
    name: "roundedCost",
    description: "No description provided.",
    schema: z.object({})
  },
  safe: false,
  exported: false
}, __toolRegistry);
async function ___buildStatus_impl() {
  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("dist/lib/agents/agency-agent/agent.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "dist/lib/agents/agency-agent/agent.agency", scopeName: "_buildStatus", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
  }
  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: "_buildStatus",
            args: {},
            isBuiltin: false,
            moduleId: "dist/lib/agents/agency-agent/agent.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt({
          "left": ``,
          "right": await __call(roundedCost, {
            type: "positional",
            args: []
          }),
          "context": ``
        });
        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 _buildStatus threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "_buildStatus",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "_buildStatus",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "_buildStatus",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const _buildStatus = __AgencyFunction.create({
  name: "_buildStatus",
  module: "dist/lib/agents/agency-agent/agent.agency",
  fn: ___buildStatus_impl,
  params: [],
  toolDefinition: {
    name: "_buildStatus",
    description: "No description provided.",
    schema: z.object({})
  },
  safe: false,
  exported: false
}, __toolRegistry);
async function __sample_impl(arr) {
  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("dist/lib/agents/agency-agent/agent.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["arr"] = arr;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "dist/lib/agents/agency-agent/agent.agency", scopeName: "sample", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("arr" in __overrides) {
      arr = __overrides["arr"];
      __stack.args["arr"] = arr;
    }
  }
  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: "sample",
            args: {
              arr
            },
            isBuiltin: false,
            moduleId: "dist/lib/agents/agency-agent/agent.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(__stack.args.arr[await __callMethod(Math, "floor", {
          type: "positional",
          args: [await __callMethod(Math, "random", {
            type: "positional",
            args: []
          }) * __stack.args.arr.length]
        })]);
        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 sample threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "sample",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "sample",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "sample",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const sample = __AgencyFunction.create({
  name: "sample",
  module: "dist/lib/agents/agency-agent/agent.agency",
  fn: __sample_impl,
  params: [{
    name: "arr",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "sample",
    description: "No description provided.",
    schema: z.object({ "arr": z.array(z.any()) })
  },
  safe: false,
  exported: false
}, __toolRegistry);
async function __printHeader_impl() {
  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("dist/lib/agents/agency-agent/agent.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "dist/lib/agents/agency-agent/agent.agency", scopeName: "printHeader", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
  }
  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: "printHeader",
            args: {},
            isBuiltin: false,
            moduleId: "dist/lib/agents/agency-agent/agent.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.fig = await __call(sample, {
          type: "positional",
          args: [__readStatic(figs, "figs", "/Users/adityabhargava/agency-lang/packages/agency-lang/dist/lib/agents/agency-agent/images/images.agency")]
        });
        if (hasInterrupts(__stack.locals.fig)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__stack.locals.fig);
          return;
        }
      });
      await runner.step(2, async (runner2) => {
        __self.__retryable = false;
        __stack.locals.data = await __call(box, {
          type: "named",
          positionalArgs: [],
          namedArgs: {
            title: `Agency`,
            padding: 1,
            borderColor: `cyan`,
            titleColor: `cyan`
          },
          blockArg: __AgencyFunction.create({ name: "__block_0", module: "dist/lib/agents/agency-agent/agent.agency", fn: async (b) => {
            const __bsetup = setupFunction();
            const __bstack = __bsetup.stack;
            const __self2 = __bstack.locals;
            __bstack.args["b"] = b;
            const runner3 = new Runner(__ctx, __bstack, { state: __bstack, moduleId: "dist/lib/agents/agency-agent/agent.agency", scopeName: "__block_0" });
            try {
              await runner3.step(0, async (runner4) => {
                await __callMethod(__bstack.args.b, "row", {
                  type: "named",
                  positionalArgs: [],
                  namedArgs: {
                    gap: 1
                  },
                  blockArg: __AgencyFunction.create({ name: "__block_1", module: "dist/lib/agents/agency-agent/agent.agency", fn: async (r) => {
                    const __bsetup2 = setupFunction();
                    const __bstack2 = __bsetup2.stack;
                    const __self3 = __bstack2.locals;
                    __bstack2.args["r"] = r;
                    const runner5 = new Runner(__ctx, __bstack2, { state: __bstack2, moduleId: "dist/lib/agents/agency-agent/agent.agency", scopeName: "__block_1" });
                    try {
                      await runner5.step(0, async (runner6) => {
                        await __callMethod(__bstack2.args.r, "column", {
                          type: "named",
                          positionalArgs: [],
                          namedArgs: {},
                          blockArg: __AgencyFunction.create({ name: "__block_2", module: "dist/lib/agents/agency-agent/agent.agency", fn: async (left) => {
                            const __bsetup3 = setupFunction();
                            const __bstack3 = __bsetup3.stack;
                            const __self4 = __bstack3.locals;
                            __bstack3.args["left"] = left;
                            const runner7 = new Runner(__ctx, __bstack3, { state: __bstack3, moduleId: "dist/lib/agents/agency-agent/agent.agency", scopeName: "__block_2" });
                            try {
                              await runner7.step(0, async (runner8) => {
                                await __callMethod(__bstack3.args.left, "text", {
                                  type: "named",
                                  positionalArgs: [`Welcome to the Agency Agent!`],
                                  namedArgs: {
                                    bold: true
                                  }
                                });
                              });
                              await runner7.step(1, async (runner8) => {
                                await __callMethod(__bstack3.args.left, "text", {
                                  type: "positional",
                                  args: [`Ask me to write code, look up docs, or just chat.`]
                                });
                              });
                              await runner7.step(2, async (runner8) => {
                                await __callMethod(__bstack3.args.left, "hline", {
                                  type: "positional",
                                  args: []
                                });
                              });
                              await runner7.step(3, async (runner8) => {
                                await __callMethod(__bstack3.args.left, "text", {
                                  type: "named",
                                  positionalArgs: [`Getting Started`],
                                  namedArgs: {
                                    bold: true,
                                    fgColor: `cyan`
                                  }
                                });
                              });
                              await runner7.step(4, async (runner8) => {
                                await __callMethod(__bstack3.args.left, "text", {
                                  type: "named",
                                  positionalArgs: [`/help for commands \xB7 /exit to quit`],
                                  namedArgs: {
                                    dim: true
                                  }
                                });
                              });
                              return runner7.halted ? runner7.haltResult : void 0;
                            } finally {
                              __ctx.stateStack.pop();
                            }
                          }, params: [{ name: "left", hasDefault: false, defaultValue: void 0, variadic: false }], toolDefinition: null }, __toolRegistry)
                        });
                      });
                      await runner5.step(1, async (runner6) => {
                        await __callMethod(__bstack2.args.r, "vline", {
                          type: "positional",
                          args: []
                        });
                      });
                      await runner5.step(2, async (runner6) => {
                        await __callMethod(__bstack2.args.r, "column", {
                          type: "named",
                          positionalArgs: [],
                          namedArgs: {},
                          blockArg: __AgencyFunction.create({ name: "__block_3", module: "dist/lib/agents/agency-agent/agent.agency", fn: async (right) => {
                            const __bsetup3 = setupFunction();
                            const __bstack3 = __bsetup3.stack;
                            const __self4 = __bstack3.locals;
                            __bstack3.args["right"] = right;
                            const runner7 = new Runner(__ctx, __bstack3, { state: __bstack3, moduleId: "dist/lib/agents/agency-agent/agent.agency", scopeName: "__block_3" });
                            try {
                              await runner7.step(0, async (runner8) => {
                                await __callMethod(__bstack3.args.right, "raw", {
                                  type: "positional",
                                  args: [__stack.locals.fig]
                                });
                              });
                              return runner7.halted ? runner7.haltResult : void 0;
                            } finally {
                              __ctx.stateStack.pop();
                            }
                          }, params: [{ name: "right", hasDefault: false, defaultValue: void 0, variadic: false }], toolDefinition: null }, __toolRegistry)
                        });
                      });
                      return runner5.halted ? runner5.haltResult : void 0;
                    } finally {
                      __ctx.stateStack.pop();
                    }
                  }, params: [{ name: "r", hasDefault: false, defaultValue: void 0, variadic: false }], toolDefinition: null }, __toolRegistry)
                });
              });
              return runner3.halted ? runner3.haltResult : void 0;
            } finally {
              __ctx.stateStack.pop();
            }
          }, params: [{ name: "b", hasDefault: false, defaultValue: void 0, variadic: false }], toolDefinition: null }, __toolRegistry)
        });
        if (hasInterrupts(__stack.locals.data)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__stack.locals.data);
          return;
        }
      });
      await runner.step(3, async (runner2) => {
        const __funcResult = await __call(print, {
          type: "positional",
          args: [await __call(render, {
            type: "named",
            positionalArgs: [__stack.locals.data],
            namedArgs: {
              color: true
            }
          })]
        });
        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 printHeader threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "printHeader",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "printHeader",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "printHeader",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const printHeader = __AgencyFunction.create({
  name: "printHeader",
  module: "dist/lib/agents/agency-agent/agent.agency",
  fn: __printHeader_impl,
  params: [],
  toolDefinition: {
    name: "printHeader",
    description: "No description provided.",
    schema: z.object({})
  },
  safe: false,
  exported: false
}, __toolRegistry);
graph.node("main", async (__state) => {
  const __setupData = setupNode({
    state: __state
  });
  const __stack = __setupData.stack;
  const __step = __setupData.step;
  const __self = __setupData.self;
  const __ctx = getRuntimeContext().ctx;
  let __forked;
  let __functionCompleted = false;
  const runner = new Runner(__ctx, __stack, { nodeContext: true, state: __stack, moduleId: "dist/lib/agents/agency-agent/agent.agency", scopeName: "main", threads: __setupData.threads });
  try {
    await agencyStore.run({
      ...getRuntimeContext(),
      ctx: __ctx,
      stack: __ctx.stateStack,
      threads: __setupData.threads
    }, async () => {
      await runner.hook(0, async () => {
        await callHook({
          name: "onNodeStart",
          data: {
            nodeName: "main"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        const __funcResult = await __call(printHeader, {
          type: "positional",
          args: []
        });
        if (hasInterrupts(__funcResult)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt({
            ...__state,
            data: __funcResult
          });
          return;
        }
      });
      await runner.handle(2, async (__data) => approve(), async (runner2) => {
        await runner2.step(0, async (runner3) => {
          __stack.locals.projectContext = await __call(loadAgentsMd, {
            type: "positional",
            args: [await __call(cwd, {
              type: "positional",
              args: []
            })]
          });
          if (hasInterrupts(__stack.locals.projectContext)) {
            await getRuntimeContext().ctx.pendingPromises.awaitAll();
            runner3.halt({
              ...__state,
              data: __stack.locals.projectContext
            });
            return;
          }
        });
      });
      await runner.step(3, async (runner2) => {
        getRuntimeContext().ctx.globals.set("dist/lib/agents/agency-agent/agent.agency", "_context", `

Current date: ${await __call(today, {
          type: "positional",
          args: []
        })}
Current working directory: ${await __call(cwd, {
          type: "positional",
          args: []
        })}${__stack.locals.projectContext}`);
      });
      await runner.step(4, async (runner2) => {
        __self.__retryable = false;
        __stack.locals.handler = await __call(cliPolicyHandler, {
          type: "positional",
          args: [{
            "file": await __call(policyPath, {
              type: "positional",
              args: []
            }),
            "fields": getRuntimeContext().ctx.globals.get("dist/lib/agents/agency-agent/agent.agency", "ALWAYS_FIELDS")
          }]
        });
        if (hasInterrupts(__stack.locals.handler)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt({
            ...__state,
            data: __stack.locals.handler
          });
          return;
        }
      });
      await runner.handle(5, async (__data) => await __call(__stack.locals.handler, {
        type: "positional",
        args: [__data]
      }), async (runner2) => {
        await runner2.step(0, async (runner3) => {
          __self.__retryable = false;
          const __funcResult = await __call(repl, {
            type: "named",
            positionalArgs: [],
            namedArgs: {
              status: _buildStatus,
              onSubmit: _runTurn,
              prompt: `> `,
              historyFile: await __call(historyPath, {
                type: "positional",
                args: []
              }),
              historyMax: 1e3,
              paletteCommands: {
                "/exit": `Exit the agent`,
                "/clear": `Clear the conversation transcript`,
                "/help": `Show available slash commands`
              }
            }
          });
          if (hasInterrupts(__funcResult)) {
            await getRuntimeContext().ctx.pendingPromises.awaitAll();
            runner3.halt({
              ...__state,
              data: __funcResult
            });
            return;
          }
        });
      });
      await runner.step(6, async (runner2) => {
        __self.__retryable = false;
      });
      await runner.step(7, async (runner2) => {
        const __funcResult = await __call(print, {
          type: "positional",
          args: [await __callMethod(color, "cyan", {
            type: "positional",
            args: [`
Goodbye!`]
          })]
        });
        if (hasInterrupts(__funcResult)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt({
            ...__state,
            data: __funcResult
          });
          return;
        }
      });
    });
    if (runner.halted) return runner.haltResult;
    await runner.hook(8, async () => {
      await callHook({
        name: "onNodeEnd",
        data: {
          nodeName: "main",
          data: void 0
        }
      });
    });
    return {
      messages: __threads(),
      data: void 0
    };
  } 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(`Node main crashed: ${__errMsg}`);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "main"
      });
    }
    return {
      messages: __threads(),
      data: failure(__error instanceof Error ? __error.message : String(__error), { functionName: "main" })
    };
  }
});
async function main({ messages, callbacks } = {}) {
  return runNode({
    ctx: __globalCtx,
    nodeName: "main",
    data: {},
    messages,
    callbacks,
    initializeGlobals: __initializeGlobals,
    registerTopLevelCallbacks: __registerTopLevelCallbacks,
    moduleDir: __dirname
  });
}
const __mainNodeParams = [];
if (__process.argv[1] === fileURLToPath(import.meta.url)) {
  try {
    const initialState = {
      messages: new ThreadStore(),
      data: {}
    };
    await main(initialState);
  } catch (__error) {
    console.error(`
Agent crashed: ${__error.message}`);
    throw __error;
  }
}
var stdin_default = graph;
const __sourceMap = { "dist/lib/agents/agency-agent/agent.agency:__cb_top_0": { "2": { "line": 64, "col": 2 } }, "dist/lib/agents/agency-agent/agent.agency:__cb_top_1": { "1": { "line": 85, "col": 2 }, "1.0": { "line": 86, "col": 4 } }, "dist/lib/agents/agency-agent/agent.agency:truncate": { "1": { "line": 69, "col": 2 }, "2": { "line": 72, "col": 2 }, "1.0": { "line": 70, "col": 4 } }, "dist/lib/agents/agency-agent/agent.agency:formatArgs": { "1": { "line": 76, "col": 2 }, "2": { "line": 77, "col": 2 }, "3": { "line": 81, "col": 2 }, "2.0": { "line": 78, "col": 4 }, "2.1": { "line": 79, "col": 4 } }, "dist/lib/agents/agency-agent/agent.agency:policyDir": { "1": { "line": 102, "col": 2 }, "2": { "line": 103, "col": 2 }, "3": { "line": 106, "col": 2 }, "2.0": { "line": 104, "col": 4 } }, "dist/lib/agents/agency-agent/agent.agency:policyPath": { "1": { "line": 110, "col": 2 } }, "dist/lib/agents/agency-agent/agent.agency:historyPath": { "1": { "line": 114, "col": 2 } }, "dist/lib/agents/agency-agent/agent.agency:loadAgentsMd": { "1": { "line": 187, "col": 2 }, "2": { "line": 190, "col": 2 }, "4": { "line": 191, "col": 2 }, "5": { "line": 194, "col": 2 }, "1.0": { "line": 188, "col": 4 }, "2.0": { "line": 190, "col": 2 }, "4.0": { "line": 192, "col": 4 } }, "dist/lib/agents/agency-agent/agent.agency:_runTurn": { "1": { "line": 204, "col": 2 }, "2": { "line": 207, "col": 2 }, "3": { "line": 210, "col": 2 }, "5": { "line": 214, "col": 2 }, "7": { "line": 218, "col": 2 }, "8": { "line": 238, "col": 2 }, "9": { "line": 239, "col": 2 }, "1.0": { "line": 205, "col": 4 }, "2.0": { "line": 208, "col": 4 }, "3.0": { "line": 211, "col": 4 }, "3.1": { "line": 212, "col": 4 }, "5.0": { "line": 215, "col": 4 }, "5.1": { "line": 216, "col": 4 } }, "dist/lib/agents/agency-agent/agent.agency:roundedCost": { "1": { "line": 243, "col": 2 } }, "dist/lib/agents/agency-agent/agent.agency:_buildStatus": { "1": { "line": 247, "col": 2 } }, "dist/lib/agents/agency-agent/agent.agency:sample": { "1": { "line": 255, "col": 2 } }, "dist/lib/agents/agency-agent/agent.agency:printHeader": { "1": { "line": 259, "col": 2 }, "2": { "line": 260, "col": 2 }, "3": { "line": 275, "col": 2 } }, "dist/lib/agents/agency-agent/agent.agency:__block_0": { "2.0": { "line": 261, "col": 4 } }, "dist/lib/agents/agency-agent/agent.agency:__block_1": { "2.0.0": { "line": 262, "col": 6 }, "2.0.1": { "line": 269, "col": 6 }, "2.0.2": { "line": 270, "col": 6 } }, "dist/lib/agents/agency-agent/agent.agency:__block_2": { "2.0.0.0": { "line": 263, "col": 8 }, "2.0.0.1": { "line": 264, "col": 8 }, "2.0.0.2": { "line": 265, "col": 8 }, "2.0.0.3": { "line": 266, "col": 8 }, "2.0.0.4": { "line": 267, "col": 8 } }, "dist/lib/agents/agency-agent/agent.agency:__block_3": { "2.0.2.0": { "line": 271, "col": 8 } }, "dist/lib/agents/agency-agent/agent.agency:main": { "1": { "line": 279, "col": 2 }, "2": { "line": 288, "col": 2 }, "3": { "line": 289, "col": 2 }, "4": { "line": 293, "col": 2 }, "5": { "line": 302, "col": 2 }, "7": { "line": 317, "col": 2 }, "2.0": { "line": 288, "col": 2 }, "5.0": { "line": 303, "col": 4 } } };
export {
  __getCheckpoints,
  __mainNodeParams,
  __setDebugger,
  __setLLMClient,
  __setTraceFile,
  __sourceMap,
  __toolRegistry,
  approve,
  stdin_default as default,
  hasInterrupts,
  interrupt,
  isDebugger,
  isInterrupt,
  main,
  reject,
  respondToInterrupts,
  rewindFrom
};
