import { print, printJSON, parseJSON, input, sleep, round, read, write, readImage, notify, range, mostCommon, keys, values, entries, emit, callback } from "agency-lang/stdlib/index.js";
import { _setMemoryId, _shouldRunMemory, _buildExtractionPrompt, _applyExtractionResult, _buildForgetPrompt, _applyForgetResult, _recall, _enableMemory, _disableMemory, _pushMemoryFrame, _popMemoryFrame } from "agency-lang/stdlib-lib/memory.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,
  failure,
  isFailure,
  __tryCall,
  AgencyFunction as __AgencyFunction,
  UNSET as __UNSET,
  __call,
  __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/memory.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/memory.agency")) {
    return;
  }
  __ctx.globals.markInitialized("stdlib/memory.agency");
}
__registerGlobalsInit("stdlib/memory.agency", __initializeGlobals);
async function __registerTopLevelCallbacks(__ctx) {
  __ctx.topLevelCallbacks = [];
}
__functionRefReviver.registry = __toolRegistry;
const ExtractionResult = z.object({ "entities": z.array(z.object({ "name": z.string(), "type": z.string(), "observations": z.array(z.string()) })), "relations": z.array(z.object({ "from": z.string(), "to": z.string(), "type": z.string() })), "expirations": z.array(z.object({ "entityName": z.string(), "observationContent": z.string() })) });
const ForgetResult = z.object({ "observations": z.array(z.object({ "entityName": z.string(), "observationContent": z.string() })), "relations": z.array(z.object({ "fromName": z.string(), "toName": z.string(), "type": z.string() })) });
const MemoryConfig = z.object({ "dir": z.string(), "model": z.union([z.string(), z.null()]), "autoExtract": z.union([z.object({ "interval": z.union([z.number(), z.null()]) }), z.null()]), "compaction": z.union([z.object({ "trigger": z.union([z.literal("token"), z.literal("messages"), z.null()]), "threshold": z.union([z.number(), z.null()]) }), z.null()]), "embeddings": z.union([z.object({ "model": z.union([z.string(), z.null()]) }), z.null()]) });
async function __isMemoryActive_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/memory.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/memory.agency", scopeName: "isMemoryActive", 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: "isMemoryActive",
            args: {},
            isBuiltin: false,
            moduleId: "stdlib/memory.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __self.__retryable = false;
        __functionCompleted = true;
        runner2.halt(await __call(_shouldRunMemory, {
          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 isMemoryActive threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "isMemoryActive",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "isMemoryActive",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "isMemoryActive",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const isMemoryActive = __AgencyFunction.create({
  name: "isMemoryActive",
  module: "stdlib/memory.agency",
  fn: __isMemoryActive_impl,
  params: [],
  toolDefinition: {
    name: "isMemoryActive",
    description: `Return \`true\` iff there is an active memory frame on the current
  branch's stateStack \u2014 i.e. memory is on and \`remember\`/\`recall\` will
  reach a real store. Returns \`false\` when memory was never enabled,
  was explicitly turned off via \`disableMemory()\`, or the call is
  outside any runtime frame.

  Useful for branching in user code (\`if (isMemoryActive()) { ... }\`)
  and for integration tests that want to verify push/pop semantics
  without poking at the stateStack directly.`,
    schema: z.object({})
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __setMemoryId_impl(id) {
  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/memory.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["id"] = id;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/memory.agency", scopeName: "setMemoryId", 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;
    }
  }
  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: "setMemoryId",
            args: {
              id
            },
            isBuiltin: false,
            moduleId: "stdlib/memory.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __self.__retryable = false;
        const __funcResult = await __call(_setMemoryId, {
          type: "positional",
          args: [__stack.args.id]
        });
        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 setMemoryId threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "setMemoryId",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "setMemoryId",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "setMemoryId",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const setMemoryId = __AgencyFunction.create({
  name: "setMemoryId",
  module: "stdlib/memory.agency",
  fn: __setMemoryId_impl,
  params: [{
    name: "id",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "setMemoryId",
    description: `Set the memory scope for this agent run. Call this before other
  memory operations to scope reads and writes to a specific user,
  thread, or workspace. If never called, the scope defaults to "default".

  Memory must be enabled (either via \`agency.json\` or via
  \`enableMemory(...)\`) for this to do anything; without configuration
  this is a no-op.

  The id is orthogonal to which memory frame is active \u2014 it persists
  across \`enableMemory\` / \`disableMemory\` calls. If you want a fresh
  scope when switching stores, call \`setMemoryId(...)\` explicitly.

  @param id - A unique identifier for the memory scope (e.g. user ID)`,
    schema: z.object({ "id": z.string() })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __enableMemory_impl(config) {
  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/memory.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["config"] = config;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/memory.agency", scopeName: "enableMemory", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("config" in __overrides) {
      config = __overrides["config"];
      __stack.args["config"] = config;
    }
  }
  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: "enableMemory",
            args: {
              config
            },
            isBuiltin: false,
            moduleId: "stdlib/memory.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __self.__retryable = false;
        const __funcResult = await __call(_enableMemory, {
          type: "positional",
          args: [__stack.args.config]
        });
        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 enableMemory threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "enableMemory",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "enableMemory",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "enableMemory",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const enableMemory = __AgencyFunction.create({
  name: "enableMemory",
  module: "stdlib/memory.agency",
  fn: __enableMemory_impl,
  params: [{
    name: "config",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "enableMemory",
    description: `Turn memory on for the current execution branch using \`config\`.

  Pushes a new memory frame onto the active stateStack. Storage is
  shared process-wide by absolute directory, so multiple calls
  (across runs, forks, or modules) that point at the same dir share
  one underlying store.

  Same-dir push is a no-op \u2014 the common pattern of declaring
  \`static const _ = enableMemory({...})\` AND calling
  \`enableMemory({...})\` from \`main()\` is safe. Pushing a different
  dir stacks the new frame on top; pop with \`disableMemory()\` or
  use the block form \`memory({...}) as { ... }\` for lexical scoping.

  \`config.dir\` is resolved against \`process.cwd()\` (NOT the module
  dir, deliberately \u2014 mirrors how \`agency.json\`'s \`memory.dir\` is
  resolved so the same string in JSON and in code points at the same
  place). The directory is auto-created if missing.

  Per-fork: each fork branch has its own frame stack, so an
  \`enableMemory\` in one branch does not affect siblings.

  @param config - Memory configuration with \`dir\` required`,
    schema: z.object({ "config": MemoryConfig })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __disableMemory_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/memory.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/memory.agency", scopeName: "disableMemory", 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: "disableMemory",
            args: {},
            isBuiltin: false,
            moduleId: "stdlib/memory.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __self.__retryable = false;
        const __funcResult = await __call(_disableMemory, {
          type: "positional",
          args: []
        });
        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 disableMemory threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "disableMemory",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "disableMemory",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "disableMemory",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const disableMemory = __AgencyFunction.create({
  name: "disableMemory",
  module: "stdlib/memory.agency",
  fn: __disableMemory_impl,
  params: [],
  toolDefinition: {
    name: "disableMemory",
    description: `Pop the top memory frame from the current branch's stateStack.

  Frame-scoped: a \`disableMemory()\` inside a fork branch only
  affects that branch.

  WARNING: this pops whatever is on top, including the JSON-seeded
  bottom frame from \`agency.json\`. Library authors should not call
  this casually \u2014 they will shadow the caller's configured memory.
  Prefer the block form \`memory({...}) as { ... }\` for lexical
  scoping, which restores the previous frame on exit.`,
    schema: z.object({})
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __memory_impl(config, 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/memory.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["config"] = config;
  __stack.args["block"] = block === __UNSET ? null : block;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/memory.agency", scopeName: "memory", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("config" in __overrides) {
      config = __overrides["config"];
      __stack.args["config"] = config;
    }
    if ("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: "memory",
            args: {
              config,
              block
            },
            isBuiltin: false,
            moduleId: "stdlib/memory.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __self.__retryable = false;
        __stack.locals.pushed = await __call(_pushMemoryFrame, {
          type: "positional",
          args: [__stack.args.config]
        });
        if (hasInterrupts(__stack.locals.pushed)) {
          await getRuntimeContext().ctx.pendingPromises.awaitAll();
          runner2.halt(__stack.locals.pushed);
          return;
        }
      });
      await runner.step(2, async (runner2) => {
        __stack.locals.result = await __tryCall(async () => await __call(block, {
          type: "positional",
          args: []
        }), {
          checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
          functionName: "memory",
          args: __stack.args
        });
      });
      await runner.ifElse(3, [
        {
          condition: async () => __stack.locals.pushed,
          body: async (runner2) => {
            await runner2.step(0, async (runner3) => {
              __self.__retryable = false;
              const __funcResult = await __call(_popMemoryFrame, {
                type: "positional",
                args: []
              });
              if (hasInterrupts(__funcResult)) {
                await getRuntimeContext().ctx.pendingPromises.awaitAll();
                runner3.halt(__funcResult);
                return;
              }
            });
          }
        }
      ]);
      await runner.step(4, async (runner2) => {
        __self.__retryable = false;
      });
      await runner.step(5, 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 memory threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "memory",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "memory",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "memory",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const memory = __AgencyFunction.create({
  name: "memory",
  module: "stdlib/memory.agency",
  fn: __memory_impl,
  params: [{
    name: "config",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }, {
    name: "block",
    hasDefault: true,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "memory",
    description: `Run \`block\` with \`config\` pushed as the active memory frame; pop
  the frame when the block returns (or fails). Mirrors the \`guard()\`
  pattern in \`std::thread\` so push/pop balancing flows through the
  same \`try\` expression \u2014 Agency has no \`finally\`, so the agency-side
  body uses \`try block()\` to capture the result and runs \`pop\` after.

  The pop only fires when the push actually happened: \`_pushMemoryFrame\`
  returns \`false\` if the new frame's dir matches the current top
  (dedup), and the matching no-pop preserves the caller's frame
  instead of unbalancing it. This fixes the prior \`_memoryBlock\`
  unbalanced-pop bug.

  Returns a \`Result\` (success holds the block's return value, failure
  holds an error from inside the block). Same convention as \`guard()\`.

  Example:
    const r = memory({ dir: "./mem-user-a" }) as {
      remember("alice's favorite color is blue")
    }

  @param config - Memory configuration with \`dir\` required
  @param block - The code to run with the frame active`,
    schema: z.object({ "config": MemoryConfig })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __remember_impl(content) {
  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/memory.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["content"] = content;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/memory.agency", scopeName: "remember", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("content" in __overrides) {
      content = __overrides["content"];
      __stack.args["content"] = content;
    }
  }
  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: "remember",
            args: {
              content
            },
            isBuiltin: false,
            moduleId: "stdlib/memory.agency"
          }
        });
      });
      await runner.ifElse(1, [
        {
          condition: async () => await __call(_shouldRunMemory, {
            type: "positional",
            args: []
          }),
          body: async (runner2) => {
            await runner2.thread(0, "create", {}, async (runner3) => {
              await runner3.step(0, async (runner4) => {
                __self.__retryable = false;
                __stack.locals.prompt = await __call(_buildExtractionPrompt, {
                  type: "positional",
                  args: [__stack.args.content]
                });
                if (hasInterrupts(__stack.locals.prompt)) {
                  await getRuntimeContext().ctx.pendingPromises.awaitAll();
                  runner4.halt(__stack.locals.prompt);
                  return;
                }
              });
              await runner3.step(1, async (runner4) => {
                __self.__removedTools = __self.__removedTools || [];
                __stack.locals.result = await runPrompt({
                  prompt: __stack.locals.prompt,
                  messages: __threads().getOrCreateActive(),
                  responseFormat: z.object({
                    response: ExtractionResult
                  }),
                  clientConfig: {},
                  maxToolCallRounds: 10,
                  removedTools: __self.__removedTools,
                  checkpointInfo: runner4.getCheckpointInfo()
                });
                if (hasInterrupts(__stack.locals.result)) {
                  await getRuntimeContext().ctx.pendingPromises.awaitAll();
                  runner4.halt(__stack.locals.result);
                  return;
                }
              });
              await runner3.step(2, async (runner4) => {
                __self.__retryable = false;
                const __funcResult = await __call(_applyExtractionResult, {
                  type: "positional",
                  args: [__stack.locals.result]
                });
                if (hasInterrupts(__funcResult)) {
                  await getRuntimeContext().ctx.pendingPromises.awaitAll();
                  runner4.halt(__funcResult);
                  return;
                }
              });
            });
            await runner2.step(1, async (runner3) => {
              __self.__retryable = false;
            });
          }
        }
      ]);
      await runner.step(2, async (runner2) => {
        __self.__retryable = false;
      });
    });
    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 remember threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "remember",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "remember",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "remember",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const remember = __AgencyFunction.create({
  name: "remember",
  module: "stdlib/memory.agency",
  fn: __remember_impl,
  params: [{
    name: "content",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "remember",
    description: `Extract and store structured facts from the given text into the
  knowledge graph. Uses the LLM to identify entities, observations,
  and relations.

  The LLM call is wrapped in a thread block so memory's prompts run
  on an isolated message history and don't pollute the agent's main
  conversation. Cost and tokens still flow through the runtime's
  per-run accounting.

  @param content - Natural language text containing facts to remember`,
    schema: z.object({ "content": z.string() })
  },
  safe: false,
  exported: true
}, __toolRegistry);
async function __recall_impl(query) {
  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/memory.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["query"] = query;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/memory.agency", scopeName: "recall", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("query" in __overrides) {
      query = __overrides["query"];
      __stack.args["query"] = query;
    }
  }
  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: "recall",
            args: {
              query
            },
            isBuiltin: false,
            moduleId: "stdlib/memory.agency"
          }
        });
      });
      await runner.step(1, async (runner2) => {
        __functionCompleted = true;
        runner2.halt(await __call(_recall, {
          type: "positional",
          args: [__stack.args.query]
        }));
        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 recall threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "recall",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "recall",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "recall",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const recall = __AgencyFunction.create({
  name: "recall",
  module: "stdlib/memory.agency",
  fn: __recall_impl,
  params: [{
    name: "query",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "recall",
    description: `Retrieve relevant facts from the knowledge graph as a formatted
  string. Combines structured lookup, embedding similarity, and
  LLM-powered retrieval; returns up to 10 entities ranked by match
  quality.

  Returns an empty string if memory is not configured or nothing matches.

  @param query - A natural language query describing what to recall`,
    schema: z.object({ "query": z.string() })
  },
  safe: true,
  exported: true
}, __toolRegistry);
async function __forget_impl(query) {
  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/memory.agency")) {
    await __initializeGlobals(__ctx);
  }
  let __funcStartTime = performance.now();
  __stack.args["query"] = query;
  __self.__retryable = __self.__retryable ?? true;
  const runner = new Runner(__ctx, __stack, { state: __stack, moduleId: "stdlib/memory.agency", scopeName: "forget", threads: __setupData.threads });
  let __resultCheckpointId = -1;
  if (__ctx._pendingArgOverrides) {
    const __overrides = __ctx._pendingArgOverrides;
    __ctx._pendingArgOverrides = void 0;
    if ("query" in __overrides) {
      query = __overrides["query"];
      __stack.args["query"] = query;
    }
  }
  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: "forget",
            args: {
              query
            },
            isBuiltin: false,
            moduleId: "stdlib/memory.agency"
          }
        });
      });
      await runner.ifElse(1, [
        {
          condition: async () => await __call(_shouldRunMemory, {
            type: "positional",
            args: []
          }),
          body: async (runner2) => {
            await runner2.thread(0, "create", {}, async (runner3) => {
              await runner3.step(0, async (runner4) => {
                __self.__retryable = false;
                __stack.locals.prompt = await __call(_buildForgetPrompt, {
                  type: "positional",
                  args: [__stack.args.query]
                });
                if (hasInterrupts(__stack.locals.prompt)) {
                  await getRuntimeContext().ctx.pendingPromises.awaitAll();
                  runner4.halt(__stack.locals.prompt);
                  return;
                }
              });
              await runner3.step(1, async (runner4) => {
                __self.__removedTools = __self.__removedTools || [];
                __stack.locals.result = await runPrompt({
                  prompt: __stack.locals.prompt,
                  messages: __threads().getOrCreateActive(),
                  responseFormat: z.object({
                    response: ForgetResult
                  }),
                  clientConfig: {},
                  maxToolCallRounds: 10,
                  removedTools: __self.__removedTools,
                  checkpointInfo: runner4.getCheckpointInfo()
                });
                if (hasInterrupts(__stack.locals.result)) {
                  await getRuntimeContext().ctx.pendingPromises.awaitAll();
                  runner4.halt(__stack.locals.result);
                  return;
                }
              });
              await runner3.step(2, async (runner4) => {
                __self.__retryable = false;
                const __funcResult = await __call(_applyForgetResult, {
                  type: "positional",
                  args: [__stack.locals.result]
                });
                if (hasInterrupts(__funcResult)) {
                  await getRuntimeContext().ctx.pendingPromises.awaitAll();
                  runner4.halt(__funcResult);
                  return;
                }
              });
            });
            await runner2.step(1, async (runner3) => {
              __self.__retryable = false;
            });
          }
        }
      ]);
      await runner.step(2, async (runner2) => {
        __self.__retryable = false;
      });
    });
    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 forget threw an exception (converted to Failure): " + __errMsg);
      if (__errStack) __log.error(__errStack);
      __ctx.statelogClient?.error?.({
        errorType: "runtimeError",
        message: __errMsg,
        functionName: "forget",
        retryable: __self.__retryable
      });
    }
    return failure(
      __error instanceof Error ? __error.message : String(__error),
      {
        checkpoint: getRuntimeContext().ctx.getResultCheckpoint(),
        retryable: __self.__retryable,
        functionName: "forget",
        args: __stack.args
      }
    );
  } finally {
    __stateStack()?.pop();
    if (__functionCompleted) {
      await callHook({
        name: "onFunctionEnd",
        data: {
          functionName: "forget",
          timeTaken: performance.now() - __funcStartTime
        }
      });
    }
  }
}
const forget = __AgencyFunction.create({
  name: "forget",
  module: "stdlib/memory.agency",
  fn: __forget_impl,
  params: [{
    name: "query",
    hasDefault: false,
    defaultValue: void 0,
    variadic: false
  }],
  toolDefinition: {
    name: "forget",
    description: `Soft-delete facts matching the query from the knowledge graph.
  Does not erase data \u2014 affected observations are marked with a
  validTo timestamp so the audit trail is preserved.

  The LLM call is wrapped in a thread block so memory's prompts run
  on an isolated message history and don't pollute the agent's main
  conversation.

  @param query - A natural language description of what to forget`,
    schema: z.object({ "query": z.string() })
  },
  safe: false,
  exported: true
}, __toolRegistry);
var stdin_default = graph;
const __sourceMap = { "stdlib/memory.agency:isMemoryActive": { "1": { "line": 59, "col": 2 } }, "stdlib/memory.agency:setMemoryId": { "1": { "line": 78, "col": 2 } }, "stdlib/memory.agency:enableMemory": { "1": { "line": 106, "col": 2 } }, "stdlib/memory.agency:disableMemory": { "1": { "line": 122, "col": 2 } }, "stdlib/memory.agency:memory": { "1": { "line": 150, "col": 2 }, "2": { "line": 151, "col": 2 }, "3": { "line": 152, "col": 2 }, "5": { "line": 155, "col": 2 }, "3.0": { "line": 153, "col": 4 } }, "stdlib/memory.agency:remember": { "1": { "line": 171, "col": 2 }, "1.0.0": { "line": 173, "col": 6 }, "1.0.1": { "line": 174, "col": 6 }, "1.0.2": { "line": 175, "col": 6 }, "1.0": { "line": 172, "col": 4 } }, "stdlib/memory.agency:recall": { "1": { "line": 191, "col": 2 } }, "stdlib/memory.agency:forget": { "1": { "line": 206, "col": 2 }, "1.0.0": { "line": 208, "col": 6 }, "1.0.1": { "line": 209, "col": 6 }, "1.0.2": { "line": 210, "col": 6 }, "1.0": { "line": 207, "col": 4 } } };
export {
  MemoryConfig,
  __getCheckpoints,
  __setDebugger,
  __setLLMClient,
  __setTraceFile,
  __sourceMap,
  __toolRegistry,
  approve,
  stdin_default as default,
  disableMemory,
  enableMemory,
  forget,
  hasInterrupts,
  interrupt,
  isDebugger,
  isInterrupt,
  isMemoryActive,
  memory,
  recall,
  reject,
  remember,
  respondToInterrupts,
  rewindFrom,
  setMemoryId
};
