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 { _listThreadsRaw, _getThread, _setThreadSummary, _currentThreadId } from "agency-lang/stdlib-lib/threads.js";
import { fileURLToPath } from "url";
import __process from "process";
import { z } from "agency-lang/zod";
import { nanoid } from "agency-lang";
import path from "path";
import {
  RuntimeContext,
  Runner,
  setupFunction,
  runPrompt,
  callHook,
  checkpoint as __checkpoint_impl,
  getCheckpoint as __getCheckpoint_impl,
  restore as __restore_impl,
  _run as __runtime_run_impl,
  interrupt,
  isInterrupt,
  hasInterrupts,
  isDebugger,
  respondToInterrupts as _respondToInterrupts,
  rewindFrom as _rewindFrom,
  RestoreSignal,
  GuardExceededError,
  __registerGlobalsInit,
  success,
  failure,
  isFailure,
  __tryCall,
  AgencyFunction as __AgencyFunction,
  UNSET as __UNSET,
  __call,
  __callMethod,
  __threads,
  __stateStack,
  getRuntimeContext,
  agencyStore,
  functionRefReviver as __functionRefReviver,
  DeterministicClient as __DeterministicClient,
  createLogger as __createLogger
} from "agency-lang/runtime";
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const __cwd = __process.cwd();
const getDirname = () => __dirname;
const __globalCtx = new RuntimeContext({
  statelogConfig: {
    host: "https://statelog.adit.io",
    apiKey: __process.env["STATELOG_API_KEY"] || "",
    projectId: "agency-lang",
    debugMode: false,
    observability: true,
    logFile: "statelog.log"
  },
  smoltalkDefaults: {
    openAiApiKey: __process.env["OPENAI_API_KEY"] || "",
    googleApiKey: __process.env["GEMINI_API_KEY"] || "",
    model: "gpt-4o-mini",
    logLevel: "warn",
    statelog: {
      host: "https://statelog.adit.io",
      projectId: "smoltalk",
      apiKey: __process.env["STATELOG_SMOLTALK_API_KEY"] || "",
      traceId: nanoid()
    }
  },
  dirname: __dirname,
  logLevel: "info",
  traceConfig: {
    program: "stdlib/threads.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/threads.agency")) {
    return;
  }
  __ctx.globals.markInitialized("stdlib/threads.agency");
}
__registerGlobalsInit("stdlib/threads.agency", __initializeGlobals);
async function __registerTopLevelCallbacks(__ctx) {
  __ctx.topLevelCallbacks = [];
}
__functionRefReviver.registry = __toolRegistry;
const ThreadMessage = z.object({ "role": z.string(), "content": z.string() });
const ThreadInfo = z.object({ "id": z.string(), "label": z.union([z.string(), z.null()]), "summary": z.union([z.string(), z.null()]), "parentId": z.union([z.string(), z.null()]), "threadType": z.string(), "messageCount": z.number(), "isActive": z.boolean() });
const SummaryResult = z.object({ "summary": z.string() });
async function __summarize_impl(messages) {
  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/threads.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["messages"] = messages;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/threads.agency", scopeName: "summarize", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("messages" in __overrides) {
      messages = __overrides["messages"];
      __stack.args["messages"] = messages;
    }
  }
  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: "summarize",
            args: {
              messages
            },
            isBuiltin: false,
            moduleId: "stdlib/threads.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.transcript = ``;
      });
      await runner.loop(2, __stack.args.messages, async (m, _, runner2) => {
        await runner2.step(0, async (runner3) => {
          __stack.locals.transcript = __stack.locals.transcript + `[${m.role}] ${m.content}
`;
        });
      });
      await runner.step(3, async (runner2) => {
        __stack.locals.summary = ``;
      });
      await runner.thread(4, "create", { hidden: true }, async (runner2) => {
        await runner2.step(0, async (runner3) => {
          __self.__removedTools = __self.__removedTools || [];
          __stack.locals.r = await runPrompt({
            prompt: `Summarize this conversation in 1-2 sentences:
${__stack.locals.transcript}`,
            messages: __threads().getOrCreateActive(),
            responseFormat: z.object({
              response: SummaryResult
            }),
            clientConfig: {},
            maxToolCallRounds: 10,
            removedTools: __self.__removedTools,
            checkpointInfo: runner3.getCheckpointInfo()
          });
          if (hasInterrupts(__stack.locals.r)) {
            await getRuntimeContext().ctx.pendingPromises.awaitAll();
            runner3.halt(__stack.locals.r);
            return;
          }
        });
        await runner2.step(1, async (runner3) => {
          __stack.locals.summary = __stack.locals.r.summary;
        });
      });
      await runner.step(5, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(__stack.locals.summary);
        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 summarize threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "summarize",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "summarize",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "summarize",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const summarize = __AgencyFunction.create({
  name: "summarize",
  module: "stdlib/threads.agency",
  fn: __summarize_impl,
  params: [{
    name: "messages",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "summarize",
    description: `One-shot LLM summarization used by the lazy summarize path.
  Wrapped in a \`thread {}\` block so the summarizer prompt runs on
  an isolated message history and doesn't pollute the agent's main
  conversation. Uses structured output so the returned text comes
  back on a known field instead of free-form completion text.

  @param messages - The thread's messages to summarize`,
    schema: z.object({ "messages": z.array(ThreadMessage) })
  },
  safe: false,
  exported: false
}, __toolRegistry);
async function __summaryFor_impl(id, existing, messages) {
  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/threads.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["id"] = id;
  __stack.args["existing"] = existing;
  __stack.args["messages"] = messages;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/threads.agency", scopeName: "summaryFor", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("id" in __overrides) {
      id = __overrides["id"];
      __stack.args["id"] = id;
    }
    if ("existing" in __overrides) {
      existing = __overrides["existing"];
      __stack.args["existing"] = existing;
    }
    if ("messages" in __overrides) {
      messages = __overrides["messages"];
      __stack.args["messages"] = messages;
    }
  }
  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: "summaryFor",
            args: {
              id,
              existing,
              messages
            },
            isBuiltin: false,
            moduleId: "stdlib/threads.agency"
          }
        });
      });
      await runner.ifElse(1, [
        {
          condition: async () => __stack.args.existing !== null,
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __functionCompleted = true;
              runner3.halt(__stack.args.existing);
              return;
            });
          }
        }
      ]);
      await runner.step(2, async (runner2) => {
        __stack.locals.s = await __call(summarize, {
          type: "positional",
          args: [__stack.args.messages]
        });
        if (hasInterrupts(__stack.locals.s)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__stack.locals.s);
          return;
        }
      });
      await runner.step(3, async (runner2) => {
        __self.__retryable = false;
        const __funcResult = await __call(_setThreadSummary, {
          type: "positional",
          args: [__stack.args.id, __stack.locals.s]
        });
        if (hasInterrupts(__funcResult)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__funcResult);
          return;
        }
      });
      await runner.step(4, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(__stack.locals.s);
        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 summaryFor threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "summaryFor",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "summaryFor",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "summaryFor",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const summaryFor = __AgencyFunction.create({
  name: "summaryFor",
  module: "stdlib/threads.agency",
  fn: __summaryFor_impl,
  params: [{
    name: "id",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "existing",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "messages",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "summaryFor",
    description: "No description provided.",
    schema: z.object({ "id": z.string(), "existing": z.union([z.string(), z.null()]), "messages": z.array(ThreadMessage) })
  },
  safe: false,
  exported: false
}, __toolRegistry);
async function __listThreads_impl(lazySummarize = __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/threads.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["lazySummarize"] = lazySummarize === __UNSET ? true : lazySummarize;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/threads.agency", scopeName: "listThreads", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("lazySummarize" in __overrides) {
      lazySummarize = __overrides["lazySummarize"];
      __stack.args["lazySummarize"] = lazySummarize;
    }
  }
  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: "listThreads",
            args: {
              lazySummarize
            },
            isBuiltin: false,
            moduleId: "stdlib/threads.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __stack.locals.raw = await __tryCall(async () => await __call(_listThreadsRaw, {
          type: "positional",
          args: []
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "listThreads",
          args: __stack.args
        });
      });
      await runner.ifElse(2, [
        {
          condition: async () => await isFailure(__stack.locals.raw),
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __functionCompleted = true;
              runner3.halt(__stack.locals.raw);
              return;
            });
          }
        }
      ]);
      await runner.step(3, async (runner2) => {
        __stack.locals.out = [];
      });
      await runner.loop(4, __stack.locals.raw.value, async (t, _, runner2) => {
        await runner2.step(0, async (runner3) => {
          __stack.locals.summary = null;
        });
        await runner2.ifElse(1, [
          {
            condition: async () => __stack.args.lazySummarize,
            body: async (runner3) => {
              await runner3.step(0, async (runner4) => {
              });
              await runner3.ifElse(1, [
                {
                  condition: async () => t.isActive,
                  body: async (runner4) => {
                    await runner4.step(0, async (runner5) => {
                      __stack.locals.summary = t.summary;
                    });
                  }
                }
              ], async (runner4) => {
                await runner4.step(1, async (runner5) => {
                  __stack.locals.summary = await __call(summaryFor, {
                    type: "positional",
                    args: [t.id, t.summary, t.messages]
                  });
                  if (hasInterrupts(__stack.locals.summary)) {
                    await getRuntimeContext().ctx.pendingPromises.awaitAll();
                    runner5.halt(__stack.locals.summary);
                    return;
                  }
                });
              });
            }
          }
        ], async (runner3) => {
          await runner3.step(2, async (runner4) => {
          });
          await runner3.ifElse(3, [
            {
              condition: async () => t.summary !== null,
              body: async (runner4) => {
                await runner4.step(0, async (runner5) => {
                  __stack.locals.summary = t.summary;
                });
              }
            },
            {
              condition: async () => t.label !== null,
              body: async (runner4) => {
                await runner4.step(1, async (runner5) => {
                  __stack.locals.summary = t.label;
                });
              }
            }
          ], async (runner4) => {
            await runner4.step(2, async (runner5) => {
              __stack.locals.summary = ``;
            });
          });
        });
        await runner2.step(2, async (runner3) => {
          await __callMethod(__stack.locals.out, "push", {
            type: "positional",
            args: [{
              "id": t.id,
              "label": t.label,
              "summary": __stack.locals.summary,
              "parentId": t.parentId,
              "threadType": t.threadType,
              "messageCount": t.messageCount,
              "isActive": t.isActive
            }]
          });
        });
      });
      await runner.step(5, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await success(__stack.locals.out));
        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 listThreads threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "listThreads",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "listThreads",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "listThreads",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const listThreads = __AgencyFunction.create({
  name: "listThreads",
  module: "stdlib/threads.agency",
  fn: __listThreads_impl,
  params: [{
    name: "lazySummarize",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "listThreads",
    description: `Return every thread in the current run, including the active one.

  Summary generation: threads opened with \`thread(summarize: true)\`
  are summarized eagerly when they close (see the global onThreadEnd
  hook in \`lib/stdlib/threads.ts\`), so their summary is already
  cached by the time \`listThreads()\` runs. Threads that did NOT opt
  in eagerly trigger exactly one LLM round-trip the first time
  \`listThreads()\` is called on them (the "lazy" path). Active
  threads are skipped on both paths so the in-flight conversation
  is not summarized mid-stream. The computed summary is stashed on
  the underlying \`MessageThread\` so subsequent calls read it back
  without re-prompting.

  Pass \`lazySummarize: false\` to skip the on-demand LLM round-trip
  entirely. Threads without a cached summary fall back to their
  label (or \`""\` if no label is set), so the call stays free even
  when no eager summary is available. Useful in tests and in
  performance-sensitive surfaces where you'd rather see "no summary
  yet" than pay for one synchronously.

  Returns a \`Result\` \u2014 success holds \`ThreadInfo[]\`, failure holds
  the error (e.g. called outside an Agency frame). See
  [error handling](https://agency-lang.com/guide/error-handling).

  @param lazySummarize - When true (default), generate summaries
                         on-demand for any thread that doesn't have
                         one cached. When false, fall back to the
                         label (or \`""\`).`,
    schema: z.object({ "lazySummarize": z.boolean().nullable().describe("Default: true") })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __currentThreadId_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/threads.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/threads.agency", scopeName: "currentThreadId", 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: "currentThreadId",
            args: {},
            isBuiltin: false,
            moduleId: "stdlib/threads.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __call(_currentThreadId, {
          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 currentThreadId threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "currentThreadId",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "currentThreadId",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "currentThreadId",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const currentThreadId = __AgencyFunction.create({
  name: "currentThreadId",
  module: "stdlib/threads.agency",
  fn: __currentThreadId_impl,
  params: [],
  toolDefinition: {
    name: "currentThreadId",
    description: `Slug-form id of the active thread (e.g. "t3"), or \`""\` outside any
  runtime frame. Useful with \`thread(continue: id)\` when you want to
  capture a thread's id at the moment it was active so you can
  resume it later.`,
    schema: z.object({})
  },
  safe: true,
  exported: true
}, __toolRegistry);
async function __getThread_impl(id, offset = __UNSET, limit = __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/threads.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["id"] = id;
  __stack.args["offset"] = offset === __UNSET ? 0 : offset;
  __stack.args["limit"] = limit === __UNSET ? 50 : limit;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/threads.agency", scopeName: "getThread", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("id" in __overrides) {
      id = __overrides["id"];
      __stack.args["id"] = id;
    }
    if ("offset" in __overrides) {
      offset = __overrides["offset"];
      __stack.args["offset"] = offset;
    }
    if ("limit" in __overrides) {
      limit = __overrides["limit"];
      __stack.args["limit"] = limit;
    }
  }
  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: "getThread",
            args: {
              id,
              offset,
              limit
            },
            isBuiltin: false,
            moduleId: "stdlib/threads.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __tryCall(async () => await __call(_getThread, {
          type: "positional",
          args: [__stack.args.id, __stack.args.offset, __stack.args.limit]
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "getThread",
          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 getThread threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "getThread",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "getThread",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "getThread",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const getThread = __AgencyFunction.create({
  name: "getThread",
  module: "stdlib/threads.agency",
  fn: __getThread_impl,
  params: [{
    name: "id",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "offset",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "limit",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "getThread",
    description: `Read a slice of a thread's messages. Returns success holding \`[]\`
  for an unknown id; returns failure when called outside an Agency
  frame.

  Pagination: \`offset\` is 0-indexed; \`limit\` defaults to 50. Pass
  larger explicit values for full-thread reads.

  Returns a \`Result\` \u2014 success holds \`ThreadMessage[]\`. See
  [error handling](https://agency-lang.com/guide/error-handling).

  @param id - Thread slug (e.g. "t1") from \`listThreads()\`
  @param offset - 0-indexed start of the message slice
  @param limit - Maximum number of messages to return`,
    schema: z.object({ "id": z.string(), "offset": z.number().nullable().describe("Default: 0"), "limit": z.number().nullable().describe("Default: 50") })
  },
  safe: false,
  exported: true
}, __toolRegistry);
var stdin_default = graph;
const __sourceMap = { "stdlib/threads.agency:summarize": { "1": { "line": 71, "col": 2 }, "2": { "line": 72, "col": 2 }, "3": { "line": 75, "col": 2 }, "4": { "line": 76, "col": 2 }, "5": { "line": 80, "col": 2 }, "2.0": { "line": 73, "col": 4 }, "4.0": { "line": 77, "col": 4 }, "4.1": { "line": 78, "col": 4 } }, "stdlib/threads.agency:summaryFor": { "1": { "line": 90, "col": 2 }, "2": { "line": 93, "col": 2 }, "3": { "line": 94, "col": 2 }, "4": { "line": 95, "col": 2 }, "1.0": { "line": 91, "col": 4 } }, "stdlib/threads.agency:listThreads": { "1": { "line": 129, "col": 2 }, "2": { "line": 130, "col": 2 }, "3": { "line": 133, "col": 2 }, "4": { "line": 134, "col": 2 }, "5": { "line": 167, "col": 2 }, "2.0": { "line": 131, "col": 4 }, "4.0": { "line": 135, "col": 4 }, "4.1.1.0": { "line": 141, "col": 8 }, "4.1.1.1": { "line": 143, "col": 8 }, "4.1.1": { "line": 140, "col": 6 }, "4.1.3.0": { "line": 150, "col": 8 }, "4.1.3.1": { "line": 152, "col": 8 }, "4.1.3.2": { "line": 154, "col": 8 }, "4.1.3": { "line": 149, "col": 6 }, "4.1": { "line": 136, "col": 4 }, "4.2": { "line": 157, "col": 4 } }, "stdlib/threads.agency:currentThreadId": { "1": { "line": 177, "col": 2 } }, "stdlib/threads.agency:getThread": { "1": { "line": 196, "col": 2 } } };
export {
  ThreadInfo,
  ThreadMessage,
  __getCheckpoints,
  __setDebugger,
  __setLLMClient,
  __setTraceFile,
  __sourceMap,
  __toolRegistry,
  approve,
  currentThreadId,
  stdin_default as default,
  getThread,
  hasInterrupts,
  interrupt,
  isDebugger,
  isInterrupt,
  listThreads,
  reject,
  respondToInterrupts,
  rewindFrom
};
