{"version":3,"sources":["../src/handoff.ts","../src/prepare-step.ts","../src/snapshot.ts","../src/agent.ts","../src/agent-recording.ts","../src/node/recording-file.ts"],"names":["AsyncLocalStorage","ZiroError","brandZiroError","z","defineTool","getTracer","ATTR","toolsToModelDefinitions","getCurrentBudget","tools","instrumentTools","fireAgentSuspended","fireAgentResumed","injectWorkingMemoryIntoMessages","generateText","isBudgetExceededError","executeToolCalls","baseMaxSteps","withBudget","BudgetExceededError","createReplayLanguageModel","readFile"],"mappings":";;;;;;;;;;;;AAmFO,IAAM,YAAA,GAAe,IAAIA,6BAAA,EAAgC;AAOzD,IAAM,gBAAA,GAAN,cAA+BC,cAAA,CAAU;AAAA,EAC5B,IAAA,GAAO,kBAAA;AAAA,EAChB,KAAA;AAAA,EACA,QAAA;AAAA,EACA,KAAA;AAAA,EAET,YAAY,IAAA,EAAqE;AAC/E,IAAA,KAAA;AAAA,MACE,CAAA,cAAA,EAAiB,IAAA,CAAK,KAAK,CAAA,cAAA,EAAiB,IAAA,CAAK,QAAQ,CAAA,SAAA,EAC7C,IAAA,CAAK,KAAA,CAAM,IAAA,CAAK,UAAK,CAAC,CAAA,+DAAA,CAAA;AAAA,MAElC,EAAE,MAAM,cAAA;AAAe,KACzB;AACA,IAAA,IAAA,CAAK,QAAQ,IAAA,CAAK,KAAA;AAClB,IAAA,IAAA,CAAK,WAAW,IAAA,CAAK,QAAA;AACrB,IAAA,IAAA,CAAK,QAAQ,IAAA,CAAK,KAAA;AAClB,IAAAC,mBAAA,CAAe,IAAI,CAAA;AAAA,EACrB;AACF,CAAA;AAEA,IAAM,kBAAA,GAAqBC,MAAE,MAAA,CAAO;AAAA,EAClC,QAAQA,KAAA,CACL,MAAA,GACA,QAAA,EAAS,CACT,SAAS,8DAA8D;AAC5E,CAAC,CAAA;AAcM,SAAS,gBAAA,CACd,SACA,OAAA,EACM;AACN,EAAA,MAAM,MAAA,GAAS,CAAC,WAAA,CAAY,OAAO,CAAA;AACnC,EAAA,MAAM,MAAA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A,CAAoC,KAAK,CAAA;AAC7E,EAAA,MAAM,KAAA,GAAQ,YAAA,CAAa,KAAA,IAAS,mCAAA,CAAoC,KAAK,CAAA;AAC7E,EAAA,MAAM,QAAQ,WAAA,CAAY,EAAE,GAAG,YAAA,EAAc,KAAA,EAAO,OAAO,CAAA;AAC3D,EAAA,OAAO,KAAA,CAAM,IAAI,UAAU,CAAA;AAC7B;AAGA,eAAsB,6BAAA,CACpB,KAAA,EACA,YAAA,EACA,UAAA,EACyB;AACzB,EAAA,OAAO,wBAAA,CAAyB,wBAAA,CAAyB,KAAK,CAAA,EAAG,cAAc,UAAU,CAAA;AAC3F;;;AC/NA,eAAsB,+BAAA,CACpB,aAAA,EACA,YAAA,EACA,UAAA,EACyB;AACzB,EAAA,MAAM,KAAA,GAAQ,MAAMY,iBAAA,CAAS,aAAA,EAAe,MAAM,CAAA;AAClD,EAAA,OAAO,6BAAA,CAA8B,KAAA,EAAO,YAAA,EAAc,UAAU,CAAA;AACtE","file":"node.cjs","sourcesContent":["/**\n * Multi-agent handoffs (RFC 0007).\n *\n * Allows an agent to delegate the conversation to another, specialised\n * agent by exposing each handoff as an LLM-callable tool named\n * `transfer_to_<agentName>`. The LLM picks the next agent the same way\n * it picks any other tool, so the routing decision is auditable in the\n * standard step trace.\n *\n * Per-handoff `inputFilter(messages)` controls how much of the parent's\n * message history is forwarded to the target agent — the documented\n * mitigation for context-pollution failure modes.\n *\n * Explicitly out of scope here: LLM-as-router (rejected in RFC 0007\n * §\"Explicitly NOT shipping\") and a graph engine (deferred to\n * `@ziro-agent/workflow`).\n */\n\nimport { AsyncLocalStorage } from 'node:async_hooks';\nimport { brandZiroError, type ChatMessage, ZiroError } from '@ziro-agent/core';\nimport { defineTool, type Tool } from '@ziro-agent/tools';\nimport { ATTR, getTracer } from '@ziro-agent/tracing';\nimport { z } from 'zod';\nimport type { Agent, AgentRunResult } from './agent.js';\n\n/**\n * Either an `Agent` (default `inputFilter` = passthrough) or an\n * explicit `HandoffSpec` for fine-grained control.\n */\nexport type Handoff = Agent | HandoffSpec;\n\nexport interface HandoffSpec {\n  /** Target sub-agent. Required. */\n  agent: Agent;\n  /**\n   * Transform the parent's message history before the sub-agent sees\n   * it. Default: passthrough. Common patterns:\n   *\n   *   `(msgs) => msgs.slice(-10)`           // last 10 messages only\n   *   `(msgs) => msgs.filter(m => m.role !== 'system')`  // strip parent's system prompt\n   *\n   * Documented production failure mode this mitigates: context\n   * pollution (sub-agent's reasoning derailed by irrelevant earlier\n   * turns).\n   */\n  inputFilter?: (messages: ChatMessage[]) => ChatMessage[];\n  /**\n   * Override the auto-derived tool description shown to the LLM.\n   * Default: `\"Transfer the conversation to the <name> agent. Use\n   * when the user's request requires its specialised capabilities.\"`\n   */\n  description?: string;\n}\n\n/**\n * Frame pushed onto AsyncLocalStorage for the duration of a single\n * agent run, so handoff tools (which receive only `(input, ctx)`) can\n * still see the parent's current `messages` and forward them.\n *\n * Internal — not exported from the package.\n */\nexport interface HandoffFrame {\n  messages: ChatMessage[];\n  /** Depth of nested handoff calls. Used by `maxHandoffDepth` guard. */\n  depth: number;\n  /**\n   * Shared mutable sink. Every frame opened during a single top-level\n   * `agent.run()` (including all nested handoff calls) points to the\n   * SAME object — mutating it is therefore visible to every enclosing\n   * agent loop, regardless of how deeply nested the throw originated.\n   *\n   * The `executeToolCalls` layer flattens any thrown `Error` to a\n   * plain `{ name, message }` (cross-realm safety) — losing the\n   * original `HandoffLoopError` instance. We stash the live error\n   * here BEFORE throwing so every parent agent loop above the\n   * deepest handoff can re-throw the rich object verbatim.\n   *\n   * @internal\n   */\n  loopErrorSink: { error?: HandoffLoopError };\n}\n\n/** @internal */\nexport const handoffStore = new AsyncLocalStorage<HandoffFrame>();\n\n/**\n * Thrown when a chain of handoffs exceeds `maxHandoffDepth`. Helps\n * catch the \"triage agent calls itself\" recursive misconfiguration\n * before it costs real money.\n */\nexport class HandoffLoopError extends ZiroError {\n  override readonly name = 'HandoffLoopError';\n  readonly depth: number;\n  readonly maxDepth: number;\n  readonly chain: readonly string[];\n\n  constructor(args: { depth: number; maxDepth: number; chain: readonly string[] }) {\n    super(\n      `Handoff depth ${args.depth} exceeded max ${args.maxDepth}. ` +\n        `Chain: ${args.chain.join(' → ')}. ` +\n        `Configure CreateAgentOptions.maxHandoffDepth or fix the loop.`,\n      { code: 'handoff_loop' },\n    );\n    this.depth = args.depth;\n    this.maxDepth = args.maxDepth;\n    this.chain = args.chain;\n    brandZiroError(this);\n  }\n}\n\nconst handoffInputSchema = z.object({\n  reason: z\n    .string()\n    .optional()\n    .describe('Optional one-sentence justification for choosing this agent.'),\n});\n\n/**\n * Build the LLM-facing tool that, when invoked, runs the target agent\n * with the (filtered) message history and returns its `text` output as\n * the tool result.\n *\n * The tool name follows the convention\n * `transfer_to_<sanitised_agent_name>` — sanitisation lower-cases and\n * replaces non-`[a-z0-9_]` runs with `_`, matching OpenAI's function\n * name rules.\n *\n * @internal — exported for tests; not part of the public API.\n */\nexport function buildHandoffTool(\n  handoff: Handoff,\n  options: { maxHandoffDepth: number; parentChain: readonly string[] },\n): Tool {\n  const isSpec = !isAgentLike(handoff);\n  const target = isSpec ? handoff.agent : handoff;\n  const inputFilter = isSpec ? handoff.inputFilter : undefined;\n  const description =\n    (isSpec ? handoff.description : undefined) ??\n    `Transfer the conversation to the ${target.name} agent. Use when the user's request requires its specialised capabilities.`;\n\n  const toolName = handoffToolName(target.name);\n\n  return defineTool({\n    name: toolName,\n    description,\n    input: handoffInputSchema,\n    async execute(args, ctx) {\n      const frame = handoffStore.getStore();\n      if (!frame) {\n        // Should be unreachable: the agent loop always wraps execution\n        // in `handoffStore.run`. Surface loudly if it ever happens.\n        throw new Error(\n          `Handoff tool \"${toolName}\" was invoked outside of an agent run scope. ` +\n            `This is a bug in @ziro-agent/agent — please file an issue.`,\n        );\n      }\n\n      const nextDepth = frame.depth + 1;\n      const nextChain = [...options.parentChain, target.name];\n      const parentName = options.parentChain[options.parentChain.length - 1] ?? 'agent';\n\n      if (nextDepth > options.maxHandoffDepth) {\n        const loopErr = new HandoffLoopError({\n          depth: nextDepth,\n          maxDepth: options.maxHandoffDepth,\n          chain: nextChain,\n        });\n        // Stash on the SHARED sink so every enclosing agent loop can\n        // re-throw the rich instance even after `executeToolCalls`\n        // flattens our thrown error to `{ name, message }`.\n        frame.loopErrorSink.error = loopErr;\n        throw loopErr;\n      }\n\n      const filtered = inputFilter ? inputFilter(frame.messages) : frame.messages;\n\n      // Open a `ziro.agent.handoff` span around the sub-run. Parent and\n      // target names are denormalised so a query like\n      // `parent=\"triage\" AND target=\"billing\"` works without joining\n      // spans. The span attributes are set BEFORE the sub-run so the\n      // exporter still sees them if the sub-run throws midway.\n      return await getTracer().withSpan(\n        'ziro.agent.handoff',\n        async (span) => {\n          span.setAttributes({\n            [ATTR.HandoffParentAgent]: parentName,\n            [ATTR.HandoffTargetAgent]: target.name,\n            [ATTR.HandoffDepth]: nextDepth,\n            [ATTR.HandoffMaxDepth]: options.maxHandoffDepth,\n            [ATTR.HandoffChain]: nextChain.join('>'),\n            [ATTR.HandoffMessageCount]: filtered.length,\n            [ATTR.HandoffFiltered]: Boolean(inputFilter),\n          });\n          const reason = (args as { reason?: string } | undefined)?.reason;\n          if (reason) span.setAttribute(ATTR.HandoffReason, reason);\n\n          // We deliberately do NOT forward `budget` here: the parent's\n          // BudgetSpec already lives in AsyncLocalStorage via `withBudget`,\n          // and `target.run()` will compose into the same scope through\n          // `intersectSpecs`. Re-passing it would double-wrap and silently\n          // halve `maxUsd` because of intersection semantics.\n          const subResult: AgentRunResult = await handoffStore.run(\n            {\n              messages: filtered,\n              depth: nextDepth,\n              // Crucial: nested frame keeps the SAME sink reference so\n              // depth-N writes are visible to every depth-<N agent loop.\n              loopErrorSink: frame.loopErrorSink,\n            },\n            () =>\n              target.run({\n                messages: filtered,\n                ...(ctx.abortSignal ? { abortSignal: ctx.abortSignal } : {}),\n                ...(ctx.metadata ? { metadata: ctx.metadata } : {}),\n              }),\n          );\n\n          // The parent agent receives the sub-agent's final text as the\n          // tool result. Step traces and tracing spans capture the full\n          // sub-run separately via `instrumentAgent()`.\n          return subResult.text;\n        },\n        { kind: 'internal' },\n      );\n    },\n  });\n}\n\n/**\n * Sanitise an agent name into a valid OpenAI function name fragment\n * (lower-case, `[a-z0-9_]` only). Empty input falls back to `agent`.\n */\nexport function handoffToolName(agentName: string): string {\n  const cleaned = agentName\n    .toLowerCase()\n    .replace(/[^a-z0-9_]+/g, '_')\n    .replace(/^_+|_+$/g, '');\n  return `transfer_to_${cleaned || 'agent'}`;\n}\n\n/**\n * Structural test: is this a bare `Agent` (vs a `HandoffSpec`)? Uses\n * the `run` method as the discriminator — `Agent` always has it,\n * `HandoffSpec` never does at top-level.\n */\nfunction isAgentLike(handoff: Handoff): handoff is Agent {\n  return typeof (handoff as Agent).run === 'function';\n}\n","import type { ChatMessage, LanguageModel } from '@ziro-agent/core';\nimport { type Tool, toolsToModelDefinitions } from '@ziro-agent/tools';\n\n/**\n * Context for {@link PrepareStep} — invoked before each `generateText` in the\n * agent loop (RFC 0004 / Vercel `prepareStep` pattern).\n */\nexport interface PrepareStepContext {\n  /** 1-based step index (matches `step-start` / `AgentStep.index`). */\n  stepIndex: number;\n  /**\n   * Messages passed to the model this iteration (after memory transforms).\n   * Treat as read-only; the hook receives a fresh structured clone.\n   */\n  messages: ChatMessage[];\n}\n\n/**\n * Optional return value from {@link PrepareStep}. All fields are independent:\n * omit a field to leave the agent default for that axis.\n */\nexport interface PrepareStepResult {\n  /** Use this model for the current `generateText` call only. */\n  model?: LanguageModel;\n  /**\n   * Replace the first `role: 'system'` message for this call only, or\n   * prepend one if the list has no system message.\n   */\n  system?: string;\n  /**\n   * Restrict which tools are sent to the model this step. **Empty array**\n   * removes all tools for this step. **Omit** to keep the full agent tool map.\n   */\n  activeTools?: string[];\n}\n\n/**\n * Per-step hook on `createAgent` / `agent.run` / `agent.resume`.\n */\nexport type PrepareStep = (\n  ctx: PrepareStepContext,\n) => PrepareStepResult | undefined | Promise<PrepareStepResult | undefined>;\n\n/**\n * Applies {@link PrepareStep} for one agent iteration. Always clones\n * `baseMessages` so the hook cannot mutate the live conversation array.\n */\nexport async function resolvePrepareForStep(\n  prepare: PrepareStep | undefined,\n  stepIndex: number,\n  baseMessages: ChatMessage[],\n  defaultModel: LanguageModel,\n  allTools: Record<string, Tool>,\n): Promise<{\n  messages: ChatMessage[];\n  model: LanguageModel;\n  toolsForStep: Record<string, Tool>;\n  toolDefs: ReturnType<typeof toolsToModelDefinitions> | undefined;\n}> {\n  let messages = structuredClone(baseMessages);\n  let model = defaultModel;\n  let toolsForStep: Record<string, Tool> = allTools;\n  if (prepare) {\n    const out = await prepare({ stepIndex, messages });\n    if (out && typeof out === 'object') {\n      if (out.model !== undefined) model = out.model;\n      if (out.system !== undefined) {\n        const sys = out.system;\n        const si = messages.findIndex((m) => m.role === 'system');\n        if (si >= 0) {\n          messages = messages.map((m, i) =>\n            i === si ? { role: 'system' as const, content: sys } : m,\n          );\n        } else {\n          messages = [{ role: 'system' as const, content: sys }, ...messages];\n        }\n      }\n      if (out.activeTools !== undefined) {\n        const entries: [string, Tool][] = [];\n        for (const name of out.activeTools) {\n          const t = allTools[name];\n          if (t) entries.push([name, t]);\n        }\n        toolsForStep = Object.fromEntries(entries);\n      }\n    }\n  }\n  const toolDefs =\n    Object.keys(toolsForStep).length > 0 ? toolsToModelDefinitions(toolsForStep) : undefined;\n  return { messages, model, toolsForStep, toolDefs };\n}\n","import {\n  type ApprovalDecision,\n  type Approver,\n  type BudgetSpec,\n  type BudgetUsage,\n  brandZiroError,\n  type ChatMessage,\n  type PendingApproval,\n  type SerializableBudgetSpec,\n  type TokenUsage,\n  ZiroError,\n} from '@ziro-agent/core';\nimport type { RepairToolCall, ToolExecutionResult } from '@ziro-agent/tools';\nimport type { PrepareStep } from './prepare-step.js';\nimport type { StopWhen } from './stop-when.js';\nimport type { AgentFinishReason, AgentStep, StepEventListener } from './types.js';\n\n/**\n * Current snapshot shape version. Bumped any time the shape changes in a\n * non-additive way; the SDK accepts older versions transparently via\n * {@link migrateSnapshot}.\n *\n * - **v1** (v0.1.0 → v0.1.8): original shape per RFC 0002.\n * - **v2** (v0.1.9+): `resolvedSiblings[]` items now carry `parsedArgs`\n *   so resume can faithfully reconstruct the original `ToolCallPart.args`\n *   when synthesising the suspended step. Closes the gap reported in\n *   RFC 0004 §v0.1.9 trust-recovery / RFC 0002 amend.\n */\nexport const CURRENT_SNAPSHOT_VERSION = 2;\nexport type SnapshotVersion = 1 | 2;\n\n/**\n * JSON-serializable snapshot of an agent run that suspended waiting for\n * human approval. See RFC 0002. Persist this with whatever store fits\n * (Redis, Postgres, S3, in-memory) and feed it back into `agent.resume`.\n *\n * Backwards compatibility: the SDK accepts both v1 and v2 snapshots on\n * `resume()` and runs them through {@link migrateSnapshot} transparently.\n * v1 snapshots persisted before v0.1.9 will keep resuming for the\n * documented 12-month support window (see `apps/docs/content/docs/migration.mdx`).\n */\nexport interface AgentSnapshot {\n  /**\n   * Shape version. New snapshots emit `2`; v1 snapshots are migrated\n   * on-load. Branches on this when persistence layers need to know\n   * which schema to apply (rare — most callers should let\n   * `migrateSnapshot()` normalise).\n   */\n  readonly version: SnapshotVersion;\n  /** True for any object created by `AgentSuspendedError` — cross-realm safe. */\n  readonly __ziro_snapshot__: true;\n  /** Caller-supplied stable id (echoed back through `resume`). */\n  agentId?: string;\n  createdAt: string;\n  /** Budget scope id at the moment of suspension, if a budget was active. */\n  scopeId?: string;\n  /** 1-indexed step where the suspension happened. */\n  step: number;\n  /** Conversation up to (but not including) the pending tool result. */\n  messages: ChatMessage[];\n  /** Steps already completed before suspension. */\n  steps: AgentStep[];\n  totalUsage: TokenUsage;\n  /**\n   * Budget usage accumulated before suspension. Carried into the resumed\n   * scope via `withBudget`'s `presetUsage` so a multi-day pause cannot\n   * silently bypass `maxUsd`.\n   */\n  budgetUsage?: BudgetUsage;\n  /**\n   * Snapshot of the user's `BudgetSpec` minus non-serializable fields\n   * (function-form `onExceed`). The caller may re-supply a fresh\n   * `BudgetSpec` to `resume` — the spec on the snapshot is a fallback.\n   */\n  budgetSpec?: SerializableBudgetSpec;\n  /** All tool calls in the suspended batch awaiting approval. */\n  pendingApprovals: PendingApproval[];\n  /**\n   * Tool calls in the same batch that already executed (approval not\n   * required, or approver returned `approve`) before suspension was\n   * triggered for a sibling. Their `tool.execute()` side-effects are\n   * already applied; on resume their results are combined with the\n   * post-approval results to form the single tool message appended to\n   * the conversation.\n   *\n   * v2: each entry carries `parsedArgs` so the synthesised\n   * `ToolCallPart` on resume includes the validated input the tool\n   * actually received. v1 entries lack this field; resume falls back to\n   * `undefined` for those siblings (matching pre-v0.1.9 behaviour).\n   *\n   * Empty when the entire batch was pending.\n   */\n  resolvedSiblings: ToolExecutionResult[];\n}\n\n/**\n * Forward-migrate a snapshot of any supported version to the current\n * shape ({@link CURRENT_SNAPSHOT_VERSION}). Idempotent — passing a v2\n * snapshot returns an equivalent v2 snapshot.\n *\n * Today the only migration is v1 → v2: it bumps `version` and leaves\n * `resolvedSiblings[].parsedArgs` undefined (the field is optional, so\n * v2 callers handle the absence by falling back to the v1 behaviour).\n *\n * Any other version triggers a thrown error so unknown future versions\n * cannot silently corrupt a resume.\n */\nexport function migrateSnapshot(snapshot: AgentSnapshot): AgentSnapshot {\n  if (snapshot.version === CURRENT_SNAPSHOT_VERSION) return snapshot;\n  if (snapshot.version === 1) {\n    return {\n      ...snapshot,\n      version: 2 as const,\n    };\n  }\n  throw new Error(\n    `Cannot migrate AgentSnapshot — unknown version ${(snapshot as { version?: unknown }).version}. ` +\n      `This SDK supports versions 1 and 2.`,\n  );\n}\n\n/**\n * Thrown from `agent.run` when a tool call's `requiresApproval` gate\n * fires and either no `approver` was supplied or the approver returned\n * `{ decision: 'suspend' }`.\n *\n * The caller persists `error.snapshot` (it is JSON-serializable) and\n * later calls `agent.resume(snapshot, { decisions })` to continue.\n */\nexport class AgentSuspendedError extends ZiroError {\n  override readonly name = 'AgentSuspendedError';\n  readonly snapshot: AgentSnapshot;\n  /** Cross-realm-safe brand — survives `JSON.parse(JSON.stringify(err))` when re-thrown. */\n  readonly __ziro_suspended__: true = true;\n  constructor(args: { snapshot: AgentSnapshot; message?: string }) {\n    super(\n      args.message ??\n        `Agent suspended for human approval (step ${args.snapshot.step}, ` +\n          `${args.snapshot.pendingApprovals.length} pending tool ` +\n          `call${args.snapshot.pendingApprovals.length === 1 ? '' : 's'}).`,\n      { code: 'agent_suspended' },\n    );\n    this.snapshot = args.snapshot;\n    brandZiroError(this);\n  }\n}\n\n/** Type-guard usable across realms (does not depend on `instanceof`). */\nexport function isAgentSuspendedError(value: unknown): value is AgentSuspendedError {\n  return (\n    typeof value === 'object' &&\n    value !== null &&\n    (value as { __ziro_suspended__?: boolean }).__ziro_suspended__ === true\n  );\n}\n\nexport interface AgentResumeOptions {\n  /**\n   * Decision for every tool call in `snapshot.pendingApprovals`. Missing\n   * entries default to `{ decision: 'suspend' }` — the loop will re-emit\n   * an `AgentSuspendedError` carrying an updated snapshot.\n   */\n  decisions: Record<string, ApprovalDecision>;\n  /**\n   * Re-supply (or replace) the budget. When omitted the resume reuses the\n   * snapshot's `budgetSpec`. Original `budgetUsage` carries forward via\n   * `withBudget(presetUsage)` regardless of which spec is used.\n   */\n  budget?: BudgetSpec;\n  /** Default budget for tool calls during the resumed run. */\n  toolBudget?: BudgetSpec;\n  /** Approver for any FURTHER approvals that come up after resume. */\n  approver?: Approver;\n  abortSignal?: AbortSignal;\n  onEvent?: StepEventListener;\n  /** Step-cap override (otherwise inherited from `CreateAgentOptions`). */\n  maxSteps?: number;\n  /** stopWhen override (otherwise inherited). */\n  stopWhen?: StopWhen;\n  /**\n   * Free-form metadata propagated to the approver and tool-execute ctx\n   * during the resumed run.\n   */\n  metadata?: Record<string, unknown>;\n  /** Per-resume override of {@link CreateAgentOptions.repairToolCall}. */\n  repairToolCall?: RepairToolCall;\n  /** Per-resume override of {@link CreateAgentOptions.prepareStep}. */\n  prepareStep?: PrepareStep;\n}\n\n/**\n * Attribute-only summary of how a resume turned out — useful for\n * tracing / OTel observers and for callers who want a one-line status.\n */\nexport interface ResumeSummary {\n  decisionCounts: { approve: number; reject: number; suspend: number };\n  finishReason: AgentFinishReason;\n  stepsAdded: number;\n}\n","import {\n  type ApprovalDecision,\n  type Approver,\n  BudgetExceededError,\n  type BudgetSpec,\n  type BudgetUsage,\n  type ChatMessage,\n  fireAgentResumed,\n  fireAgentSuspended,\n  generateText,\n  getCurrentBudget,\n  isBudgetExceededError,\n  type LanguageModel,\n  type PendingApproval,\n  type SerializableBudgetSpec,\n  type TextPart,\n  type TokenUsage,\n  type ToolCallPart,\n  type ToolResultPart,\n  withBudget,\n} from '@ziro-agent/core';\nimport type { AgentMemoryConfig } from '@ziro-agent/memory';\nimport { injectWorkingMemoryIntoMessages, type MemoryProcessor } from '@ziro-agent/memory';\nimport {\n  executeToolCalls,\n  type RepairToolCall,\n  type Tool,\n  type ToolExecutionResult,\n} from '@ziro-agent/tools';\nimport { ATTR, getTracer, instrumentTools } from '@ziro-agent/tracing';\nimport type { Checkpointer, CheckpointId, CheckpointMeta } from './checkpointer.js';\nimport { buildHandoffTool, type Handoff, handoffStore } from './handoff.js';\nimport { type PrepareStep, resolvePrepareForStep } from './prepare-step.js';\nimport {\n  type AgentResumeOptions,\n  type AgentSnapshot,\n  AgentSuspendedError,\n  CURRENT_SNAPSHOT_VERSION,\n  migrateSnapshot,\n} from './snapshot.js';\nimport type { StopWhen } from './stop-when.js';\nimport type {\n  AgentBudgetExceededInfo,\n  AgentFinishReason,\n  AgentStep,\n  StepEvent,\n  StepEventListener,\n} from './types.js';\n\nexport interface CreateAgentOptions {\n  model: LanguageModel;\n  tools?: Record<string, Tool>;\n  /**\n   * Stable, human-readable agent name. Used for:\n   *  - Auto-generating handoff tool names (`transfer_to_<name>`).\n   *  - Tracing / log correlation (`ziro.agent.name` attribute).\n   *\n   * Recommended convention: short, snake_case-ish (e.g. `triage`,\n   * `billing`, `tech_support`). Defaults to `agent` when omitted; this\n   * is fine for single-agent setups but causes tool-name collisions\n   * when used in `handoffs[]` — supply a unique name in that case.\n   */\n  name?: string;\n  /**\n   * Specialised sub-agents the LLM may delegate the conversation to\n   * via auto-generated `transfer_to_<name>` tools. Pass either a bare\n   * `Agent` (full message-history passthrough) or a {@link HandoffSpec}\n   * for `inputFilter` / custom description. See RFC 0007.\n   *\n   * Available since v0.2.0.\n   */\n  handoffs?: Handoff[];\n  /**\n   * Hard cap on the depth of nested handoffs in a single run. Throws\n   * `HandoffLoopError` if exceeded. Default `5`.\n   */\n  maxHandoffDepth?: number;\n  /** System message passed to the model on every step. */\n  system?: string;\n  /** Hard cap on iterations. Default 10. */\n  maxSteps?: number;\n  /**\n   * Predicate evaluated after every step; return true to stop early.\n   * Combine with `stepCountIs`, `totalTokensExceeds`, etc.\n   */\n  stopWhen?: StopWhen;\n  /**\n   * Invoked before each LLM step. Return a partial result to swap `model`,\n   * replace the first system message for that call, or restrict which tool\n   * names are exposed (RFC 0004 `prepareStep` adoption matrix).\n   */\n  prepareStep?: PrepareStep;\n  /** Default temperature for every step. */\n  temperature?: number;\n  /** Per-step LLM call timeout. Set 0 / undefined to disable. */\n  timeoutMs?: number;\n  /**\n   * Optional persistence boundary. When supplied, every\n   * `AgentSuspendedError` thrown by `run()` / `resume()` automatically\n   * `put`s its snapshot under `runOptions.threadId` (or the agent-level\n   * `defaultThreadId`) before re-throwing — so the caller can recover\n   * with `agent.resumeFromCheckpoint(threadId)` after a process restart\n   * without writing any persistence glue.\n   *\n   * Future strategies (`'message'` / `'invocation'` per RFC 0006\n   * §strategies) auto-checkpoint inside the loop too; they ship in v0.2\n   * once `AgentSnapshot` captures non-suspended mid-run state.\n   *\n   * Available since v0.1.9.\n   */\n  checkpointer?: Checkpointer;\n  /**\n   * Default thread id used by `checkpointer` when neither `run` nor\n   * `resume` overrides it. Useful when an agent instance is dedicated\n   * to a single conversation; otherwise pass `threadId` per-call.\n   */\n  defaultThreadId?: string;\n  /**\n   * Optional three-tier memory (RFC 0011). Working memory is merged into the\n   * first `system` message each LLM step; memory processors and conversation\n   * transforms run on a copy — full history stays in `AgentRunResult.messages`\n   * and checkpoints.\n   */\n  memory?: AgentMemoryConfig;\n  /**\n   * When `true`, every tool (including auto-generated handoff tools) is wrapped\n   * with `instrumentTools` from `@ziro-agent/tracing`. Until `setTracer(...)` is\n   * installed, spans are no-ops. Default `false` so callers who already pass\n   * `instrumentTools(...)` maps do not double-wrap.\n   */\n  traceTools?: boolean;\n  /**\n   * Default {@link RepairToolCall} for every `run()` / `resume()` unless\n   * overridden per-call on {@link AgentRunOptions} / {@link AgentResumeOptions}.\n   */\n  repairToolCall?: RepairToolCall;\n}\n\nexport interface AgentRunOptions {\n  /** Either a single user prompt or a full message list. */\n  prompt?: string;\n  messages?: ChatMessage[];\n  abortSignal?: AbortSignal;\n  /** Subscribe to fine-grained step events while the agent runs. */\n  onEvent?: StepEventListener;\n  /**\n   * Per-run override of {@link CreateAgentOptions.prepareStep}. When both are\n   * set, this wins.\n   */\n  prepareStep?: PrepareStep;\n  /**\n   * Budget enforced across the entire run: every nested `generateText` and\n   * `executeToolCalls` invocation participates in the same scope via\n   * `AsyncLocalStorage`. See RFC 0001.\n   *\n   * `BudgetSpec.maxSteps` is honored here (it is intentionally ignored at\n   * the `generateText` layer). If both `maxSteps` on `CreateAgentOptions`\n   * and on `budget` are set, the tighter wins.\n   */\n  budget?: BudgetSpec;\n  /**\n   * Per-tool-call default budget. Composed (intersected) with each tool's\n   * declared `defineTool({ budget })` and with the outer agent budget.\n   * Most useful as a \"safety net\" against a single rogue tool burning the\n   * whole agent budget.\n   */\n  toolBudget?: BudgetSpec;\n  /**\n   * Resolves `tool.requiresApproval` gates inline. When unset and any\n   * tool needs approval, the agent suspends with `AgentSuspendedError`\n   * (carrying a serializable `AgentSnapshot`). See RFC 0002.\n   */\n  approver?: Approver;\n  /**\n   * Stable id stamped onto any `AgentSnapshot` produced during this run\n   * (for the caller's storage layer). Optional.\n   */\n  agentId?: string;\n  /**\n   * Per-call thread id for `checkpointer` auto-persist. Falls back to\n   * `CreateAgentOptions.defaultThreadId`. When neither is set, an\n   * agent-level `checkpointer` is a no-op (the snapshot still arrives\n   * via `AgentSuspendedError` so callers may persist manually).\n   */\n  threadId?: string;\n  /**\n   * Free-form metadata propagated to the approver and tool-execute ctx.\n   */\n  metadata?: Record<string, unknown>;\n  /** Per-run override of {@link CreateAgentOptions.repairToolCall}. */\n  repairToolCall?: RepairToolCall;\n}\n\nexport interface AgentRunResult {\n  /** Final assistant text — concatenated from the last step. */\n  text: string;\n  /** Every step the agent took, in order. */\n  steps: AgentStep[];\n  /** Sum of token usage across every LLM call. */\n  totalUsage: TokenUsage;\n  /** Why the loop terminated. */\n  finishReason: AgentFinishReason;\n  /** Final conversation, including system, user, assistant, and tool messages. */\n  messages: ChatMessage[];\n  /**\n   * Populated when the loop terminated via `onExceed: 'truncate'`. With the\n   * default `'throw'` semantics, the run rejects with `BudgetExceededError`\n   * instead and this field is never reached.\n   */\n  budgetExceeded?: AgentBudgetExceededInfo;\n}\n\nexport interface ResumeFromCheckpointOptions extends AgentResumeOptions {\n  /**\n   * When omitted, loads the latest checkpoint for the thread. Pass an\n   * id to resume from a specific point (useful for retry experiments).\n   */\n  checkpointId?: CheckpointId;\n}\n\nexport interface Agent {\n  /**\n   * Stable, human-readable agent name (default `'agent'`). Drives\n   * handoff tool naming and tracing attributes.\n   */\n  readonly name: string;\n  readonly tools: Record<string, Tool>;\n  /**\n   * The {@link Checkpointer} the agent was created with, or `undefined`\n   * when none was supplied. Re-exposed so callers can manually `list`\n   * / `delete` checkpoints without holding a separate reference.\n   */\n  readonly checkpointer?: Checkpointer;\n  /**\n   * Same object passed to `createAgent({ memory })`. `longTerm` is for app\n   * tools and RAG; working and conversation tiers are applied inside the loop.\n   */\n  readonly memory?: AgentMemoryConfig;\n  run(options: AgentRunOptions): Promise<AgentRunResult>;\n  /**\n   * Continue an agent run that was suspended via `AgentSuspendedError`.\n   * `decisions` must contain a decision for every tool call in\n   * `snapshot.pendingApprovals`; missing entries default to\n   * `{ decision: 'suspend' }` and the loop will re-emit a fresh\n   * suspension error. See RFC 0002.\n   */\n  resume(snapshot: AgentSnapshot, options: AgentResumeOptions): Promise<AgentRunResult>;\n  /**\n   * Convenience wrapper around `checkpointer.get(threadId, ?id)` +\n   * `resume(snapshot, options)`. Throws `Error(\"No checkpoint found ...\")`\n   * when no snapshot exists for the thread — callers should treat that\n   * as \"nothing to resume from\" and fall back to a fresh `run()`.\n   *\n   * Requires the agent to have been created with a `checkpointer`.\n   *\n   * Available since v0.1.9.\n   */\n  resumeFromCheckpoint(\n    threadId: string,\n    options: ResumeFromCheckpointOptions,\n  ): Promise<AgentRunResult>;\n  /**\n   * Lists checkpoint metadata for a thread (newest first). Delegates to\n   * {@link Checkpointer.list}; use this when you only hold the `Agent`\n   * reference.\n   *\n   * Requires `createAgent({ checkpointer })`.\n   */\n  listCheckpoints(threadId: string, opts?: { limit?: number }): Promise<CheckpointMeta[]>;\n}\n\n/**\n * Mutable, in-flight loop state shared between the initial `run` path and\n * the `resume` path. Both entry points populate this and then hand it to\n * `iterateLoop` which runs the standard `generateText → executeToolCalls`\n * loop from `nextStepIndex` to `stepCap`.\n */\ninterface LoopState {\n  messages: ChatMessage[];\n  steps: AgentStep[];\n  totalUsage: TokenUsage;\n  /** 1-indexed; the iteration starts at this step number. */\n  nextStepIndex: number;\n  /** Effective step cap = min(CreateAgent.maxSteps, BudgetSpec.maxSteps). */\n  stepCap: number;\n  finishReason: AgentFinishReason;\n  budgetInfo?: AgentBudgetExceededInfo;\n  /**\n   * Tool results produced **before** entering iterateLoop (e.g. by\n   * `resume` after applying the human decisions). When non-empty, the\n   * loop appends them as a tool message and synthesizes a step before\n   * making any new LLM call.\n   */\n  pendingToolResults?: ToolExecutionResult[];\n  /**\n   * Tool calls that produced the `pendingToolResults` above (so the\n   * synthesized step has accurate `toolCalls`).\n   */\n  pendingToolCalls?: ToolCallPart[];\n}\n\nlet warnedUncappedBudgetThisProcess = false;\n\n/**\n * RFC 0001 §Unresolved Q1: optional `budget` stays for prototyping, but the\n * first top-level uncapped `agent.run` per process emits a one-time warning.\n * Suppressed under Vitest (`VITEST=true`) or when `ZIRO_SUPPRESS_UNCAPPED_BUDGET_WARN=1`.\n */\nfunction maybeWarnUncappedBudget(agentName: string, runOptions: AgentRunOptions): void {\n  if (warnedUncappedBudgetThisProcess) return;\n  if (runOptions.budget !== undefined) return;\n  if (getCurrentBudget() !== undefined) return;\n  if (process.env.VITEST === 'true') return;\n  if (process.env.ZIRO_SUPPRESS_UNCAPPED_BUDGET_WARN === '1') return;\n  warnedUncappedBudgetThisProcess = true;\n  process.emitWarning(\n    `[ziro-agent] \"${agentName}\" agent.run() was called without a budget (uncapped until v1.0). ` +\n      'Pass { budget: { maxUsdPerRun: number } } or set ZIRO_SUPPRESS_UNCAPPED_BUDGET_WARN=1 to silence. See rfcs/0001-budget-guard.md.',\n    { type: 'ZiroBudget', code: 'ZIRO_UNCAPPED_AGENT_BUDGET' },\n  );\n}\n\n/**\n * Create a tool-using agent. Internally runs a `generateText → executeToolCalls`\n * loop, threading messages back to the model until either:\n *   - the model returns no tool calls (natural completion)\n *   - `stopWhen` returns true\n *   - `maxSteps` is reached\n *   - `abortSignal` fires\n *   - a tool call requires human approval (`AgentSuspendedError` thrown — RFC 0002)\n */\nexport function createAgent(options: CreateAgentOptions): Agent {\n  const agentName = options.name ?? 'agent';\n  const baseMaxSteps = options.maxSteps ?? 10;\n  const checkpointer = options.checkpointer;\n  const maxHandoffDepth = options.maxHandoffDepth ?? 5;\n\n  // Merge user-supplied tools with auto-generated handoff tools.\n  // Handoff tool names follow `transfer_to_<sanitised_name>` and would\n  // collide noisily with user tools — fail fast if so.\n  const baseTools: Record<string, Tool> = { ...(options.tools ?? {}) };\n  if (options.handoffs?.length) {\n    for (const h of options.handoffs) {\n      const tool = buildHandoffTool(h, {\n        maxHandoffDepth,\n        parentChain: [agentName],\n      });\n      if (tool.name in baseTools) {\n        throw new Error(\n          `Handoff tool name \"${tool.name}\" collides with an existing tool. ` +\n            `Either rename the user tool or set a unique \\`name\\` on the target agent.`,\n        );\n      }\n      baseTools[tool.name] = tool;\n    }\n  }\n  const tools = options.traceTools === true ? instrumentTools(baseTools) : baseTools;\n  const agentRepairDefault = options.repairToolCall;\n\n  /**\n   * Auto-persist the snapshot from any `AgentSuspendedError` thrown by\n   * `fn` so the caller can later `agent.resumeFromCheckpoint(threadId)`.\n   *\n   * No-ops when no `checkpointer` is configured, or when neither the\n   * agent-level `defaultThreadId` nor a per-call `threadId` is set —\n   * the snapshot still arrives via the thrown error so manual storage\n   * is always possible.\n   *\n   * Persistence failure is logged on `console.error` and does NOT mask\n   * the original `AgentSuspendedError`: durability is best-effort, the\n   * ground truth is the in-flight error.\n   */\n  const withAutoCheckpoint = async (\n    threadId: string | undefined,\n    fn: () => Promise<AgentRunResult>,\n  ): Promise<AgentRunResult> => {\n    try {\n      return await fn();\n    } catch (err) {\n      if (checkpointer && threadId && err instanceof AgentSuspendedError) {\n        try {\n          await checkpointer.put(threadId, err.snapshot);\n        } catch (persistErr) {\n          // Don't shadow the original suspension — persistence is\n          // best-effort. Surface the failure so ops can see it.\n          // eslint-disable-next-line no-console\n          console.error('[ziro-agent] checkpointer.put failed:', persistErr);\n        }\n      }\n      throw err;\n    }\n  };\n\n  const agent: Agent = {\n    name: agentName,\n    tools,\n    ...(checkpointer ? { checkpointer } : {}),\n    ...(options.memory ? { memory: options.memory } : {}),\n    async run(runOptions: AgentRunOptions): Promise<AgentRunResult> {\n      maybeWarnUncappedBudget(agentName, runOptions);\n      const exec = async (): Promise<AgentRunResult> => {\n        const state = seedFromRunOptions(runOptions, baseMaxSteps);\n        return await iterateLoop(state, runOptions);\n      };\n      const tid = runOptions.threadId ?? options.defaultThreadId;\n      // Wrap the run in a fresh handoff frame ONLY when one isn't\n      // already in scope — nested handoff calls (the sub-agent's run)\n      // already established the frame in `buildHandoffTool.execute`,\n      // and over-writing it here would reset the depth counter and\n      // break `maxHandoffDepth` enforcement.\n      const wrapHandoff = (fn: () => Promise<AgentRunResult>): Promise<AgentRunResult> => {\n        if (handoffStore.getStore() !== undefined) return fn();\n        const initialMessages = runOptions.messages ?? [];\n        return handoffStore.run({ messages: initialMessages, depth: 0, loopErrorSink: {} }, fn);\n      };\n      return await wrapHandoff(() =>\n        withAutoCheckpoint(tid, () => runWithBudget(runOptions, exec)),\n      );\n    },\n\n    async resume(\n      rawSnapshot: AgentSnapshot,\n      resumeOptions: AgentResumeOptions,\n    ): Promise<AgentRunResult> {\n      // Forward-migrate so the rest of this method only deals with the\n      // current snapshot shape. v1 snapshots persisted before v0.1.9\n      // resume transparently (their `resolvedSiblings[].parsedArgs` is\n      // simply undefined; `seedFromSnapshot` falls back to the pre-v2\n      // behaviour for those entries).\n      const snapshot = migrateSnapshot(rawSnapshot);\n\n      // Build a `runOptions`-shaped object so the rest of the loop sees\n      // a uniform interface. We keep the snapshot-derived budget as a\n      // fallback if the caller didn't re-supply one.\n      const resolvedBudget =\n        resumeOptions.budget ?? deserializeBudgetSpec(snapshot.budgetSpec) ?? undefined;\n      const resumeRepair =\n        resumeOptions.repairToolCall !== undefined\n          ? resumeOptions.repairToolCall\n          : agentRepairDefault;\n      const cleanRo: AgentRunOptions = {\n        ...(resumeOptions.toolBudget !== undefined ? { toolBudget: resumeOptions.toolBudget } : {}),\n        ...(resumeOptions.approver !== undefined ? { approver: resumeOptions.approver } : {}),\n        ...(resumeOptions.abortSignal !== undefined\n          ? { abortSignal: resumeOptions.abortSignal }\n          : {}),\n        ...(resumeOptions.onEvent !== undefined ? { onEvent: resumeOptions.onEvent } : {}),\n        ...(resumeOptions.prepareStep !== undefined\n          ? { prepareStep: resumeOptions.prepareStep }\n          : {}),\n        ...(resumeOptions.metadata !== undefined ? { metadata: resumeOptions.metadata } : {}),\n        ...(resumeRepair ? { repairToolCall: resumeRepair } : {}),\n        ...(snapshot.agentId !== undefined ? { agentId: snapshot.agentId } : {}),\n        ...(resolvedBudget !== undefined ? { budget: resolvedBudget } : {}),\n      };\n\n      const exec = async (): Promise<AgentRunResult> => {\n        const decisions = resumeOptions.decisions ?? {};\n        const decisionCounts = countDecisions(decisions, snapshot.pendingApprovals);\n\n        // Resolve every pending tool call into a real ToolExecutionResult,\n        // collecting any that turn into NEW pending approvals so we can\n        // re-suspend with a refreshed snapshot.\n        const newlyResolved: ToolExecutionResult[] = [];\n        const stillPending: PendingApproval[] = [];\n        for (const pending of snapshot.pendingApprovals) {\n          const decision = decisions[pending.toolCallId] ?? { decision: 'suspend' };\n          const result = await applyDecisionToPending(tools, pending, decision, cleanRo);\n          if (result.pendingApproval) {\n            stillPending.push(result.pendingApproval);\n            // Don't append a tool result for still-pending calls.\n          } else {\n            newlyResolved.push(result);\n          }\n        }\n\n        if (stillPending.length > 0) {\n          // Re-throw with an updated snapshot — the previously-resolved\n          // siblings stay in `resolvedSiblings`, and the newly-resolved\n          // ones are merged in too so resume #2 doesn't re-run them.\n          const merged: AgentSnapshot = {\n            ...snapshot,\n            createdAt: new Date().toISOString(),\n            pendingApprovals: stillPending,\n            resolvedSiblings: [...snapshot.resolvedSiblings, ...newlyResolved],\n          };\n          fireAgentSuspended({\n            ...(snapshot.agentId !== undefined ? { agentId: snapshot.agentId } : {}),\n            ...(snapshot.scopeId !== undefined ? { scopeId: snapshot.scopeId } : {}),\n            step: snapshot.step,\n            pendingCount: stillPending.length,\n          });\n          throw new AgentSuspendedError({ snapshot: merged });\n        }\n\n        // Combine resolved siblings + newly-resolved into a single tool\n        // message + synthesized step, then continue the loop.\n        const allResults = [...snapshot.resolvedSiblings, ...newlyResolved];\n        const state = seedFromSnapshot(snapshot, allResults, baseMaxSteps);\n\n        fireAgentResumed({\n          ...(snapshot.agentId !== undefined ? { agentId: snapshot.agentId } : {}),\n          ...(snapshot.scopeId !== undefined ? { scopeId: snapshot.scopeId } : {}),\n          step: snapshot.step,\n          decisionCounts,\n        });\n\n        return await iterateLoop(state, cleanRo);\n      };\n\n      // Resume opens its own budget scope with the snapshot's accumulated\n      // usage carried forward, so a multi-day pause cannot bypass maxUsd.\n      const tid = snapshot.agentId ? undefined : options.defaultThreadId;\n      // Note: we don't pull threadId from resumeOptions because the\n      // canonical thread identity is established at run time. If the\n      // caller wants to retarget, they can manually checkpointer.put\n      // after a successful resume.\n      return await withAutoCheckpoint(tid, () =>\n        runWithBudget(cleanRo, exec, snapshot.budgetUsage),\n      );\n    },\n\n    async resumeFromCheckpoint(\n      threadId: string,\n      resumeOptions: ResumeFromCheckpointOptions,\n    ): Promise<AgentRunResult> {\n      if (!checkpointer) {\n        throw new Error(\n          'agent.resumeFromCheckpoint() requires a `checkpointer` on createAgent({ checkpointer }).',\n        );\n      }\n      const snap = await checkpointer.get(threadId, resumeOptions.checkpointId);\n      if (!snap) {\n        throw new Error(\n          `No checkpoint found for thread \"${threadId}\"` +\n            (resumeOptions.checkpointId ? ` (id \"${resumeOptions.checkpointId}\")` : '') +\n            '. Treat this as \"nothing to resume from\" and call agent.run() instead.',\n        );\n      }\n      // Strip our own option before forwarding so AgentResumeOptions\n      // stays clean.\n      const { checkpointId: _ignored, ...rest } = resumeOptions;\n      return await this.resume(snap, rest);\n    },\n\n    async listCheckpoints(threadId: string, opts?: { limit?: number }): Promise<CheckpointMeta[]> {\n      if (!checkpointer) {\n        throw new Error(\n          'agent.listCheckpoints() requires a `checkpointer` on createAgent({ checkpointer }).',\n        );\n      }\n      return checkpointer.list(threadId, opts);\n    },\n  };\n\n  return agent;\n\n  // ============================================================\n  // Loop implementation — shared between `run` and `resume`.\n  // (Function declarations are hoisted; placement after `return`\n  //  keeps the public surface readable up top.)\n  // ============================================================\n\n  async function buildLlmMessages(\n    state: LoopState,\n    ro: AgentRunOptions,\n    stepIndex: number,\n  ): Promise<ChatMessage[]> {\n    const mem = options.memory;\n    if (!mem) return state.messages;\n    const tracer = getTracer();\n    const ctx = { threadId: ro.threadId ?? options.defaultThreadId, stepIndex };\n    const processors = mem.processors ?? [];\n    const procCount = processors.length;\n\n    return tracer.withSpan(\n      'ziro.memory.build_llm_messages',\n      async (root) => {\n        root.setAttributes({\n          [ATTR.AgentStepIndex]: stepIndex,\n          [ATTR.MemoryProcessorCount]: procCount,\n          ...(ctx.threadId ? { [ATTR.ThreadId]: ctx.threadId } : {}),\n        });\n\n        let msgs: ChatMessage[] = [...state.messages];\n        const workingMem = mem.working;\n        if (workingMem) {\n          msgs = await tracer.withSpan(\n            'ziro.memory.working',\n            async (span) => {\n              span.setAttributes({\n                [ATTR.MemoryPhase]: 'working',\n                ...(ctx.threadId ? { [ATTR.ThreadId]: ctx.threadId } : {}),\n              });\n              const w = await workingMem.read();\n              span.addEvent('ziro.memory.read', {\n                [ATTR.MemoryWorkingCharCount]: w.length,\n              });\n              return injectWorkingMemoryIntoMessages(msgs, w);\n            },\n            { kind: 'internal' },\n          );\n        }\n\n        let idx = 0;\n        for (const p of processors) {\n          const i = idx;\n          idx += 1;\n          const proc = p as MemoryProcessor;\n          msgs = await tracer.withSpan(\n            'ziro.memory.processor',\n            async (span) => {\n              span.setAttributes({\n                [ATTR.MemoryPhase]: 'processor',\n                [ATTR.MemoryProcessorIndex]: i,\n                [ATTR.MemoryProcessorCount]: procCount,\n                ...(proc.name ? { [ATTR.MemoryProcessorName]: proc.name } : {}),\n                ...(ctx.threadId ? { [ATTR.ThreadId]: ctx.threadId } : {}),\n              });\n              return await Promise.resolve(proc.process(msgs, ctx));\n            },\n            { kind: 'internal' },\n          );\n        }\n\n        const conversationMem = mem.conversation;\n        if (conversationMem) {\n          msgs = await tracer.withSpan(\n            'ziro.memory.conversation',\n            async (span) => {\n              span.setAttributes({\n                [ATTR.MemoryPhase]: 'conversation',\n                ...(ctx.threadId ? { [ATTR.ThreadId]: ctx.threadId } : {}),\n              });\n              return await Promise.resolve(conversationMem.prepareForModel(msgs, ctx));\n            },\n            { kind: 'internal' },\n          );\n        }\n        return msgs;\n      },\n      { kind: 'internal' },\n    );\n  }\n\n  async function iterateLoop(state: LoopState, ro: AgentRunOptions): Promise<AgentRunResult> {\n    const effectiveRepairToolCall = ro.repairToolCall ?? agentRepairDefault;\n    const emit = async (event: StepEvent) => {\n      if (ro.onEvent) await ro.onEvent(event);\n    };\n\n    const truncate = ro.budget?.onExceed === 'truncate';\n    const captureSnapshot = (): AgentRunResult => ({\n      text: state.steps[state.steps.length - 1]?.text ?? '',\n      steps: state.steps,\n      totalUsage: state.totalUsage,\n      finishReason: state.finishReason,\n      messages: state.messages,\n    });\n\n    const handleBudgetThrow = async (\n      err: BudgetExceededError,\n      origin: AgentBudgetExceededInfo['origin'],\n    ): Promise<undefined> => {\n      const info = toAgentBudgetInfo(err, origin);\n      await emit({ type: 'budget-exceeded', info });\n      if (truncate) {\n        state.budgetInfo = info;\n        state.finishReason = 'budgetExceeded';\n        return undefined;\n      }\n      (err as BudgetExceededError & { __agentPartial?: AgentRunResult }).__agentPartial =\n        captureSnapshot();\n      throw err;\n    };\n\n    // If the seeding code (e.g. `resume`) handed us pre-resolved tool\n    // results for a step that already happened, replay them as a\n    // synthesized step BEFORE entering the LLM-call loop.\n    if (state.pendingToolResults && state.pendingToolCalls) {\n      const replayResults = state.pendingToolResults;\n      const replayCalls = state.pendingToolCalls;\n      const stepIdx = state.nextStepIndex - 1; // the suspended step\n\n      for (const r of replayResults) {\n        await emit({ type: 'tool-result', index: stepIdx, result: r });\n      }\n      const toolContent: ToolResultPart[] = replayResults.map((r) => ({\n        type: 'tool-result',\n        toolCallId: r.toolCallId,\n        toolName: r.toolName,\n        result: r.result,\n        ...(r.isError ? { isError: true } : {}),\n      }));\n      state.messages.push({ role: 'tool', content: toolContent });\n\n      const synthStep: AgentStep = {\n        index: stepIdx,\n        text: '',\n        content: replayCalls,\n        toolCalls: replayCalls,\n        toolResults: replayResults,\n        finishReason: 'tool-calls',\n        usage: {},\n      };\n      state.steps.push(synthStep);\n      await emit({ type: 'step-finish', step: synthStep });\n\n      // Promote tool budget overruns to a loop-level halt, same as the\n      // standard path below.\n      const toolBudgetHit = replayResults.find((r) => r.budgetExceeded);\n      if (toolBudgetHit?.budgetExceeded) {\n        const synthErr = synthBudgetErrorFromToolResult(toolBudgetHit, state);\n        await handleBudgetThrow(synthErr, 'tool');\n        return finalizeResult(state, emit);\n      }\n\n      // Pre-resolved results consumed; clear so they don't replay.\n      state.pendingToolResults = undefined;\n      state.pendingToolCalls = undefined;\n    }\n\n    for (let i = state.nextStepIndex - 1; i < state.stepCap; i++) {\n      if (ro.abortSignal?.aborted) {\n        state.finishReason = 'aborted';\n        break;\n      }\n\n      const stepIndex = i + 1;\n      await emit({ type: 'step-start', index: stepIndex });\n\n      const baseMsgs = await buildLlmMessages(state, ro, stepIndex);\n      const prepare = ro.prepareStep ?? options.prepareStep;\n      const {\n        messages: stepMsgs,\n        model: stepModel,\n        toolsForStep,\n        toolDefs: stepToolDefs,\n      } = await resolvePrepareForStep(prepare, stepIndex, baseMsgs, options.model, tools);\n\n      let llmResult: Awaited<ReturnType<typeof generateText>>;\n      try {\n        llmResult = await generateText({\n          model: stepModel,\n          messages: stepMsgs,\n          ...(stepToolDefs ? { tools: stepToolDefs } : {}),\n          ...(options.temperature !== undefined ? { temperature: options.temperature } : {}),\n          ...(ro.abortSignal ? { abortSignal: ro.abortSignal } : {}),\n        });\n      } catch (err) {\n        if (isBudgetExceededError(err)) {\n          await handleBudgetThrow(err, 'preflight');\n          break;\n        }\n        throw err;\n      }\n\n      addUsageInPlace(state.totalUsage, llmResult.usage);\n\n      await emit({\n        type: 'llm-finish',\n        index: stepIndex,\n        text: llmResult.text,\n        toolCalls: llmResult.toolCalls,\n      });\n\n      if (llmResult.toolCalls.length > 0) {\n        const assistantContent = llmResult.content.filter(\n          (p): p is TextPart | ToolCallPart => p.type === 'text' || p.type === 'tool-call',\n        );\n        state.messages.push({ role: 'assistant', content: assistantContent });\n      } else {\n        state.messages.push({ role: 'assistant', content: llmResult.text });\n      }\n\n      let toolResults: ToolExecutionResult[] = [];\n      if (llmResult.toolCalls.length > 0) {\n        const approvalContext = {\n          step: stepIndex,\n          messages: [...state.messages] as ReadonlyArray<unknown>,\n        };\n        // Refresh the handoff frame's `messages` snapshot BEFORE\n        // running tools so any handoff-derived tool sees the latest\n        // conversation state. We only mutate the existing frame —\n        // never create a new one — so depth tracking is preserved.\n        const frame = handoffStore.getStore();\n        if (frame) frame.messages = [...state.messages];\n        toolResults = await executeToolCalls({\n          tools: toolsForStep,\n          toolCalls: llmResult.toolCalls,\n          step: stepIndex,\n          ...(ro.abortSignal ? { abortSignal: ro.abortSignal } : {}),\n          ...(ro.toolBudget ? { toolBudget: ro.toolBudget } : {}),\n          ...(ro.approver ? { approver: ro.approver } : {}),\n          ...(ro.metadata ? { metadata: ro.metadata } : {}),\n          ...(effectiveRepairToolCall ? { repairToolCall: effectiveRepairToolCall } : {}),\n          approvalContext,\n        });\n\n        for (const r of toolResults) {\n          await emit({ type: 'tool-result', index: stepIndex, result: r });\n        }\n\n        // Suspension check — RFC 0002. If any result carries a\n        // pendingApproval, the loop captures full state and throws\n        // AgentSuspendedError. Sibling results that already executed\n        // are preserved in `snapshot.resolvedSiblings`.\n        const pending = toolResults.filter((r) => r.pendingApproval);\n        if (pending.length > 0) {\n          const resolvedSiblings = toolResults.filter((r) => !r.pendingApproval);\n          const snap: AgentSnapshot = {\n            version: CURRENT_SNAPSHOT_VERSION,\n            __ziro_snapshot__: true,\n            ...(ro.agentId !== undefined ? { agentId: ro.agentId } : {}),\n            createdAt: new Date().toISOString(),\n            ...(getCurrentBudget()?.scopeId\n              ? { scopeId: getCurrentBudget()?.scopeId as string }\n              : {}),\n            step: stepIndex,\n            messages: [...state.messages],\n            steps: [...state.steps],\n            totalUsage: { ...state.totalUsage },\n            ...(getCurrentBudget()?.used !== undefined\n              ? { budgetUsage: { ...(getCurrentBudget()?.used as BudgetUsage) } }\n              : {}),\n            ...(ro.budget ? { budgetSpec: serializeBudgetSpec(ro.budget) } : {}),\n            pendingApprovals: pending.map((r) => r.pendingApproval as PendingApproval),\n            resolvedSiblings,\n          };\n          fireAgentSuspended({\n            ...(snap.agentId !== undefined ? { agentId: snap.agentId } : {}),\n            ...(snap.scopeId !== undefined ? { scopeId: snap.scopeId } : {}),\n            step: snap.step,\n            pendingCount: pending.length,\n          });\n          throw new AgentSuspendedError({ snapshot: snap });\n        }\n\n        const toolContent: ToolResultPart[] = toolResults.map((r) => ({\n          type: 'tool-result',\n          toolCallId: r.toolCallId,\n          toolName: r.toolName,\n          result: r.result,\n          ...(r.isError ? { isError: true } : {}),\n        }));\n        state.messages.push({ role: 'tool', content: toolContent });\n      }\n\n      const step: AgentStep = {\n        index: stepIndex,\n        text: llmResult.text,\n        content: llmResult.content,\n        toolCalls: llmResult.toolCalls,\n        toolResults,\n        finishReason: llmResult.finishReason,\n        usage: llmResult.usage,\n      };\n      state.steps.push(step);\n      await emit({ type: 'step-finish', step });\n\n      const toolBudgetHit = toolResults.find((r) => r.budgetExceeded);\n      if (toolBudgetHit?.budgetExceeded) {\n        const synthErr = synthBudgetErrorFromToolResult(toolBudgetHit, state);\n        await handleBudgetThrow(synthErr, 'tool');\n        break;\n      }\n\n      // RFC 0007: HandoffLoopError is a configuration bug, not a\n      // recoverable tool error — abort the run rather than letting\n      // it loop until maxSteps. The `executeToolCalls` layer\n      // serialises thrown Errors into plain `{ name, message }`\n      // (cross-realm safety), so the live instance is stashed on the\n      // shared `loopErrorSink` walked through every nested frame;\n      // we re-throw it verbatim here.\n      const liveLoopError = handoffStore.getStore()?.loopErrorSink.error;\n      if (liveLoopError) throw liveLoopError;\n\n      if (llmResult.toolCalls.length === 0) {\n        state.finishReason = 'completed';\n        break;\n      }\n\n      if (\n        options.stopWhen &&\n        (await options.stopWhen({ steps: state.steps, totalUsage: state.totalUsage }))\n      ) {\n        state.finishReason = 'stopWhen';\n        break;\n      }\n\n      if (i === state.stepCap - 1) {\n        state.finishReason = 'maxSteps';\n        break;\n      }\n    }\n\n    return finalizeResult(state, emit);\n  }\n\n  // ============================================================\n  // Helpers — closure-scoped over `tools`/`baseMaxSteps`/`options`.\n  // ============================================================\n\n  function seedFromRunOptions(ro: AgentRunOptions, baseMaxSteps: number): LoopState {\n    const messages: ChatMessage[] = [];\n    if (options.system) messages.push({ role: 'system', content: options.system });\n    if (ro.messages?.length) {\n      messages.push(...ro.messages);\n    } else if (ro.prompt) {\n      messages.push({ role: 'user', content: ro.prompt });\n    } else {\n      throw new Error('createAgent.run requires either `prompt` or `messages`.');\n    }\n    const stepCap =\n      ro.budget?.maxSteps !== undefined ? Math.min(baseMaxSteps, ro.budget.maxSteps) : baseMaxSteps;\n    return {\n      messages,\n      steps: [],\n      totalUsage: {},\n      nextStepIndex: 1,\n      stepCap,\n      finishReason: 'completed',\n    };\n  }\n\n  function seedFromSnapshot(\n    snapshot: AgentSnapshot,\n    resolvedResults: ToolExecutionResult[],\n    baseMaxSteps: number,\n  ): LoopState {\n    // Reconstruct the toolCalls array from the snapshot's pending\n    // approvals + the resolvedSiblings that already ran. Order: matches\n    // the order of `resolvedResults`.\n    //\n    // v2: each ToolExecutionResult carries `parsedArgs` so we can echo\n    // the validated input the tool actually received. v1 snapshots lack\n    // it — `args` falls back to undefined (pre-v0.1.9 behaviour).\n    const toolCalls: ToolCallPart[] = resolvedResults.map((r) => ({\n      type: 'tool-call' as const,\n      toolCallId: r.toolCallId,\n      toolName: r.toolName,\n      args: r.parsedArgs as unknown,\n    }));\n    const stepCap =\n      snapshot.budgetSpec?.maxSteps !== undefined\n        ? Math.min(baseMaxSteps, snapshot.budgetSpec.maxSteps)\n        : baseMaxSteps;\n    return {\n      messages: [...snapshot.messages],\n      steps: [...snapshot.steps],\n      totalUsage: { ...snapshot.totalUsage },\n      nextStepIndex: snapshot.step + 1,\n      stepCap,\n      finishReason: 'completed',\n      pendingToolResults: resolvedResults,\n      pendingToolCalls: toolCalls,\n    };\n  }\n\n  async function finalizeResult(\n    state: LoopState,\n    emit: (event: StepEvent) => Promise<void>,\n  ): Promise<AgentRunResult> {\n    await emit({ type: 'agent-finish', reason: state.finishReason });\n    const last = state.steps[state.steps.length - 1];\n    return {\n      text: last?.text ?? '',\n      steps: state.steps,\n      totalUsage: state.totalUsage,\n      finishReason: state.finishReason,\n      messages: state.messages,\n      ...(state.budgetInfo ? { budgetExceeded: state.budgetInfo } : {}),\n    };\n  }\n}\n\n// ============================================================\n// Module-level helpers (shared between run + resume).\n// ============================================================\n\n/**\n * Wrap `exec` in a `withBudget` scope honouring the user's `onExceed`\n * settings (throw / truncate / function form). Used by both `run` and\n * `resume`. `presetUsage` is supplied by `resume` so accumulated spend\n * carries across a HITL pause.\n */\nasync function runWithBudget(\n  ro: AgentRunOptions,\n  exec: () => Promise<AgentRunResult>,\n  presetUsage?: BudgetUsage,\n): Promise<AgentRunResult> {\n  if (!ro.budget) return await exec();\n  try {\n    return await withBudget(\n      ro.budget,\n      exec,\n      presetUsage !== undefined ? { presetUsage } : undefined,\n    );\n  } catch (err) {\n    if (!isBudgetExceededError(err)) throw err;\n    const onExceed = ro.budget.onExceed;\n\n    if (typeof onExceed === 'function') {\n      const ctx = {\n        spec: ro.budget,\n        used: err.partialUsage,\n        remaining: computeRemaining(ro.budget, err.partialUsage),\n        scopeId: err.scopeId,\n      };\n      let resolution: { handled: boolean; replacement?: unknown };\n      try {\n        resolution = await Promise.resolve(onExceed(ctx));\n      } catch (resolverErr) {\n        if (resolverErr instanceof Error) {\n          (resolverErr as Error & { cause?: unknown }).cause = err;\n        }\n        throw resolverErr;\n      }\n      if (resolution.handled) return resolution.replacement as AgentRunResult;\n      throw err;\n    }\n\n    if (onExceed === 'truncate') {\n      const partial = (err as BudgetExceededError & { __agentPartial?: AgentRunResult })\n        .__agentPartial;\n      if (partial) {\n        return {\n          ...partial,\n          finishReason: 'budgetExceeded',\n          budgetExceeded: toAgentBudgetInfo(err, 'preflight'),\n        };\n      }\n      return {\n        text: '',\n        steps: [],\n        totalUsage: {},\n        messages: [],\n        finishReason: 'budgetExceeded',\n        budgetExceeded: toAgentBudgetInfo(err, 'preflight'),\n      };\n    }\n    throw err;\n  }\n}\n\n/**\n * Run a single pending tool through the user-supplied decision, returning\n * a `ToolExecutionResult` ready to splice into the conversation. Mirrors\n * `executeToolCalls`'s behaviour for the approve/reject paths so the\n * tool-message shape stays uniform between run and resume.\n *\n * `suspend` decisions yield a result whose `pendingApproval` is set —\n * the caller (`agent.resume`) detects this and re-suspends.\n */\nasync function applyDecisionToPending(\n  tools: Record<string, Tool>,\n  pending: PendingApproval,\n  decision: ApprovalDecision,\n  ro: AgentRunOptions,\n): Promise<ToolExecutionResult> {\n  const start = performance.now();\n  const tool = tools[pending.toolName];\n  if (!tool) {\n    return {\n      toolCallId: pending.toolCallId,\n      toolName: pending.toolName,\n      result: {\n        name: 'ToolMissing',\n        message:\n          `Tool \"${pending.toolName}\" was not registered on the agent that ` +\n          'received this resume call.',\n      },\n      isError: true,\n      durationMs: performance.now() - start,\n    };\n  }\n\n  if (decision.decision === 'reject') {\n    return {\n      toolCallId: pending.toolCallId,\n      toolName: pending.toolName,\n      result: {\n        name: 'ApprovalRejected',\n        message: decision.reason ?? `Tool \"${pending.toolName}\" rejected by approver.`,\n      },\n      isError: true,\n      durationMs: performance.now() - start,\n      parsedArgs: pending.parsedInput,\n    };\n  }\n\n  if (decision.decision === 'suspend') {\n    return {\n      toolCallId: pending.toolCallId,\n      toolName: pending.toolName,\n      result: null,\n      isError: false,\n      durationMs: performance.now() - start,\n      parsedArgs: pending.parsedInput,\n      pendingApproval: pending,\n    };\n  }\n\n  // approve — re-validate any modifiedInput so the tool gets a typed\n  // payload at runtime.\n  let approvedInput = pending.parsedInput;\n  if (decision.modifiedInput !== undefined) {\n    try {\n      approvedInput = tool.input.parse(decision.modifiedInput);\n    } catch (err) {\n      return {\n        toolCallId: pending.toolCallId,\n        toolName: pending.toolName,\n        result: serializeError(err),\n        isError: true,\n        durationMs: performance.now() - start,\n        parsedArgs: pending.parsedInput,\n      };\n    }\n  }\n\n  const composedBudget = ro.toolBudget ?? tool.budget ?? undefined;\n  const runExecute = async (): Promise<unknown> => {\n    const value = await Promise.resolve(\n      tool.execute(approvedInput, {\n        toolCallId: pending.toolCallId,\n        ...(ro.abortSignal ? { abortSignal: ro.abortSignal } : {}),\n        ...(ro.metadata ? { metadata: ro.metadata } : {}),\n      }),\n    );\n    return tool.output ? tool.output.parse(value) : value;\n  };\n  try {\n    const out = composedBudget ? await withBudget(composedBudget, runExecute) : await runExecute();\n    return {\n      toolCallId: pending.toolCallId,\n      toolName: pending.toolName,\n      result: out,\n      isError: false,\n      durationMs: performance.now() - start,\n      parsedArgs: approvedInput,\n    };\n  } catch (err) {\n    if (isBudgetExceededError(err)) {\n      return {\n        toolCallId: pending.toolCallId,\n        toolName: pending.toolName,\n        result: serializeError(err),\n        isError: true,\n        durationMs: performance.now() - start,\n        parsedArgs: approvedInput,\n        budgetExceeded: {\n          kind: err.kind,\n          limit: err.limit,\n          observed: err.observed,\n          scopeId: err.scopeId,\n        },\n      };\n    }\n    return {\n      toolCallId: pending.toolCallId,\n      toolName: pending.toolName,\n      result: serializeError(err),\n      isError: true,\n      durationMs: performance.now() - start,\n      parsedArgs: approvedInput,\n    };\n  }\n}\n\nfunction countDecisions(\n  decisions: Record<string, ApprovalDecision>,\n  pending: PendingApproval[],\n): { approve: number; reject: number; suspend: number } {\n  const counts = { approve: 0, reject: 0, suspend: 0 };\n  for (const p of pending) {\n    const d = decisions[p.toolCallId]?.decision ?? 'suspend';\n    counts[d as 'approve' | 'reject' | 'suspend']++;\n  }\n  return counts;\n}\n\nfunction synthBudgetErrorFromToolResult(\n  toolResult: ToolExecutionResult,\n  state: LoopState,\n): BudgetExceededError {\n  const be = toolResult.budgetExceeded;\n  if (!be) {\n    throw new Error('synthBudgetErrorFromToolResult called without budgetExceeded');\n  }\n  return new BudgetExceededError({\n    kind: be.kind,\n    limit: be.limit,\n    observed: be.observed,\n    scopeId: be.scopeId,\n    partialUsage: getCurrentBudget()?.used ?? {\n      usd: 0,\n      tokens: 0,\n      llmCalls: 0,\n      steps: state.steps.length,\n      durationMs: 0,\n    },\n    preflight: false,\n  });\n}\n\nfunction toAgentBudgetInfo(\n  err: BudgetExceededError,\n  origin: AgentBudgetExceededInfo['origin'],\n): AgentBudgetExceededInfo {\n  return {\n    kind: err.kind,\n    limit: err.limit,\n    observed: err.observed,\n    scopeId: err.scopeId,\n    partialUsage: err.partialUsage,\n    origin,\n  };\n}\n\n/**\n * Build a `BudgetContext.remaining` snapshot from the spec + observed usage.\n * Mirrors the math in `core/src/budget/scope.ts#toContext` so user-visible\n * resolver context shape stays consistent across layers.\n */\nfunction computeRemaining(\n  spec: BudgetSpec,\n  used: BudgetUsage,\n): {\n  usd?: number;\n  tokens?: number;\n  llmCalls?: number;\n  steps?: number;\n  durationMs?: number;\n} {\n  const out: {\n    usd?: number;\n    tokens?: number;\n    llmCalls?: number;\n    steps?: number;\n    durationMs?: number;\n  } = {};\n  if (spec.maxUsd !== undefined) out.usd = Math.max(0, spec.maxUsd - used.usd);\n  if (spec.maxTokens !== undefined) out.tokens = Math.max(0, spec.maxTokens - used.tokens);\n  if (spec.maxLlmCalls !== undefined) out.llmCalls = Math.max(0, spec.maxLlmCalls - used.llmCalls);\n  if (spec.maxSteps !== undefined) out.steps = Math.max(0, spec.maxSteps - used.steps);\n  if (spec.maxDurationMs !== undefined) {\n    out.durationMs = Math.max(0, spec.maxDurationMs - used.durationMs);\n  }\n  return out;\n}\n\nfunction addUsageInPlace(target: TokenUsage, add: TokenUsage): void {\n  const sum = (a?: number, b?: number) =>\n    a === undefined && b === undefined ? undefined : (a ?? 0) + (b ?? 0);\n  target.promptTokens = sum(target.promptTokens, add.promptTokens);\n  target.completionTokens = sum(target.completionTokens, add.completionTokens);\n  target.totalTokens = sum(target.totalTokens, add.totalTokens);\n  target.cachedPromptTokens = sum(target.cachedPromptTokens, add.cachedPromptTokens);\n  target.reasoningTokens = sum(target.reasoningTokens, add.reasoningTokens);\n}\n\n/**\n * Strip non-serializable fields from a `BudgetSpec` so the snapshot\n * stays JSON-safe. Function-form `onExceed` collapses to `'throw'`; the\n * caller can re-supply the spec on resume to restore the resolver.\n */\nfunction serializeBudgetSpec(spec: BudgetSpec): SerializableBudgetSpec {\n  const out: SerializableBudgetSpec = {};\n  if (spec.tenantId !== undefined) out.tenantId = spec.tenantId;\n  if (spec.hard !== undefined) out.hard = spec.hard;\n  if (spec.maxUsd !== undefined) out.maxUsd = spec.maxUsd;\n  if (spec.maxTokens !== undefined) out.maxTokens = spec.maxTokens;\n  if (spec.maxLlmCalls !== undefined) out.maxLlmCalls = spec.maxLlmCalls;\n  if (spec.maxSteps !== undefined) out.maxSteps = spec.maxSteps;\n  if (spec.maxDurationMs !== undefined) out.maxDurationMs = spec.maxDurationMs;\n  if (spec.warnAt !== undefined) out.warnAt = { ...spec.warnAt };\n  if (spec.onExceed === 'throw' || spec.onExceed === 'truncate') {\n    out.onExceed = spec.onExceed;\n  } else if (typeof spec.onExceed === 'function') {\n    // Function form cannot survive serialization; fall back to throw and\n    // document that the caller should re-supply the spec on resume.\n    out.onExceed = 'throw';\n  }\n  return out;\n}\n\nfunction deserializeBudgetSpec(spec: SerializableBudgetSpec | undefined): BudgetSpec | undefined {\n  if (!spec) return undefined;\n  return spec as BudgetSpec; // shape is already a structural superset\n}\n\nfunction serializeError(err: unknown): { message: string; name?: string } {\n  if (err instanceof Error) {\n    return { name: err.name, message: err.message };\n  }\n  return { message: String(err) };\n}\n","import {\n  brandZiroError,\n  type LanguageModel,\n  type ModelGenerateResult,\n  ZiroError,\n} from '@ziro-agent/core';\nimport { createReplayLanguageModel } from '@ziro-agent/core/testing';\nimport { defineTool, type Tool, type ToolExecutionResult } from '@ziro-agent/tools';\nimport { z } from 'zod';\nimport {\n  type Agent,\n  type AgentRunOptions,\n  type AgentRunResult,\n  type CreateAgentOptions,\n  createAgent,\n} from './agent.js';\nimport type { AgentStep } from './types.js';\n\nexport const AGENT_RECORDING_VERSION = 1 as const;\n\ntype SerializedToolResult = Pick<\n  ToolExecutionResult,\n  'toolCallId' | 'toolName' | 'result' | 'isError'\n> & {\n  parsedArgs?: unknown;\n  budgetExceeded?: ToolExecutionResult['budgetExceeded'];\n};\n\n/**\n * One JSON line emitted by {@link runWithAgentRecording} per finished agent\n * step (after tools ran for that step).\n */\nexport interface AgentRecordingStepLine {\n  v: typeof AGENT_RECORDING_VERSION;\n  kind: 'step';\n  step: {\n    index: number;\n    text: string;\n    content: ModelGenerateResult['content'];\n    toolCalls: ModelGenerateResult['toolCalls'];\n    toolResults: SerializedToolResult[];\n    finishReason: ModelGenerateResult['finishReason'];\n    usage: ModelGenerateResult['usage'];\n  };\n}\n\n/** Thrown when replayed tool calls diverge from the recorded trace. */\nexport class ReplayMismatchError extends ZiroError {\n  override readonly name = 'ReplayMismatchError';\n  constructor(message: string) {\n    super(message, { code: 'replay_mismatch' });\n    brandZiroError(this);\n  }\n}\n\nfunction jsonSafeClone(value: unknown): unknown {\n  try {\n    return JSON.parse(JSON.stringify(value, jsonReplacer)) as unknown;\n  } catch {\n    return String(value);\n  }\n}\n\nfunction jsonReplacer(_key: string, val: unknown): unknown {\n  if (val instanceof Error) return { name: val.name, message: val.message };\n  return val;\n}\n\nfunction serializeToolResult(tr: ToolExecutionResult): SerializedToolResult {\n  const base: SerializedToolResult = {\n    toolCallId: tr.toolCallId,\n    toolName: tr.toolName,\n    result: jsonSafeClone(tr.result),\n    isError: tr.isError,\n  };\n  if (tr.parsedArgs !== undefined) base.parsedArgs = jsonSafeClone(tr.parsedArgs);\n  if (tr.budgetExceeded) base.budgetExceeded = { ...tr.budgetExceeded };\n  return base;\n}\n\nfunction serializeAgentStepLine(step: AgentStep): AgentRecordingStepLine {\n  return {\n    v: AGENT_RECORDING_VERSION,\n    kind: 'step',\n    step: {\n      index: step.index,\n      text: step.text,\n      content: step.content,\n      toolCalls: step.toolCalls,\n      toolResults: step.toolResults.map(serializeToolResult),\n      finishReason: step.finishReason,\n      usage: step.usage,\n    },\n  };\n}\n\n/**\n * Run an agent while appending one JSON line per completed step (RFC 0015).\n * Skips HITL suspension paths — only steps that fully finish are recorded.\n */\nexport async function runWithAgentRecording(\n  agent: Agent,\n  options: AgentRunOptions & {\n    recording: { writeLine: (line: string) => void | Promise<void> };\n  },\n): Promise<AgentRunResult> {\n  const { recording, onEvent, ...rest } = options;\n  return agent.run({\n    ...rest,\n    onEvent: async (ev) => {\n      if (onEvent) await onEvent(ev);\n      if (ev.type === 'step-finish') {\n        const line = JSON.stringify(serializeAgentStepLine(ev.step));\n        await Promise.resolve(recording.writeLine(`${line}\\n`));\n      }\n    },\n  });\n}\n\n/** RFC 0015 name — same as {@link runWithAgentRecording}. */\nexport const recordAgentRun = runWithAgentRecording;\n\n/**\n * Parse JSONL produced by {@link runWithAgentRecording}.\n */\nexport function parseAgentRecordingJsonl(text: string): AgentRecordingStepLine[] {\n  const out: AgentRecordingStepLine[] = [];\n  for (const raw of text.split('\\n')) {\n    const line = raw.trim();\n    if (!line) continue;\n    const o = JSON.parse(line) as AgentRecordingStepLine;\n    if (o.v !== AGENT_RECORDING_VERSION || o.kind !== 'step') {\n      throw new Error(`Unsupported agent recording line: ${line.slice(0, 120)}`);\n    }\n    out.push(o);\n  }\n  return out;\n}\n\n/**\n * Build a {@link LanguageModel} that reproduces recorded LLM steps in order.\n */\nexport function createReplayModelFromAgentRecording(\n  lines: readonly AgentRecordingStepLine[],\n  options?: { modelId?: string },\n): LanguageModel {\n  const responses: ModelGenerateResult[] = lines.map((l) => ({\n    text: l.step.text,\n    content: [...l.step.content],\n    toolCalls: [...l.step.toolCalls],\n    finishReason: l.step.finishReason,\n    usage: { ...l.step.usage },\n  }));\n  return createReplayLanguageModel(responses, options);\n}\n\n/**\n * Build deterministic tool stubs keyed by tool name so {@link createAgent}\n * can replay a trace without calling real side effects.\n */\nexport function createReplayToolsFromAgentRecording(\n  lines: readonly AgentRecordingStepLine[],\n): Record<string, Tool> {\n  const byCallId = new Map<string, SerializedToolResult>();\n  for (const l of lines) {\n    for (const tr of l.step.toolResults) {\n      byCallId.set(tr.toolCallId, tr);\n    }\n  }\n\n  const names = new Set<string>();\n  for (const l of lines) {\n    for (const tc of l.step.toolCalls) {\n      names.add(tc.toolName);\n    }\n  }\n\n  const tools: Record<string, Tool> = {};\n  for (const name of names) {\n    tools[name] = defineTool({\n      name,\n      description: 'Deterministic replay stub.',\n      input: z.unknown(),\n      mutates: false,\n      requiresApproval: false,\n      execute: async (_input, ctx) => {\n        const rec = byCallId.get(ctx.toolCallId);\n        if (!rec || rec.toolName !== name) {\n          throw new ReplayMismatchError(\n            `No recorded tool result for toolCallId=\"${ctx.toolCallId}\" toolName=\"${name}\".`,\n          );\n        }\n        if (rec.isError) {\n          const r = rec.result as { message?: string; name?: string };\n          const err = new Error(r?.message ?? 'Recorded tool error');\n          if (r?.name) err.name = r.name;\n          throw err;\n        }\n        return rec.result;\n      },\n    });\n  }\n  return tools;\n}\n\n/** Options for {@link replayAgentFromRecording} — `model` / `tools` default to replay stubs. */\nexport type ReplayAgentFromRecordingAgentOptions = Omit<CreateAgentOptions, 'model' | 'tools'> &\n  Partial<Pick<CreateAgentOptions, 'model' | 'tools'>>;\n\n/** {@link createReplayRunBundleFromRecording} return shape (RFC 0015). */\nexport interface ReplayRunBundle {\n  readonly agent: Agent;\n  run(runOptions: AgentRunOptions): Promise<AgentRunResult>;\n}\n\n/**\n * One-call replay: {@link createReplayModelFromAgentRecording} +\n * {@link createReplayToolsFromAgentRecording} + {@link createAgent} + {@link Agent.run}.\n */\nexport async function replayAgentFromRecording(\n  lines: readonly AgentRecordingStepLine[],\n  agentOptions: ReplayAgentFromRecordingAgentOptions,\n  runOptions: AgentRunOptions,\n): Promise<AgentRunResult> {\n  const model = agentOptions.model ?? createReplayModelFromAgentRecording(lines);\n  const tools = agentOptions.tools ?? createReplayToolsFromAgentRecording(lines);\n  const agent = createAgent({ ...agentOptions, model, tools });\n  return agent.run(runOptions);\n}\n\n/** Parse JSONL then {@link replayAgentFromRecording}. */\nexport async function replayAgentFromRecordingJsonl(\n  jsonl: string,\n  agentOptions: ReplayAgentFromRecordingAgentOptions,\n  runOptions: AgentRunOptions,\n): Promise<AgentRunResult> {\n  return replayAgentFromRecording(parseAgentRecordingJsonl(jsonl), agentOptions, runOptions);\n}\n\n/**\n * Build a replay {@link Agent} without running — pair with {@link Agent.run} /\n * {@link Agent.resumeFromCheckpoint} as needed (RFC 0015 convenience).\n */\nexport function createReplayAgentFromRecording(\n  lines: readonly AgentRecordingStepLine[],\n  agentOptions: ReplayAgentFromRecordingAgentOptions,\n): Agent {\n  const model = agentOptions.model ?? createReplayModelFromAgentRecording(lines);\n  const tools = agentOptions.tools ?? createReplayToolsFromAgentRecording(lines);\n  return createAgent({ ...agentOptions, model, tools });\n}\n\n/**\n * Returns `{ agent, run }` where `run` delegates to {@link Agent.run} on the\n * replay-configured agent (RFC 0015 `replayRun`-style bundle).\n */\nexport function createReplayRunBundleFromRecording(\n  lines: readonly AgentRecordingStepLine[],\n  agentOptions: ReplayAgentFromRecordingAgentOptions,\n): ReplayRunBundle {\n  const agent = createReplayAgentFromRecording(lines, agentOptions);\n  return {\n    agent,\n    run: (runOptions) => agent.run(runOptions),\n  };\n}\n","import { readFile } from 'node:fs/promises';\n\nimport type { AgentRunOptions, AgentRunResult } from '../agent.js';\nimport {\n  type ReplayAgentFromRecordingAgentOptions,\n  replayAgentFromRecordingJsonl,\n} from '../agent-recording.js';\n\n/**\n * Read a JSONL agent recording from disk and {@link replayAgentFromRecordingJsonl}.\n *\n * **Node-only** — import from `@ziro-agent/agent/node`, not the browser-safe\n * main entry.\n */\nexport async function replayAgentRunFromRecordingFile(\n  recordingPath: string,\n  agentOptions: ReplayAgentFromRecordingAgentOptions,\n  runOptions: AgentRunOptions,\n): Promise<AgentRunResult> {\n  const jsonl = await readFile(recordingPath, 'utf8');\n  return replayAgentFromRecordingJsonl(jsonl, agentOptions, runOptions);\n}\n"]}