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 { map } from "agency-lang/stdlib/array.js";
import { writePolicyFile, Policy, InterruptKind, InterruptDataKey, InterruptDataVal } from "agency-lang/stdlib/policy.js";
import { highlight } from "agency-lang/stdlib/syntax.js";
import { args } from "agency-lang/stdlib/system.js";
import { systemMessage, userMessage, assistantMessage } 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,
  ThreadStore,
  Runner,
  setupNode,
  setupFunction,
  runNode,
  runPrompt,
  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,
  success,
  failure,
  isSuccess,
  isFailure,
  __validateType,
  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/policy/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(map);
__registerTool(writePolicyFile);
__registerTool(Policy);
__registerTool(InterruptKind);
__registerTool(InterruptDataKey);
__registerTool(InterruptDataVal);
__registerTool(highlight);
__registerTool(args);
__registerTool(systemMessage);
__registerTool(userMessage);
__registerTool(assistantMessage);
async function __initializeGlobals(__ctx) {
  if (__ctx.globals.isInitialized("dist/lib/agents/policy/agent.agency")) {
    return;
  }
  __ctx.globals.markInitialized("dist/lib/agents/policy/agent.agency");
  getRuntimeContext().ctx.pushHandler(async (__data) => approve());
  try {
    __ctx.globals.set("dist/lib/agents/policy/agent.agency", "systemPrompt", await __call(read, {
      type: "positional",
      args: [`system.md`, `./prompts`]
    }));
  } finally {
    getRuntimeContext().ctx.popHandler();
  }
  __ctx.globals.set("dist/lib/agents/policy/agent.agency", "currentPolicy", {});
}
__registerGlobalsInit("dist/lib/agents/policy/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/policy/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/policy/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/policy/agent.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        const __funcResult = await __call(print, {
          type: "positional",
          args: [`Calling ${__stack.args.data.toolName}...`]
        });
        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/policy/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/policy/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/policy/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/policy/agent.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        const __funcResult = await __call(print, {
          type: "positional",
          args: [`Finished calling ${__stack.args.data.toolName}.`]
        });
        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_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/policy/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);
