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 { dirname, basename } from "agency-lang/stdlib/path.js";
import { exists } from "agency-lang/stdlib/shell.js";
import { chooseOption, ChoiceItem } from "agency-lang/stdlib/ui.js";
import { _checkPolicy, _validatePolicy, _writePolicyFile } from "agency-lang/stdlib-lib/policy.js";
import { fileURLToPath } from "url";
import __process from "process";
import { z } from "agency-lang/zod";
import { nanoid } from "agency-lang";
import path from "path";
import {
  RuntimeContext,
  Runner,
  setupFunction,
  callHook,
  checkpoint as __checkpoint_impl,
  getCheckpoint as __getCheckpoint_impl,
  restore as __restore_impl,
  _run as __runtime_run_impl,
  interrupt,
  isInterrupt,
  hasInterrupts,
  isDebugger,
  respondToInterrupts as _respondToInterrupts,
  rewindFrom as _rewindFrom,
  RestoreSignal,
  GuardExceededError,
  __registerGlobalsInit,
  failure,
  isFailure,
  __tryCall,
  AgencyFunction as __AgencyFunction,
  UNSET as __UNSET,
  __call,
  __callMethod,
  __stateStack,
  getRuntimeContext,
  agencyStore,
  functionRefReviver as __functionRefReviver,
  DeterministicClient as __DeterministicClient,
  createLogger as __createLogger
} from "agency-lang/runtime";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const __cwd = __process.cwd();
const getDirname = () => __dirname;
const __globalCtx = new RuntimeContext({
  statelogConfig: {
    host: "https://statelog.adit.io",
    apiKey: __process.env["STATELOG_API_KEY"] || "",
    projectId: "agency-lang",
    debugMode: false,
    observability: true,
    logFile: "statelog.log"
  },
  smoltalkDefaults: {
    openAiApiKey: __process.env["OPENAI_API_KEY"] || "",
    googleApiKey: __process.env["GEMINI_API_KEY"] || "",
    model: "gpt-4o-mini",
    logLevel: "warn",
    statelog: {
      host: "https://statelog.adit.io",
      projectId: "smoltalk",
      apiKey: __process.env["STATELOG_SMOLTALK_API_KEY"] || "",
      traceId: nanoid()
    }
  },
  dirname: __dirname,
  logLevel: "info",
  traceConfig: {
    program: "stdlib/policy.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(dirname);
__registerTool(basename);
__registerTool(exists);
__registerTool(chooseOption);
__registerTool(ChoiceItem);
async function __initializeGlobals(__ctx) {
  if (__ctx.globals.isInitialized("stdlib/policy.agency")) {
    return;
  }
  __ctx.globals.markInitialized("stdlib/policy.agency");
  __ctx.globals.set("stdlib/policy.agency", "_opts", {
    "file": ``,
    "fields": {}
  });
  __ctx.globals.set("stdlib/policy.agency", "_policy", {});
  __ctx.globals.set("stdlib/policy.agency", "_loaded", false);
  __ctx.globals.set("stdlib/policy.agency", "_pendingSave", false);
}
__registerGlobalsInit("stdlib/policy.agency", __initializeGlobals);
async function __registerTopLevelCallbacks(__ctx) {
  __ctx.topLevelCallbacks = [];
}
__functionRefReviver.registry = __toolRegistry;
const InterruptDataKey = z.string();
const InterruptDataVal = z.string();
const InterruptKind = z.string();
const PolicyRule = z.object({ "match": z.union([z.record(z.string(), z.string()), z.null()]), "action": z.union([z.literal("approve"), z.literal("reject"), z.literal("propagate")]) });
const Policy = z.record(z.string(), z.array(PolicyRule));
const Decision = z.union([z.literal("approve"), z.literal("reject"), z.literal("approve-always"), z.literal("approve-always-here"), z.literal("reject-always")]);
const ScopedField = z.object({ "field": z.string(), "matchSubpaths": z.boolean() });
const ScopedRuleFields = z.record(z.string(), z.array(ScopedField));
async function __checkPolicy_impl(policy, interrupt2) {
  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/policy.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["policy"] = policy;
  __stack.args["interrupt"] = interrupt2;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/policy.agency", scopeName: "checkPolicy", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("policy" in __overrides) {
      policy = __overrides["policy"];
      __stack.args["policy"] = policy;
    }
    if ("interrupt" in __overrides) {
      interrupt2 = __overrides["interrupt"];
      __stack.args["interrupt"] = interrupt2;
    }
  }
  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: "checkPolicy",
            args: {
              policy,
              interrupt: interrupt2
            },
            isBuiltin: false,
            moduleId: "stdlib/policy.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __self.__retryable = false;
        __functionCompleted = true;
        runner2.halt(await __call(_checkPolicy, {
          type: "positional",
          args: [__stack.args.policy, __stack.args.interrupt]
        }));
        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 checkPolicy threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "checkPolicy",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "checkPolicy",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "checkPolicy",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const checkPolicy = __AgencyFunction.create({
  name: "checkPolicy",
  module: "stdlib/policy.agency",
  fn: __checkPolicy_impl,
  params: [{
    name: "policy",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "interrupt",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "checkPolicy",
    description: `Evaluate a policy against an interrupt. Returns approve(), reject(), or propagate() based on the first matching rule. Policy is a JSON object keyed by interrupt kind, where each kind maps to an ordered array of rules with optional match fields (glob patterns) and an action.`,
    schema: z.object({ "policy": z.record(z.string(), z.any()), "interrupt": z.record(z.string(), z.any()) })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __validatePolicy_impl(policy) {
  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/policy.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["policy"] = policy;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/policy.agency", scopeName: "validatePolicy", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("policy" in __overrides) {
      policy = __overrides["policy"];
      __stack.args["policy"] = policy;
    }
  }
  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: "validatePolicy",
            args: {
              policy
            },
            isBuiltin: false,
            moduleId: "stdlib/policy.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __self.__retryable = false;
        __functionCompleted = true;
        runner2.halt(await __call(_validatePolicy, {
          type: "positional",
          args: [__stack.args.policy]
        }));
        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 validatePolicy threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "validatePolicy",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "validatePolicy",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "validatePolicy",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const validatePolicy = __AgencyFunction.create({
  name: "validatePolicy",
  module: "stdlib/policy.agency",
  fn: __validatePolicy_impl,
  params: [{
    name: "policy",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "validatePolicy",
    description: `Validate that a policy object is well-formed. Returns { success: true } if valid, or { success: false, error: "..." } with a description of the problem.`,
    schema: z.object({ "policy": z.record(z.string(), z.any()) })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __buildScopedMatch_impl(intr, fields) {
  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/policy.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["intr"] = intr;
  __stack.args["fields"] = fields;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/policy.agency", scopeName: "buildScopedMatch", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("intr" in __overrides) {
      intr = __overrides["intr"];
      __stack.args["intr"] = intr;
    }
    if ("fields" in __overrides) {
      fields = __overrides["fields"];
      __stack.args["fields"] = fields;
    }
  }
  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: "buildScopedMatch",
            args: {
              intr,
              fields
            },
            isBuiltin: false,
            moduleId: "stdlib/policy.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.specs = [];
      });
      await runner.ifElse(2, [
        {
          condition: async () => __stack.args.fields[__stack.args.intr.kind] !== void 0,
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __stack.locals.specs = __stack.args.fields[__stack.args.intr.kind];
            });
          }
        }
      ]);
      await runner.step(3, async (runner2) => {
        __stack.locals.match = {};
      });
      await runner.loop(4, __stack.locals.specs, async (spec, _, runner2) => {
        await runner2.step(0, async (runner3) => {
          __stack.locals.value = __stack.args.intr.data[spec.field];
        });
        await runner2.ifElse(1, [
          {
            condition: async () => __stack.locals.value === null,
            body: async (runner3) => {
              await runner3.step(0, async (runner4) => {
                runner4.continueLoop();
                return;
              });
            }
          }
        ]);
        await runner2.ifElse(2, [
          {
            condition: async () => spec.matchSubpaths,
            body: async (runner3) => {
              await runner3.step(0, async (runner4) => {
                __stack.locals.match[spec.field] = `{${__stack.locals.value},${__stack.locals.value}/**}`;
              });
            }
          }
        ], async (runner3) => {
          await runner3.step(1, async (runner4) => {
            __stack.locals.match[spec.field] = __stack.locals.value;
          });
        });
      });
      await runner.step(5, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(__stack.locals.match);
        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 buildScopedMatch threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "buildScopedMatch",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "buildScopedMatch",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "buildScopedMatch",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const buildScopedMatch = __AgencyFunction.create({
  name: "buildScopedMatch",
  module: "stdlib/policy.agency",
  fn: __buildScopedMatch_impl,
  params: [{
    name: "intr",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "fields",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "buildScopedMatch",
    description: `Given the per-kind ScopedField[] config, build a match object pinned
  to the meaningful fields of this interrupt. Returns {} when the kind
  isn't in the fields map. Pure.`,
    schema: z.object({ "intr": z.record(z.string(), z.any()), "fields": ScopedRuleFields })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __recordRule_impl(policy, kind, 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("stdlib/policy.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["policy"] = policy;
  __stack.args["kind"] = kind;
  __stack.args["action"] = action;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/policy.agency", scopeName: "recordRule", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("policy" in __overrides) {
      policy = __overrides["policy"];
      __stack.args["policy"] = policy;
    }
    if ("kind" in __overrides) {
      kind = __overrides["kind"];
      __stack.args["kind"] = kind;
    }
    if ("action" in __overrides) {
      action = __overrides["action"];
      __stack.args["action"] = action;
    }
  }
  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: "recordRule",
            args: {
              policy,
              kind,
              action
            },
            isBuiltin: false,
            moduleId: "stdlib/policy.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.existing = __stack.args.policy[__stack.args.kind] || [];
      });
      await runner.step(2, async (runner2) => {
        __stack.locals.next = {
          ...__stack.args.policy,
          [__stack.args.kind]: [...__stack.locals.existing, {
            "action": __stack.args.action
          }]
        };
      });
      await runner.step(3, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(__stack.locals.next);
        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 recordRule threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "recordRule",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "recordRule",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "recordRule",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const recordRule = __AgencyFunction.create({
  name: "recordRule",
  module: "stdlib/policy.agency",
  fn: __recordRule_impl,
  params: [{
    name: "policy",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "kind",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "action",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "recordRule",
    description: `Return a new policy with a catch-all rule for \`kind\` appended.
  First-match-wins inside \`checkPolicy\`, so a single bare rule covers
  every future interrupt of that kind. Pure \u2014 no I/O.

  WARNING: append order matters. A second call for the same kind with
  a different action is dead \u2014 the earlier rule wins. Reset the kind's
  rules first if you want to flip a previous decision.`,
    schema: z.object({ "policy": Policy, "kind": InterruptKind, "action": z.union([z.literal("approve"), z.literal("reject")]) })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __recordScopedRule_impl(policy, intr, fields) {
  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/policy.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["policy"] = policy;
  __stack.args["intr"] = intr;
  __stack.args["fields"] = fields;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/policy.agency", scopeName: "recordScopedRule", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("policy" in __overrides) {
      policy = __overrides["policy"];
      __stack.args["policy"] = policy;
    }
    if ("intr" in __overrides) {
      intr = __overrides["intr"];
      __stack.args["intr"] = intr;
    }
    if ("fields" in __overrides) {
      fields = __overrides["fields"];
      __stack.args["fields"] = fields;
    }
  }
  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: "recordScopedRule",
            args: {
              policy,
              intr,
              fields
            },
            isBuiltin: false,
            moduleId: "stdlib/policy.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.match = await __call(buildScopedMatch, {
          type: "positional",
          args: [__stack.args.intr, __stack.args.fields]
        });
        if (hasInterrupts(__stack.locals.match)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__stack.locals.match);
          return;
        }
      });
      await runner.step(2, async (runner2) => {
        __stack.locals.existing = __stack.args.policy[__stack.args.intr.kind] || [];
      });
      await runner.step(3, async (runner2) => {
        __stack.locals.next = {
          ...__stack.args.policy,
          [__stack.args.intr.kind]: [{
            "match": __stack.locals.match,
            "action": `approve`
          }, ...__stack.locals.existing]
        };
      });
      await runner.step(4, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(__stack.locals.next);
        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 recordScopedRule threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "recordScopedRule",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "recordScopedRule",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "recordScopedRule",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const recordScopedRule = __AgencyFunction.create({
  name: "recordScopedRule",
  module: "stdlib/policy.agency",
  fn: __recordScopedRule_impl,
  params: [{
    name: "policy",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "intr",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "fields",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "recordScopedRule",
    description: `Return a new policy with a scoped approve rule prepended for the
  interrupt's kind. Prepended (not appended) so the more-specific
  rule wins over any later catch-all in first-match-wins order. Pure.`,
    schema: z.object({ "policy": Policy, "intr": z.record(z.string(), z.any()), "fields": ScopedRuleFields })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __parsePolicyFile_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("stdlib/policy.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: "stdlib/policy.agency", scopeName: "parsePolicyFile", 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: "parsePolicyFile",
            args: {
              path: path2
            },
            isBuiltin: false,
            moduleId: "stdlib/policy.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.dir = await __call(dirname, {
          type: "positional",
          args: [__stack.args.path]
        });
        if (hasInterrupts(__stack.locals.dir)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__stack.locals.dir);
          return;
        }
      });
      await runner.step(2, async (runner2) => {
        __stack.locals.name = await __call(basename, {
          type: "positional",
          args: [__stack.args.path]
        });
        if (hasInterrupts(__stack.locals.name)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__stack.locals.name);
          return;
        }
      });
      await runner.ifElse(3, [
        {
          condition: async () => !await __call(exists, {
            type: "positional",
            args: [__stack.locals.name, __stack.locals.dir]
          }),
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __functionCompleted = true;
              runner3.halt({});
              return;
            });
          }
        }
      ]);
      await runner.step(4, async (runner2) => {
        __self.__retryable = false;
        __stack.locals.readResult = await __call(read, {
          type: "positional",
          args: [__stack.locals.name, __stack.locals.dir]
        });
        if (hasInterrupts(__stack.locals.readResult)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__stack.locals.readResult);
          return;
        }
      });
      await runner.ifElse(5, [
        {
          condition: async () => await isFailure(__stack.locals.readResult),
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              const __funcResult = await __call(print, {
                type: "positional",
                args: [`Could not read ${__stack.args.path}: ${__stack.locals.readResult.error}`]
              });
              if (hasInterrupts(__funcResult)) {
                await getRuntimeContext().ctx.pendingPromises.awaitAll();
                runner3.halt(__funcResult);
                return;
              }
            });
            await runner2.step(1, async (runner3) => {
              __functionCompleted = true;
              runner3.halt({});
              return;
            });
          }
        }
      ]);
      await runner.step(6, async (runner2) => {
        __stack.locals.parsed = await __tryCall(async () => await __call(parseJSON, {
          type: "positional",
          args: [__stack.locals.readResult.value]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "parsePolicyFile",
          args: __stack.args
        });
      });
      await runner.ifElse(7, [
        {
          condition: async () => await isFailure(__stack.locals.parsed),
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              const __funcResult = await __call(print, {
                type: "positional",
                args: [`Malformed JSON in ${__stack.args.path}; ignoring and starting fresh.`]
              });
              if (hasInterrupts(__funcResult)) {
                await getRuntimeContext().ctx.pendingPromises.awaitAll();
                runner3.halt(__funcResult);
                return;
              }
            });
            await runner2.step(1, async (runner3) => {
              __functionCompleted = true;
              runner3.halt({});
              return;
            });
          }
        }
      ]);
      await runner.step(8, async (runner2) => {
        __stack.locals.valid = await __call(validatePolicy, {
          type: "positional",
          args: [__stack.locals.parsed.value]
        });
        if (hasInterrupts(__stack.locals.valid)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__stack.locals.valid);
          return;
        }
      });
      await runner.ifElse(9, [
        {
          condition: async () => !__stack.locals.valid.success,
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              const __funcResult = await __call(print, {
                type: "positional",
                args: [`Invalid policy in ${__stack.args.path} (${__stack.locals.valid.error}); ignoring and starting fresh.`]
              });
              if (hasInterrupts(__funcResult)) {
                await getRuntimeContext().ctx.pendingPromises.awaitAll();
                runner3.halt(__funcResult);
                return;
              }
            });
            await runner2.step(1, async (runner3) => {
              __functionCompleted = true;
              runner3.halt({});
              return;
            });
          }
        }
      ]);
      await runner.step(10, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(__stack.locals.parsed.value);
        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 parsePolicyFile threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "parsePolicyFile",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "parsePolicyFile",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "parsePolicyFile",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const parsePolicyFile = __AgencyFunction.create({
  name: "parsePolicyFile",
  module: "stdlib/policy.agency",
  fn: __parsePolicyFile_impl,
  params: [{
    name: "path",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "parsePolicyFile",
    description: `Read + parse + validate a policy file from disk. Returns {} on any
  failure (missing, unreadable, malformed JSON, invalid schema) with a
  warning to the user. Raises std::read.

  @param path - The policy file path`,
    schema: z.object({ "path": z.string() })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __writePolicyFile_impl(path2, policy, allowedPaths = __UNSET) {
  const __setupData = setupFunction();
  const __stack = __setupData.stack;
  const __step = __setupData.step;
  const __self = __setupData.self;
  const __ctx = getRuntimeContext().ctx;
  let __forked;
  let __functionCompleted = false;
  if (!__ctx.globals.isInitialized("stdlib/policy.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["path"] = path2;
  __stack.args["policy"] = policy;
  __stack.args["allowedPaths"] = allowedPaths === __UNSET ? [] : allowedPaths;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/policy.agency", scopeName: "writePolicyFile", 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;
    }
    if ("policy" in __overrides) {
      policy = __overrides["policy"];
      __stack.args["policy"] = policy;
    }
    if ("allowedPaths" in __overrides) {
      allowedPaths = __overrides["allowedPaths"];
      __stack.args["allowedPaths"] = allowedPaths;
    }
  }
  try {
    await agencyStore.run({
      ...getRuntimeContext(),
      ctx: __ctx,
      stack: __setupData.stateStack,
      threads: __setupData.threads
    }, async () => {
      await runner.hook(0, async () => {
        await callHook({
          name: "onFunctionStart",
          data: {
            functionName: "writePolicyFile",
            args: {
              path: path2,
              policy,
              allowedPaths
            },
            isBuiltin: false,
            moduleId: "stdlib/policy.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __tryCall(async () => await __call(_writePolicyFile, {
          type: "positional",
          args: [__stack.args.path, __stack.args.policy, __stack.args.allowedPaths]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "writePolicyFile",
          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 writePolicyFile threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "writePolicyFile",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "writePolicyFile",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "writePolicyFile",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const writePolicyFile = __AgencyFunction.create({
  name: "writePolicyFile",
  module: "stdlib/policy.agency",
  fn: __writePolicyFile_impl,
  params: [{
    name: "path",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "policy",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "allowedPaths",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "writePolicyFile",
    description: `Validate and write a policy to a JSON file. Throws if the policy is invalid. Set allowedPaths to restrict where the policy file may be written.

  @param path - The destination file path
  @param policy - The policy to write
  @param allowedPaths - Only allow writing under these path prefixes`,
    schema: z.object({ "path": z.string(), "policy": Policy, "allowedPaths": z.array(z.string()).nullable().describe("Default: []") })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __maybeLoad_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/policy.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/policy.agency", scopeName: "maybeLoad", 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: "maybeLoad",
            args: {},
            isBuiltin: false,
            moduleId: "stdlib/policy.agency"
          }
        });
      });
      await runner.ifElse(1, [
        {
          condition: async () => !getRuntimeContext().ctx.globals.get("stdlib/policy.agency", "_loaded"),
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              getRuntimeContext().ctx.globals.set("stdlib/policy.agency", "_loaded", true);
            });
            await runner2.handle(1, async (__data) => approve(), async (runner3) => {
              await runner3.step(0, async (runner4) => {
                getRuntimeContext().ctx.globals.set("stdlib/policy.agency", "_policy", await __call(parsePolicyFile, {
                  type: "positional",
                  args: [getRuntimeContext().ctx.globals.get("stdlib/policy.agency", "_opts").file]
                }));
                if (hasInterrupts(getRuntimeContext().ctx.globals.get("stdlib/policy.agency", "_policy"))) {
                  await getRuntimeContext().ctx.pendingPromises.awaitAll();
                  runner4.halt(getRuntimeContext().ctx.globals.get("stdlib/policy.agency", "_policy"));
                  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 maybeLoad threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "maybeLoad",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "maybeLoad",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "maybeLoad",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const maybeLoad = __AgencyFunction.create({
  name: "maybeLoad",
  module: "stdlib/policy.agency",
  fn: __maybeLoad_impl,
  params: [],
  toolDefinition: {
    name: "maybeLoad",
    description: "No description provided.",
    schema: z.object({})
  },
  safe: false,
  exported: false
}, __toolRegistry);
async function __maybeFlush_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/policy.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/policy.agency", scopeName: "maybeFlush", 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: "maybeFlush",
            args: {},
            isBuiltin: false,
            moduleId: "stdlib/policy.agency"
          }
        });
      });
      await runner.ifElse(1, [
        {
          condition: async () => getRuntimeContext().ctx.globals.get("stdlib/policy.agency", "_pendingSave"),
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              getRuntimeContext().ctx.globals.set("stdlib/policy.agency", "_pendingSave", false);
            });
            await runner2.handle(1, async (__data) => approve(), async (runner3) => {
              await runner3.step(0, async (runner4) => {
                const __funcResult = await __call(writePolicyFile, {
                  type: "positional",
                  args: [getRuntimeContext().ctx.globals.get("stdlib/policy.agency", "_opts").file, getRuntimeContext().ctx.globals.get("stdlib/policy.agency", "_policy"), []]
                });
                if (hasInterrupts(__funcResult)) {
                  await getRuntimeContext().ctx.pendingPromises.awaitAll();
                  runner4.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 maybeFlush threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "maybeFlush",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "maybeFlush",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "maybeFlush",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const maybeFlush = __AgencyFunction.create({
  name: "maybeFlush",
  module: "stdlib/policy.agency",
  fn: __maybeFlush_impl,
  params: [],
  toolDefinition: {
    name: "maybeFlush",
    description: "No description provided.",
    schema: z.object({})
  },
  safe: false,
  exported: false
}, __toolRegistry);
async function __flushPolicy_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/policy.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/policy.agency", scopeName: "flushPolicy", 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: "flushPolicy",
            args: {},
            isBuiltin: false,
            moduleId: "stdlib/policy.agency"
          }
        });
      });
      await runner.ifElse(1, [
        {
          condition: async () => getRuntimeContext().ctx.globals.get("stdlib/policy.agency", "_pendingSave"),
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              getRuntimeContext().ctx.globals.set("stdlib/policy.agency", "_pendingSave", false);
            });
            await runner2.handle(1, async (__data) => approve(), async (runner3) => {
              await runner3.step(0, async (runner4) => {
                const __funcResult = await __call(writePolicyFile, {
                  type: "positional",
                  args: [getRuntimeContext().ctx.globals.get("stdlib/policy.agency", "_opts").file, getRuntimeContext().ctx.globals.get("stdlib/policy.agency", "_policy"), []]
                });
                if (hasInterrupts(__funcResult)) {
                  await getRuntimeContext().ctx.pendingPromises.awaitAll();
                  runner4.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 flushPolicy threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "flushPolicy",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "flushPolicy",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "flushPolicy",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const flushPolicy = __AgencyFunction.create({
  name: "flushPolicy",
  module: "stdlib/policy.agency",
  fn: __flushPolicy_impl,
  params: [],
  toolDefinition: {
    name: "flushPolicy",
    description: "No description provided.",
    schema: z.object({})
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __describeScopedMatch_impl(intr) {
  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/policy.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["intr"] = intr;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/policy.agency", scopeName: "describeScopedMatch", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("intr" in __overrides) {
      intr = __overrides["intr"];
      __stack.args["intr"] = intr;
    }
  }
  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: "describeScopedMatch",
            args: {
              intr
            },
            isBuiltin: false,
            moduleId: "stdlib/policy.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.match = await __call(buildScopedMatch, {
          type: "positional",
          args: [__stack.args.intr, getRuntimeContext().ctx.globals.get("stdlib/policy.agency", "_opts").fields]
        });
        if (hasInterrupts(__stack.locals.match)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__stack.locals.match);
          return;
        }
      });
      await runner.step(2, async (runner2) => {
        __stack.locals.ks = await __call(keys, {
          type: "positional",
          args: [__stack.locals.match]
        });
        if (hasInterrupts(__stack.locals.ks)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__stack.locals.ks);
          return;
        }
      });
      await runner.ifElse(3, [
        {
          condition: async () => __stack.locals.ks.length === 0,
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __functionCompleted = true;
              runner3.halt(`(no scoped fields)`);
              return;
            });
          }
        }
      ]);
      await runner.step(4, async (runner2) => {
        __stack.locals.parts = [];
      });
      await runner.loop(5, __stack.locals.ks, async (k, _, runner2) => {
        await runner2.step(0, async (runner3) => {
          await __callMethod(__stack.locals.parts, "push", {
            type: "positional",
            args: [`${k}=${__stack.locals.match[k]}`]
          });
        });
      });
      await runner.step(6, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __callMethod(__stack.locals.parts, "join", {
          type: "positional",
          args: [`, `]
        }));
        return;
      });
    });
    if (runner.halted) {
      if (isFailure(runner.haltResult)) {
        runner.haltResult.retryable = runner.haltResult.retryable && __self.__retryable;
      }
      return runner.haltResult;
    }
  } catch (__error) {
    if (__error instanceof RestoreSignal) {
      throw __error;
    }
    if (__error instanceof GuardExceededError) {
      throw __error;
    }
    {
      const __errMsg = __error instanceof Error ? __error.message : String(__error);
      const __errStack = __error instanceof Error && __error.stack ? __error.stack : "";
      const __log = __createLogger(__ctx.logLevel);
      __log.error("Function describeScopedMatch threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "describeScopedMatch",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "describeScopedMatch",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "describeScopedMatch",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const describeScopedMatch = __AgencyFunction.create({
  name: "describeScopedMatch",
  module: "stdlib/policy.agency",
  fn: __describeScopedMatch_impl,
  params: [{
    name: "intr",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "describeScopedMatch",
    description: "No description provided.",
    schema: z.object({ "intr": z.any() })
  },
  safe: false,
  exported: false
}, __toolRegistry);
const AskUserResult = z.object({ "action": Decision, "reason": z.union([z.string(), z.null()]) });
async function __askUser_impl(intr) {
  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/policy.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["intr"] = intr;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/policy.agency", scopeName: "askUser", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("intr" in __overrides) {
      intr = __overrides["intr"];
      __stack.args["intr"] = intr;
    }
  }
  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: "askUser",
            args: {
              intr
            },
            isBuiltin: false,
            moduleId: "stdlib/policy.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
      });
      await runner.step(2, async (runner2) => {
        __stack.locals.kindFields = [];
      });
      await runner.ifElse(3, [
        {
          condition: async () => getRuntimeContext().ctx.globals.get("stdlib/policy.agency", "_opts").fields[__stack.args.intr.kind] !== void 0,
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __stack.locals.kindFields = getRuntimeContext().ctx.globals.get("stdlib/policy.agency", "_opts").fields[__stack.args.intr.kind];
            });
          }
        }
      ]);
      await runner.step(4, async (runner2) => {
        __stack.locals.scopedAvailable = __stack.locals.kindFields.length > 0;
      });
      await runner.step(5, async (runner2) => {
        __stack.locals.title = `Interrupt: ${__stack.args.intr.kind}`;
      });
      await runner.step(6, async (runner2) => {
        __stack.locals.body = `${__stack.args.intr.message}
data: ${await __callMethod(JSON, "stringify", {
          type: "positional",
          args: [__stack.args.intr.data]
        })}`;
      });
      await runner.step(7, async (runner2) => {
        __stack.locals.items = [{
          "key": `a`,
          "label": `approve once`
        }, {
          "key": `r`,
          "label": `reject once`
        }, {
          "key": `aa`,
          "label": `approve always (every future ${__stack.args.intr.kind})`
        }];
      });
      await runner.ifElse(8, [
        {
          condition: async () => __stack.locals.scopedAvailable,
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              await __callMethod(__stack.locals.items, "push", {
                type: "positional",
                args: [{
                  "key": `ap`,
                  "label": `approve always here (${await __call(describeScopedMatch, {
                    type: "positional",
                    args: [__stack.args.intr]
                  })})`
                }]
              });
            });
          }
        }
      ]);
      await runner.step(9, async (runner2) => {
        await __callMethod(__stack.locals.items, "push", {
          type: "positional",
          args: [{
            "key": `rr`,
            "label": `reject always`
          }]
        });
      });
      await runner.step(10, async (runner2) => {
        __self.__retryable = false;
        __stack.locals.answer = await __call(chooseOption, {
          type: "named",
          positionalArgs: [__stack.locals.title, __stack.locals.body, __stack.locals.items],
          namedArgs: {
            allowFreeText: true
          }
        });
        if (hasInterrupts(__stack.locals.answer)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__stack.locals.answer);
          return;
        }
      });
      await runner.ifElse(11, [
        {
          condition: async () => __stack.locals.answer === `a`,
          body: async (runner2) => {
            __functionCompleted = true;
            runner2.halt({
              "action": `approve`,
              "reason": null
            });
            return;
          }
        },
        {
          condition: async () => __stack.locals.answer === `r`,
          body: async (runner2) => {
            __functionCompleted = true;
            runner2.halt({
              "action": `reject`,
              "reason": null
            });
            return;
          }
        },
        {
          condition: async () => __stack.locals.answer === `aa`,
          body: async (runner2) => {
            __functionCompleted = true;
            runner2.halt({
              "action": `approve-always`,
              "reason": null
            });
            return;
          }
        },
        {
          condition: async () => __stack.locals.answer === `ap`,
          body: async (runner2) => {
            __functionCompleted = true;
            runner2.halt({
              "action": `approve-always-here`,
              "reason": null
            });
            return;
          }
        },
        {
          condition: async () => __stack.locals.answer === `rr`,
          body: async (runner2) => {
            __functionCompleted = true;
            runner2.halt({
              "action": `reject-always`,
              "reason": null
            });
            return;
          }
        }
      ], async (runner2) => {
        __functionCompleted = true;
        runner2.halt({
          "action": `reject`,
          "reason": __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 askUser threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "askUser",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "askUser",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "askUser",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const askUser = __AgencyFunction.create({
  name: "askUser",
  module: "stdlib/policy.agency",
  fn: __askUser_impl,
  params: [{
    name: "intr",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "askUser",
    description: "No description provided.",
    schema: z.object({ "intr": z.any() })
  },
  safe: false,
  exported: false
}, __toolRegistry);
async function ___handler_impl(intr) {
  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/policy.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["intr"] = intr;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/policy.agency", scopeName: "_handler", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("intr" in __overrides) {
      intr = __overrides["intr"];
      __stack.args["intr"] = intr;
    }
  }
  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: "_handler",
            args: {
              intr
            },
            isBuiltin: false,
            moduleId: "stdlib/policy.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        const __funcResult = await __call(maybeFlush, {
          type: "positional",
          args: []
        });
        if (hasInterrupts(__funcResult)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__funcResult);
          return;
        }
      });
      await runner.step(2, async (runner2) => {
        const __funcResult = await __call(maybeLoad, {
          type: "positional",
          args: []
        });
        if (hasInterrupts(__funcResult)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__funcResult);
          return;
        }
      });
      await runner.step(3, async (runner2) => {
        __stack.locals.decision = await __call(checkPolicy, {
          type: "positional",
          args: [getRuntimeContext().ctx.globals.get("stdlib/policy.agency", "_policy"), __stack.args.intr]
        });
        if (hasInterrupts(__stack.locals.decision)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__stack.locals.decision);
          return;
        }
      });
      await runner.ifElse(4, [
        {
          condition: async () => __stack.locals.decision.type === `approve`,
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __functionCompleted = true;
              runner3.halt(await approve());
              return;
            });
          }
        }
      ]);
      await runner.ifElse(5, [
        {
          condition: async () => __stack.locals.decision.type === `reject`,
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __functionCompleted = true;
              runner3.halt(await reject());
              return;
            });
          }
        }
      ]);
      await runner.step(6, async (runner2) => {
        __stack.locals.answer = await __call(askUser, {
          type: "positional",
          args: [__stack.args.intr]
        });
        if (hasInterrupts(__stack.locals.answer)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__stack.locals.answer);
          return;
        }
      });
      await runner.ifElse(7, [
        {
          condition: async () => __stack.locals.answer.action === `approve-always`,
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              getRuntimeContext().ctx.globals.set("stdlib/policy.agency", "_policy", await __call(recordRule, {
                type: "positional",
                args: [getRuntimeContext().ctx.globals.get("stdlib/policy.agency", "_policy"), __stack.args.intr.kind, `approve`]
              }));
              if (hasInterrupts(getRuntimeContext().ctx.globals.get("stdlib/policy.agency", "_policy"))) {
                await getRuntimeContext().ctx.pendingPromises.awaitAll();
                runner3.halt(getRuntimeContext().ctx.globals.get("stdlib/policy.agency", "_policy"));
                return;
              }
            });
            await runner2.step(1, async (runner3) => {
              getRuntimeContext().ctx.globals.set("stdlib/policy.agency", "_pendingSave", true);
            });
            await runner2.step(2, async (runner3) => {
              __functionCompleted = true;
              runner3.halt(await approve());
              return;
            });
          }
        }
      ]);
      await runner.ifElse(8, [
        {
          condition: async () => __stack.locals.answer.action === `approve-always-here`,
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              getRuntimeContext().ctx.globals.set("stdlib/policy.agency", "_policy", await __call(recordScopedRule, {
                type: "positional",
                args: [getRuntimeContext().ctx.globals.get("stdlib/policy.agency", "_policy"), __stack.args.intr, getRuntimeContext().ctx.globals.get("stdlib/policy.agency", "_opts").fields]
              }));
              if (hasInterrupts(getRuntimeContext().ctx.globals.get("stdlib/policy.agency", "_policy"))) {
                await getRuntimeContext().ctx.pendingPromises.awaitAll();
                runner3.halt(getRuntimeContext().ctx.globals.get("stdlib/policy.agency", "_policy"));
                return;
              }
            });
            await runner2.step(1, async (runner3) => {
              getRuntimeContext().ctx.globals.set("stdlib/policy.agency", "_pendingSave", true);
            });
            await runner2.step(2, async (runner3) => {
              __functionCompleted = true;
              runner3.halt(await approve());
              return;
            });
          }
        }
      ]);
      await runner.ifElse(9, [
        {
          condition: async () => __stack.locals.answer.action === `reject-always`,
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              getRuntimeContext().ctx.globals.set("stdlib/policy.agency", "_policy", await __call(recordRule, {
                type: "positional",
                args: [getRuntimeContext().ctx.globals.get("stdlib/policy.agency", "_policy"), __stack.args.intr.kind, `reject`]
              }));
              if (hasInterrupts(getRuntimeContext().ctx.globals.get("stdlib/policy.agency", "_policy"))) {
                await getRuntimeContext().ctx.pendingPromises.awaitAll();
                runner3.halt(getRuntimeContext().ctx.globals.get("stdlib/policy.agency", "_policy"));
                return;
              }
            });
            await runner2.step(1, async (runner3) => {
              getRuntimeContext().ctx.globals.set("stdlib/policy.agency", "_pendingSave", true);
            });
            await runner2.step(2, async (runner3) => {
              __functionCompleted = true;
              runner3.halt(await reject());
              return;
            });
          }
        }
      ]);
      await runner.ifElse(10, [
        {
          condition: async () => __stack.locals.answer.action === `approve`,
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __functionCompleted = true;
              runner3.halt(await approve());
              return;
            });
          }
        }
      ]);
      await runner.step(11, async (runner2) => {
      });
      await runner.ifElse(12, [
        {
          condition: async () => __stack.locals.answer.reason !== null,
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __functionCompleted = true;
              runner3.halt(await reject(__stack.locals.answer.reason));
              return;
            });
          }
        }
      ]);
      await runner.step(13, async (runner2) => {
      });
      await runner.step(14, async (runner2) => {
        __stack.locals.reason = await __call(input, {
          type: "positional",
          args: [`Why are you rejecting? (press enter to skip) `]
        });
        if (hasInterrupts(__stack.locals.reason)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__stack.locals.reason);
          return;
        }
      });
      await runner.ifElse(15, [
        {
          condition: async () => __stack.locals.reason === ``,
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __functionCompleted = true;
              runner3.halt(await reject());
              return;
            });
          }
        }
      ]);
      await runner.step(16, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await reject(__stack.locals.reason));
        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 _handler threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "_handler",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "_handler",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "_handler",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const _handler = __AgencyFunction.create({
  name: "_handler",
  module: "stdlib/policy.agency",
  fn: ___handler_impl,
  params: [{
    name: "intr",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "_handler",
    description: "No description provided.",
    schema: z.object({ "intr": z.any() })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __cliPolicyHandler_impl(opts) {
  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/policy.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["opts"] = opts;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/policy.agency", scopeName: "cliPolicyHandler", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("opts" in __overrides) {
      opts = __overrides["opts"];
      __stack.args["opts"] = opts;
    }
  }
  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: "cliPolicyHandler",
            args: {
              opts
            },
            isBuiltin: false,
            moduleId: "stdlib/policy.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        getRuntimeContext().ctx.globals.set("stdlib/policy.agency", "_opts", __stack.args.opts);
      });
      await runner.step(2, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(_handler);
        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 cliPolicyHandler threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "cliPolicyHandler",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "cliPolicyHandler",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "cliPolicyHandler",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const cliPolicyHandler = __AgencyFunction.create({
  name: "cliPolicyHandler",
  module: "stdlib/policy.agency",
  fn: __cliPolicyHandler_impl,
  params: [{
    name: "opts",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "cliPolicyHandler",
    description: `CLI sugar for an interactive policy handler. Owns load + save +
  prompt + record + return approve/reject. Install on the outermost
  \`handle\`. Call exactly ONCE per program \u2014 internal state is module-
  level.

  Users of this helper should bind the returned handler to a variable
  before using it with \`handle ... with\`, e.g.:

  const handler = cliPolicyHandler({ file: ..., fields: ... })
  handle { ... } with handler

  @param opts.file - Path to the on-disk policy file
  @param opts.fields - Per-kind config controlling the "approve-always-here" option`,
    schema: z.object({ "opts": z.object({ "file": z.string(), "fields": ScopedRuleFields }) })
  },
  safe: false,
  exported: true
}, __toolRegistry);
var stdin_default = graph;
const __sourceMap = { "stdlib/policy.agency:checkPolicy": { "1": { "line": 245, "col": 2 } }, "stdlib/policy.agency:validatePolicy": { "1": { "line": 261, "col": 2 } }, "stdlib/policy.agency:buildScopedMatch": { "1": { "line": 299, "col": 2 }, "2": { "line": 300, "col": 2 }, "3": { "line": 303, "col": 2 }, "4": { "line": 304, "col": 2 }, "5": { "line": 315, "col": 2 }, "2.0": { "line": 301, "col": 4 }, "4.0": { "line": 305, "col": 4 }, "4.1": { "line": 306, "col": 4 }, "4.2.0": { "line": 310, "col": 6 }, "4.2.1": { "line": 312, "col": 6 }, "4.2": { "line": 309, "col": 4 } }, "stdlib/policy.agency:recordRule": { "1": { "line": 353, "col": 2 }, "2": { "line": 354, "col": 2 }, "3": { "line": 360, "col": 2 } }, "stdlib/policy.agency:recordScopedRule": { "1": { "line": 388, "col": 2 }, "2": { "line": 389, "col": 2 }, "3": { "line": 390, "col": 2 }, "4": { "line": 397, "col": 2 } }, "stdlib/policy.agency:parsePolicyFile": { "1": { "line": 419, "col": 2 }, "2": { "line": 420, "col": 2 }, "3": { "line": 421, "col": 2 }, "4": { "line": 424, "col": 2 }, "5": { "line": 425, "col": 2 }, "6": { "line": 429, "col": 2 }, "7": { "line": 430, "col": 2 }, "8": { "line": 434, "col": 2 }, "9": { "line": 435, "col": 2 }, "10": { "line": 441, "col": 2 }, "3.0": { "line": 422, "col": 4 }, "5.0": { "line": 426, "col": 4 }, "5.1": { "line": 427, "col": 4 }, "7.0": { "line": 431, "col": 4 }, "7.1": { "line": 432, "col": 4 }, "9.0": { "line": 436, "col": 4 }, "9.1": { "line": 439, "col": 4 } }, "stdlib/policy.agency:writePolicyFile": { "1": { "line": 466, "col": 2 } }, "stdlib/policy.agency:maybeLoad": { "1": { "line": 474, "col": 2 }, "1.0": { "line": 475, "col": 4 }, "1.1.0": { "line": 477, "col": 4 }, "1.1": { "line": 477, "col": 4 } }, "stdlib/policy.agency:maybeFlush": { "1": { "line": 487, "col": 2 }, "1.0": { "line": 488, "col": 4 }, "1.1": { "line": 490, "col": 4 } }, "stdlib/policy.agency:flushPolicy": { "1": { "line": 506, "col": 2 }, "1.0": { "line": 507, "col": 4 }, "1.1": { "line": 508, "col": 4 } }, "stdlib/policy.agency:describeScopedMatch": { "1": { "line": 516, "col": 2 }, "2": { "line": 517, "col": 2 }, "3": { "line": 518, "col": 2 }, "4": { "line": 521, "col": 2 }, "5": { "line": 522, "col": 2 }, "6": { "line": 525, "col": 2 }, "3.0": { "line": 519, "col": 4 }, "5.0": { "line": 523, "col": 4 } }, "stdlib/policy.agency:askUser": { "2": { "line": 553, "col": 2 }, "3": { "line": 554, "col": 2 }, "4": { "line": 557, "col": 2 }, "5": { "line": 559, "col": 2 }, "6": { "line": 560, "col": 2 }, "7": { "line": 562, "col": 2 }, "8": { "line": 576, "col": 2 }, "9": { "line": 584, "col": 2 }, "10": { "line": 589, "col": 2 }, "11": { "line": 590, "col": 2 }, "3.0": { "line": 555, "col": 4 }, "8.0": { "line": 577, "col": 4 } }, "stdlib/policy.agency:_handler": { "1": { "line": 625, "col": 2 }, "2": { "line": 626, "col": 2 }, "3": { "line": 628, "col": 2 }, "4": { "line": 629, "col": 2 }, "5": { "line": 632, "col": 2 }, "6": { "line": 636, "col": 2 }, "7": { "line": 637, "col": 2 }, "8": { "line": 642, "col": 2 }, "9": { "line": 647, "col": 2 }, "10": { "line": 652, "col": 2 }, "12": { "line": 659, "col": 2 }, "14": { "line": 665, "col": 2 }, "15": { "line": 666, "col": 2 }, "16": { "line": 669, "col": 2 }, "4.0": { "line": 630, "col": 4 }, "5.0": { "line": 633, "col": 4 }, "7.0": { "line": 638, "col": 4 }, "7.1": { "line": 639, "col": 4 }, "7.2": { "line": 640, "col": 4 }, "8.0": { "line": 643, "col": 4 }, "8.1": { "line": 644, "col": 4 }, "8.2": { "line": 645, "col": 4 }, "9.0": { "line": 648, "col": 4 }, "9.1": { "line": 649, "col": 4 }, "9.2": { "line": 650, "col": 4 }, "10.0": { "line": 653, "col": 4 }, "12.0": { "line": 660, "col": 4 }, "15.0": { "line": 667, "col": 4 } }, "stdlib/policy.agency:cliPolicyHandler": { "1": { "line": 741, "col": 2 }, "2": { "line": 742, "col": 2 } } };
export {
  Decision,
  InterruptDataKey,
  InterruptDataVal,
  InterruptKind,
  Policy,
  PolicyRule,
  ScopedField,
  ScopedRuleFields,
  __getCheckpoints,
  __setDebugger,
  __setLLMClient,
  __setTraceFile,
  __sourceMap,
  __toolRegistry,
  _handler,
  approve,
  buildScopedMatch,
  checkPolicy,
  cliPolicyHandler,
  stdin_default as default,
  flushPolicy,
  hasInterrupts,
  interrupt,
  isDebugger,
  isInterrupt,
  parsePolicyFile,
  recordRule,
  recordScopedRule,
  reject,
  respondToInterrupts,
  rewindFrom,
  validatePolicy,
  writePolicyFile
};
