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 { setMemoryId } from "agency-lang/stdlib/memory.js";
import { systemMessage } from "agency-lang/stdlib/thread.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,
  runPrompt,
  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,
  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: "stdlib/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(setMemoryId);
__registerTool(systemMessage);
async function __initializeGlobals(__ctx) {
  if (__ctx.globals.isInitialized("stdlib/agent.agency")) {
    return;
  }
  __ctx.globals.markInitialized("stdlib/agent.agency");
  __ctx.globals.set("stdlib/agent.agency", "_todos", []);
  __ctx.globals.set("stdlib/agent.agency", "_handoffTarget", ``);
  __ctx.globals.set("stdlib/agent.agency", "_firstEntry", {});
}
__registerGlobalsInit("stdlib/agent.agency", __initializeGlobals);
async function __registerTopLevelCallbacks(__ctx) {
  __ctx.topLevelCallbacks = [];
}
__functionRefReviver.registry = __toolRegistry;
const Todo = z.object({ "id": z.string(), "text": z.string(), "status": z.union([z.literal("pending"), z.literal("in_progress"), z.literal("completed")]) });
async function __todoWrite_impl(todos) {
  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/agent.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["todos"] = todos;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/agent.agency", scopeName: "todoWrite", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("todos" in __overrides) {
      todos = __overrides["todos"];
      __stack.args["todos"] = todos;
    }
  }
  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: "todoWrite",
            args: {
              todos
            },
            isBuiltin: false,
            moduleId: "stdlib/agent.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        getRuntimeContext().ctx.globals.set("stdlib/agent.agency", "_todos", __stack.args.todos);
      });
      await runner.step(2, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(getRuntimeContext().ctx.globals.get("stdlib/agent.agency", "_todos"));
        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 todoWrite threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "todoWrite",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "todoWrite",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "todoWrite",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const todoWrite = __AgencyFunction.create({
  name: "todoWrite",
  module: "stdlib/agent.agency",
  fn: __todoWrite_impl,
  params: [{
    name: "todos",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "todoWrite",
    description: `Replace the current todo list. Each todo has an id, text, and status (one of 'pending', 'in_progress', 'completed'). Use this to track multi-step work as you go: mark a todo 'in_progress' before starting it and 'completed' when done. Returns the new list.`,
    schema: z.object({ "todos": z.array(Todo) })
  },
  safe: true,
  exported: true
}, __toolRegistry);
async function __todoList_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("stdlib/agent.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/agent.agency", scopeName: "todoList", 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: "todoList",
            args: {},
            isBuiltin: false,
            moduleId: "stdlib/agent.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(getRuntimeContext().ctx.globals.get("stdlib/agent.agency", "_todos"));
        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 todoList threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "todoList",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "todoList",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "todoList",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const todoList = __AgencyFunction.create({
  name: "todoList",
  module: "stdlib/agent.agency",
  fn: __todoList_impl,
  params: [],
  toolDefinition: {
    name: "todoList",
    description: `Return the current todo list.`,
    schema: z.object({})
  },
  safe: true,
  exported: true
}, __toolRegistry);
async function __question_impl(prompt) {
  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/agent.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["prompt"] = prompt;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/agent.agency", scopeName: "question", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("prompt" in __overrides) {
      prompt = __overrides["prompt"];
      __stack.args["prompt"] = prompt;
    }
  }
  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: "question",
            args: {
              prompt
            },
            isBuiltin: false,
            moduleId: "stdlib/agent.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        const __response = getRuntimeContext().ctx.getInterruptResponse(__self.__interruptId_1);
        if (__response) {
          if (__response.type === "approve") {
            if (__response.value !== void 0) {
              __stack.locals.answer = __response.value;
              ;
            } else {
              __stack.locals.answer = true;
              ;
            }
          } else if (__response.type === "reject") {
            runner2.halt(failure("interrupt rejected", { retryable: false, checkpoint: getRuntimeContext().ctx.getResultCheckpoint() }));
            return;
          }
        } else {
          const __handlerResult = await interruptWithHandlers("std::question", __stack.args.prompt, {
            "prompt": __stack.args.prompt
          }, "std::agent", __ctx, __stateStack());
          if (isRejected(__handlerResult)) {
            runner2.halt(failure(__handlerResult.value ?? "interrupt rejected", { retryable: false, checkpoint: getRuntimeContext().ctx.checkpoints.get(__resultCheckpointId) }));
            return;
          }
          if (isApproved(__handlerResult)) {
            __stack.locals.answer = __handlerResult.value;
            ;
          } else {
            __self.__interruptId_1 = __handlerResult[0].interruptId;
            const __checkpointId = getRuntimeContext().ctx.checkpoints.create(__stateStack(), __ctx, { moduleId: "stdlib/agent.agency", scopeName: "question", 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(__stack.locals.answer);
        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 question threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "question",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "question",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "question",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const question = __AgencyFunction.create({
  name: "question",
  module: "stdlib/agent.agency",
  fn: __question_impl,
  params: [{
    name: "prompt",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "question",
    description: `Ask the user a question and wait for their reply. Unlike input(), this raises an interrupt so the host (CLI, web UI, etc.) can present the prompt in its own way; the host resolves the interrupt with the answer string.`,
    schema: z.object({ "prompt": z.string() })
  },
  safe: false,
  exported: true
}, __toolRegistry);
const AgentSpec = z.object({ "systemPrompt": z.string(), "tools": z.array(z.any()), "memory": z.union([z.boolean(), z.null()]) });
const RouterConfig = z.object({ "start": z.string(), "agents": z.record(z.string(), z.object({ "systemPrompt": z.string(), "tools": z.array(z.any()), "memory": z.union([z.boolean(), z.null()]) })), "maxHops": z.number(), "context": z.union([z.string(), z.null()]) });
async function __handoff_impl(category, reason, validCategories) {
  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/agent.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["category"] = category;
  __stack.args["reason"] = reason;
  __stack.args["validCategories"] = validCategories;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/agent.agency", scopeName: "handoff", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("category" in __overrides) {
      category = __overrides["category"];
      __stack.args["category"] = category;
    }
    if ("reason" in __overrides) {
      reason = __overrides["reason"];
      __stack.args["reason"] = reason;
    }
    if ("validCategories" in __overrides) {
      validCategories = __overrides["validCategories"];
      __stack.args["validCategories"] = validCategories;
    }
  }
  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: "handoff",
            args: {
              category,
              reason,
              validCategories
            },
            isBuiltin: false,
            moduleId: "stdlib/agent.agency"
          }
        });
      });
      await runner.ifElse(1, [
        {
          condition: async () => !await __callMethod(__stack.args.validCategories, "includes", {
            type: "positional",
            args: [__stack.args.category]
          }),
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __stack.locals.validList = await __callMethod(__stack.args.validCategories, "join", {
                type: "positional",
                args: [`, `]
              });
            });
            await runner2.step(1, async (runner3) => {
              __functionCompleted = true;
              runner3.halt(`Error: '${__stack.args.category}' is not a valid handoff target. Valid: ${__stack.locals.validList}. If the request is in scope for you, just answer it.`);
              return;
            });
          }
        }
      ]);
      await runner.step(2, async (runner2) => {
        getRuntimeContext().ctx.globals.set("stdlib/agent.agency", "_handoffTarget", __stack.args.category);
      });
      await runner.step(3, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(`Handoff scheduled \u2014 return now without further reply.`);
        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 handoff threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "handoff",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "handoff",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "handoff",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const handoff = __AgencyFunction.create({
  name: "handoff",
  module: "stdlib/agent.agency",
  fn: __handoff_impl,
  params: [{
    name: "category",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "reason",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "validCategories",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "handoff",
    description: `Re-route the user's current message to a different specialist.
  After you call this, your turn closes and the original message
  is re-routed to the chosen specialist. Anything you say after
  \`handoff()\` is discarded \u2014 return immediately.

  Bias toward staying: most follow-ups are continuations of the
  current topic. Only call this when the message clearly needs
  a different specialist's tools.

  @param category - The specialist to re-route to
  @param reason - Brief explanation (recorded for debugging)
  @param validCategories - PFA-bound by \`route()\` \u2014 do not set manually`,
    schema: z.object({ "category": z.string(), "reason": z.string(), "validCategories": z.array(z.string()) })
  },
  safe: true,
  exported: true
}, __toolRegistry);
async function __consumeHandoff_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("stdlib/agent.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/agent.agency", scopeName: "consumeHandoff", 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: "consumeHandoff",
            args: {},
            isBuiltin: false,
            moduleId: "stdlib/agent.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.result = getRuntimeContext().ctx.globals.get("stdlib/agent.agency", "_handoffTarget");
      });
      await runner.step(2, async (runner2) => {
        getRuntimeContext().ctx.globals.set("stdlib/agent.agency", "_handoffTarget", ``);
      });
      await runner.step(3, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(__stack.locals.result);
        return;
      });
    });
    if (runner.halted) {
      if (isFailure(runner.haltResult)) {
        runner.haltResult.retryable = runner.haltResult.retryable && __self.__retryable;
      }
      return runner.haltResult;
    }
  } catch (__error) {
    if (__error instanceof RestoreSignal) {
      throw __error;
    }
    if (__error instanceof GuardExceededError) {
      throw __error;
    }
    {
      const __errMsg = __error instanceof Error ? __error.message : String(__error);
      const __errStack = __error instanceof Error && __error.stack ? __error.stack : "";
      const __log = __createLogger(__ctx.logLevel);
      __log.error("Function consumeHandoff threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "consumeHandoff",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "consumeHandoff",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "consumeHandoff",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const consumeHandoff = __AgencyFunction.create({
  name: "consumeHandoff",
  module: "stdlib/agent.agency",
  fn: __consumeHandoff_impl,
  params: [],
  toolDefinition: {
    name: "consumeHandoff",
    description: `Read and clear the pending handoff target. Returns "" when no
  handoff was requested. Used internally by \`route()\`; exposed for
  tests + advanced users writing custom dispatch loops.`,
    schema: z.object({})
  },
  safe: true,
  exported: true
}, __toolRegistry);
async function __runOneTurn_impl(category, userMsg, config, allowHandoff) {
  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/agent.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["category"] = category;
  __stack.args["userMsg"] = userMsg;
  __stack.args["config"] = config;
  __stack.args["allowHandoff"] = allowHandoff;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/agent.agency", scopeName: "runOneTurn", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("category" in __overrides) {
      category = __overrides["category"];
      __stack.args["category"] = category;
    }
    if ("userMsg" in __overrides) {
      userMsg = __overrides["userMsg"];
      __stack.args["userMsg"] = userMsg;
    }
    if ("config" in __overrides) {
      config = __overrides["config"];
      __stack.args["config"] = config;
    }
    if ("allowHandoff" in __overrides) {
      allowHandoff = __overrides["allowHandoff"];
      __stack.args["allowHandoff"] = allowHandoff;
    }
  }
  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: "runOneTurn",
            args: {
              category,
              userMsg,
              config,
              allowHandoff
            },
            isBuiltin: false,
            moduleId: "stdlib/agent.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.reply = ``;
      });
      await runner.thread(2, "create", { label: __stack.args.category, summarize: true, session: __stack.args.category }, async (runner2) => {
        await runner2.step(0, async (runner3) => {
          __stack.locals.spec = __stack.args.config.agents[__stack.args.category];
        });
        await runner2.ifElse(1, [
          {
            condition: async () => __stack.locals.spec.memory === true,
            body: async (runner3) => {
              await runner3.step(0, async (runner4) => {
                __self.__retryable = false;
                const __funcResult = await __call(setMemoryId, {
                  type: "positional",
                  args: [__stack.args.category]
                });
                if (hasInterrupts(__funcResult)) {
                  await getRuntimeContext().ctx.pendingPromises.awaitAll();
                  runner4.halt(__funcResult);
                  return;
                }
              });
            }
          }
        ]);
        await runner2.step(2, async (runner3) => {
          __self.__retryable = false;
        });
        await runner2.ifElse(3, [
          {
            condition: async () => !getRuntimeContext().ctx.globals.get("stdlib/agent.agency", "_firstEntry")[__stack.args.category],
            body: async (runner3) => {
              await runner3.step(0, async (runner4) => {
                getRuntimeContext().ctx.globals.get("stdlib/agent.agency", "_firstEntry")[__stack.args.category] = true;
              });
              await runner3.step(1, async (runner4) => {
                __self.__retryable = false;
                const __funcResult = await __call(systemMessage, {
                  type: "positional",
                  args: [__stack.locals.spec.systemPrompt + (__stack.args.config.context || ``)]
                });
                if (hasInterrupts(__funcResult)) {
                  await getRuntimeContext().ctx.pendingPromises.awaitAll();
                  runner4.halt(__funcResult);
                  return;
                }
              });
            }
          }
        ]);
        await runner2.step(4, async (runner3) => {
          __self.__retryable = false;
        });
        await runner2.step(5, async (runner3) => {
          __stack.locals.tools = [...__stack.locals.spec.tools];
        });
        await runner2.ifElse(6, [
          {
            condition: async () => __stack.args.allowHandoff,
            body: async (runner3) => {
              await runner3.step(0, async (runner4) => {
                __stack.locals.validTargets = [];
              });
              await runner3.loop(1, await __call(keys, {
                type: "positional",
                args: [__stack.args.config.agents]
              }), async (c, _, runner4) => {
                await runner4.ifElse(0, [
                  {
                    condition: async () => c !== __stack.args.category,
                    body: async (runner5) => {
                      await runner5.step(0, async (runner6) => {
                        await __callMethod(__stack.locals.validTargets, "push", {
                          type: "positional",
                          args: [c]
                        });
                      });
                    }
                  }
                ]);
              });
              await runner3.step(2, async (runner4) => {
                await __callMethod(__stack.locals.tools, "push", {
                  type: "positional",
                  args: [await __callMethod(handoff, "partial", {
                    type: "named",
                    positionalArgs: [],
                    namedArgs: {
                      validCategories: __stack.locals.validTargets
                    }
                  })]
                });
              });
            }
          }
        ]);
        await runner2.step(7, async (runner3) => {
          __self.__removedTools = __self.__removedTools || [];
          __stack.locals.reply = await runPrompt({
            prompt: __stack.args.userMsg,
            messages: __threads().getOrCreateActive(),
            clientConfig: {
              "memory": __stack.locals.spec.memory === true,
              "tools": __stack.locals.tools
            },
            maxToolCallRounds: 10,
            removedTools: __self.__removedTools,
            checkpointInfo: runner3.getCheckpointInfo()
          });
          if (hasInterrupts(__stack.locals.reply)) {
            await getRuntimeContext().ctx.pendingPromises.awaitAll();
            runner3.halt(__stack.locals.reply);
            return;
          }
        });
      });
      await runner.step(3, async (runner2) => {
        __self.__retryable = false;
      });
      await runner.step(4, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(__stack.locals.reply);
        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 runOneTurn threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "runOneTurn",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "runOneTurn",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "runOneTurn",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const runOneTurn = __AgencyFunction.create({
  name: "runOneTurn",
  module: "stdlib/agent.agency",
  fn: __runOneTurn_impl,
  params: [{
    name: "category",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "userMsg",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "config",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "allowHandoff",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "runOneTurn",
    description: `Single iteration of route()'s hop loop. Owns the thread block,
  memory scoping, first-entry system-message seeding, and tool-array
  assembly. Returns the LLM's reply (string).`,
    schema: z.object({ "category": z.string(), "userMsg": z.string(), "config": RouterConfig, "allowHandoff": z.boolean() })
  },
  safe: false,
  exported: false
}, __toolRegistry);
async function __route_impl(config, userMsg) {
  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/agent.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["config"] = config;
  __stack.args["userMsg"] = userMsg;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/agent.agency", scopeName: "route", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("config" in __overrides) {
      config = __overrides["config"];
      __stack.args["config"] = config;
    }
    if ("userMsg" in __overrides) {
      userMsg = __overrides["userMsg"];
      __stack.args["userMsg"] = userMsg;
    }
  }
  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: "route",
            args: {
              config,
              userMsg
            },
            isBuiltin: false,
            moduleId: "stdlib/agent.agency"
          }
        });
      });
      await runner.ifElse(1, [
        {
          condition: async () => __stack.args.config.agents[__stack.args.config.start] === void 0,
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __functionCompleted = true;
              runner3.halt(`Error: start category '${__stack.args.config.start}' not in agents map`);
              return;
            });
          }
        }
      ]);
      await runner.step(2, async (runner2) => {
        __stack.locals.category = __stack.args.config.start;
      });
      await runner.step(3, async (runner2) => {
        __stack.locals.hop = 0;
      });
      await runner.step(4, async (runner2) => {
        __stack.locals.reply = ``;
      });
      await runner.step(5, async (runner2) => {
        __stack.locals.done = false;
      });
      await runner.whileLoop(6, async () => !__stack.locals.done && __stack.locals.hop < __stack.args.config.maxHops, async (runner2) => {
        await runner2.step(0, async (runner3) => {
          __stack.locals.reply = await __call(runOneTurn, {
            type: "positional",
            args: [__stack.locals.category, __stack.args.userMsg, __stack.args.config, true]
          });
          if (hasInterrupts(__stack.locals.reply)) {
            await getRuntimeContext().ctx.pendingPromises.awaitAll();
            runner3.halt(__stack.locals.reply);
            return;
          }
        });
        await runner2.step(1, async (runner3) => {
          __stack.locals.target = await __call(consumeHandoff, {
            type: "positional",
            args: []
          });
          if (hasInterrupts(__stack.locals.target)) {
            await getRuntimeContext().ctx.pendingPromises.awaitAll();
            runner3.halt(__stack.locals.target);
            return;
          }
        });
        await runner2.ifElse(2, [
          {
            condition: async () => __stack.locals.target === ``,
            body: async (runner3) => {
              await runner3.step(0, async (runner4) => {
                __stack.locals.done = true;
              });
            }
          }
        ], async (runner3) => {
          await runner3.step(1, async (runner4) => {
            __stack.locals.category = __stack.locals.target;
          });
          await runner3.step(2, async (runner4) => {
            __stack.locals.hop = __stack.locals.hop + 1;
          });
        });
      });
      await runner.ifElse(7, [
        {
          condition: async () => !__stack.locals.done,
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
            });
            await runner2.step(1, async (runner3) => {
              __stack.locals.reply = await __call(runOneTurn, {
                type: "positional",
                args: [__stack.locals.category, __stack.args.userMsg, __stack.args.config, false]
              });
              if (hasInterrupts(__stack.locals.reply)) {
                await getRuntimeContext().ctx.pendingPromises.awaitAll();
                runner3.halt(__stack.locals.reply);
                return;
              }
            });
          }
        }
      ]);
      await runner.step(8, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(__stack.locals.reply);
        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 route threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "route",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "route",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "route",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const route = __AgencyFunction.create({
  name: "route",
  module: "stdlib/agent.agency",
  fn: __route_impl,
  params: [{
    name: "config",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "userMsg",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "route",
    description: `Run one user turn through a multi-specialist agent. Owns the hop
  loop, handoff signal, and force-answer fallback. The router
  injects a \`handoff(category, reason)\` tool into each specialist's
  toolset so the LLM can re-route the message when it's out of scope.
  When \`maxHops\` is reached, the handoff tool is stripped from the
  last call so the LLM is forced to answer.

  @param config - Start category, per-category agent specs, max hops, optional context string
  @param userMsg - The user's input message for this turn`,
    schema: z.object({ "config": RouterConfig, "userMsg": z.string() })
  },
  safe: false,
  exported: true
}, __toolRegistry);
var stdin_default = graph;
const __sourceMap = { "stdlib/agent.agency:todoWrite": { "1": { "line": 92, "col": 2 }, "2": { "line": 93, "col": 2 } }, "stdlib/agent.agency:todoList": { "1": { "line": 100, "col": 2 } }, "stdlib/agent.agency:question": { "1": { "line": 107, "col": 2 }, "2": { "line": 110, "col": 2 } }, "stdlib/agent.agency:handoff": { "1": { "line": 202, "col": 2 }, "2": { "line": 206, "col": 2 }, "3": { "line": 207, "col": 2 }, "1.0": { "line": 203, "col": 4 }, "1.1": { "line": 204, "col": 4 } }, "stdlib/agent.agency:consumeHandoff": { "1": { "line": 222, "col": 2 }, "2": { "line": 223, "col": 2 }, "3": { "line": 224, "col": 2 } }, "stdlib/agent.agency:runOneTurn": { "1": { "line": 238, "col": 2 }, "2": { "line": 239, "col": 2 }, "4": { "line": 264, "col": 2 }, "2.0": { "line": 240, "col": 4 }, "2.1.0": { "line": 242, "col": 6 }, "2.1": { "line": 241, "col": 4 }, "2.3.0": { "line": 245, "col": 6 }, "2.3.1": { "line": 247, "col": 6 }, "2.3": { "line": 244, "col": 4 }, "2.5": { "line": 249, "col": 4 }, "2.6.0": { "line": 251, "col": 6 }, "2.6.1.0.0": { "line": 254, "col": 10 }, "2.6.1.0": { "line": 253, "col": 8 }, "2.6.1": { "line": 252, "col": 6 }, "2.6.2": { "line": 257, "col": 6 }, "2.6": { "line": 250, "col": 4 }, "2.7": { "line": 259, "col": 4 } }, "stdlib/agent.agency:route": { "1": { "line": 306, "col": 2 }, "2": { "line": 309, "col": 2 }, "3": { "line": 310, "col": 2 }, "4": { "line": 311, "col": 2 }, "5": { "line": 312, "col": 2 }, "6": { "line": 313, "col": 2 }, "7": { "line": 323, "col": 2 }, "8": { "line": 327, "col": 2 }, "1.0": { "line": 307, "col": 4 }, "6.0": { "line": 314, "col": 4 }, "6.1": { "line": 315, "col": 4 }, "6.2.0": { "line": 317, "col": 6 }, "6.2.1": { "line": 319, "col": 6 }, "6.2.2": { "line": 320, "col": 6 }, "6.2": { "line": 316, "col": 4 }, "7.1": { "line": 325, "col": 4 } } };
export {
  AgentSpec,
  RouterConfig,
  __getCheckpoints,
  __setDebugger,
  __setLLMClient,
  __setTraceFile,
  __sourceMap,
  __toolRegistry,
  approve,
  consumeHandoff,
  stdin_default as default,
  handoff,
  hasInterrupts,
  interrupt,
  isDebugger,
  isInterrupt,
  question,
  reject,
  respondToInterrupts,
  rewindFrom,
  route,
  todoList,
  todoWrite
};