const Question = z.object({ "type": z.literal("askQuestion"), "question": z.string() });
const Done = z.object({ "type": z.literal("done") });
const Action = z.union([Question, Done]);
const PolicyAction = z.union([z.literal("approve"), z.literal("reject"), z.literal("propagate")]);
async function __addToPolicy_impl(interruptKind, matchArgName, matchArgValue, action) {
  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/policy/agent.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["interruptKind"] = interruptKind;
  __stack.args["matchArgName"] = matchArgName;
  __stack.args["matchArgValue"] = matchArgValue;
  __stack.args["action"] = action;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "dist/lib/agents/policy/agent.agency", scopeName: "addToPolicy", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("interruptKind" in __overrides) {
      interruptKind = __overrides["interruptKind"];
      __stack.args["interruptKind"] = interruptKind;
    }
    if ("matchArgName" in __overrides) {
      matchArgName = __overrides["matchArgName"];
      __stack.args["matchArgName"] = matchArgName;
    }
    if ("matchArgValue" in __overrides) {
      matchArgValue = __overrides["matchArgValue"];
      __stack.args["matchArgValue"] = matchArgValue;
    }
    if ("action" in __overrides) {
      action = __overrides["action"];
      __stack.args["action"] = action;
    }
  }
  try {
    const __vr_action = __validateType(__stack.args["action"], PolicyAction);
    if (!__vr_action.success) {
      return __vr_action;
    }
    __stack.args["action"] = __vr_action.value;
    await agencyStore.run({
      ...getRuntimeContext(),
      ctx: __ctx,
      stack: __setupData.stateStack,
      threads: __setupData.threads
    }, async () => {
      await runner.hook(0, async () => {
        await callHook({
          name: "onFunctionStart",
          data: {
            functionName: "addToPolicy",
            args: {
              interruptKind,
              matchArgName,
              matchArgValue,
              action
            },
            isBuiltin: false,
            moduleId: "dist/lib/agents/policy/agent.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.match = {
          [__stack.args.matchArgName]: __stack.args.matchArgValue
        };
      });
      await runner.ifElse(2, [
        {
          condition: async () => !getRuntimeContext().ctx.globals.get("dist/lib/agents/policy/agent.agency", "currentPolicy")[__stack.args.interruptKind],
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              getRuntimeContext().ctx.globals.get("dist/lib/agents/policy/agent.agency", "currentPolicy")[__stack.args.interruptKind] = [];
            });
          }
        }
      ]);
      await runner.step(3, async (runner2) => {
        await __callMethod(getRuntimeContext().ctx.globals.get("dist/lib/agents/policy/agent.agency", "currentPolicy")[__stack.args.interruptKind], "push", {
          type: "positional",
          args: [{
            "match": __stack.locals.match,
            "action": __stack.args.action
          }]
        });
      });
      await runner.step(4, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await success(getRuntimeContext().ctx.globals.get("dist/lib/agents/policy/agent.agency", "currentPolicy")));
        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 addToPolicy threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "addToPolicy",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "addToPolicy",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "addToPolicy",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const addToPolicy = __AgencyFunction.create({
  name: "addToPolicy",
  module: "dist/lib/agents/policy/agent.agency",
  fn: __addToPolicy_impl,
  params: [{
    name: "interruptKind",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "matchArgName",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "matchArgValue",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "action",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "addToPolicy",
    description: `Add a rule to the current policy for the given interrupt kind, matching on the specified argument and value, with the specified action.
  Use only "approve", "reject", or "propagate" as the action. DO NOT use "allow" or "deny".
  Returns the current policy after adding the rule.`,
    schema: z.object({ "interruptKind": InterruptKind, "matchArgName": InterruptDataKey, "matchArgValue": InterruptDataVal, "action": PolicyAction })
  },
  safe: false,
  exported: false
}, __toolRegistry);
async function __getPolicy_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/policy/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/policy/agent.agency", scopeName: "getPolicy", 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: "getPolicy",
            args: {},
            isBuiltin: false,
            moduleId: "dist/lib/agents/policy/agent.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(getRuntimeContext().ctx.globals.get("dist/lib/agents/policy/agent.agency", "currentPolicy"));
        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 getPolicy threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "getPolicy",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "getPolicy",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "getPolicy",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const getPolicy = __AgencyFunction.create({
  name: "getPolicy",
  module: "dist/lib/agents/policy/agent.agency",
  fn: __getPolicy_impl,
  params: [],
  toolDefinition: {
    name: "getPolicy",
    description: `Get the current policy object.`,
    schema: z.object({})
  },
  safe: false,
  exported: false
}, __toolRegistry);
async function __setPolicy_impl(newPolicy) {
  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/policy/agent.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["newPolicy"] = newPolicy;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "dist/lib/agents/policy/agent.agency", scopeName: "setPolicy", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("newPolicy" in __overrides) {
      newPolicy = __overrides["newPolicy"];
      __stack.args["newPolicy"] = newPolicy;
    }
  }
  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: "setPolicy",
            args: {
              newPolicy
            },
            isBuiltin: false,
            moduleId: "dist/lib/agents/policy/agent.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        getRuntimeContext().ctx.globals.set("dist/lib/agents/policy/agent.agency", "currentPolicy", __stack.args.newPolicy);
      });
      await runner.step(2, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(getRuntimeContext().ctx.globals.get("dist/lib/agents/policy/agent.agency", "currentPolicy"));
        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 setPolicy threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "setPolicy",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "setPolicy",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "setPolicy",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const setPolicy = __AgencyFunction.create({
  name: "setPolicy",
  module: "dist/lib/agents/policy/agent.agency",
  fn: __setPolicy_impl,
  params: [{
    name: "newPolicy",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "setPolicy",
    description: `Replace the current policy with a new policy object. Returns the new policy.

  @param newPolicy - The new policy object to set as the current policy.`,
    schema: z.object({ "newPolicy": Policy })
  },
  safe: false,
  exported: false
}, __toolRegistry);
async function __deleteFromPolicy_impl(interruptKind, index) {
  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/policy/agent.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["interruptKind"] = interruptKind;
  __stack.args["index"] = index;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "dist/lib/agents/policy/agent.agency", scopeName: "deleteFromPolicy", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("interruptKind" in __overrides) {
      interruptKind = __overrides["interruptKind"];
      __stack.args["interruptKind"] = interruptKind;
    }
    if ("index" in __overrides) {
      index = __overrides["index"];
      __stack.args["index"] = index;
    }
  }
  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: "deleteFromPolicy",
            args: {
              interruptKind,
              index
            },
            isBuiltin: false,
            moduleId: "dist/lib/agents/policy/agent.agency"
          }
        });
      });
      await runner.ifElse(1, [
        {
          condition: async () => getRuntimeContext().ctx.globals.get("dist/lib/agents/policy/agent.agency", "currentPolicy")[__stack.args.interruptKind] && __stack.args.index < getRuntimeContext().ctx.globals.get("dist/lib/agents/policy/agent.agency", "currentPolicy")[__stack.args.interruptKind].length,
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              await __callMethod(getRuntimeContext().ctx.globals.get("dist/lib/agents/policy/agent.agency", "currentPolicy")[__stack.args.interruptKind], "splice", {
                type: "positional",
                args: [__stack.args.index, 1]
              });
            });
            await runner2.step(1, async (runner3) => {
              __functionCompleted = true;
              runner3.halt(true);
              return;
            });
          }
        }
      ]);
      await runner.step(2, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(false);
        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 deleteFromPolicy threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "deleteFromPolicy",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "deleteFromPolicy",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "deleteFromPolicy",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const deleteFromPolicy = __AgencyFunction.create({
  name: "deleteFromPolicy",
  module: "dist/lib/agents/policy/agent.agency",
  fn: __deleteFromPolicy_impl,
  params: [{
    name: "interruptKind",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "index",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "deleteFromPolicy",
    description: `Delete the rule at the specified index for the given interrupt kind from the current policy.
  Returns true if the rule was successfully deleted, or false if the index was out of bounds.`,
    schema: z.object({ "interruptKind": InterruptKind, "index": z.number() })
  },
  safe: false,
  exported: false
}, __toolRegistry);
async function __savePolicy_impl(path2) {
  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/policy/agent.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["path"] = path2;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "dist/lib/agents/policy/agent.agency", scopeName: "savePolicy", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("path" in __overrides) {
      path2 = __overrides["path"];
      __stack.args["path"] = path2;
    }
  }
  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: "savePolicy",
            args: {
              path: path2
            },
            isBuiltin: false,
            moduleId: "dist/lib/agents/policy/agent.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __self.__retryable = false;
        __functionCompleted = true;
        runner2.halt(await __call(writePolicyFile, {
          type: "positional",
          args: [__stack.args.path, getRuntimeContext().ctx.globals.get("dist/lib/agents/policy/agent.agency", "currentPolicy")]
        }));
        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 savePolicy threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "savePolicy",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "savePolicy",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "savePolicy",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const savePolicy = __AgencyFunction.create({
  name: "savePolicy",
  module: "dist/lib/agents/policy/agent.agency",
  fn: __savePolicy_impl,
  params: [{
    name: "path",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "savePolicy",
    description: `Validate and save the current policy to a JSON file.

  @param path - The file path where the policy should be saved.`,
    schema: z.object({ "path": z.string() })
  },
  safe: false,
  exported: false
}, __toolRegistry);
async function __get_impl(array, index) {
  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/policy/agent.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["array"] = array;
  __stack.args["index"] = index;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "dist/lib/agents/policy/agent.agency", scopeName: "get", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("array" in __overrides) {
      array = __overrides["array"];
      __stack.args["array"] = array;
    }
    if ("index" in __overrides) {
      index = __overrides["index"];
      __stack.args["index"] = index;
    }
  }
  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: "get",
            args: {
              array,
              index
            },
            isBuiltin: false,
            moduleId: "dist/lib/agents/policy/agent.agency"
          }
        });
      });
      await runner.ifElse(1, [
        {
          condition: async () => __stack.args.index < __stack.args.array.length,
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __functionCompleted = true;
              runner3.halt(await success(__stack.args.array[__stack.args.index]));
              return;
            });
          }
        }
      ]);
      await runner.step(2, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(failure(`Index out of bounds: ${__stack.args.index} >= ${__stack.args.array.length}`, { checkpoint: getRuntimeContext().ctx.getResultCheckpoint(), functionName: "get", args: __stack.args }));
        return;
      });
    });
    if (runner.halted) {
      if (isFailure(runner.haltResult)) {
        runner.haltResult.retryable = runner.haltResult.retryable && __self.__retryable;
      }
      return runner.haltResult;
    }
  } catch (__error) {
    if (__error instanceof RestoreSignal) {
      throw __error;
    }
    if (__error instanceof GuardExceededError) {
      throw __error;
    }
    {
      const __errMsg = __error instanceof Error ? __error.message : String(__error);
      const __errStack = __error instanceof Error && __error.stack ? __error.stack : "";
      const __log = __createLogger(__ctx.logLevel);
      __log.error("Function get threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "get",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "get",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "get",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const get = __AgencyFunction.create({
  name: "get",
  module: "dist/lib/agents/policy/agent.agency",
  fn: __get_impl,
  params: [{
    name: "array",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "index",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "get",
    description: "No description provided.",
    schema: z.object({ "array": z.array(z.any()), "index": z.number() })
  },
  safe: false,
  exported: false
}, __toolRegistry);
async function __highlightJSON_impl(obj) {
  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/policy/agent.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["obj"] = obj;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "dist/lib/agents/policy/agent.agency", scopeName: "highlightJSON", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("obj" in __overrides) {
      obj = __overrides["obj"];
      __stack.args["obj"] = obj;
    }
  }
  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: "highlightJSON",
            args: {
              obj
            },
            isBuiltin: false,
            moduleId: "dist/lib/agents/policy/agent.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __self.__retryable = false;
        __functionCompleted = true;
        runner2.halt(await __call(highlight, {
          type: "positional",
          args: [await __callMethod(JSON, "stringify", {
            type: "positional",
            args: [__stack.args.obj, null, 2]
          }), `json`]
        }));
        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 highlightJSON threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "highlightJSON",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "highlightJSON",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "highlightJSON",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const highlightJSON = __AgencyFunction.create({
  name: "highlightJSON",
  module: "dist/lib/agents/policy/agent.agency",
  fn: __highlightJSON_impl,
  params: [{
    name: "obj",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "highlightJSON",
    description: "No description provided.",
    schema: z.object({ "obj": z.record(z.string(), z.any()) })
  },
  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/policy/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) => {
        __stack.locals.cliArgs = await __call(args, {
          type: "positional",
          args: []
        });
        if (hasInterrupts(__stack.locals.cliArgs)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt({
            ...__state,
            data: __stack.locals.cliArgs
          });
          return;
        }
      });
      await runner.ifElse(2, [
        {
          condition: async () => __stack.locals.cliArgs.length < 2,
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              const __funcResult = await __call(print, {
                type: "positional",
                args: [`Usage: agency policy gen <file>`]
              });
              if (hasInterrupts(__funcResult)) {
                await getRuntimeContext().ctx.pendingPromises.awaitAll();
                runner3.halt({
                  ...__state,
                  data: __funcResult
                });
                return;
              }
            });
            await runner2.step(1, async (runner3) => {
              runner3.halt({
                messages: __threads(),
                data: void 0
              });
              return;
            });
          }
        }
      ]);
      await runner.step(3, async (runner2) => {
        __stack.locals.__pipe_0 = __stack.locals.cliArgs[0];
      });
      __stack.locals.interruptKinds = await runner.pipe(4, __stack.locals.__pipe_0, async (__pipeArg) => await __call(__readStatic(parseJSON, "parseJSON", "/Users/adityabhargava/agency-lang/packages/agency-lang/stdlib/index.agency"), {
        type: "positional",
        args: [__pipeArg]
      }));
      await runner.step(5, async (runner2) => {
        __stack.locals.outputPath = __stack.locals.cliArgs[1];
      });
      await runner.step(6, async (runner2) => {
        __stack.locals.__pipe_1 = await __call(get, {
          type: "positional",
          args: [__stack.locals.cliArgs, 2]
        });
      });
      __stack.locals.existingPolicy = await runner.pipe(7, __stack.locals.__pipe_1, async (__pipeArg) => await __call(__readStatic(parseJSON, "parseJSON", "/Users/adityabhargava/agency-lang/packages/agency-lang/stdlib/index.agency"), {
        type: "positional",
        args: [__pipeArg]
      }));
      await runner.ifElse(8, [
        {
          condition: async () => await isFailure(__stack.locals.interruptKinds),
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __stack.locals.error = __stack.locals.interruptKinds.error;
            });
            await runner2.step(1, async (runner3) => {
              const __funcResult = await __call(print, {
                type: "positional",
                args: [`Failed to parse interrupt kinds: ${__stack.locals.error}`]
              });
              if (hasInterrupts(__funcResult)) {
                await getRuntimeContext().ctx.pendingPromises.awaitAll();
                runner3.halt({
                  ...__state,
                  data: __funcResult
                });
                return;
              }
            });
            await runner2.step(2, async (runner3) => {
              runner3.halt({
                messages: __threads(),
                data: void 0
              });
              return;
            });
          }
        }
      ]);
      await runner.step(9, async (runner2) => {
        __self.__retryable = false;
        __stack.locals.contextMessage = `This agent can produce the following interrupts:
${await __callMethod(await await __call(map, {
          type: "named",
          positionalArgs: [__stack.locals.interruptKinds.value],
          namedArgs: {},
          blockArg: __AgencyFunction.create({ name: "__block_0", module: "dist/lib/agents/policy/agent.agency", fn: async (kind) => {
            const __bsetup = setupFunction();
            const __bstack = __bsetup.stack;
            const __self2 = __bstack.locals;
            __bstack.args["kind"] = kind;
            const runner3 = new Runner(__ctx, __bstack, { state: __bstack, moduleId: "dist/lib/agents/policy/agent.agency", scopeName: "__block_0" });
            try {
              await runner3.step(0, async (runner4) => {
                runner4.halt(`- ${__bstack.args.kind}
`);
                return;
              });
              return runner3.halted ? runner3.haltResult : void 0;
            } finally {
              __ctx.stateStack.pop();
            }
          }, params: [{ name: "kind", hasDefault: false, defaultValue: void 0, variadic: false }], toolDefinition: null }, __toolRegistry)
        }), "join", {
          type: "positional",
          args: [``]
        })}`;
      });
      await runner.ifElse(10, [
        {
          condition: async () => await isSuccess(__stack.locals.existingPolicy),
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __stack.locals.thePolicy = __stack.locals.existingPolicy.value;
            });
            await runner2.step(1, async (runner3) => {
              getRuntimeContext().ctx.globals.set("dist/lib/agents/policy/agent.agency", "currentPolicy", __stack.locals.thePolicy);
            });
            await runner2.step(2, async (runner3) => {
              __stack.locals.contextMessage = `
${__stack.locals.contextMessage}

Current policy:
\`\`\`json
${await __call(highlightJSON, {
                type: "positional",
                args: [getRuntimeContext().ctx.globals.get("dist/lib/agents/policy/agent.agency", "currentPolicy")]
              })}
\`\`\`

What would you like to change?
    `;
            });
          }
        }
      ], async (runner2) => {
        await runner2.step(3, async (runner3) => {
          __stack.locals.contextMessage = `
${__stack.locals.contextMessage}

What actions would you like to allow?
    `;
        });
      });
      await runner.step(11, async (runner2) => {
        const __funcResult = await __call(print, {
          type: "positional",
          args: [__stack.locals.contextMessage]
        });
        if (hasInterrupts(__funcResult)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt({
            ...__state,
            data: __funcResult
          });
          return;
        }
      });
      await runner.step(12, async (runner2) => {
        __stack.locals.userInput = await __call(input, {
          type: "positional",
          args: [`> `]
        });
        if (hasInterrupts(__stack.locals.userInput)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt({
            ...__state,
            data: __stack.locals.userInput
          });
          return;
        }
      });
      await runner.step(13, async (runner2) => {
        __stack.locals.prompt = `
  Current policy: ${await __callMethod(JSON, "stringify", {
          type: "positional",
          args: [getRuntimeContext().ctx.globals.get("dist/lib/agents/policy/agent.agency", "currentPolicy"), null, 2]
        })}

  Decide the next step. If the user is describing what they want, build or update the policy and use addToPolicy, setPolicy, or deleteFromPolicy. Show the user the policy and get confirmation that it looks good. When you are done, return  { type: "done" }. Otherwise, ask the user a question to clarify what they want, and return { type: "askQuestion", question: "..." }.
  `;
      });
      await runner.step(14, async (runner2) => {
        __self.__retryable = false;
        const __funcResult = await __call(systemMessage, {
          type: "positional",
          args: [getRuntimeContext().ctx.globals.get("dist/lib/agents/policy/agent.agency", "systemPrompt")]
        });
        if (hasInterrupts(__funcResult)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt({
            ...__state,
            data: __funcResult
          });
          return;
        }
      });
      await runner.step(15, async (runner2) => {
        __self.__retryable = false;
        const __funcResult = await __call(assistantMessage, {
          type: "positional",
          args: [__stack.locals.contextMessage]
        });
        if (hasInterrupts(__funcResult)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt({
            ...__state,
            data: __funcResult
          });
          return;
        }
      });
      await runner.step(16, async (runner2) => {
        __self.__retryable = false;
        const __funcResult = await __call(userMessage, {
          type: "positional",
          args: [__stack.locals.userInput]
        });
        if (hasInterrupts(__funcResult)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt({
            ...__state,
            data: __funcResult
          });
          return;
        }
      });
      await runner.step(17, async (runner2) => {
        __stack.locals.tools = [addToPolicy, getPolicy, setPolicy, deleteFromPolicy];
      });
      await runner.step(18, async (runner2) => {
        __self.__removedTools = __self.__removedTools || [];
        __stack.locals.action = await runPrompt({
          prompt: __stack.locals.prompt,
          messages: __threads().getOrCreateActive(),
          responseFormat: z.object({
            response: Action
          }),
          clientConfig: {
            "tools": __stack.locals.tools
          },
          maxToolCallRounds: 10,
          removedTools: __self.__removedTools,
          checkpointInfo: runner2.getCheckpointInfo()
        });
        if (hasInterrupts(__stack.locals.action)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt({
            messages: __threads(),
            data: __stack.locals.action
          });
          return;
        }
      });
      await runner.whileLoop(19, async () => __stack.locals.action.type !== `done`, async (runner2) => {
        await runner2.step(0, async (runner3) => {
          const __funcResult = await __call(print, {
            type: "positional",
            args: [__stack.locals.action.question]
          });
          if (hasInterrupts(__funcResult)) {
            await getRuntimeContext().ctx.pendingPromises.awaitAll();
            runner3.halt({
              ...__state,
              data: __funcResult
            });
            return;
          }
        });
        await runner2.step(1, async (runner3) => {
          __stack.locals.userInput = await __call(input, {
            type: "positional",
            args: [`> `]
          });
          if (hasInterrupts(__stack.locals.userInput)) {
            await getRuntimeContext().ctx.pendingPromises.awaitAll();
            runner3.halt({
              ...__state,
              data: __stack.locals.userInput
            });
            return;
          }
        });
        await runner2.step(2, async (runner3) => {
          __self.__removedTools = __self.__removedTools || [];
          __stack.locals.action = await runPrompt({
            prompt: __stack.locals.userInput,
            messages: __threads().getOrCreateActive(),
            responseFormat: z.object({
              response: Action
            }),
            clientConfig: {
              "tools": __stack.locals.tools
            },
            maxToolCallRounds: 10,
            removedTools: __self.__removedTools,
            checkpointInfo: runner3.getCheckpointInfo()
          });
          if (hasInterrupts(__stack.locals.action)) {
            await getRuntimeContext().ctx.pendingPromises.awaitAll();
            runner3.halt({
              messages: __threads(),
              data: __stack.locals.action
            });
            return;
          }
        });
      });
      await runner.step(20, async (runner2) => {
        const __funcResult = await __call(print, {
          type: "positional",
          args: [`Done. Final policy:`]
        });
        if (hasInterrupts(__funcResult)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt({
            ...__state,
            data: __funcResult
          });
          return;
        }
      });
      await runner.step(21, async (runner2) => {
        const __funcResult = await __call(printJSON, {
          type: "positional",
          args: [getRuntimeContext().ctx.globals.get("dist/lib/agents/policy/agent.agency", "currentPolicy")]
        });
        if (hasInterrupts(__funcResult)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt({
            ...__state,
            data: __funcResult
          });
          return;
        }
      });
      await runner.step(22, async (runner2) => {
        __stack.locals.result = await __call(savePolicy, {
          type: "positional",
          args: [__stack.locals.outputPath]
        });
        if (hasInterrupts(__stack.locals.result)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt({
            ...__state,
            data: __stack.locals.result
          });
          return;
        }
      });
      await runner.ifElse(23, [
        {
          condition: async () => await isFailure(__stack.locals.result),
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __stack.locals.error = __stack.locals.result.error;
            });
            await runner2.step(1, async (runner3) => {
              const __funcResult = await __call(print, {
                type: "positional",
                args: [`Failed to save policy: ${__stack.locals.error}`]
              });
              if (hasInterrupts(__funcResult)) {
                await getRuntimeContext().ctx.pendingPromises.awaitAll();
                runner3.halt({
                  ...__state,
                  data: __funcResult
                });
                return;
              }
            });
            await runner2.step(2, async (runner3) => {
              runner3.halt({
                messages: __threads(),
                data: void 0
              });
              return;
            });
          }
        }
      ]);
      await runner.step(24, async (runner2) => {
        const __funcResult = await __call(print, {
          type: "positional",
          args: [`Saved policy to ${__stack.locals.outputPath}.`]
        });
        if (hasInterrupts(__funcResult)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt({
            ...__state,
            data: __funcResult
          });
          return;
        }
      });
    });
    if (runner.halted) return runner.haltResult;
    await runner.hook(25, 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/policy/agent.agency:__cb_top_0": { "1": { "line": 13, "col": 2 } }, "dist/lib/agents/policy/agent.agency:__cb_top_1": { "1": { "line": 17, "col": 2 } }, "dist/lib/agents/policy/agent.agency:addToPolicy": { "1": { "line": 48, "col": 2 }, "2": { "line": 51, "col": 2 }, "3": { "line": 54, "col": 2 }, "4": { "line": 59, "col": 2 }, "2.0": { "line": 52, "col": 4 } }, "dist/lib/agents/policy/agent.agency:getPolicy": { "1": { "line": 66, "col": 2 } }, "dist/lib/agents/policy/agent.agency:setPolicy": { "1": { "line": 75, "col": 2 }, "2": { "line": 76, "col": 2 } }, "dist/lib/agents/policy/agent.agency:deleteFromPolicy": { "1": { "line": 84, "col": 2 }, "2": { "line": 88, "col": 2 }, "1.0": { "line": 85, "col": 4 }, "1.1": { "line": 86, "col": 4 } }, "dist/lib/agents/policy/agent.agency:savePolicy": { "1": { "line": 97, "col": 2 } }, "dist/lib/agents/policy/agent.agency:get": { "1": { "line": 101, "col": 2 }, "2": { "line": 104, "col": 2 }, "1.0": { "line": 102, "col": 4 } }, "dist/lib/agents/policy/agent.agency:highlightJSON": { "1": { "line": 108, "col": 2 } }, "dist/lib/agents/policy/agent.agency:main": { "1": { "line": 112, "col": 2 }, "2": { "line": 113, "col": 2 }, "3": { "line": 118, "col": 2 }, "4": { "line": 118, "col": 2 }, "5": { "line": 119, "col": 2 }, "6": { "line": 120, "col": 2 }, "7": { "line": 120, "col": 2 }, "8": { "line": 122, "col": 2 }, "9": { "line": 127, "col": 2 }, "10": { "line": 129, "col": 2 }, "11": { "line": 149, "col": 2 }, "12": { "line": 151, "col": 2 }, "13": { "line": 154, "col": 2 }, "14": { "line": 160, "col": 2 }, "15": { "line": 161, "col": 2 }, "16": { "line": 162, "col": 2 }, "17": { "line": 164, "col": 2 }, "18": { "line": 166, "col": 2 }, "19": { "line": 169, "col": 2 }, "20": { "line": 176, "col": 2 }, "21": { "line": 177, "col": 2 }, "22": { "line": 178, "col": 2 }, "23": { "line": 179, "col": 2 }, "24": { "line": 183, "col": 2 }, "2.0": { "line": 114, "col": 4 }, "2.1": { "line": 115, "col": 4 }, "8.0": { "line": 122, "col": 2 }, "8.1": { "line": 123, "col": 4 }, "8.2": { "line": 124, "col": 4 }, "10.0": { "line": 129, "col": 2 }, "10.1": { "line": 130, "col": 4 }, "10.2": { "line": 131, "col": 4 }, "10.3": { "line": 142, "col": 4 }, "19.0": { "line": 170, "col": 4 }, "19.1": { "line": 171, "col": 4 }, "19.2": { "line": 172, "col": 4 }, "23.0": { "line": 179, "col": 2 }, "23.1": { "line": 180, "col": 4 }, "23.2": { "line": 181, "col": 4 } }, "dist/lib/agents/policy/agent.agency:__block_0": {} };
export {
  __getCheckpoints,
  __mainNodeParams,
  __setDebugger,
  __setLLMClient,
  __setTraceFile,
  __sourceMap,
  __toolRegistry,
  approve,
  stdin_default as default,
  hasInterrupts,
  interrupt,
  isDebugger,
  isInterrupt,
  main,
  reject,
  respondToInterrupts,
  rewindFrom
};
