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 { _systemMessage, _userMessage, _assistantMessage, _getCost, _getTokens, _pushGuard, _popGuard } from "agency-lang/stdlib-lib/thread.js";
import { fileURLToPath } from "url";
import __process from "process";
import { z } from "agency-lang/zod";
import { nanoid } from "agency-lang";
import path from "path";
import {
  RuntimeContext,
  Runner,
  setupFunction,
  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,
  __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/thread.agency"
  }
});
const graph = __globalCtx.graph;
function approve(value) {
  return { type: "approve", value };
}
function reject(value) {
  return { type: "reject", value };
}
function propagate() {
  return { type: "propagate" };
}
const respondToInterrupts = (interrupts, responses, opts) => _respondToInterrupts({ ctx: __globalCtx, interrupts, responses, overrides: opts?.overrides, metadata: opts?.metadata, registerTopLevelCallbacks: __registerTopLevelCallbacks, moduleDir: __dirname });
const rewindFrom = (checkpoint2, overrides, opts) => _rewindFrom({ ctx: __globalCtx, checkpoint: checkpoint2, overrides, metadata: opts?.metadata, registerTopLevelCallbacks: __registerTopLevelCallbacks, moduleDir: __dirname });
const __setDebugger = (dbg) => {
  __globalCtx.debuggerState = dbg;
};
const __setTraceFile = (filePath) => {
  __globalCtx.traceConfig.traceFile = filePath;
};
const __setLLMClient = (client) => {
  __globalCtx.setLLMClient(client);
};
const __getCheckpoints = () => __globalCtx.checkpoints;
if (__process.env.AGENCY_LLM_MOCKS) {
  __globalCtx.setLLMClient(
    new __DeterministicClient(JSON.parse(__process.env.AGENCY_LLM_MOCKS))
  );
}
const __toolRegistry = __functionRefReviver.registry ??= {};
function __registerTool(value, _aliasName) {
  if (__AgencyFunction.isAgencyFunction(value)) {
    __toolRegistry[`${value.module}:${value.name}`] = value;
  }
}
const checkpoint = __AgencyFunction.create({ name: "checkpoint", module: "__runtime", fn: __checkpoint_impl, params: [], toolDefinition: null }, __toolRegistry);
const getCheckpoint = __AgencyFunction.create({ name: "getCheckpoint", module: "__runtime", fn: __getCheckpoint_impl, params: [{ name: "checkpointId", hasDefault: false, defaultValue: void 0, variadic: false }], toolDefinition: null }, __toolRegistry);
const restore = __AgencyFunction.create({ name: "restore", module: "__runtime", fn: __restore_impl, params: [{ name: "checkpointIdOrCheckpoint", hasDefault: false, defaultValue: void 0, variadic: false }, { name: "options", hasDefault: false, defaultValue: void 0, variadic: false }], toolDefinition: null }, __toolRegistry);
const _run = __AgencyFunction.create({ name: "_run", module: "__runtime", fn: __runtime_run_impl, params: [{ name: "compiled", hasDefault: false, defaultValue: void 0, variadic: false }, { name: "node", hasDefault: false, defaultValue: void 0, variadic: false }, { name: "args", hasDefault: false, defaultValue: void 0, variadic: false }, { name: "wallClock", hasDefault: false, defaultValue: void 0, variadic: false }, { name: "memory", hasDefault: false, defaultValue: void 0, variadic: false }, { name: "ipcPayload", hasDefault: false, defaultValue: void 0, variadic: false }, { name: "stdout", hasDefault: false, defaultValue: void 0, variadic: false }], toolDefinition: null }, __toolRegistry);
function setLLMClient(client) {
  __globalCtx.setLLMClient(client);
}
function registerTools(tools) {
  for (const tool of tools) {
    if (__AgencyFunction.isAgencyFunction(tool)) {
      __toolRegistry[`${tool.module}:${tool.name}`] = tool;
    }
  }
}
__registerTool(print);
__registerTool(printJSON);
__registerTool(parseJSON);
__registerTool(input);
__registerTool(sleep);
__registerTool(round);
__registerTool(read);
__registerTool(write);
__registerTool(readImage);
__registerTool(notify);
__registerTool(range);
__registerTool(mostCommon);
__registerTool(keys);
__registerTool(values);
__registerTool(entries);
__registerTool(emit);
__registerTool(callback);
async function __initializeGlobals(__ctx) {
  if (__ctx.globals.isInitialized("stdlib/thread.agency")) {
    return;
  }
  __ctx.globals.markInitialized("stdlib/thread.agency");
}
__registerGlobalsInit("stdlib/thread.agency", __initializeGlobals);
async function __registerTopLevelCallbacks(__ctx) {
  __ctx.topLevelCallbacks = [];
}
__functionRefReviver.registry = __toolRegistry;
async function __systemMessage_impl(msg) {
  const __setupData = setupFunction();
  const __stack = __setupData.stack;
  const __step = __setupData.step;
  const __self = __setupData.self;
  const __ctx = getRuntimeContext().ctx;
  let __forked;
  let __functionCompleted = false;
  if (!__ctx.globals.isInitialized("stdlib/thread.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["msg"] = msg;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/thread.agency", scopeName: "systemMessage", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("msg" in __overrides) {
      msg = __overrides["msg"];
      __stack.args["msg"] = msg;
    }
  }
  try {
    await agencyStore.run({
      ...getRuntimeContext(),
      ctx: __ctx,
      stack: __setupData.stateStack,
      threads: __setupData.threads
    }, async () => {
      await runner.hook(0, async () => {
        await callHook({
          name: "onFunctionStart",
          data: {
            functionName: "systemMessage",
            args: {
              msg
            },
            isBuiltin: false,
            moduleId: "stdlib/thread.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __self.__retryable = false;
        const __funcResult = await __call(_systemMessage, {
          type: "positional",
          args: [__stack.args.msg]
        });
        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 systemMessage threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "systemMessage",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "systemMessage",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "systemMessage",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const systemMessage = __AgencyFunction.create({
  name: "systemMessage",
  module: "stdlib/thread.agency",
  fn: __systemMessage_impl,
  params: [{
    name: "msg",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "systemMessage",
    description: `Add a system message to the current thread's message history.
  The message becomes part of the conversation context for subsequent
  llm() calls.

  @param msg - The system message content`,
    schema: z.object({ "msg": z.string() })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __userMessage_impl(msg) {
  const __setupData = setupFunction();
  const __stack = __setupData.stack;
  const __step = __setupData.step;
  const __self = __setupData.self;
  const __ctx = getRuntimeContext().ctx;
  let __forked;
  let __functionCompleted = false;
  if (!__ctx.globals.isInitialized("stdlib/thread.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["msg"] = msg;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/thread.agency", scopeName: "userMessage", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("msg" in __overrides) {
      msg = __overrides["msg"];
      __stack.args["msg"] = msg;
    }
  }
  try {
    await agencyStore.run({
      ...getRuntimeContext(),
      ctx: __ctx,
      stack: __setupData.stateStack,
      threads: __setupData.threads
    }, async () => {
      await runner.hook(0, async () => {
        await callHook({
          name: "onFunctionStart",
          data: {
            functionName: "userMessage",
            args: {
              msg
            },
            isBuiltin: false,
            moduleId: "stdlib/thread.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __self.__retryable = false;
        const __funcResult = await __call(_userMessage, {
          type: "positional",
          args: [__stack.args.msg]
        });
        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 userMessage threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "userMessage",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "userMessage",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "userMessage",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const userMessage = __AgencyFunction.create({
  name: "userMessage",
  module: "stdlib/thread.agency",
  fn: __userMessage_impl,
  params: [{
    name: "msg",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "userMessage",
    description: `Add a user message to the current thread's message history.
  Use this when you want to seed the conversation with prior user
  context that wasn't actually typed by the user this turn.

  @param msg - The user message content`,
    schema: z.object({ "msg": z.string() })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __assistantMessage_impl(msg) {
  const __setupData = setupFunction();
  const __stack = __setupData.stack;
  const __step = __setupData.step;
  const __self = __setupData.self;
  const __ctx = getRuntimeContext().ctx;
  let __forked;
  let __functionCompleted = false;
  if (!__ctx.globals.isInitialized("stdlib/thread.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["msg"] = msg;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/thread.agency", scopeName: "assistantMessage", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("msg" in __overrides) {
      msg = __overrides["msg"];
      __stack.args["msg"] = msg;
    }
  }
  try {
    await agencyStore.run({
      ...getRuntimeContext(),
      ctx: __ctx,
      stack: __setupData.stateStack,
      threads: __setupData.threads
    }, async () => {
      await runner.hook(0, async () => {
        await callHook({
          name: "onFunctionStart",
          data: {
            functionName: "assistantMessage",
            args: {
              msg
            },
            isBuiltin: false,
            moduleId: "stdlib/thread.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __self.__retryable = false;
        const __funcResult = await __call(_assistantMessage, {
          type: "positional",
          args: [__stack.args.msg]
        });
        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 assistantMessage threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "assistantMessage",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "assistantMessage",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "assistantMessage",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const assistantMessage = __AgencyFunction.create({
  name: "assistantMessage",
  module: "stdlib/thread.agency",
  fn: __assistantMessage_impl,
  params: [{
    name: "msg",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "assistantMessage",
    description: `Add an assistant message to the current thread's message history.
  Use this to inject prior assistant turns when reconstructing a
  conversation programmatically.

  @param msg - The assistant message content`,
    schema: z.object({ "msg": z.string() })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __getCost_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/thread.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/thread.agency", scopeName: "getCost", 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: "getCost",
            args: {},
            isBuiltin: false,
            moduleId: "stdlib/thread.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __call(_getCost, {
          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 getCost threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "getCost",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "getCost",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "getCost",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const getCost = __AgencyFunction.create({
  name: "getCost",
  module: "stdlib/thread.agency",
  fn: __getCost_impl,
  params: [],
  toolDefinition: {
    name: "getCost",
    description: `Get the cumulative cost (USD, floating point) of all LLM calls
  contributing to the current execution branch.

  Inside a fork/race branch, this returns the parent's accumulated
  cost plus the cost incurred so far inside this branch. After all
  branches join, the parent sees the sum of its own cost plus every
  branch's cost (race losers included \u2014 their LLM calls really
  happened and cost real money).

  To measure a specific section, capture getCost() before and after:
    const before = getCost()
    // ... do work ...
    const sectionCost = getCost() - before`,
    schema: z.object({})
  },
  safe: true,
  exported: true
}, __toolRegistry);
async function __getTokens_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/thread.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/thread.agency", scopeName: "getTokens", 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: "getTokens",
            args: {},
            isBuiltin: false,
            moduleId: "stdlib/thread.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __call(_getTokens, {
          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 getTokens threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "getTokens",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "getTokens",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "getTokens",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const getTokens = __AgencyFunction.create({
  name: "getTokens",
  module: "stdlib/thread.agency",
  fn: __getTokens_impl,
  params: [],
  toolDefinition: {
    name: "getTokens",
    description: `Get the cumulative token count for the current execution branch.
  Same per-branch semantics as getCost().`,
    schema: z.object({})
  },
  safe: true,
  exported: true
}, __toolRegistry);
const GuardFailureData = z.object({ "type": z.string(), "maxCost": z.union([z.number(), z.null()]), "actualCost": z.union([z.number(), z.null()]), "maxTime": z.union([z.number(), z.null()]), "actualTime": z.union([z.number(), z.null()]) });
async function __guard_impl(cost = __UNSET, time = __UNSET, block = __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/thread.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["cost"] = cost === __UNSET ? null : cost;
  __stack.args["time"] = time === __UNSET ? null : time;
  __stack.args["block"] = block === __UNSET ? null : block;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/thread.agency", scopeName: "guard", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("cost" in __overrides) {
      cost = __overrides["cost"];
      __stack.args["cost"] = cost;
    }
    if ("time" in __overrides) {
      time = __overrides["time"];
      __stack.args["time"] = time;
    }
    if ("block" in __overrides) {
      block = __overrides["block"];
      __stack.args["block"] = block;
    }
  }
  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: "guard",
            args: {
              cost,
              time,
              block
            },
            isBuiltin: false,
            moduleId: "stdlib/thread.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __self.__retryable = false;
        __stack.locals.count = await __call(_pushGuard, {
          type: "positional",
          args: [__stack.args.cost, __stack.args.time]
        });
        if (hasInterrupts(__stack.locals.count)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__stack.locals.count);
          return;
        }
      });
      await runner.step(2, async (runner2) => {
        __stack.locals.result = await __tryCall(async () => await __call(block, {
          type: "positional",
          args: []
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "guard",
          args: __stack.args
        });
      });
      await runner.step(3, async (runner2) => {
        __self.__retryable = false;
        const __funcResult = await __call(_popGuard, {
          type: "positional",
          args: [__stack.locals.count]
        });
        if (hasInterrupts(__funcResult)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__funcResult);
          return;
        }
      });
      await runner.step(4, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(__stack.locals.result);
        return;
      });
    });
    if (runner.halted) {
      if (isFailure(runner.haltResult)) {
        runner.haltResult.retryable = runner.haltResult.retryable && __self.__retryable;
      }
      return runner.haltResult;
    }
  } catch (__error) {
    if (__error instanceof RestoreSignal) {
      throw __error;
    }
    if (__error instanceof GuardExceededError) {
      throw __error;
    }
    {
      const __errMsg = __error instanceof Error ? __error.message : String(__error);
      const __errStack = __error instanceof Error && __error.stack ? __error.stack : "";
      const __log = __createLogger(__ctx.logLevel);
      __log.error("Function guard threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "guard",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "guard",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "guard",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const guard = __AgencyFunction.create({
  name: "guard",
  module: "stdlib/thread.agency",
  fn: __guard_impl,
  params: [{
    name: "cost",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "time",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "block",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "guard",
    description: `Run a block under a cost limit, a time limit, or both. The block
  aborts as soon as either limit is exceeded; whichever fires first
  wins. At least one of \`cost\` or \`time\` must be supplied.

  On success, returns \`success(blockReturnValue)\`. The block's local
  variables are scoped to the block \u2014 only the block's return value
  is observable from the caller. Use isFailure(result) to branch on
  the trip; inspect \`result.error.type\` to distinguish:
    - "guardFailure" \u2014 cumulative LLM cost exceeded \`cost\`. Read
      \`result.error.maxCost\` and \`result.error.actualCost\`.
    - "timeoutFailure" \u2014 compute time inside the block exceeded
      \`time\`. Read \`result.error.maxTime\` and \`result.error.actualTime\`
      (milliseconds).

  Time semantics are compute-time: wall clock only ticks while a
  Runner is actively executing inside the guarded scope. Time spent
  paused on an interrupt (e.g. waiting for user input) does NOT count
  against the budget; on resume the timer is re-armed with the
  remaining budget.

  Nested guards are independent: an inner trip does not trip an outer
  guard. Fork/race branches: cost guards are cloned per branch (each
  branch independently tracks cost-since-push); time guards are NOT
  cloned \u2014 the parent's timer is the single source of truth and the
  abort cascade propagates to every branch.

  \`thread { ... }\` and \`subthread { ... }\` isolate message history
  but NOT cost or abort plumbing. A guard wrapping a thread block
  sees every LLM call inside it.

  Limitations: tool calls whose body is a JS function (rather than
  Agency code) cannot be aborted mid-execution \u2014 the JS function runs
  to completion in the background and its result is discarded. Memory
  layer LLM calls (memory.text / memory.embed) currently bypass cost
  guards. Cost deltas from inside a fork only propagate to an outer
  cost guard at fork completion, not mid-flight.

  @param cost - Maximum cost in dollars (e.g. $2.00 or 2.00). null = no cost limit.
  @param time - Maximum compute time in milliseconds (e.g. 30s, 5m, or a raw number). null = no time limit.
  @param block - The work to run under the guard.

  Example:
    const result = guard(cost: $2.0, time: 30s) as {
      const a = llm("step 1")
      const b = llm("step 2")
      return a + b
    }
    if (isFailure(result)) {
      print("Guard tripped: " + result.error.type)
    } else {
      print(result.value)
    }`,
    schema: z.object({ "cost": z.union([z.number(), z.null()]).nullable().describe("Default: null"), "time": z.union([z.number(), z.null()]).nullable().describe("Default: null") })
  },
  safe: false,
  exported: true
}, __toolRegistry);
var stdin_default = graph;
const __sourceMap = { "stdlib/thread.agency:systemMessage": { "1": { "line": 24, "col": 2 } }, "stdlib/thread.agency:userMessage": { "1": { "line": 35, "col": 2 } }, "stdlib/thread.agency:assistantMessage": { "1": { "line": 46, "col": 2 } }, "stdlib/thread.agency:getCost": { "1": { "line": 65, "col": 2 } }, "stdlib/thread.agency:getTokens": { "1": { "line": 73, "col": 2 } }, "stdlib/thread.agency:guard": { "1": { "line": 143, "col": 2 }, "2": { "line": 144, "col": 2 }, "3": { "line": 145, "col": 2 }, "4": { "line": 146, "col": 2 } } };
export {
  GuardFailureData,
  __getCheckpoints,
  __setDebugger,
  __setLLMClient,
  __setTraceFile,
  __sourceMap,
  __toolRegistry,
  approve,
  assistantMessage,
  stdin_default as default,
  getCost,
  getTokens,
  guard,
  hasInterrupts,
  interrupt,
  isDebugger,
  isInterrupt,
  reject,
  respondToInterrupts,
  rewindFrom,
  systemMessage,
  userMessage
};
