framework-agents 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,7 @@
1
+ import {
2
+ Agent
3
+ } from "./chunk-2XXGDP7B.js";
4
+ export {
5
+ Agent
6
+ };
7
+ //# sourceMappingURL=agent-GDFFNEW5.js.map
@@ -703,7 +703,7 @@ function createSubAgentMiddleware(opts) {
703
703
  execute: async ({ subagent, input }) => {
704
704
  const def = opts.subagents.find((s) => s.name === subagent);
705
705
  if (!def) throw new AgentError("SUBAGENT_UNKNOWN", `Unknown subagent: ${subagent}`, false);
706
- const { Agent: AgentClass } = await import("./agent-ZEGATFZY.js");
706
+ const { Agent: AgentClass } = await import("./agent-GDFFNEW5.js");
707
707
  const sub = new AgentClass({
708
708
  name: def.name,
709
709
  description: def.description,
@@ -1808,4 +1808,4 @@ export {
1808
1808
  runWithBudget,
1809
1809
  Agent
1810
1810
  };
1811
- //# sourceMappingURL=chunk-VIGLIWEY.js.map
1811
+ //# sourceMappingURL=chunk-2XXGDP7B.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/types/index.ts","../src/types/content.ts","../src/utils/index.ts","../src/middleware/index.ts","../src/tools/index.ts","../src/conversation/index.ts","../src/state/index.ts","../src/sessions/index.ts","../src/structured/index.ts","../src/agent/index.ts","../src/memory/index.ts","../src/models/pricing.ts","../src/runtime/index.ts"],"sourcesContent":["import { z } from \"zod\";\nimport { ContentBlockSchema, type ContentBlock } from \"./content.js\";\n\nexport * from \"./content.js\";\n\nexport type Brand<T, B extends string> = T & { readonly __brand: B };\n\nexport type AgentId = Brand<string, \"AgentId\">;\nexport type RunId = Brand<string, \"RunId\">;\nexport type ToolName = Brand<string, \"ToolName\">;\n\nexport const ChatMessageSchema = z.object({\n id: z.string().optional(),\n role: z.enum([\"system\", \"user\", \"assistant\", \"tool\"]),\n content: z.union([z.string(), z.array(ContentBlockSchema)]),\n /** Provider user-identification; behavior varies, optional. */\n name: z.string().optional(),\n toolCallId: z.string().optional(),\n toolName: z.string().optional(),\n /** Pinned messages survive conversation-manager trimming. */\n pinned: z.boolean().optional(),\n});\n\nexport interface ChatMessage {\n id?: string;\n role: \"system\" | \"user\" | \"assistant\" | \"tool\";\n content: string | ContentBlock[];\n name?: string;\n toolCallId?: string;\n toolName?: string;\n pinned?: boolean;\n}\n\nexport interface AgentResult {\n text: string;\n messages: ChatMessage[];\n toolCalls: ExecutedToolCall[];\n usage: TokenUsage;\n /** Typed answer when the agent ran with `responseFormat`. */\n structuredResponse?: unknown;\n /** The invocation state object (same reference mutated during the run). */\n invocationState?: Record<string, unknown>;\n}\n\nexport interface ExecutedToolCall {\n id: string;\n name: string;\n args: unknown;\n output: unknown;\n /** Downstream-only data (never sent to the model). See Tool.toResult. */\n artifact?: unknown;\n}\n\nexport interface TokenUsage {\n inputTokens: number;\n outputTokens: number;\n /**\n * Reasoning/thinking tokens, when the provider reports them. A SUBSET of\n * `outputTokens` on every supported provider — count for reporting, never\n * add on top for budgets or cost.\n */\n reasoningTokens?: number;\n /** USD cost, when a price is known (see models/pricing). Never guessed. */\n costUsd?: number;\n}\n\nexport type Result<T, E = AgentError> =\n | { ok: true; value: T }\n | { ok: false; error: E };\n\nexport class AgentError extends Error {\n readonly code: string;\n readonly retryable: boolean;\n constructor(code: string, message: string, retryable = false) {\n super(message);\n this.name = \"AgentError\";\n this.code = code;\n this.retryable = retryable;\n }\n}\n\nlet messageSeq = 0;\n\n/** Factory helpers — stable ids, no class hierarchy. */\nexport function system(content: string | ContentBlock[]): ChatMessage {\n return { id: `msg_${++messageSeq}`, role: \"system\", content };\n}\n\nexport function user(content: string | ContentBlock[], opts?: { id?: string; name?: string }): ChatMessage {\n return { id: opts?.id ?? `msg_${++messageSeq}`, role: \"user\", content, name: opts?.name };\n}\n\nexport function assistant(content: string | ContentBlock[]): ChatMessage {\n return { id: `msg_${++messageSeq}`, role: \"assistant\", content };\n}\n\nexport function toolResult(toolCallId: string, toolName: string, content: string | ContentBlock[]): ChatMessage {\n return { id: `msg_${++messageSeq}`, role: \"tool\", content, toolCallId, toolName };\n}\n\n/** Serialize history for persistence (plain JSON-safe objects). */\nexport function serializeMessages(messages: ChatMessage[]): unknown[] {\n return messages.map((m) => ({ ...m }));\n}\n\n/** Deserialize + validate history (e.g. resume from disk). Throws on bad shape. */\nexport function deserializeMessages(raw: unknown[]): ChatMessage[] {\n return z.array(ChatMessageSchema).parse(raw);\n}\n","import { z } from \"zod\";\n\n/**\n * Content blocks — standard, provider-neutral message payload\n * Standard message payload: text, reasoning, multimodal and tool-call blocks.\n * `content` stays `string | ContentBlock[]`: strings for simple cases,\n * blocks for multimodal / reasoning / tool-call payloads.\n */\n\nexport const TextBlockSchema = z.object({ type: z.literal(\"text\"), text: z.string() });\nexport const ReasoningBlockSchema = z.object({ type: z.literal(\"reasoning\"), reasoning: z.string() });\nexport const ImageBlockSchema = z.object({\n type: z.literal(\"image\"),\n url: z.string().optional(),\n data: z.string().optional(),\n mimeType: z.string().optional(),\n fileId: z.string().optional(),\n});\nexport const AudioBlockSchema = z.object({\n type: z.literal(\"audio\"),\n url: z.string().optional(),\n data: z.string().optional(),\n mimeType: z.string().optional(),\n fileId: z.string().optional(),\n});\nexport const FileBlockSchema = z.object({\n type: z.literal(\"file\"),\n url: z.string().optional(),\n data: z.string().optional(),\n mimeType: z.string().optional(),\n fileId: z.string().optional(),\n});\nexport const ToolCallBlockSchema = z.object({\n type: z.literal(\"tool_call\"),\n id: z.string(),\n name: z.string(),\n args: z.unknown(),\n});\nexport const NonStandardBlockSchema = z.object({ type: z.literal(\"non_standard\"), value: z.unknown() });\n\nexport const ContentBlockSchema = z.discriminatedUnion(\"type\", [\n TextBlockSchema,\n ReasoningBlockSchema,\n ImageBlockSchema,\n AudioBlockSchema,\n FileBlockSchema,\n ToolCallBlockSchema,\n NonStandardBlockSchema,\n]);\n\nexport type ContentBlock = z.infer<typeof ContentBlockSchema>;\nexport type TextBlock = z.infer<typeof TextBlockSchema>;\nexport type ReasoningBlock = z.infer<typeof ReasoningBlockSchema>;\nexport type ImageBlock = z.infer<typeof ImageBlockSchema>;\n\n/** Plain-text view of any content shape — what the model \"reads\". */\nexport function textOf(content: string | ContentBlock[]): string {\n if (typeof content === \"string\") return content;\n return content\n .map((b) => {\n switch (b.type) {\n case \"text\":\n return b.text;\n case \"reasoning\":\n return b.reasoning;\n case \"tool_call\":\n return \"\";\n case \"non_standard\":\n return \"\";\n default:\n return \"\";\n }\n })\n .join(\"\");\n}\n\n/**\n * Text for re-sending history to a provider: reasoning blocks are dropped —\n * a model's own past thinking must not come back as ordinary assistant text\n * (duplicated context, and Anthropic rejects thinking-as-text turns).\n */\nexport function wireTextOf(content: string | ContentBlock[]): string {\n if (typeof content === \"string\") return content;\n return content\n .filter((b) => b.type !== \"reasoning\")\n .map((b) => (b.type === \"text\" ? b.text : \"\"))\n .join(\"\");\n}\n\nexport function hasImages(content: string | ContentBlock[]): boolean {\n return typeof content !== \"string\" && content.some((b) => b.type === \"image\");\n}\n\n/** Images in wire-ready form (url or base64 data). */\nexport function imagesOf(content: string | ContentBlock[]): { url?: string; data?: string; mimeType?: string }[] {\n if (typeof content === \"string\") return [];\n return content.filter((b) => b.type === \"image\").map((b) => ({ url: b.url, data: b.data, mimeType: b.mimeType }));\n}\n","export async function sleep(ms: number, signal?: AbortSignal): Promise<void> {\n signal?.throwIfAborted();\n if (ms <= 0) return;\n await new Promise<void>((resolve, reject) => {\n const t = setTimeout(resolve, ms);\n signal?.addEventListener(\n \"abort\",\n () => {\n clearTimeout(t);\n reject(new DOMException(\"Aborted\", \"AbortError\"));\n },\n { once: true },\n );\n });\n}\n\n/**\n * Local token estimate — dependency-free approximation, not a BPE.\n * Counts word-ish runs, numbers, CJK characters, and punctuation clusters\n * separately (close to subword behavior on prose; ±30% on code).\n * Calibrated so `estimateTokens(\"abcd\") === 1`. Prefer provider usage\n * metadata when available; use this for budgets and triggers only.\n */\nexport function estimateTokens(text: string): number {\n if (!text) return 0;\n const words = text.match(/[A-Za-z]+(?:'[A-Za-z]+)?|\\d+(?:\\.\\d+)?|[\\u4E00-\\u9FFF\\u3040-\\u30FF\\uAC00-\\uD7AF]|[^A-Za-z\\d\\s]/g);\n if (!words) return 0;\n let tokens = 0;\n for (const w of words) {\n if (/^[\\u4E00-\\u9FFF\\u3040-\\u30FF\\uAC00-\\uD7AF]$/.test(w)) {\n tokens += 1;\n } else if (/^[A-Za-z]+(?:'[A-Za-z]+)?$/.test(w)) {\n tokens += Math.max(1, Math.ceil(w.length / 5));\n } else {\n tokens += 1;\n }\n }\n return tokens;\n}\n\n/** Rough USD cost for usage against a per-1M-token price table. */\nexport function estimateCostUsd(\n usage: { inputTokens: number; outputTokens: number },\n price: { inputPerMillion: number; outputPerMillion: number },\n): number {\n return (usage.inputTokens * price.inputPerMillion + usage.outputTokens * price.outputPerMillion) / 1_000_000;\n}\n","import { AgentError } from \"../types/index.js\";\nimport type { InvocationState } from \"../state/index.js\";\nimport { sleep } from \"../utils/index.js\";\nimport type { ChatMessage, ContentBlock } from \"../types/index.js\";\nimport type { ModelCompletion, ModelProvider, ResponseFormatWire } from \"../models/index.js\";\nimport type { Tool } from \"../tools/index.js\";\n\n/**\n * Middleware — control the agent loop without forking it.\n *\n * Execution order:\n * - beforeModel / beforeTool: registration order\n * - afterModel / afterTool: REVERSE order\n * - wrapModel / aroundTool: nested, first registered = outermost\n */\n\nexport interface HookContext {\n step: number;\n /** Per-run data, shared by reference (never sent to the model). */\n invocationState?: InvocationState;\n}\n\nexport interface ModelRequest {\n messages: ChatMessage[];\n tools: { name: string; description: string; parametersSchema?: Record<string, unknown> }[];\n responseFormat?: ResponseFormatWire;\n}\n\nexport interface ToolCallRef {\n name: string;\n args: unknown;\n}\n\nexport interface AgentMiddleware {\n name: string;\n /** Tools contributed by this middleware (merged into the agent's tool list). */\n tools?: Tool[];\n beforeModel?: (req: ModelRequest, ctx: HookContext) => Promise<ModelRequest | undefined> | ModelRequest | undefined;\n wrapModel?: (\n req: ModelRequest,\n next: (req: ModelRequest) => Promise<ModelCompletion>,\n ctx: HookContext,\n ) => Promise<ModelCompletion>;\n afterModel?: (res: ModelCompletion, req: ModelRequest, ctx: HookContext) => Promise<ModelCompletion | undefined> | ModelCompletion | undefined;\n beforeTool?: (call: ToolCallRef, ctx: HookContext) => Promise<ToolCallRef | undefined> | ToolCallRef | undefined;\n aroundTool?: (call: ToolCallRef, next: () => Promise<unknown>, ctx: HookContext) => Promise<unknown>;\n afterTool?: (call: ToolCallRef, output: unknown, ctx: HookContext) => Promise<unknown> | unknown;\n}\n\n/** Identity factory — documents intent and locks the type. */\nexport function createMiddleware(m: AgentMiddleware): AgentMiddleware {\n return m;\n}\n\n/** Thrown (usually by approval middleware) to skip execution with feedback for the model. */\nexport class ToolRejection extends Error {\n readonly feedback: string;\n constructor(feedback: string) {\n super(feedback);\n this.name = \"ToolRejection\";\n this.feedback = feedback;\n }\n}\n\n// ---------------------------------------------------------------------------\n// Retry verdicts (stampRetryable / getRetryable)\n// ---------------------------------------------------------------------------\n\nconst RETRYABLE = Symbol.for(\"framework.retryable\");\n\n/** Mark an error retryable (true) or fatal (false). Shape and type are untouched. */\nexport function stampRetryable<T extends Error>(err: T, retryable: boolean): T {\n (err as unknown as Record<symbol, boolean>)[RETRYABLE] = retryable;\n return err;\n}\n\n/** Read a verdict: true/false, or undefined when never marked. AgentError maps to its flag. */\nexport function getRetryable(err: unknown): boolean | undefined {\n if (err instanceof AgentError) return err.retryable;\n if (err instanceof Error) return (err as unknown as Record<symbol, boolean | undefined>)[RETRYABLE];\n return undefined;\n}\n\nexport interface BackoffOptions {\n maxRetries?: number;\n initialDelayMs?: number;\n backoffFactor?: number;\n maxDelayMs?: number;\n jitter?: boolean;\n}\n\nexport function backoffDelayMs(attempt: number, opts: Required<Omit<BackoffOptions, \"maxRetries\">>): number {\n const grown = opts.initialDelayMs * opts.backoffFactor ** attempt;\n const capped = Math.min(grown, opts.maxDelayMs);\n if (!opts.jitter) return capped;\n return capped * (0.75 + Math.random() * 0.5);\n}\n\nfunction normalizeBackoff(opts: BackoffOptions): Required<Omit<BackoffOptions, \"maxRetries\">> & { maxRetries: number } {\n return {\n maxRetries: Math.max(0, opts.maxRetries ?? 2),\n initialDelayMs: Math.max(0, opts.initialDelayMs ?? 1000),\n backoffFactor: Math.max(0, opts.backoffFactor ?? 2),\n maxDelayMs: Math.max(0, opts.maxDelayMs ?? 60000),\n jitter: opts.jitter ?? true,\n };\n}\n\nexport type RetryFilter = ((error: Error) => boolean) | (new (...args: never[]) => Error)[];\n\nfunction shouldRetryErr(filter: RetryFilter | undefined, err: unknown): boolean {\n if (!(err instanceof Error)) return true;\n if (getRetryable(err) === false) return false;\n if (!filter) return getRetryable(err) ?? true;\n if (Array.isArray(filter)) return filter.some((C) => err instanceof C);\n return filter(err);\n}\n\n// ---------------------------------------------------------------------------\n// Built-ins\n// ---------------------------------------------------------------------------\n\n/** Cap model calls per run; exceeded -> AgentError(BUDGET_EXCEEDED). Stateless (uses step). */\nexport function modelCallLimit(maxCalls: number): AgentMiddleware {\n return {\n name: \"model-call-limit\",\n beforeModel: (_req, ctx) => {\n if (ctx.step >= maxCalls) {\n throw new AgentError(\"BUDGET_EXCEEDED\", `Exceeded model call limit (${maxCalls})`, false);\n }\n return undefined;\n },\n };\n}\n\n/** Retry failing tool executions with exponential backoff. AgentErrors pass through untouched. */\nexport function toolRetry(opts: { attempts?: number; backoffMs?: number } = {}): AgentMiddleware {\n const attempts = Math.max(1, opts.attempts ?? 2);\n const backoffMs = opts.backoffMs ?? 0;\n return {\n name: \"tool-retry\",\n aroundTool: async (call, next, _ctx) => {\n let last: unknown;\n for (let i = 0; i < attempts; i++) {\n try {\n return await next();\n } catch (err) {\n if (err instanceof AgentError) throw err;\n last = err;\n if (i < attempts - 1 && backoffMs > 0) await sleep(backoffMs);\n }\n }\n throw last;\n },\n };\n}\n\nexport interface RetryMiddlewareOptions extends BackoffOptions {\n retryOn?: RetryFilter;\n onFailure?: \"error\" | \"continue\" | ((error: Error) => string);\n /** Limit retries to these tool names (tool retry only). */\n tools?: string[];\n}\n\n/**\n * Full tool retry: exponential backoff + jitter, error-class filtering,\n * per-tool scoping, and exhausted-failure behavior (continue as tool\n * message vs rethrow). Honors stampRetryable verdicts.\n */\nexport function toolRetryMiddleware(opts: RetryMiddlewareOptions = {}): AgentMiddleware {\n const cfg = normalizeBackoff(opts);\n const only = opts.tools ? new Set(opts.tools) : undefined;\n return {\n name: \"tool-retry\",\n aroundTool: async (call, next) => {\n if (only && !only.has(call.name)) return next();\n let last: unknown;\n for (let i = 0; i <= cfg.maxRetries; i++) {\n try {\n return await next();\n } catch (err) {\n last = err;\n const retryable = err instanceof Error ? shouldRetryErr(opts.retryOn, err) : true;\n if (!retryable || i === cfg.maxRetries) break;\n await sleep(backoffDelayMs(i, cfg));\n }\n }\n if (opts.onFailure === \"error\") throw last;\n if (typeof opts.onFailure === \"function\") return opts.onFailure(last as Error);\n if (opts.onFailure === \"continue\") {\n // Degrade gracefully: the error becomes tool feedback, the run finishes.\n const message = last instanceof Error ? last.message : String(last);\n return `Tool \"${call.name}\" failed after retries: ${message}`;\n }\n throw last;\n },\n };\n}\n\n/**\n * Model retry with the same backoff/filter/onFailure semantics.\n * onFailure \"continue\" synthesizes an empty-text completion so the loop ends gracefully.\n */\nexport function modelRetryMiddleware(opts: RetryMiddlewareOptions = {}): AgentMiddleware {\n const cfg = normalizeBackoff(opts);\n return {\n name: \"model-retry\",\n wrapModel: async (req, next) => {\n let last: unknown;\n for (let i = 0; i <= cfg.maxRetries; i++) {\n try {\n return await next(req);\n } catch (err) {\n last = err;\n const retryable = err instanceof Error ? shouldRetryErr(opts.retryOn, err) : true;\n if (!retryable || i === cfg.maxRetries) break;\n await sleep(backoffDelayMs(i, cfg));\n }\n }\n if (opts.onFailure === \"error\") throw last;\n if (typeof opts.onFailure === \"function\") {\n return { text: opts.onFailure(last as Error), toolCalls: [], usage: { inputTokens: 0, outputTokens: 0 } };\n }\n if (opts.onFailure === \"continue\") {\n const message = last instanceof Error ? last.message : String(last);\n return { text: `Model call failed after retries: ${message}`, toolCalls: [], usage: { inputTokens: 0, outputTokens: 0 } };\n }\n throw last;\n },\n };\n}\n\n/** Fall back across providers when the primary model fails (first success wins). */\nexport function modelFallbackMiddleware(...fallbacks: ModelProvider[]): AgentMiddleware {\n return {\n name: \"model-fallback\",\n wrapModel: async (req, next) => {\n try {\n return await next(req);\n } catch (primaryErr) {\n let last = primaryErr;\n for (const fb of fallbacks) {\n try {\n return await fb.complete({\n messages: req.messages,\n tools: req.tools,\n ...(req.responseFormat ? { responseFormat: req.responseFormat } : {}),\n });\n } catch (err) {\n last = err;\n }\n }\n throw last;\n }\n },\n };\n}\n\n/** Per-run tool-call budgets (global + per-tool). Exceeded calls are blocked with feedback or throw. */\nexport function toolCallLimitMiddleware(opts: {\n toolName?: string;\n runLimit?: number;\n exitBehavior?: \"continue\" | \"error\";\n}): AgentMiddleware {\n if (opts.runLimit == null) throw new Error(\"toolCallLimitMiddleware: runLimit is required\");\n const counts = new Map<string, number>();\n return {\n name: \"tool-call-limit\",\n beforeModel: (_req, ctx) => {\n if (ctx.step === 0) counts.clear();\n return undefined;\n },\n beforeTool: (call) => {\n if (opts.toolName && call.name !== opts.toolName) return undefined;\n const key = opts.toolName ?? \"*\";\n const used = (counts.get(key) ?? 0) + 1;\n counts.set(key, used);\n if (used > (opts.runLimit ?? Number.POSITIVE_INFINITY)) {\n if (opts.exitBehavior === \"error\") {\n throw new AgentError(\"BUDGET_EXCEEDED\", `Tool call limit exceeded for ${opts.toolName ?? \"all tools\"} (${opts.runLimit})`, false);\n }\n throw new ToolRejection(`Tool \"${call.name}\" call limit exceeded (${opts.runLimit}). Do not retry this tool; finish with what you have.`);\n }\n return undefined;\n },\n };\n}\n\nexport type HitlDecision = \"approve\" | { edit: unknown } | { reject: string } | { suspend: true };\n\n/** Thrown to suspend a run for human review. Persisted by checkpoint when checkpointer+threadId are set. */\nexport class HitlInterrupt extends Error {\n readonly interruptId: string;\n readonly tool: string;\n readonly args: unknown;\n constructor(interruptId: string, tool: string, args: unknown) {\n super(`Approval needed for tool \"${tool}\" (interrupt ${interruptId})`);\n this.name = \"HitlInterrupt\";\n this.interruptId = interruptId;\n this.tool = tool;\n this.args = args;\n }\n}\n\n/** Stable key binding a decision to one tool call (used across suspend/resume). */\nexport function hitlKey(tool: string, args: unknown): string {\n return `${tool}:${JSON.stringify(args ?? {})}`;\n}\n\nexport interface HitlDecideRequest {\n name: string;\n args: unknown;\n allowed: (\"approve\" | \"edit\" | \"reject\")[];\n interruptId: string;\n}\n\n/**\n * Human-in-the-loop: pause tool execution for approval/edit/reject.\n * Single-process version — `decide` is called inline (CLI prompt, API\n * handler, test stub). Checkpointed resume lands with durable runtime (P3).\n */\nexport function humanInTheLoopMiddleware(opts: {\n interruptOn: Record<string, boolean | { allowedDecisions?: (\"approve\" | \"edit\" | \"reject\")[] }>;\n /** Inline decider. May return { suspend: true } to checkpoint + throw HitlInterrupt. Omit to always suspend. */\n decide?: (req: HitlDecideRequest) => Promise<HitlDecision> | HitlDecision;\n}): AgentMiddleware {\n return {\n name: \"human-in-the-loop\",\n beforeTool: async (call, ctx) => {\n const rule = opts.interruptOn[call.name];\n if (!rule) return undefined;\n const allowed = rule === true ? ([\"approve\", \"edit\", \"reject\"] as const) : (rule.allowedDecisions ?? [\"approve\", \"edit\", \"reject\"]);\n const id = hitlKey(call.name, call.args);\n // Decision keys: exact hitlKey(tool, args) first, then a bare TOOL NAME —\n // the human picks the scope. The wildcard matters for resume: a model\n // re-issuing a call regenerates arg text (temperature), so exact keys\n // never converge; \"publish\": \"approve\" approves the re-issued call.\n const all = (ctx.invocationState?.__hitlDecisions as Record<string, HitlDecision> | undefined) ?? {};\n const stored = all[id] ?? all[call.name];\n const decision: HitlDecision = stored ?? (opts.decide ? await opts.decide({ name: call.name, args: call.args, allowed: [...allowed], interruptId: id }) : { suspend: true });\n if (typeof decision === \"object\" && \"suspend\" in decision) {\n throw new HitlInterrupt(id, call.name, call.args);\n }\n if (decision === \"approve\") {\n if (!allowed.includes(\"approve\")) throw new AgentError(\"HITL_DECISION\", `\"approve\" not allowed for ${call.name}`, false);\n return undefined;\n }\n if (typeof decision === \"object\" && \"edit\" in decision) {\n if (!allowed.includes(\"edit\")) throw new AgentError(\"HITL_DECISION\", `\"edit\" not allowed for ${call.name}`, false);\n return { name: call.name, args: decision.edit };\n }\n const message = (decision as { reject: string }).reject;\n if (!allowed.includes(\"reject\")) throw new AgentError(\"HITL_DECISION\", `\"reject\" not allowed for ${call.name}`, false);\n throw new ToolRejection(typeof message === \"string\" && message ? message : `User rejected ${call.name}. Do not retry this tool call.`);\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// PII\n// ---------------------------------------------------------------------------\n\nexport interface PIIMatch {\n text: string;\n start: number;\n end: number;\n}\n\nexport type PIIDetector = RegExp | string | ((content: string) => PIIMatch[]);\nexport type PIIStrategy = \"block\" | \"redact\" | \"mask\" | \"hash\";\n\nconst BUILTIN_DETECTORS: Record<string, RegExp> = {\n email: /[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\\.[a-zA-Z]{2,}/g,\n credit_card: /\\b(?:\\d[ -]?){13,16}\\b/g,\n ip: /\\b(?:\\d{1,3}\\.){3}\\d{1,3}\\b/g,\n};\n\nfunction findMatches(detector: PIIDetector, content: string): PIIMatch[] {\n if (typeof detector === \"function\") return detector(content);\n const re = typeof detector === \"string\" ? new RegExp(detector, \"g\") : new RegExp(detector.source, detector.flags.includes(\"g\") ? detector.flags : `${detector.flags}g`);\n const out: PIIMatch[] = [];\n let m: RegExpExecArray | null;\n while ((m = re.exec(content)) !== null) {\n out.push({ text: m[0], start: m.index, end: m.index + m[0].length });\n if (m[0].length === 0) re.lastIndex += 1;\n }\n return out;\n}\n\nfunction djb2(text: string): string {\n let h = 5381;\n for (let i = 0; i < text.length; i++) h = ((h << 5) + h + text.charCodeAt(i)) >>> 0;\n return h.toString(16).padStart(8, \"0\");\n}\n\nfunction applyStrategy(text: string, type: string, strategy: PIIStrategy): string {\n switch (strategy) {\n case \"redact\":\n return `[REDACTED_${type.toUpperCase()}]`;\n case \"mask\": {\n const visible = text.slice(-4);\n return `${\"*\".repeat(Math.max(0, text.length - 4))}${visible}`;\n }\n case \"hash\":\n return `<${type}_hash:${djb2(text)}>`;\n case \"block\":\n throw new AgentError(\"PII_BLOCKED\", `Blocked ${type} in content`, false);\n }\n}\n\nfunction scrubText(content: string, type: string, detector: PIIDetector, strategy: PIIStrategy): string {\n const matches = findMatches(detector, content).sort((a, b) => b.start - a.start);\n let out = content;\n for (const m of matches) out = out.slice(0, m.start) + applyStrategy(m.text, type, strategy) + out.slice(m.end);\n return out;\n}\n\nfunction scrubBlocks(blocks: ContentBlock[], fn: (text: string) => string): ContentBlock[] {\n return blocks.map((b) => {\n if (b.type === \"text\") return { ...b, text: fn(b.text) };\n if (b.type === \"reasoning\") return { ...b, reasoning: fn(b.reasoning) };\n return b;\n });\n}\n\n/** PII detection with redact/mask/hash/block strategies across input, output, and tool results. */\nexport function piiMiddleware(\n piiType: string,\n opts: {\n strategy?: PIIStrategy;\n detector?: PIIDetector;\n applyToInput?: boolean;\n applyToOutput?: boolean;\n applyToToolResults?: boolean;\n } = {},\n): AgentMiddleware {\n const strategy = opts.strategy ?? \"redact\";\n const detector = opts.detector ?? BUILTIN_DETECTORS[piiType] ?? (() => [] as PIIMatch[]);\n const scrub = (s: string) => scrubText(s, piiType, detector, strategy);\n return {\n name: `pii-${piiType}`,\n beforeModel: (req) => {\n if (opts.applyToInput === false) return undefined;\n return {\n ...req,\n messages: req.messages.map((m) =>\n typeof m.content === \"string\" ? { ...m, content: scrub(m.content) } : { ...m, content: scrubBlocks(m.content, scrub) },\n ),\n };\n },\n afterModel: (res) => {\n if (!opts.applyToOutput) return undefined;\n return { ...res, text: scrub(res.text) };\n },\n afterTool: (_call, output) => {\n if (!opts.applyToToolResults || typeof output !== \"string\") return output;\n return scrub(output);\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Summarization + context editing\n// ---------------------------------------------------------------------------\n\nimport { estimateTokens } from \"../utils/index.js\";\nimport { textOf } from \"../types/index.js\";\n\nfunction messageTokens(m: ChatMessage): number {\n return estimateTokens(typeof m.content === \"string\" ? m.content : textOf(m.content));\n}\n\n/**\n * Auto-summarize history when estimated tokens pass `triggerTokens`,\n * keeping the newest `keepMessages`. Text-oriented: summarized-away\n * multimodal blocks survive only as prose (store media externally and\n * pass URLs if images must persist).\n */\nexport function summarizationMiddleware(opts: {\n model: ModelProvider;\n triggerTokens: number;\n keepMessages?: number;\n summaryPrefix?: string;\n summarize?: (messages: ChatMessage[]) => Promise<string>;\n}): AgentMiddleware {\n const keep = Math.max(1, opts.keepMessages ?? 20);\n return {\n name: \"summarization\",\n beforeModel: async (req) => {\n const total = req.messages.reduce((n, m) => n + messageTokens(m), 0);\n if (total < opts.triggerTokens) return undefined;\n const compress = req.messages.slice(0, Math.max(0, req.messages.length - keep));\n if (!compress.length) return undefined;\n const summary = opts.summarize\n ? await opts.summarize(compress)\n : await summarizeWithModel(opts.model, compress);\n const prefix = opts.summaryPrefix ?? \"Summary of earlier context:\";\n return {\n ...req,\n messages: [\n req.messages[0],\n { role: \"assistant\", content: `${prefix}\\n${summary}` },\n ...req.messages.slice(req.messages.length - keep),\n ],\n };\n },\n };\n}\n\nasync function summarizeWithModel(model: ModelProvider, messages: ChatMessage[]): Promise<string> {\n const transcript = messages.map((m) => `[${m.role}] ${typeof m.content === \"string\" ? m.content : textOf(m.content)}`).join(\"\\n\");\n const res = await model.complete({\n messages: [{ role: \"user\", content: `Summarize this conversation history concisely, preserving decisions, names, and open items:\\n${transcript}` }],\n tools: [],\n });\n return res.text;\n}\n\nexport interface ClearToolUsesOptions {\n triggerTokens?: number;\n keep?: number;\n clearToolInputs?: boolean;\n excludeTools?: string[];\n placeholder?: string;\n}\n\n/** Clear older tool outputs past a token budget; newest `keep` results survive. */\nexport class ClearToolUsesEdit {\n private opts: Required<ClearToolUsesOptions>;\n constructor(opts: ClearToolUsesOptions = {}) {\n this.opts = {\n triggerTokens: opts.triggerTokens ?? 100000,\n keep: opts.keep ?? 3,\n clearToolInputs: opts.clearToolInputs ?? false,\n excludeTools: opts.excludeTools ?? [],\n placeholder: opts.placeholder ?? \"[cleared]\",\n };\n }\n\n apply(messages: ChatMessage[]): ChatMessage[] {\n const total = messages.reduce((n, m) => n + messageTokens(m), 0);\n if (total < this.opts.triggerTokens) return messages;\n const excluded = new Set(this.opts.excludeTools);\n const toolIdx = messages.map((m, i) => (m.role === \"tool\" && m.toolName && !excluded.has(m.toolName) ? i : -1)).filter((i) => i >= 0);\n const clearable = new Set(toolIdx.slice(0, Math.max(0, toolIdx.length - this.opts.keep)));\n return messages.map((m, i) => {\n if (!clearable.has(i) || m.role !== \"tool\") return m;\n return { ...m, content: this.opts.placeholder };\n });\n }\n\n clearInputs(messages: ChatMessage[]): ChatMessage[] {\n if (!this.opts.clearToolInputs) return messages;\n const excluded = new Set(this.opts.excludeTools);\n return messages.map((m) => {\n if (typeof m.content === \"string\" || m.role !== \"assistant\") return m;\n return {\n ...m,\n content: m.content.map((b) =>\n b.type === \"tool_call\" && !excluded.has(b.name) ? { ...b, args: {} } : b,\n ),\n };\n });\n }\n}\n\nexport function contextEditingMiddleware(opts: { edits?: ClearToolUsesEdit[] }): AgentMiddleware {\n const edits = opts.edits ?? [new ClearToolUsesEdit()];\n return {\n name: \"context-editing\",\n beforeModel: (req) => {\n let messages = req.messages;\n for (const edit of edits) {\n messages = edit.clearInputs(edit.apply(messages));\n }\n return messages === req.messages ? undefined : { ...req, messages };\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Todo list\n// ---------------------------------------------------------------------------\n\nexport interface TodoItem {\n content: string;\n status: \"pending\" | \"active\" | \"completed\";\n}\n\n/** Task planning: contributes a `write_todos` tool and tracks state per run. */\nexport function todoListMiddleware(): AgentMiddleware & { listTodos(): TodoItem[] } {\n let todos: TodoItem[] = [];\n return {\n name: \"todo-list\",\n tools: [\n defineTool({\n name: \"write_todos\",\n description: \"Track multi-step progress. Set exactly one item active at a time; mark completed as you finish.\",\n schema: z.object({ todos: z.array(z.object({ content: z.string(), status: z.enum([\"pending\", \"active\", \"completed\"]) })) }),\n execute: async ({ todos: next }: { todos: TodoItem[] }) => {\n todos = next;\n const open = todos.filter((t) => t.status !== \"completed\").length;\n return `Todos updated (${open} open):\\n${todos.map((t) => `- [${t.status === \"completed\" ? \"x\" : \" \"}] ${t.content}`).join(\"\\n\")}`;\n },\n }),\n ],\n beforeModel: (req, ctx) => {\n if (ctx.step === 0) todos = [];\n const hinted = req.messages[0]?.content;\n const hint = \"For multi-step tasks, plan with write_todos first; keep exactly one item active.\";\n if (typeof hinted === \"string\" && !hinted.includes(\"write_todos\")) {\n return { ...req, messages: [{ ...req.messages[0], content: `${hinted}\\n${hint}` }, ...req.messages.slice(1)] };\n }\n return undefined;\n },\n listTodos: () => [...todos],\n };\n}\n\n// ---------------------------------------------------------------------------\n// LLM tool selector + emulator\n// ---------------------------------------------------------------------------\n\n/** Narrow 10+ tools to the relevant few before the main model call. */\nexport function llmToolSelectorMiddleware(opts: {\n model: ModelProvider;\n maxTools?: number;\n alwaysInclude?: string[];\n systemPrompt?: string;\n}): AgentMiddleware {\n return {\n name: \"llm-tool-selector\",\n beforeModel: async (req) => {\n if (opts.maxTools != null && req.tools.length <= opts.maxTools && !opts.alwaysInclude) return undefined;\n const lastUser = [...req.messages].reverse().find((m) => m.role === \"user\");\n const menu = req.tools.map((t) => `- ${t.name}: ${t.description}`).join(\"\\n\");\n const res = await opts.model.complete({\n messages: [\n { role: \"system\", content: opts.systemPrompt ?? \"Pick relevant tools. Reply with ONLY a comma-separated list of tool names.\" },\n { role: \"user\", content: `Tools:\\n${menu}\\n\\nQuery: ${lastUser ? textOf(lastUser.content) : \"\"}` },\n ],\n tools: [],\n });\n const picked = new Set(res.text.split(\",\").map((s) => s.trim()).filter(Boolean));\n for (const name of opts.alwaysInclude ?? []) picked.add(name);\n let tools = req.tools.filter((t) => picked.has(t.name));\n if (opts.maxTools != null) tools = tools.slice(0, opts.maxTools);\n if (!tools.length) return undefined;\n return { ...req, tools };\n },\n };\n}\n\n/** Emulate tool execution with an LLM — testing/prototyping without side effects. */\nexport function toolEmulatorMiddleware(opts: { tools?: string[]; model?: ModelProvider } = {}): AgentMiddleware {\n const only = opts.tools ? new Set(opts.tools) : undefined;\n return {\n name: \"tool-emulator\",\n aroundTool: async (call, next, _ctx) => {\n if ((only && !only.has(call.name)) || !opts.model) {\n if (!opts.model) return `[emulated ${call.name}] no emulator model configured`;\n return next();\n }\n const res = await opts.model.complete({\n messages: [{ role: \"user\", content: `Emulate tool \"${call.name}\" with arguments ${JSON.stringify(call.args)}. Reply with ONLY the plausible tool output.` }],\n tools: [],\n });\n return res.text;\n },\n };\n}\n\n// ---------------------------------------------------------------------------\n// Filesystem tools\n// ---------------------------------------------------------------------------\n\nimport { z } from \"zod\";\nimport { defineTool } from \"../tools/index.js\";\nimport { mkdir, readdir, readFile, writeFile } from \"node:fs/promises\";\nimport { dirname, resolve } from \"node:path\";\n\n/** ls/read_file/write_file/edit_file scoped to `root` (escapes rejected). */\nexport function filesystemTools(root: string): Tool[] {\n const base = resolve(root);\n const resolveIn = (p: string): string => {\n const full = resolve(base, p);\n if (full !== base && !full.startsWith(`${base}/`)) throw new AgentError(\"FS_ESCAPE\", `Path escapes root: ${p}`, false);\n return full;\n };\n return [\n defineTool({\n name: \"ls\",\n description: \"List files in a directory (relative to workspace root).\",\n schema: z.object({ path: z.string().optional() }),\n execute: async ({ path }: { path?: string }) => (await readdir(resolveIn(path ?? \".\"))).join(\"\\n\"),\n }),\n defineTool({\n name: \"read_file\",\n description: \"Read a file's full text.\",\n schema: z.object({ path: z.string() }),\n execute: async ({ path }: { path: string }) => readFile(resolveIn(path), \"utf8\"),\n }),\n defineTool({\n name: \"write_file\",\n description: \"Write (create or overwrite) a file.\",\n schema: z.object({ path: z.string(), content: z.string() }),\n execute: async ({ path, content }: { path: string; content: string }) => {\n const full = resolveIn(path);\n await mkdir(dirname(full), { recursive: true });\n await writeFile(full, content, \"utf8\");\n return `wrote ${path} (${content.length} chars)`;\n },\n }),\n defineTool({\n name: \"edit_file\",\n description: \"Replace the first occurrence of oldString with newString in a file.\",\n schema: z.object({ path: z.string(), oldString: z.string(), newString: z.string() }),\n execute: async ({ path, oldString, newString: ns }: { path: string; oldString: string; newString: string }) => {\n const full = resolveIn(path);\n const content = await readFile(full, \"utf8\");\n if (!content.includes(oldString)) throw new AgentError(\"FS_NO_MATCH\", `oldString not found in ${path}`, false);\n await writeFile(full, content.replace(oldString, ns), \"utf8\");\n return `edited ${path}`;\n },\n }),\n ];\n}\n\nexport function filesystemMiddleware(opts: { root: string }): AgentMiddleware {\n return { name: \"filesystem\", tools: filesystemTools(opts.root) };\n}\n\n// ---------------------------------------------------------------------------\n// Subagents (task tool)\n// ---------------------------------------------------------------------------\n\nimport type { Agent } from \"../agent/index.js\";\n\n/**\n * Spawn named subagents via a `task` tool — isolates context so the\n * supervisor stays clean while the subagent goes deep.\n */\nexport function createSubAgentMiddleware(opts: {\n model: ModelProvider;\n subagents: { name: string; description: string; systemPrompt?: string; tools?: Tool[] }[];\n}): AgentMiddleware {\n return {\n name: \"subagents\",\n tools: [\n defineTool({\n name: \"task\",\n description: `Delegate to a specialist subagent. Available: ${opts.subagents.map((s) => `${s.name} (${s.description})`).join(\"; \")}. Returns the subagent's final answer.`,\n schema: z.object({ subagent: z.string(), input: z.string() }),\n execute: async ({ subagent, input }: { subagent: string; input: string }) => {\n const def = opts.subagents.find((s) => s.name === subagent);\n if (!def) throw new AgentError(\"SUBAGENT_UNKNOWN\", `Unknown subagent: ${subagent}`, false);\n const { Agent: AgentClass } = await import(\"../agent/index.js\");\n const sub: Agent = new AgentClass({\n name: def.name,\n description: def.description,\n systemPrompt: def.systemPrompt,\n model: opts.model,\n tools: def.tools ?? [],\n });\n return (await sub.run(input)).text;\n },\n }),\n ],\n };\n}\n","import { z } from \"zod\";\nimport { AgentError, type ContentBlock } from \"../types/index.js\";\nimport type { ToolContext } from \"../state/index.js\";\n\nexport interface ToolResult {\n /** Model-visible content (string or blocks). */\n content: string | ContentBlock[];\n /** Downstream-only data — stored on the call record, never sent to the model. */\n artifact?: unknown;\n}\n\n/**\n * Minimal structural contract for a schema — satisfied by zod v3, v4, minis,\n * and anything with `.parse` (so consumers on ANY zod version work).\n */\nexport type AnySchema = { parse(input: unknown): unknown };\n\nexport interface Tool<TArgs = any, TOutput = any> {\n name: string;\n description: string;\n /** Any zod-like schema (v3/v4); the registry calls `.parse` for validation. */\n schema: AnySchema;\n /** Optional second arg receives ToolContext (state + invocationState). */\n execute: (args: TArgs, ctx?: ToolContext) => Promise<TOutput>;\n /**\n * Split raw output into model-visible content + downstream artifact.\n * Default: JSON/string content, no artifact. Override to keep raw payloads\n * (retrieval metadata, debug blobs) out of the model's context.\n */\n toResult?: (output: TOutput) => ToolResult;\n}\n\n/**\n * The defineTool() input: TArgs drives the arg type from `execute` itself\n * (annotate the destructure once — that IS the parsed shape), and `schema`\n * accepts any zod version (v3/v4) or anything with `.parse`:\n *\n * defineTool({ schema: z.object({ city: z.string() }),\n * execute: async ({ city }: { city: string }) => ... })\n */\nexport interface ToolSpec<TArgs = any, TOutput = unknown> {\n name: string;\n description: string;\n schema: AnySchema;\n execute: (args: TArgs, ctx?: ToolContext) => Promise<TOutput>;\n toResult?: (output: TOutput) => ToolResult;\n}\n\nexport function defaultToResult(output: unknown): ToolResult {\n return { content: typeof output === \"string\" ? output : JSON.stringify(output) };\n}\n\nexport function defineTool<TArgs = any, TOutput = unknown>(\n tool: ToolSpec<TArgs, TOutput>,\n): Tool<TArgs, TOutput> {\n if (!tool.name) throw new Error(\"Tool must have a name\");\n return { ...tool } as Tool<TArgs, TOutput>;\n}\n\n/** Validating registry — single place tools are looked up + arg-checked. */\nexport class ToolRegistry {\n private tools = new Map<string, Tool>();\n\n register(tool: Tool): this {\n if (this.tools.has(tool.name)) throw new Error(`Tool already registered: ${tool.name}`);\n this.tools.set(tool.name, tool);\n return this;\n }\n\n get(name: string): Tool | undefined {\n return this.tools.get(name);\n }\n\n list(): Tool[] {\n return [...this.tools.values()];\n }\n\n async call<T>(name: string, rawArgs: unknown): Promise<T> {\n const tool = this.tools.get(name);\n if (!tool) throw new AgentError(\"UNKNOWN_TOOL\", `Unknown tool: ${name}`, false);\n let args: unknown;\n try {\n args = tool.schema.parse(rawArgs);\n } catch (err) {\n throw new AgentError(\n \"TOOL_ARG_INVALID\",\n `Invalid args for tool \"${name}\": ${err instanceof Error ? err.message : String(err)}`,\n false,\n );\n }\n return (await tool.execute(args)) as T;\n }\n}\n","import { estimateTokens } from \"../utils/index.js\";\nimport { textOf, type ChatMessage } from \"../types/index.js\";\nimport type { ModelProvider } from \"../models/index.js\";\n\n/**\n * Conversation managers keep history within context limits.\n * - apply(): after-run management (before memory.save).\n * - beforeModel(): per-turn management inside the loop (sliding window).\n * - reduce(): explicit shrink (overflow recovery / proactive triggers).\n * Pinned messages are never removed. Tool/assistant-tool_call pairs are\n * never orphaned: trimming drops leading dangling messages.\n */\n\nexport interface ConversationManager {\n readonly name: string;\n /** Messages removed so far (lets session loading skip efficiently). */\n removedCount: number;\n apply(messages: ChatMessage[]): ChatMessage[] | Promise<ChatMessage[]>;\n reduce(messages: ChatMessage[]): ChatMessage[] | Promise<ChatMessage[]>;\n beforeModel?(messages: ChatMessage[], step: number): ChatMessage[] | Promise<ChatMessage[]>;\n}\n\nfunction hasOnlyToolCalls(content: ChatMessage[\"content\"]): boolean {\n if (typeof content === \"string\") return false;\n const blocks = content.filter((b) => b.type === \"tool_call\" || (b.type === \"text\" && b.text.trim() === \"\"));\n return blocks.length > 0 && blocks.length === content.length;\n}\n\n/** Drop leading messages that lost their pair (tool head, call-only assistant head). */\nexport function trimDangling(messages: ChatMessage[]): ChatMessage[] {\n let i = 0;\n while (i < messages.length) {\n const m = messages[i];\n if (m.pinned) break;\n if (m.role === \"tool\") {\n i += 1;\n continue;\n }\n if (m.role === \"assistant\" && hasOnlyToolCalls(m.content)) {\n i += 1;\n continue;\n }\n break;\n }\n return messages.slice(i);\n}\n\nexport function messageTokens(m: ChatMessage): number {\n const text = typeof m.content === \"string\" ? m.content : textOf(m.content);\n return estimateTokens(text);\n}\n\nexport function historyTokens(messages: ChatMessage[]): number {\n return messages.reduce((n, m) => n + messageTokens(m), 0);\n}\n\n/** Keeps full history. Pass explicitly to disable the default sliding window. */\nexport class NullConversationManager implements ConversationManager {\n readonly name = \"null\";\n removedCount = 0;\n apply(messages: ChatMessage[]): ChatMessage[] {\n return messages;\n }\n reduce(messages: ChatMessage[]): ChatMessage[] {\n return messages;\n }\n}\n\nexport interface SlidingWindowOptions {\n /** Max messages kept (excluding pinned). Default 40. */\n windowSize?: number;\n /** Permanently protect the first N messages. Default 0. */\n pinFirst?: number;\n /** Manage before every model call (true) or every N calls. Default false (after-run only). */\n perTurn?: boolean | number;\n}\n\nexport class SlidingWindowConversationManager implements ConversationManager {\n readonly name = \"sliding-window\";\n removedCount = 0;\n private windowSize: number;\n private pinFirst: number;\n private perTurn: boolean | number;\n\n constructor(opts: SlidingWindowOptions = {}) {\n this.windowSize = Math.max(1, opts.windowSize ?? 40);\n this.pinFirst = Math.max(0, opts.pinFirst ?? 0);\n this.perTurn = opts.perTurn ?? false;\n }\n\n private pin(messages: ChatMessage[]): void {\n for (let i = 0; i < Math.min(this.pinFirst, messages.length); i++) messages[i].pinned = true;\n }\n\n private trim(messages: ChatMessage[]): ChatMessage[] {\n this.pin(messages);\n const keep = new Set<ChatMessage>();\n for (const m of messages) if (m.pinned) keep.add(m);\n const rest = messages.filter((m) => !m.pinned);\n const dropped = Math.max(0, rest.length - this.windowSize);\n this.removedCount += dropped;\n for (const m of rest.slice(dropped)) keep.add(m);\n // Merge in ORIGINAL order: hoisting pinned messages to the front would\n // reorder the conversation whenever a mid-history message is pinned.\n return trimDangling(messages.filter((m) => keep.has(m)));\n }\n\n apply(messages: ChatMessage[]): ChatMessage[] {\n this.pin(messages);\n return this.trim(messages);\n }\n\n reduce(messages: ChatMessage[]): ChatMessage[] {\n return this.trim(messages);\n }\n\n beforeModel(messages: ChatMessage[], step: number): ChatMessage[] {\n if (this.perTurn === false) return messages;\n if (typeof this.perTurn === \"number\" && (step % this.perTurn !== 0 || this.perTurn <= 0)) return messages;\n return this.trim(messages);\n }\n}\n\nexport interface SummarizingOptions {\n /** Fraction of oldest messages to summarize away (0.1–0.8). Default 0.3. */\n summaryRatio?: number;\n /** Newest messages always kept. Default 10. */\n preserveRecent?: number;\n pinFirst?: number;\n summarizer?: (messages: ChatMessage[]) => Promise<string>;\n /** Model used for summaries when no `summarizer` fn is given. */\n model?: ModelProvider;\n summaryPrefix?: string;\n}\n\nexport class SummarizingConversationManager implements ConversationManager {\n readonly name = \"summarizing\";\n removedCount = 0;\n private ratio: number;\n private preserveRecent: number;\n private pinFirst: number;\n private summarizer?: (messages: ChatMessage[]) => Promise<string>;\n private model?: ModelProvider;\n private summaryPrefix: string;\n /** Set when the last apply() summarized (tests/UI can assert on it). */\n lastSummary?: string;\n\n constructor(opts: SummarizingOptions = {}) {\n this.ratio = Math.min(0.8, Math.max(0.1, opts.summaryRatio ?? 0.3));\n this.preserveRecent = Math.max(1, opts.preserveRecent ?? 10);\n this.pinFirst = Math.max(0, opts.pinFirst ?? 0);\n this.summarizer = opts.summarizer;\n this.model = opts.model;\n this.summaryPrefix = opts.summaryPrefix ?? \"Summary of earlier conversation:\";\n }\n\n private summarizable(messages: ChatMessage[]): { head: ChatMessage[]; tail: ChatMessage[] } {\n for (let i = 0; i < Math.min(this.pinFirst, messages.length); i++) messages[i].pinned = true;\n const eligible = messages.filter((m) => !m.pinned);\n const count = Math.min(eligible.length - this.preserveRecent, Math.floor(eligible.length * this.ratio));\n if (count <= 0) return { head: [], tail: messages };\n const cutoff = new Set(eligible.slice(0, count));\n return { head: messages.filter((m) => cutoff.has(m)), tail: messages.filter((m) => !cutoff.has(m)) };\n }\n\n private async summarize(head: ChatMessage[]): Promise<string> {\n if (this.summarizer) return this.summarizer(head);\n if (!this.model) {\n return head\n .map((m) => `[${m.role}] ${(typeof m.content === \"string\" ? m.content : textOf(m.content)).slice(0, 200)}`)\n .join(\"\\n\");\n }\n const transcript = head.map((m) => `[${m.role}] ${typeof m.content === \"string\" ? m.content : textOf(m.content)}`).join(\"\\n\");\n const res = await this.model.complete({\n messages: [{ role: \"user\", content: `Summarize concisely, preserving decisions, names, tool outcomes:\\n${transcript}` }],\n tools: [],\n });\n return res.text;\n }\n\n async apply(messages: ChatMessage[]): Promise<ChatMessage[]> {\n const { head, tail } = this.summarizable(messages);\n if (!head.length) return messages;\n const summary = await this.summarize(head);\n this.lastSummary = summary;\n this.removedCount += head.length - 1;\n return [{ role: \"assistant\", content: `${this.summaryPrefix}\\n${summary}` } as ChatMessage, ...trimDangling(tail)];\n }\n\n reduce(messages: ChatMessage[]): ChatMessage[] {\n return messages;\n }\n}\n","/**\n * State in three lifetimes:\n * - Conversation history: messages (model-visible), via Memory.\n * - Agent state: validated JSON key-value store, NEVER sent to the model.\n * - Invocation state: per-run data + request handle, shared by reference\n * across hooks and tools within one run, returned on the result.\n */\n\nexport type InvocationState = Record<string, unknown>;\n\nfunction assertJsonSerializable(key: string, value: unknown): void {\n try {\n JSON.stringify(value);\n } catch {\n throw new Error(`AgentState: value for \"${key}\" is not JSON-serializable`);\n }\n if (typeof value === \"function\" || typeof value === \"symbol\" || typeof value === \"bigint\") {\n throw new Error(`AgentState: value for \"${key}\" is not JSON-serializable`);\n }\n // JSON.stringify silently turns these into {}/strings — reject at set()\n // instead of corrupting the value in every later snapshot/restore.\n if (value instanceof Map || value instanceof Set || value instanceof WeakMap || value instanceof WeakSet) {\n throw new Error(`AgentState: value for \"${key}\" is a ${value.constructor.name}; use a plain object/array`);\n }\n if (typeof value === \"object\" && value !== null && !(Array.isArray(value) || Object.getPrototypeOf(value) === Object.prototype || Object.getPrototypeOf(value) === null)) {\n throw new Error(`AgentState: value for \"${key}\" has a custom prototype; plain objects round-trip, class instances don't`);\n }\n}\n\n/** Key-value store outside the model context. Tools + app logic read/write freely. */\nexport class AgentState {\n private data: Record<string, unknown>;\n\n constructor(initial: Record<string, unknown> = {}) {\n for (const [k, v] of Object.entries(initial)) assertJsonSerializable(k, v);\n this.data = { ...initial };\n }\n\n get<T = unknown>(key?: string): T | Record<string, unknown> | undefined {\n if (key === undefined) return { ...this.data };\n return this.data[key] as T | undefined;\n }\n\n set(key: string, value: unknown): void {\n assertJsonSerializable(key, value);\n this.data[key] = value;\n }\n\n delete(key: string): void {\n delete this.data[key];\n }\n\n /** Plain-object copy for snapshots/persistence. */\n toJSON(): Record<string, unknown> {\n return JSON.parse(JSON.stringify(this.data)) as Record<string, unknown>;\n }\n\n static fromJSON(raw: Record<string, unknown>): AgentState {\n return new AgentState(raw);\n }\n}\n\n/** What tools receive: agent identity + state + per-run invocation state. */\nexport interface ToolContext {\n agentName: string;\n state: AgentState;\n invocationState: InvocationState;\n}\n","import { mkdir, readdir, readFile, rm, writeFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { AgentError } from \"../types/index.js\";\nimport type { ChatMessage } from \"../types/index.js\";\n\n/**\n * Sessions: persist agent state + history across restarts.\n * - Storage: byte-moving backends (memory / local files).\n * - SessionManager: latest snapshot + immutable checkpoints (UUID ids).\n * - Agent snapshots: manual take/load with field selection + appData.\n */\n\nexport interface Storage {\n read(key: string): Promise<string | undefined>;\n write(key: string, value: string): Promise<void>;\n deletePrefix(prefix: string): Promise<void>;\n list(prefix: string): Promise<string[]>;\n}\n\nexport class InMemoryStorage implements Storage {\n private data = new Map<string, string>();\n async read(key: string): Promise<string | undefined> {\n return this.data.get(key);\n }\n async write(key: string, value: string): Promise<void> {\n this.data.set(key, value);\n }\n async deletePrefix(prefix: string): Promise<void> {\n for (const k of [...this.data.keys()]) if (k.startsWith(prefix)) this.data.delete(k);\n }\n async list(prefix: string): Promise<string[]> {\n return [...this.data.keys()].filter((k) => k.startsWith(prefix)).sort();\n }\n}\n\nexport class LocalFileStorage implements Storage {\n constructor(private root: string) {}\n\n private path(key: string): string {\n // Trailing/duplicate slashes are harmless (directory markers); only\n // traversal segments can escape the root.\n const segments = key.split(\"/\").filter((seg) => seg !== \"\");\n if (segments.includes(\"..\") || key.includes(\"\\0\")) {\n throw new AgentError(\"STORAGE_KEY_INVALID\", `Invalid storage key: ${JSON.stringify(key)}`, false);\n }\n return join(this.root, ...segments);\n }\n\n async read(key: string): Promise<string | undefined> {\n try {\n return await readFile(this.path(key), \"utf8\");\n } catch {\n return undefined;\n }\n }\n\n async write(key: string, value: string): Promise<void> {\n const full = this.path(key);\n await mkdir(join(full, \"..\"), { recursive: true });\n await writeFile(full, value, \"utf8\");\n }\n\n async deletePrefix(prefix: string): Promise<void> {\n await rm(this.path(prefix), { recursive: true, force: true });\n }\n\n async list(prefix: string): Promise<string[]> {\n const out: string[] = [];\n const walk = async (dir: string, rel: string): Promise<void> => {\n let entries;\n try {\n entries = await readdir(dir, { withFileTypes: true });\n } catch {\n return;\n }\n for (const e of entries) {\n if (e.isDirectory()) await walk(join(dir, e.name), `${rel}${e.name}/`);\n else out.push(`${prefix}${rel}${e.name}`);\n }\n };\n await walk(this.path(prefix), \"\");\n return out.sort();\n }\n}\n\nexport interface SnapshotData {\n messages?: ChatMessage[];\n state?: Record<string, unknown>;\n systemPrompt?: string;\n}\n\nexport interface Snapshot {\n id: string;\n createdAt: string;\n data: SnapshotData;\n appData?: Record<string, unknown>;\n}\n\nexport type SnapshotField = \"messages\" | \"state\" | \"systemPrompt\";\n\nexport interface TakeSnapshotOptions {\n /** Preset bundle. Currently only \"session\" (messages + state). */\n preset?: \"session\";\n include?: SnapshotField[];\n exclude?: SnapshotField[];\n appData?: Record<string, unknown>;\n}\n\nconst SESSION_PRESET: SnapshotField[] = [\"messages\", \"state\"];\n\nexport function selectSnapshotFields(\n full: Required<Pick<SnapshotData, \"messages\" | \"state\">> & Pick<SnapshotData, \"systemPrompt\">,\n opts: TakeSnapshotOptions = {},\n): SnapshotData {\n const base = new Set<SnapshotField>(opts.preset === \"session\" ? SESSION_PRESET : []);\n for (const f of opts.include ?? []) base.add(f);\n for (const f of opts.exclude ?? []) base.delete(f);\n const data: SnapshotData = {};\n if (base.has(\"messages\")) data.messages = full.messages;\n if (base.has(\"state\")) data.state = full.state;\n if (base.has(\"systemPrompt\")) data.systemPrompt = full.systemPrompt;\n return data;\n}\n\nfunction uuid(): string {\n return \"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx\".replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n return (c === \"x\" ? r : (r & 0x3) | 0x8).toString(16);\n });\n}\n\nexport interface SessionManagerOptions {\n sessionId?: string;\n storage: Storage;\n agentId?: string;\n}\n\nexport class SessionManager {\n readonly sessionId: string;\n readonly agentId: string;\n private storage: Storage;\n\n constructor(opts: SessionManagerOptions) {\n this.sessionId = opts.sessionId ?? uuid();\n this.agentId = opts.agentId ?? \"default\";\n this.storage = opts.storage;\n }\n\n private scope(): string {\n return `session/${this.sessionId}/scopes/agent/${this.agentId}/snapshots`;\n }\n\n async saveLatest(data: SnapshotData): Promise<void> {\n await this.storage.write(`${this.scope()}/snapshot_latest.json`, JSON.stringify({ data }));\n }\n\n async loadLatest(): Promise<SnapshotData | undefined> {\n const raw = await this.storage.read(`${this.scope()}/snapshot_latest.json`);\n if (!raw) return undefined;\n try {\n return (JSON.parse(raw) as { data: SnapshotData }).data;\n } catch {\n return undefined;\n }\n }\n\n /** Immutable checkpoint; returns its id. */\n async saveSnapshot(data: SnapshotData, appData?: Record<string, unknown>): Promise<string> {\n const snapshot: Snapshot = { id: uuid(), createdAt: new Date().toISOString(), data, appData };\n await this.storage.write(`${this.scope()}/immutable_history/snapshot_${snapshot.id}.json`, JSON.stringify(snapshot));\n return snapshot.id;\n }\n\n async listSnapshotIds(): Promise<string[]> {\n const keys = await this.storage.list(`${this.scope()}/immutable_history/`);\n return keys\n .map((k) => k.match(/snapshot_(.+)\\.json$/)?.[1])\n .filter((id): id is string => !!id)\n .sort();\n }\n\n async restoreSnapshot(id: string): Promise<Snapshot | undefined> {\n const raw = await this.storage.read(`${this.scope()}/immutable_history/snapshot_${id}.json`);\n if (!raw) return undefined;\n try {\n return JSON.parse(raw) as Snapshot;\n } catch {\n return undefined;\n }\n }\n\n async deleteSession(): Promise<void> {\n await this.storage.deletePrefix(`session/${this.sessionId}/`);\n }\n}\n","import { z } from \"zod\";\nimport { zodToJsonSchema } from \"zod-to-json-schema\";\nimport { AgentError } from \"../types/index.js\";\n\n/**\n * Structured output — typed agent results instead of parsed prose.\n * Two strategies:\n * - provider: native `response_format` (OpenAI-compatible APIs). Most reliable.\n * - tool: synthetic `__structured_response` tool; validation errors return as\n * tool messages so the model self-repairs within maxSteps.\n */\n\nexport type ResponseStrategy = \"auto\" | \"provider\" | \"tool\";\n\nexport interface ResponseFormat<T = unknown> {\n schema: z.ZodType<T>;\n /** Function/tool name. Default: \"structured_response\". */\n name?: string;\n strategy?: ResponseStrategy;\n /** Tool message content on success (tool strategy). */\n toolMessageContent?: string;\n /** Validation retries before STRUCTURED_NO_MATCH (tool strategy). Default 2. */\n maxAttempts?: number;\n}\n\nexport function toolStrategy<T>(schema: z.ZodType<T>, opts?: Omit<ResponseFormat<T>, \"schema\" | \"strategy\">): ResponseFormat<T> {\n return { ...opts, schema, strategy: \"tool\" };\n}\n\nexport function providerStrategy<T>(schema: z.ZodType<T>, opts?: Omit<ResponseFormat<T>, \"schema\" | \"strategy\">): ResponseFormat<T> {\n return { ...opts, schema, strategy: \"provider\" };\n}\n\nexport function responseFormatName<T>(format: ResponseFormat<T>): string {\n return format.name ?? \"structured_response\";\n}\n\nexport function responseFormatJsonSchema<T>(format: ResponseFormat<T>): Record<string, unknown> {\n return zodToJsonSchema(format.schema, { $refStrategy: \"none\" }) as Record<string, unknown>;\n}\n\n/** Validate raw model output; throws AgentError STRUCTURED_INVALID (retryable) on mismatch. */\nexport function parseStructured<T>(format: ResponseFormat<T>, raw: unknown): T {\n const parsed = format.schema.safeParse(raw);\n if (parsed.success) return parsed.data;\n throw new AgentError(\n \"STRUCTURED_INVALID\",\n `Structured output failed validation for \"${responseFormatName(format)}\": ${parsed.error.message}`,\n true,\n );\n}\n","import type { StreamEvent } from \"../streaming/index.js\";\nimport { ToolRejection, HitlInterrupt, type AgentMiddleware, type HookContext, type HitlDecision, type ModelRequest } from \"../middleware/index.js\";\nimport { NullConversationManager, type ConversationManager } from \"../conversation/index.js\";\nimport { AgentState, type InvocationState } from \"../state/index.js\";\nimport type { Checkpointer } from \"../checkpoint/index.js\";\nimport {\n selectSnapshotFields,\n type SessionManager,\n type Snapshot,\n type TakeSnapshotOptions,\n} from \"../sessions/index.js\";\nimport type { z } from \"zod\";\nimport {\n parseStructured,\n responseFormatJsonSchema,\n responseFormatName,\n type ResponseFormat,\n} from \"../structured/index.js\";\nimport {\n AgentError,\n type AgentResult,\n type ChatMessage,\n type ContentBlock,\n type TokenUsage,\n} from \"../types/index.js\";\nimport { defaultToResult, defineTool, type Tool } from \"../tools/index.js\";\nimport { zodToJsonSchema } from \"zod-to-json-schema\";\nimport type { Memory } from \"../memory/index.js\";\nimport { InMemoryMemory } from \"../memory/index.js\";\nimport type { ModelProvider } from \"../models/index.js\";\nimport { priceFor, usageCost, type ModelPrice } from \"../models/pricing.js\";\nimport type { AgentEvents } from \"../observability/index.js\";\nimport { runWithBudget } from \"../runtime/index.js\";\n\nexport type OutputVersion = \"v0\" | \"v1\";\n\nexport interface AgentOptions {\n name?: string;\n /** One-line specialty, used by the router menu. */\n description?: string;\n systemPrompt?: string;\n model: ModelProvider;\n tools?: Tool[];\n memory?: Memory;\n maxSteps?: number;\n /** Max tool executions per run; exceeded -> AgentError(BUDGET_EXCEEDED). Default: unlimited. */\n maxToolCalls?: number;\n /** Token/cost/deadline budgets enforced after every model call. */\n budgets?: TokenBudgets;\n /**\n * Output version. v0: assistant messages carry plain text (thinking streams\n * via events only). v1: thinking is also stored as `reasoning` blocks.\n */\n outputVersion?: OutputVersion;\n /** Typed final answer (tool or provider strategy). Sets `structuredResponse` on the result. */\n responseFormat?: ResponseFormat;\n /** Middleware hooks (before/after model + tool). Run in order. */\n middleware?: AgentMiddleware[];\n /** Conversation history: seed prior messages to continue a conversation. */\n initialMessages?: ChatMessage[];\n /** Agent key-value state (never sent to the model). */\n state?: Record<string, unknown> | AgentState;\n /** History management. Default: NullConversationManager (keep everything; memory still windows). */\n conversationManager?: ConversationManager;\n /** Persist state + history across restarts. Restored on first run, saved after each run. */\n sessionManager?: SessionManager;\n events?: AgentEvents;\n}\n\nexport interface TimelineEntry {\n rev: number;\n kind: \"run\" | \"edit\" | \"branch\" | \"resume\" | \"snapshot\";\n label?: string;\n at: string;\n}\n\nexport interface TokenBudgets {\n /** Total (input + output + reasoning) tokens per run. */\n maxTokens?: number;\n /** USD cap per run. Needs a known price (table lookup or `prices`) — never guessed. */\n maxCostUsd?: number;\n /** Price override when the model is missing from the pricing table. */\n prices?: ModelPrice;\n /** Wall-clock deadline per run. */\n deadlineMs?: number;\n}\n\nexport interface RunOptions {\n signal?: AbortSignal;\n /** Per-run data: shared by reference across hooks/tools, returned on the result, never sent to the model. */\n invocationState?: InvocationState;\n /** Checkpointed HITL: persist + resume human approvals locally. */\n checkpointer?: Checkpointer;\n threadId?: string;\n}\n\nconst DEFAULT_SYSTEM = \"You are a helpful agent. Use tools when needed. Be concise.\";\nconst DEFAULT_MAX_STEPS = 6;\n\n/** Tool metadata sent to the model — descriptions alone leave arg shapes to guesswork. */\nconst toolJsonSchemas = new WeakMap<Tool, Record<string, unknown> | undefined>();\nfunction toolParameters(t: Tool): Record<string, unknown> | undefined {\n if (!toolJsonSchemas.has(t)) {\n try {\n toolJsonSchemas.set(t, zodToJsonSchema(t.schema as never, { $refStrategy: \"none\" }) as Record<string, unknown>);\n } catch {\n toolJsonSchemas.set(t, undefined);\n }\n }\n return toolJsonSchemas.get(t);\n}\n\ninterface LoopRuntime {\n model: ModelProvider;\n memory?: Memory;\n systemPrompt: string;\n events?: AgentEvents;\n middleware: AgentMiddleware[];\n conversationManager: ConversationManager;\n sessionManager?: SessionManager;\n tools: Tool[];\n format?: ResponseFormat;\n strategy?: string;\n maxSteps: number;\n maxToolCalls?: number;\n budgets?: TokenBudgets;\n outputVersion: OutputVersion;\n state: AgentState;\n toolCtx: { agentName: string; state: AgentState; invocationState: InvocationState };\n ctxFor: (step: number) => HookContext;\n}\n\n/**\n * Minimal ReAct-style loop:\n * 1. load memory -> messages\n * 2. loop: model.complete -> tool calls -> execute -> append\n * 3. save memory, return AgentResult\n *\n * `run()` drains `stream()`; both fire `events` hooks identically.\n */\nexport class Agent {\n private options: Required<Omit<AgentOptions, \"events\" | \"tools\" | \"memory\" | \"maxToolCalls\" | \"budgets\" | \"responseFormat\" | \"middleware\" | \"initialMessages\" | \"state\" | \"conversationManager\" | \"sessionManager\">> & {\n tools: Tool[];\n memory?: Memory;\n maxToolCalls?: number;\n budgets?: TokenBudgets;\n responseFormat?: ResponseFormat;\n middleware: AgentMiddleware[];\n initialMessages: ChatMessage[];\n conversationManager: ConversationManager;\n sessionManager?: SessionManager;\n events?: AgentEvents;\n };\n private seeded = false;\n private restored = false;\n private lastMessages: ChatMessage[] = [];\n private revisions: TimelineEntry[] = [];\n readonly agentState: AgentState;\n private instanceSessionId?: string;\n\n constructor(options: AgentOptions) {\n this.options = {\n name: options.name ?? \"agent\",\n description: options.description ?? \"\",\n systemPrompt: options.systemPrompt ?? DEFAULT_SYSTEM,\n model: options.model,\n // Middleware-contributed tools (filesystem, todos, subagents) come first.\n // withTools()/branch() pass an already-merged list back in, so dedupe\n // by name (first occurrence wins) to keep clones from advertising\n // every middleware tool twice.\n tools: [...(options.middleware ?? []).flatMap((m) => m.tools ?? []), ...(options.tools ?? [])]\n .filter((t, i, all) => all.findIndex((o) => o.name === t.name) === i),\n memory: options.memory,\n maxSteps: options.maxSteps ?? DEFAULT_MAX_STEPS,\n maxToolCalls: options.maxToolCalls,\n budgets: options.budgets,\n outputVersion: options.outputVersion ?? \"v0\",\n responseFormat: options.responseFormat,\n middleware: options.middleware ?? [],\n initialMessages: options.initialMessages ?? [],\n conversationManager: options.conversationManager ?? new NullConversationManager(),\n sessionManager: options.sessionManager,\n events: options.events,\n };\n this.agentState = options.state instanceof AgentState ? options.state : new AgentState(options.state ?? {});\n }\n\n /** Public identity for orchestration menus and logs. */\n get name(): string {\n return this.options.name;\n }\n\n get description(): string {\n return this.options.description;\n }\n\n get model(): ModelProvider {\n return this.options.model;\n }\n\n /** Member tools (copy) — introspection for orchestration/menus. */\n get tools(): Tool[] {\n return [...this.options.tools];\n }\n\n /**\n * Clone with extra tools. Memory, session, and state are NOT carried over\n * (fresh per clone); model, tools, middleware, and formats are shared.\n * Used by coordinators (swarm handoffs) that inject control tools.\n */\n withTools(...extra: Tool[]): Agent {\n return new Agent({\n name: this.options.name,\n description: this.options.description,\n systemPrompt: this.options.systemPrompt,\n model: this.options.model,\n tools: [...this.options.tools, ...extra],\n maxSteps: this.options.maxSteps,\n maxToolCalls: this.options.maxToolCalls,\n budgets: this.options.budgets,\n outputVersion: this.options.outputVersion,\n responseFormat: this.options.responseFormat,\n middleware: [...this.options.middleware],\n conversationManager: this.options.conversationManager,\n events: this.options.events,\n });\n }\n\n /** Key-value state (never sent to the model). */\n get state(): AgentState {\n return this.agentState;\n }\n\n /** Session handle: the manager's id, or a generated per-instance id. */\n get sessionId(): string {\n if (this.options.sessionManager) return this.options.sessionManager.sessionId;\n this.instanceSessionId ??= Math.random().toString(16).slice(2, 10);\n return this.instanceSessionId;\n }\n\n /** Full conversation history from the last run (system + memory + new turns). */\n get messages(): ChatMessage[] {\n return [...this.lastMessages];\n }\n\n /** Version timeline: runs, edits, branches, resumes (append-only). */\n get timeline(): TimelineEntry[] {\n return [...this.revisions];\n }\n\n private record(kind: TimelineEntry[\"kind\"], label?: string): void {\n this.revisions.push({ rev: this.revisions.length + 1, kind, ...(label ? { label } : {}), at: new Date().toISOString() });\n }\n\n /**\n * Edit a message in the current history (by id or index) and keep the\n * version in the timeline. History + memory stay in sync.\n */\n async editMessage(idOrIndex: string | number, content: string | ContentBlock[]): Promise<ChatMessage> {\n const idx = typeof idOrIndex === \"number\"\n ? idOrIndex\n : this.lastMessages.findIndex((m) => m.id === idOrIndex);\n if (idx < 0 || idx >= this.lastMessages.length) {\n throw new AgentError(\"MESSAGE_NOT_FOUND\", `No message ${String(idOrIndex)} in history`, false);\n }\n // The following role:\"tool\" messages reference this turn's tool_call ids;\n // replacing the content would orphan them (providers 400 on unpaired tool results).\n if (\n typeof this.lastMessages[idx].content !== \"string\" &&\n this.lastMessages[idx].content.some((b) => b.type === \"tool_call\")\n ) {\n throw new AgentError(\"MESSAGE_NOT_EDITABLE\", `Message ${String(idOrIndex)} contains tool calls; branch() from a point before it instead`, false);\n }\n const updated = { ...this.lastMessages[idx], content };\n this.lastMessages = [...this.lastMessages.slice(0, idx), updated, ...this.lastMessages.slice(idx + 1)];\n if (this.options.memory) {\n await this.options.memory.clear();\n await this.options.memory.save(this.lastMessages.filter((m) => m.role !== \"system\"));\n }\n this.record(\"edit\", `message ${updated.id ?? idx}`);\n return updated;\n }\n\n /**\n * Branch the current history into an independent agent. Model, tools,\n * middleware, and formats are shared; state is copied; memory is fresh\n * (seeded with this history); sessions are NOT carried over (to avoid\n * double-persist collisions). Both timelines record the branch.\n */\n async branch(label: string, overrides: Partial<AgentOptions> = {}): Promise<Agent> {\n const memory = new InMemoryMemory();\n await memory.save(this.lastMessages.filter((m) => m.role !== \"system\"));\n const child = new Agent({\n name: this.options.name,\n description: this.options.description,\n systemPrompt: this.options.systemPrompt,\n model: this.options.model,\n tools: [...this.options.tools],\n memory,\n maxSteps: this.options.maxSteps,\n maxToolCalls: this.options.maxToolCalls,\n budgets: this.options.budgets,\n outputVersion: this.options.outputVersion,\n responseFormat: this.options.responseFormat,\n middleware: [...this.options.middleware],\n state: this.agentState.toJSON(),\n conversationManager: this.options.conversationManager,\n events: this.options.events,\n ...overrides,\n });\n child.lastMessages = [...this.lastMessages];\n child.revisions = [...this.revisions];\n child.record(\"branch\", label);\n this.record(\"branch\", label);\n return child;\n }\n\n /**\n * Pause mid-conversation: persist history + state under threadId without\n * needing an interrupt. Pair with resume() (empty decisions continue).\n */\n async pause(\n threadId: string,\n opts: { checkpointer: Checkpointer },\n ): Promise<{ threadId: string; messages: number }> {\n await opts.checkpointer.save(threadId, {\n messages: [...this.lastMessages],\n state: this.agentState.toJSON(),\n pending: [],\n });\n return { threadId, messages: this.lastMessages.length };\n }\n\n /** Manual checkpoint: messages + state (+ system prompt on request) + appData. */\n takeSnapshot(opts: TakeSnapshotOptions = { preset: \"session\" }): Snapshot {\n return {\n id: `snapshot-${Date.now().toString(36)}`,\n createdAt: new Date().toISOString(),\n data: selectSnapshotFields(\n { messages: [...this.lastMessages], state: this.agentState.toJSON(), systemPrompt: this.options.systemPrompt },\n opts,\n ),\n ...(opts.appData ? { appData: opts.appData } : {}),\n };\n }\n\n /** Restore fields present in the snapshot; absent fields keep current values. */\n async loadSnapshot(snapshot: Snapshot): Promise<void> {\n if (snapshot.data.state) {\n for (const [k, v] of Object.entries(snapshot.data.state)) this.agentState.set(k, v);\n }\n if (snapshot.data.messages) {\n this.lastMessages = [...snapshot.data.messages];\n if (this.options.memory) {\n await this.options.memory.clear();\n await this.options.memory.save(snapshot.data.messages.filter((m) => m.role !== \"system\"));\n }\n }\n }\n\n /**\n * Resume a suspended run: restores the checkpoint, seeds human decisions,\n * and continues the loop without new input. Decisions are keyed by\n * `hitlKey(tool, args)` for an exact match, or by bare tool name to cover\n * every re-issued call of that tool (models re-issue with regenerated arg\n * text, so exact keys alone would never converge).\n */\n async resume(\n threadId: string,\n decisions: Record<string, HitlDecision> = {},\n opts: { checkpointer: Checkpointer } & RunOptions,\n ): Promise<AgentResult> {\n const cp = await opts.checkpointer.load(threadId);\n if (!cp) throw new AgentError(\"CHECKPOINT_MISSING\", `No checkpoint for thread \"${threadId}\"`, false);\n if (cp.state) {\n for (const [k, v] of Object.entries(cp.state)) this.agentState.set(k, v);\n }\n this.lastMessages = [...cp.messages];\n if (this.options.memory) {\n await this.options.memory.clear();\n await this.options.memory.save(cp.messages.filter((m) => m.role !== \"system\"));\n }\n const invocationState = { ...(opts.invocationState ?? {}), __hitlDecisions: decisions };\n const gen = this.iterateContinuation(opts.signal, invocationState, { checkpointer: opts.checkpointer, threadId });\n for (;;) {\n const next = await runWithBudget(() => gen.next(), { signal: opts.signal });\n if (next.done) {\n this.record(\"resume\", threadId);\n return next.value;\n }\n }\n }\n\n private buildRuntime(invocationState: InvocationState): LoopRuntime {\n const { model, memory, systemPrompt, events, middleware, conversationManager, sessionManager } = this.options;\n const format = this.options.responseFormat;\n // \"auto\" (and unset) resolves by capability: native response_format when\n // the provider supports it, else the synthetic tool.\n const strategy = format\n ? format.strategy && format.strategy !== \"auto\"\n ? format.strategy\n : model.capabilities?.structuredOutput ? \"provider\" : \"tool\"\n : undefined;\n const tools = strategy === \"tool\" && format ? [...this.options.tools, structuredTool(format)] : this.options.tools;\n const toolCtx = { agentName: this.options.name, state: this.agentState, invocationState };\n const ctxFor = (step: number): HookContext => ({ step, invocationState });\n return {\n model, memory, systemPrompt, events, middleware, conversationManager,\n sessionManager, tools, format, strategy,\n maxSteps: this.options.maxSteps,\n maxToolCalls: this.options.maxToolCalls,\n budgets: this.options.budgets,\n outputVersion: this.options.outputVersion,\n state: this.agentState, toolCtx, ctxFor,\n };\n }\n\n /** Continue the loop from restored history (no new user message). */\n private async *iterateContinuation(\n signal: AbortSignal | undefined,\n invocationState: InvocationState,\n checkpoint?: { checkpointer: Checkpointer; threadId: string },\n ): AsyncGenerator<StreamEvent, AgentResult> {\n const rt = this.buildRuntime(invocationState);\n const messages: ChatMessage[] = [\n { role: \"system\", content: rt.systemPrompt },\n ...(rt.memory ? await rt.memory.load() : this.lastMessages.filter((m) => m.role !== \"system\")),\n ];\n return yield* this.runLoop(messages, rt, signal, invocationState, checkpoint);\n }\n\n async run(input: string | ContentBlock[], signal?: AbortSignal): Promise<AgentResult>;\n async run(input: string | ContentBlock[], opts?: RunOptions): Promise<AgentResult>;\n async run(input: string | ContentBlock[], signalOrOpts?: AbortSignal | RunOptions): Promise<AgentResult> {\n const opts: RunOptions = signalOrOpts instanceof AbortSignal ? { signal: signalOrOpts } : (signalOrOpts ?? {});\n const stream = this.stream(input, opts);\n for (;;) {\n const next = await stream.next();\n if (next.done) {\n this.record(\"run\", typeof input === \"string\" ? input.slice(0, 60) : \"blocks\");\n return next.value;\n }\n }\n }\n\n stream(input: string | ContentBlock[], signal?: AbortSignal, invocationState?: InvocationState): AsyncGenerator<StreamEvent, AgentResult>;\n stream(input: string | ContentBlock[], opts?: RunOptions): AsyncGenerator<StreamEvent, AgentResult>;\n async *stream(\n input: string | ContentBlock[],\n signalOrOpts?: AbortSignal | RunOptions,\n invocationState?: InvocationState,\n ): AsyncGenerator<StreamEvent, AgentResult> {\n const opts: RunOptions =\n signalOrOpts instanceof AbortSignal ? { signal: signalOrOpts, invocationState } : (signalOrOpts ?? {});\n const checkpoint =\n opts.checkpointer && opts.threadId ? { checkpointer: opts.checkpointer, threadId: opts.threadId } : undefined;\n const gen = this.iterate(input, opts.signal, opts.invocationState ?? {}, checkpoint);\n for (;;) {\n const next = await runWithBudget(() => gen.next(), { signal: opts.signal });\n if (next.done) return next.value;\n yield next.value;\n }\n }\n\n private async *iterate(\n input: string | ContentBlock[],\n signal?: AbortSignal,\n invocationState: InvocationState = {},\n checkpoint?: { checkpointer: Checkpointer; threadId: string },\n ): AsyncGenerator<StreamEvent, AgentResult> {\n const rt = this.buildRuntime(invocationState);\n const { memory, systemPrompt } = this.options;\n\n // Session restore wins over initialMessages: a persisted conversation\n // must not be silently replaced by the seed on the first run.\n const sessionManager = this.options.sessionManager;\n if (sessionManager && !this.restored) {\n this.restored = true;\n const latest = await sessionManager.loadLatest();\n if (latest?.state) {\n for (const [k, v] of Object.entries(latest.state)) this.agentState.set(k, v);\n }\n if (latest?.messages?.length) {\n this.lastMessages = [...latest.messages];\n if (memory && (await memory.load()).length === 0) {\n await memory.save(latest.messages.filter((m) => m.role !== \"system\"));\n }\n }\n }\n\n if (!this.seeded && this.options.initialMessages.length > 0) {\n this.seeded = true;\n if (memory && (await memory.load()).length === 0) {\n await memory.save(this.options.initialMessages.filter((m) => m.role !== \"system\"));\n } else if (!memory && this.lastMessages.length === 0) {\n this.lastMessages = [...this.options.initialMessages];\n }\n }\n\n const messages: ChatMessage[] = [\n { role: \"system\", content: systemPrompt },\n ...(memory ? await memory.load() : this.lastMessages.filter((m) => m.role !== \"system\")),\n { role: \"user\", content: input },\n ];\n return yield* this.runLoop(messages, rt, signal, invocationState, checkpoint);\n }\n\n private async *runLoop(\n messages: ChatMessage[],\n rt: LoopRuntime,\n signal: AbortSignal | undefined,\n invocationState: InvocationState,\n checkpoint?: { checkpointer: Checkpointer; threadId: string },\n ): AsyncGenerator<StreamEvent, AgentResult> {\n const { model, memory, systemPrompt, events, middleware, conversationManager, sessionManager, tools, format, strategy, toolCtx, ctxFor } = rt;\n const toolCalls: AgentResult[\"toolCalls\"] = [];\n const usage: TokenUsage = { inputTokens: 0, outputTokens: 0 };\n const startedAt = Date.now();\n let text = \"\";\n let structuredResponse: unknown;\n let hasStructured = false;\n\n try {\n for (let step = 0; step < rt.maxSteps; step++) {\n signal?.throwIfAborted();\n if (conversationManager.beforeModel) {\n const managed = await conversationManager.beforeModel(messages, step);\n // Managers may hand back the input array itself (no-op turn) —\n // resetting in place would wipe the very array we spread back in.\n if (managed !== messages) {\n messages.length = 0;\n messages.push(...managed);\n }\n }\n events?.onStep?.({ step, messages });\n yield { type: \"step\", step };\n\n let req: ModelRequest = {\n messages,\n tools: tools.map((t) => ({ name: t.name, description: t.description, ...(toolParameters(t) ? { parametersSchema: toolParameters(t) } : {}) })),\n ...(strategy === \"provider\" && format\n ? { responseFormat: { name: responseFormatName(format), schema: responseFormatJsonSchema(format) } }\n : {}),\n };\n for (const mw of middleware) req = (await mw.beforeModel?.(req, ctxFor(step))) ?? req;\n\n const pending: ({ type: \"token\"; delta: string } | { type: \"thinking\"; delta: string })[] = [];\n const callModel = (r: ModelRequest) =>\n model.complete({\n ...r,\n // Propagate the run's abort into the in-flight provider request.\n ...(signal ? { signal } : {}),\n onToken: (d) => {\n events?.onToken?.(d);\n pending.push({ type: \"token\", delta: d });\n },\n onThinking: (d) => {\n events?.onThinking?.(d);\n pending.push({ type: \"thinking\", delta: d });\n },\n });\n const modelChain = middleware\n .filter((mw) => mw.wrapModel)\n .reduceRight(\n (next, mw) => (r: ModelRequest) => mw.wrapModel!(r, next, ctxFor(step)),\n callModel,\n );\n let completion = await modelChain(req);\n for (const e of pending.splice(0)) {\n if (e.delta !== \"\") yield e;\n }\n for (const mw of [...middleware].reverse()) completion = (await mw.afterModel?.(completion, req, ctxFor(step))) ?? completion;\n\n usage.inputTokens += completion.usage.inputTokens;\n usage.outputTokens += completion.usage.outputTokens;\n usage.reasoningTokens = (usage.reasoningTokens ?? 0) + (completion.usage.reasoningTokens ?? 0);\n checkBudgets(rt, usage, startedAt, model.id);\n\n if (completion.toolCalls.length === 0) {\n text = completion.text;\n if (strategy === \"provider\" && format) {\n try {\n structuredResponse = parseStructured(format, JSON.parse(text));\n hasStructured = true;\n } catch (err) {\n const retryable = err instanceof AgentError ? err.retryable : true;\n const message = err instanceof Error ? err.message : String(err);\n if (step < rt.maxSteps - 1 && retryable) {\n messages.push({ role: \"assistant\", content: text });\n messages.push({\n role: \"user\",\n content: `Your last response was not valid for \"${responseFormatName(format)}\": ${message}. Reply with corrected JSON only.`,\n });\n continue;\n }\n throw err instanceof AgentError\n ? err\n : new AgentError(\"STRUCTURED_INVALID\", `Invalid structured output: ${message}`, true);\n }\n }\n messages.push(\n rt.outputVersion === \"v1\" && completion.thinking\n ? {\n role: \"assistant\",\n content: [\n { type: \"reasoning\", reasoning: completion.thinking },\n { type: \"text\", text },\n ],\n }\n : { role: \"assistant\", content: text },\n );\n break;\n }\n\n // Record the model's tool calls as an assistant message so the\n // history round-trips (tool messages reference these ids).\n messages.push({\n role: \"assistant\",\n content: completion.toolCalls.map((c) => ({ type: \"tool_call\", id: c.id, name: c.name, args: c.args }) as const),\n });\n\n for (const call of completion.toolCalls) {\n if (rt.maxToolCalls != null && toolCalls.length >= rt.maxToolCalls) {\n throw new AgentError(\n \"BUDGET_EXCEEDED\",\n `Exceeded maxToolCalls (${rt.maxToolCalls})`,\n false,\n );\n }\n const tool = tools.find((t) => t.name === call.name);\n if (!tool) {\n messages.push({\n role: \"tool\",\n content: `Unknown tool: ${call.name}`,\n toolCallId: call.id,\n toolName: call.name,\n });\n continue;\n }\n let toolCall = { name: call.name, args: call.args };\n let output: unknown;\n try {\n for (const mw of middleware) toolCall = (await mw.beforeTool?.(toolCall, ctxFor(step))) ?? toolCall;\n events?.onToolCall?.({ tool: toolCall.name, args: toolCall.args });\n yield { type: \"tool_call\", name: toolCall.name, args: toolCall.args };\n\n const invoke = () => tool.execute(toolCall.args, toolCtx);\n const chain = middleware\n .filter((mw) => mw.aroundTool)\n .reduceRight(\n (next, mw) => () => mw.aroundTool!(toolCall, next, ctxFor(step)),\n invoke,\n );\n output = await chain();\n } catch (err) {\n if (err instanceof HitlInterrupt) throw err;\n if (err instanceof ToolRejection) {\n output = err.feedback;\n } else {\n if (err instanceof AgentError) throw err;\n throw new AgentError(\n \"TOOL_EXECUTION\",\n `Tool \"${toolCall.name}\" failed: ${err instanceof Error ? err.message : String(err)}`,\n false,\n );\n }\n }\n for (const mw of [...middleware].reverse()) output = (await mw.afterTool?.(toolCall, output, ctxFor(step))) ?? output;\n\n const result = (tool.toResult ?? defaultToResult)(output);\n toolCalls.push({ id: call.id, name: toolCall.name, args: toolCall.args, output, ...(result.artifact !== undefined ? { artifact: result.artifact } : {}) });\n if (strategy === \"tool\" && format && toolCall.name === responseFormatName(format) && !hasStructured) {\n try {\n structuredResponse = parseStructured(format, output);\n hasStructured = true;\n } catch {\n // execute already returned a retry message; keep looping.\n }\n }\n events?.onToolResult?.({ tool: toolCall.name, output });\n yield { type: \"tool_result\", name: toolCall.name, output };\n messages.push({\n role: \"tool\",\n content: result.content,\n toolCallId: call.id,\n toolName: toolCall.name,\n });\n }\n\n // If model never produces final text within budget, synthesize from tool outputs.\n if (step === rt.maxSteps - 1) {\n text = toolCalls.length\n ? `Completed ${toolCalls.length} tool call(s). Last output: ${JSON.stringify(toolCalls.at(-1)?.output)}`\n : \"\";\n // Store it — otherwise history ends on a dangling tool message and\n // the \"answer\" the caller saw exists nowhere in the transcript.\n messages.push({ role: \"assistant\", content: text });\n }\n }\n } catch (err) {\n if (err instanceof HitlInterrupt && checkpoint) {\n const pendingArgs = JSON.stringify(err.args ?? {});\n let cut = messages.length;\n for (let i = messages.length - 1; i >= 0; i--) {\n const m = messages[i];\n if (\n m.role === \"assistant\" &&\n typeof m.content !== \"string\" &&\n m.content.some((b) => b.type === \"tool_call\" && b.name === err.tool && JSON.stringify(b.args ?? {}) === pendingArgs)\n ) {\n cut = i;\n break;\n }\n }\n await checkpoint.checkpointer.save(checkpoint.threadId, {\n messages: messages.slice(0, cut),\n state: rt.state.toJSON(),\n pending: [{ interruptId: err.interruptId, tool: err.tool, args: err.args }],\n });\n }\n throw err;\n }\n\n if (format && !hasStructured) {\n throw new AgentError(\n \"STRUCTURED_NO_MATCH\",\n `No valid \"${responseFormatName(format)}\" produced within ${rt.maxSteps} steps`,\n false,\n );\n }\n\n const managed = await conversationManager.apply(messages);\n // save() APPENDS: without the clear, every run re-saves the entire\n // (already loaded) transcript and duplicates it in memory.\n if (memory) {\n await memory.clear();\n await memory.save(managed.filter((m) => m.role !== \"system\"));\n }\n this.lastMessages = managed;\n if (sessionManager) {\n await sessionManager.saveLatest({\n messages: managed,\n state: rt.state.toJSON(),\n systemPrompt,\n });\n }\n events?.onDone?.({ text, toolCalls });\n yield { type: \"done\", text };\n // Known price -> report real cost; unknown stays undefined (never guessed).\n const costUsd = usageCost(usage, model.id, rt.budgets?.prices);\n return {\n text, messages: [...managed], toolCalls,\n usage: { ...usage, ...(costUsd !== undefined ? { costUsd } : {}) },\n invocationState,\n ...(hasStructured ? { structuredResponse } : {}),\n };\n }\n}\n\n/** Enforce token/cost/deadline budgets after every model call. */\nfunction checkBudgets(\n rt: { budgets?: TokenBudgets },\n usage: TokenUsage,\n startedAt: number,\n modelId: string,\n): void {\n const budgets = rt.budgets;\n if (!budgets) return;\n // reasoningTokens is a SUBSET of outputTokens on every supported provider,\n // so it must not be added on top (double-count would fire budgets early).\n const total = usage.inputTokens + usage.outputTokens;\n if (budgets.maxTokens != null && total > budgets.maxTokens) {\n throw new AgentError(\"BUDGET_EXCEEDED\", `Exceeded maxTokens (${budgets.maxTokens}, used ${total})`, false);\n }\n if (budgets.maxCostUsd != null) {\n const prices = budgets.prices ?? priceFor(modelId);\n if (!prices) {\n throw new AgentError(\"BUDGET_NO_PRICE\", `Cannot enforce maxCostUsd: no price for model \"${modelId}\" (set budgets.prices)`, false);\n }\n const cost = usageCost(usage, modelId, prices);\n if (cost != null && cost > budgets.maxCostUsd) {\n throw new AgentError(\"BUDGET_EXCEEDED\", `Exceeded maxCostUsd ($${budgets.maxCostUsd}, used $${cost.toFixed(4)})`, false);\n }\n }\n if (budgets.deadlineMs != null && Date.now() - startedAt > budgets.deadlineMs) {\n throw new AgentError(\"BUDGET_EXCEEDED\", `Exceeded deadline (${budgets.deadlineMs}ms)`, false);\n }\n}\n\n/** Synthetic tool for the tool strategy: valid output passes, invalid returns a retry message. */\nfunction structuredTool(format: ResponseFormat): Tool { const name = responseFormatName(format);\n const maxAttempts = format.maxAttempts ?? 2;\n let attempts = 0;\n return defineTool({\n name,\n description: `Return the final answer as structured \"${name}\". Call exactly once with valid arguments.`,\n schema: format.schema,\n execute: async (args: unknown) => {\n attempts += 1;\n const parsed = (format.schema as z.ZodType<unknown>).safeParse(args);\n if (parsed.success) return parsed.data;\n if (attempts >= maxAttempts) {\n throw new AgentError(\"STRUCTURED_NO_MATCH\", `Invalid \"${name}\" after ${attempts} attempts: ${parsed.error.message}`, false);\n }\n return `Error: invalid \"${name}\": ${parsed.error.message}. Fix the arguments and call again.`;\n },\n });\n}\n","import { mkdir, readFile, rename, writeFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\nimport { AgentError, deserializeMessages, serializeMessages, type ChatMessage } from \"../types/index.js\";\n\nexport interface Memory {\n load(): Promise<ChatMessage[]>;\n save(messages: ChatMessage[]): Promise<void>;\n clear(): Promise<void>;\n}\n\nexport class InMemoryMemory implements Memory {\n private messages: ChatMessage[] = [];\n private maxMessages: number;\n\n constructor(maxMessages = 50) {\n this.maxMessages = maxMessages;\n }\n\n async load(): Promise<ChatMessage[]> {\n return [...this.messages];\n }\n\n async save(messages: ChatMessage[]): Promise<void> {\n this.messages = [...this.messages, ...messages].slice(-this.maxMessages);\n }\n\n async clear(): Promise<void> {\n this.messages = [];\n }\n}\n\n/**\n * File-backed JSON memory: same windowing as in-memory, persisted per\n * write to `<dir>/memory.json`. Crash-safe enough for local-first use\n * (write-then-rename atomicity, validated reload).\n */\nexport class FileMemory implements Memory {\n private cache?: ChatMessage[];\n private file: string;\n private maxMessages: number;\n\n constructor(dir: string, maxMessages = 50) {\n this.file = join(dir, \"memory.json\");\n this.maxMessages = maxMessages;\n }\n\n private async readAll(): Promise<ChatMessage[]> {\n if (this.cache) return this.cache;\n let raw: string;\n try {\n raw = await readFile(this.file, \"utf8\");\n } catch {\n // Missing file = fresh memory (first run).\n this.cache = [];\n return this.cache;\n }\n try {\n this.cache = deserializeMessages(JSON.parse(raw) as unknown[]);\n } catch (err) {\n // Corrupted file must FAIL loudly: returning [] would make the next\n // save() overwrite whatever was still on disk — silent total data loss.\n throw new AgentError(\n \"MEMORY_CORRUPT\",\n `Memory file is not valid JSON for messages (${this.file}): ${err instanceof Error ? err.message : String(err)}`,\n false,\n );\n }\n return this.cache;\n }\n\n private async flush(): Promise<void> {\n await mkdir(dirname(this.file), { recursive: true });\n // Unique tmp per flush: concurrent saves sharing one fixed name race\n // on the rename and can publish a torn or half-written file.\n const tmp = `${this.file}.${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}.tmp`;\n await writeFile(tmp, JSON.stringify(serializeMessages(this.cache ?? [])), \"utf8\");\n await rename(tmp, this.file);\n }\n\n async load(): Promise<ChatMessage[]> {\n return [...(await this.readAll())];\n }\n\n async save(messages: ChatMessage[]): Promise<void> {\n const all = [...(await this.readAll()), ...messages].slice(-this.maxMessages);\n this.cache = all;\n await this.flush();\n }\n\n async clear(): Promise<void> {\n this.cache = [];\n await this.flush();\n }\n}\n","import type { TokenUsage } from \"../types/index.js\";\n\n/**\n * Per-model prices (USD per 1M tokens). Researched defaults — verify against\n * your provider bill: cloud prices change, and dedicated/self-hosted\n * endpoints (Ollama, vLLM) cost $0 in API terms.\n *\n * Why a table: TogetherAI/OpenAI-compatible and Anthropic usage payloads\n * carry token counts ONLY (no cost field). Cost is always computed\n * client-side as usage × price. (OpenRouter is the exception — it returns\n * cost directly; nothing to do there.)\n */\n\nexport interface ModelPrice {\n inputPerMillion: number;\n outputPerMillion: number;\n}\n\nconst PRICES: Record<string, ModelPrice> = {\n \"Qwen/Qwen3.5-9B\": { inputPerMillion: 0.2, outputPerMillion: 0.8 },\n \"meta-llama/Llama-3.3-70B-Instruct-Turbo\": { inputPerMillion: 0.88, outputPerMillion: 0.88 },\n \"deepseek-ai/DeepSeek-V4.1-Flash\": { inputPerMillion: 0.2, outputPerMillion: 0.6 },\n \"zai-org/GLM-5.3-Flash\": { inputPerMillion: 0.2, outputPerMillion: 0.6 },\n \"gpt-4o-mini\": { inputPerMillion: 0.15, outputPerMillion: 0.6 },\n \"claude-sonnet-4-6\": { inputPerMillion: 3, outputPerMillion: 15 },\n \"qwen2.5\": { inputPerMillion: 0, outputPerMillion: 0 },\n};\n\n/** Look up a price by bare model id (provider prefixes like `openai:`/`ollama:` are stripped). */\nexport function priceFor(modelId: string): ModelPrice | undefined {\n // Local Ollama first: even a name colliding with a cloud model (e.g.\n // `ollama:gpt-4o-mini`) runs free, so it must win over the priced table.\n if (/^ollama:/.test(modelId)) return { inputPerMillion: 0, outputPerMillion: 0 };\n const bare = modelId.includes(\":\") ? modelId.split(\":\").slice(1).join(\":\") : modelId;\n if (bare in PRICES) return PRICES[bare];\n return undefined;\n}\n\n/**\n * USD cost for usage; unknown models return undefined (never a misleading zero).\n * `outputTokens` already includes reasoning tokens on every supported provider\n * (OpenAI: reasoning_tokens ⊂ completion_tokens; Anthropic: thinking ⊂ output_tokens),\n * so they are billed at the output rate with no extra addition.\n */\nexport function usageCost(usage: TokenUsage, modelId: string, override?: ModelPrice): number | undefined {\n const price = override ?? priceFor(modelId);\n if (!price) return undefined;\n return (usage.inputTokens * price.inputPerMillion + usage.outputTokens * price.outputPerMillion) / 1_000_000;\n}\n","import { AgentError } from \"../types/index.js\";\n\nexport interface Budget {\n signal?: AbortSignal;\n timeoutMs?: number;\n}\n\nfunction toAbortError(): AgentError {\n return new AgentError(\"ABORTED\", \"Run aborted\", false);\n}\n\n/** Runtime guard: abort + timeout. Token/cost budgets land here in P1. */\nexport async function runWithBudget<T>(fn: () => Promise<T>, budget: Budget = {}): Promise<T> {\n const { signal, timeoutMs } = budget;\n try {\n signal?.throwIfAborted();\n } catch {\n throw toAbortError();\n }\n\n if (!timeoutMs && !signal) return fn();\n\n let timer: ReturnType<typeof setTimeout> | undefined;\n try {\n return await Promise.race([\n fn(),\n new Promise<never>((_, reject) => {\n if (timeoutMs) {\n timer = setTimeout(() => reject(new AgentError(\"TIMEOUT\", `Exceeded ${timeoutMs}ms`, true)), timeoutMs);\n }\n signal?.addEventListener(\n \"abort\",\n () => {\n if (timer) clearTimeout(timer);\n reject(toAbortError());\n },\n { once: true },\n );\n }),\n ]);\n } catch (err) {\n if (err instanceof DOMException && err.name === \"AbortError\") throw toAbortError();\n throw err;\n } finally {\n if (timer) clearTimeout(timer);\n }\n}\n"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OAAO,MAAM,OAAO,IAAI,KAAK;AAAA,MAC5H;AACA,aAAO,mBAAmB,IAAI,MAAM,OAAO,MAAM,OAAO;AAAA,IAC1D;AAAA,EACF,CAAC;AACH;","names":["z","z","resolve","z","z","messageTokens","mkdir","readdir","readFile","writeFile","readFile","mkdir","writeFile","readdir","zodToJsonSchema","mkdir","readFile","writeFile","dirname","join","join","readFile","mkdir","dirname","writeFile","zodToJsonSchema","managed"]}
package/dist/index.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import { z } from 'zod';
2
+ import * as zod from 'zod';
3
+ export { zod as z };
2
4
 
3
5
  /**
4
6
  * Content blocks — standard, provider-neutral message payload
@@ -807,10 +809,18 @@ interface ToolResult {
807
809
  /** Downstream-only data — stored on the call record, never sent to the model. */
808
810
  artifact?: unknown;
809
811
  }
812
+ /**
813
+ * Minimal structural contract for a schema — satisfied by zod v3, v4, minis,
814
+ * and anything with `.parse` (so consumers on ANY zod version work).
815
+ */
816
+ type AnySchema = {
817
+ parse(input: unknown): unknown;
818
+ };
810
819
  interface Tool<TArgs = any, TOutput = any> {
811
820
  name: string;
812
821
  description: string;
813
- schema: z.ZodType<TArgs, z.ZodTypeDef, any>;
822
+ /** Any zod-like schema (v3/v4); the registry calls `.parse` for validation. */
823
+ schema: AnySchema;
814
824
  /** Optional second arg receives ToolContext (state + invocationState). */
815
825
  execute: (args: TArgs, ctx?: ToolContext) => Promise<TOutput>;
816
826
  /**
@@ -821,23 +831,22 @@ interface Tool<TArgs = any, TOutput = any> {
821
831
  toResult?: (output: TOutput) => ToolResult;
822
832
  }
823
833
  /**
824
- * The defineTool() input: TSchema drives inference — `execute` receives the
825
- * schema's INPUT type (the agent loop passes the model's RAW args; parse
826
- * inside `execute` when you need strict validation — no manual generic
827
- * annotations needed):
834
+ * The defineTool() input: TArgs drives the arg type from `execute` itself
835
+ * (annotate the destructure once — that IS the parsed shape), and `schema`
836
+ * accepts any zod version (v3/v4) or anything with `.parse`:
828
837
  *
829
838
  * defineTool({ schema: z.object({ city: z.string() }),
830
- * execute: async ({ city }) => ... }) // city: string
839
+ * execute: async ({ city }: { city: string }) => ... })
831
840
  */
832
- interface ToolSpec<TSchema extends z.ZodTypeAny = z.ZodTypeAny, TOutput = unknown> {
841
+ interface ToolSpec<TArgs = any, TOutput = unknown> {
833
842
  name: string;
834
843
  description: string;
835
- schema: TSchema;
836
- execute: (args: z.input<TSchema>, ctx?: ToolContext) => Promise<TOutput>;
844
+ schema: AnySchema;
845
+ execute: (args: TArgs, ctx?: ToolContext) => Promise<TOutput>;
837
846
  toResult?: (output: TOutput) => ToolResult;
838
847
  }
839
848
  declare function defaultToResult(output: unknown): ToolResult;
840
- declare function defineTool<TSchema extends z.ZodTypeAny = z.ZodTypeAny, TOutput = unknown>(tool: ToolSpec<TSchema, TOutput>): Tool<z.output<TSchema>, TOutput>;
849
+ declare function defineTool<TArgs = any, TOutput = unknown>(tool: ToolSpec<TArgs, TOutput>): Tool<TArgs, TOutput>;
841
850
  /** Validating registry — single place tools are looked up + arg-checked. */
842
851
  declare class ToolRegistry {
843
852
  private tools;
@@ -1916,8 +1925,8 @@ declare function retrievalTool(retriever: Retriever, opts?: {
1916
1925
  k?: number;
1917
1926
  name?: string;
1918
1927
  }): Tool<{
1919
- k: number;
1920
1928
  query: string;
1929
+ k?: number;
1921
1930
  }, ScoredDoc[]>;
1922
1931
  /** SPARQL-backed retriever: keyword match over the closure, rendered as text. */
1923
1932
  declare function sparqlRetriever(store: {
@@ -2372,8 +2381,8 @@ declare class EntityLinker {
2372
2381
  }
2373
2382
  /** link_entity agent tool: mention -> canonical IRIs with scores. */
2374
2383
  declare function linkEntityTool(linker: EntityLinker): Tool<{
2375
- k: number;
2376
2384
  mention: string;
2385
+ k?: number;
2377
2386
  }, LinkedEntity[]>;
2378
2387
  interface MappingProposal {
2379
2388
  id: string;
@@ -2420,8 +2429,8 @@ declare class MappingProposals {
2420
2429
  decide(store: GraphStore, id: string, decision: MappingDecision): Promise<MappingProposal | undefined>;
2421
2430
  }
2422
2431
  declare function proposeMappingTool(proposals: MappingProposals): Tool<{
2423
- to: string;
2424
2432
  from: string;
2433
+ to: string;
2425
2434
  source: string;
2426
2435
  }, string | {
2427
2436
  id: string;
@@ -2603,9 +2612,9 @@ declare function adoptShapes(store: InMemoryGraphStore, shapes: NodeShape[]): Pr
2603
2612
  }[];
2604
2613
  }>;
2605
2614
  /** review_ontology agent tool: inventory + gaps, straight from the store. */
2606
- declare function reviewOntologyTool(store: InMemoryGraphStore): Tool<{}, OntologyReview>;
2615
+ declare function reviewOntologyTool(store: InMemoryGraphStore): Tool<any, OntologyReview>;
2607
2616
  /** propose_shapes agent tool: SHACL candidates induced from instance data. */
2608
- declare function proposeShapesTool(store: InMemoryGraphStore, opts?: ShapeInductionOptions): Tool<{}, NodeShape[]>;
2617
+ declare function proposeShapesTool(store: InMemoryGraphStore, opts?: ShapeInductionOptions): Tool<any, NodeShape[]>;
2609
2618
 
2610
2619
  /**
2611
2620
  * Semantic layer. See docs/07-semantics-governance.md.
@@ -2741,7 +2750,7 @@ declare function sparqlSelectTool(store: GraphStore): Tool<{
2741
2750
  /** Ontology lookup: find classes/properties/labels matching a term. */
2742
2751
  declare function ontologyLookupTool(store: GraphStore): Tool<{
2743
2752
  term: string;
2744
- limit: number;
2753
+ limit?: number;
2745
2754
  }, {
2746
2755
  subject: string;
2747
2756
  predicate: string;
@@ -2770,10 +2779,10 @@ declare const TurtleQuadSchema: z.ZodObject<{
2770
2779
  */
2771
2780
  declare function graphAddTool(store: GraphStore): Tool<{
2772
2781
  quads: {
2773
- object: string;
2774
- source: string;
2775
2782
  subject: string;
2776
2783
  predicate: string;
2784
+ object: string;
2785
+ source: string;
2777
2786
  }[];
2778
2787
  }, string | {
2779
2788
  committed: number;
@@ -2786,9 +2795,9 @@ type ClaimVerdict = "grounded" | "unknown" | "contradicted";
2786
2795
  * (contradicted)? Ask before answering from memory.
2787
2796
  */
2788
2797
  declare function claimCheckTool(store: GraphStore): Tool<{
2789
- object: string;
2790
2798
  subject: string;
2791
2799
  predicate: string;
2800
+ object: string;
2792
2801
  }, {
2793
2802
  verdict: ClaimVerdict;
2794
2803
  proof: {
@@ -2855,4 +2864,4 @@ declare function estimateCostUsd(usage: {
2855
2864
  outputPerMillion: number;
2856
2865
  }): number;
2857
2866
 
2858
- export { A2AClient, type A2AClientOptions, A2AServer, type A2AServerOptions, Agent, type AgentCard, AgentClient, type AgentClientOptions, AgentError, type AgentEvents, type AgentId, type AgentMiddleware, type AgentOptions, type AgentResult, AgentState, type AnthropicOptions, AnthropicProvider, type AnyMcpClient, AudioBlockSchema, type BackoffOptions, type Brand, type Budget, type ChatMessage, ChatMessageSchema, type Checkpointer, type ClaimVerdict, ClearToolUsesEdit, type ClearToolUsesOptions, CompactedMemory, type CompactionOptions, type CompleteOptions, type ConformanceCheck, type ConformanceReport, type ConformanceResult, type ConsoleEventsOptions, ConsoleSpanSink, type ContentBlock, ContentBlockSchema, type ConversationManager, type DoneEvent, EntityLinker, type EvalCase, type EvalExpect, type EvalScore, type ExecutedToolCall, FileBlockSchema, FileCheckpointer, FileMemory, type FrameworkConfig, type FrameworkFile, FrameworkFileSchema, GraphMemory, type GraphRule, type GraphStore, type HandoffSignal, type HitlDecideRequest, type HitlDecision, HitlInterrupt, type HookContext, type ImageBlock, ImageBlockSchema, InMemoryGraphStore, InMemoryMemory, InMemoryRetriever, InMemoryStorage, type InvocationState, JSONLD_PREFIXES, JsonlSpanSink, LABEL_PREDICATES, type LinkedEntity, type LoadedFrameworkFile, LocalFileStorage, type MappingDecision, type MappingProposal, MappingProposals, type MappingProposalsOptions, type McpClient, type McpClientOptions, McpHttpClient, McpStdioClient, type McpToolDef, type Memory, MemorySpanSink, type MigrationReport, type MigrationResult, MockModelProvider, type ModelCapability, type ModelCompletion, type ModelPrice, type ModelProvider, type ModelRequest, type NodeShape, NonStandardBlockSchema, NullConversationManager, OWL_VOCAB, type OllamaOptions, OllamaProvider, type OntologyReview, type OpenAICompatibleOptions, OpenAICompatibleProvider, type OrchestratedResult, type OrchestrationPlan, type OrchestrationStrategy, type OutputVersion, type PIIDetector, type PIIMatch, type PIIStrategy, type PatternBinding, type PromptTemplate, type PropertyShape, type Quad, type ReasoningBlock, ReasoningBlockSchema, RemoteSparqlAdapter, type RemoteSparqlOptions, type ResolvedAgentDef, type ResponseFormat, type ResponseFormatWire, type ResponseStrategy, type Result, type Retriever, type RetryFilter, type RetryMiddlewareOptions, type RunId, type RunOptions, type SandboxBackend, type SandboxOptions, type ScoredDoc, type ServedAgent, SessionManager, type SessionManagerOptions, type ShapeInductionOptions, type ShapeReport, type Skill, type SkillLoaderOptions, SkillRegistry, SlidingWindowConversationManager, type SlidingWindowOptions, type Snapshot, type SnapshotData, type SnapshotField, type Span, type SpanSink, type SparqlAuth, type SparqlRow, type SparqlSelect, type StepEvent, type Storage, type StoreOptions, type StreamEvent, SummarizingConversationManager, type SummarizingOptions, Swarm, type SwarmOptions, type SwarmResult, type SwarmStatus, type SwarmStreamEvent, TBOX_PREDICATES, type TBoxMigrationSpec, type TakeSnapshotOptions, type TermStat, type TextBlock, TextBlockSchema, type ThreadCheckpoint, type TimelineEntry, type TodoItem, type TokenBudgets, type TokenUsage, type Tool, ToolCallBlockSchema, type ToolCallEvent, type ToolCallRef, type ToolCallRequest, type ToolContext, type ToolName, ToolRegistry, ToolRejection, type ToolResult, type ToolResultEvent, type ToolSpec, type TriplePattern, TurtleQuadSchema, type WorkflowNode, type WorkflowOptions, __resetConfig, a2aAsTool, abPrompts, adoptShapes, assertCanHandle, assistant, backoffDelayMs, buildServedAgent, claimCheckTool, collectStream, connectMcpHttp, connectMcpStdio, consoleEvents, contextEditingMiddleware, createMiddleware, createSandboxBackend, createSubAgentMiddleware, defaultSummarize, defaultToResult, definePrompt, defineTool, deserializeMessages, discoverSkills, estimateCostUsd, estimateTokens, executeSelect, filesystemMiddleware, filesystemTools, getRetryable, graphAddTool, handleAgentRoute, hasImages, historyTokens, hitlKey, humanInTheLoopMiddleware, imagesOf, initChatModel, instantiate, jsonSchemaToZod, jsonldToQuads, linkEntityTool, llmToolSelectorMiddleware, loadConfig, loadEnvFile, loadFrameworkConfig, loadJsonl, loadPromptFile, loadSkillsInto, logError, matchGlob, matchPatterns, matchSkills, mcpToolsToFramework, messageTokens, migrateTBox, modelCallLimit, modelFallbackMiddleware, modelRetryMiddleware, ollama, ontologyLookupTool, parseSelect, parseSkillFile, parseStructured, piiMiddleware, policyFilterMiddleware, priceFor, printReport, proposeMappingTool, proposeShapes, proposeShapesTool, providerFromEnv, providerStrategy, quadsToJsonLd, readHandoffSignal, remoteSparqlTool, responseFormatJsonSchema, responseFormatName, retrievalTool, reviewOntology, reviewOntologyTool, runConformance, runEval, runJavascriptTool, runOrchestrated, runWithBudget, runWorkflow, scoreSkills, selectSnapshotFields, serializeMessages, serveFramework, sleep, sparqlRetriever, sparqlSelectTool, stampRetryable, summarizationMiddleware, supportsColor, supportsVision, system, textOf, todoListMiddleware, tokenize, toolCallLimitMiddleware, toolEmulatorMiddleware, toolResult, toolRetry, toolRetryMiddleware, toolStrategy, tracingEvents, trimDangling, usageCost, user, wireTextOf, withFileLock };
2867
+ export { A2AClient, type A2AClientOptions, A2AServer, type A2AServerOptions, Agent, type AgentCard, AgentClient, type AgentClientOptions, AgentError, type AgentEvents, type AgentId, type AgentMiddleware, type AgentOptions, type AgentResult, AgentState, type AnthropicOptions, AnthropicProvider, type AnyMcpClient, type AnySchema, AudioBlockSchema, type BackoffOptions, type Brand, type Budget, type ChatMessage, ChatMessageSchema, type Checkpointer, type ClaimVerdict, ClearToolUsesEdit, type ClearToolUsesOptions, CompactedMemory, type CompactionOptions, type CompleteOptions, type ConformanceCheck, type ConformanceReport, type ConformanceResult, type ConsoleEventsOptions, ConsoleSpanSink, type ContentBlock, ContentBlockSchema, type ConversationManager, type DoneEvent, EntityLinker, type EvalCase, type EvalExpect, type EvalScore, type ExecutedToolCall, FileBlockSchema, FileCheckpointer, FileMemory, type FrameworkConfig, type FrameworkFile, FrameworkFileSchema, GraphMemory, type GraphRule, type GraphStore, type HandoffSignal, type HitlDecideRequest, type HitlDecision, HitlInterrupt, type HookContext, type ImageBlock, ImageBlockSchema, InMemoryGraphStore, InMemoryMemory, InMemoryRetriever, InMemoryStorage, type InvocationState, JSONLD_PREFIXES, JsonlSpanSink, LABEL_PREDICATES, type LinkedEntity, type LoadedFrameworkFile, LocalFileStorage, type MappingDecision, type MappingProposal, MappingProposals, type MappingProposalsOptions, type McpClient, type McpClientOptions, McpHttpClient, McpStdioClient, type McpToolDef, type Memory, MemorySpanSink, type MigrationReport, type MigrationResult, MockModelProvider, type ModelCapability, type ModelCompletion, type ModelPrice, type ModelProvider, type ModelRequest, type NodeShape, NonStandardBlockSchema, NullConversationManager, OWL_VOCAB, type OllamaOptions, OllamaProvider, type OntologyReview, type OpenAICompatibleOptions, OpenAICompatibleProvider, type OrchestratedResult, type OrchestrationPlan, type OrchestrationStrategy, type OutputVersion, type PIIDetector, type PIIMatch, type PIIStrategy, type PatternBinding, type PromptTemplate, type PropertyShape, type Quad, type ReasoningBlock, ReasoningBlockSchema, RemoteSparqlAdapter, type RemoteSparqlOptions, type ResolvedAgentDef, type ResponseFormat, type ResponseFormatWire, type ResponseStrategy, type Result, type Retriever, type RetryFilter, type RetryMiddlewareOptions, type RunId, type RunOptions, type SandboxBackend, type SandboxOptions, type ScoredDoc, type ServedAgent, SessionManager, type SessionManagerOptions, type ShapeInductionOptions, type ShapeReport, type Skill, type SkillLoaderOptions, SkillRegistry, SlidingWindowConversationManager, type SlidingWindowOptions, type Snapshot, type SnapshotData, type SnapshotField, type Span, type SpanSink, type SparqlAuth, type SparqlRow, type SparqlSelect, type StepEvent, type Storage, type StoreOptions, type StreamEvent, SummarizingConversationManager, type SummarizingOptions, Swarm, type SwarmOptions, type SwarmResult, type SwarmStatus, type SwarmStreamEvent, TBOX_PREDICATES, type TBoxMigrationSpec, type TakeSnapshotOptions, type TermStat, type TextBlock, TextBlockSchema, type ThreadCheckpoint, type TimelineEntry, type TodoItem, type TokenBudgets, type TokenUsage, type Tool, ToolCallBlockSchema, type ToolCallEvent, type ToolCallRef, type ToolCallRequest, type ToolContext, type ToolName, ToolRegistry, ToolRejection, type ToolResult, type ToolResultEvent, type ToolSpec, type TriplePattern, TurtleQuadSchema, type WorkflowNode, type WorkflowOptions, __resetConfig, a2aAsTool, abPrompts, adoptShapes, assertCanHandle, assistant, backoffDelayMs, buildServedAgent, claimCheckTool, collectStream, connectMcpHttp, connectMcpStdio, consoleEvents, contextEditingMiddleware, createMiddleware, createSandboxBackend, createSubAgentMiddleware, defaultSummarize, defaultToResult, definePrompt, defineTool, deserializeMessages, discoverSkills, estimateCostUsd, estimateTokens, executeSelect, filesystemMiddleware, filesystemTools, getRetryable, graphAddTool, handleAgentRoute, hasImages, historyTokens, hitlKey, humanInTheLoopMiddleware, imagesOf, initChatModel, instantiate, jsonSchemaToZod, jsonldToQuads, linkEntityTool, llmToolSelectorMiddleware, loadConfig, loadEnvFile, loadFrameworkConfig, loadJsonl, loadPromptFile, loadSkillsInto, logError, matchGlob, matchPatterns, matchSkills, mcpToolsToFramework, messageTokens, migrateTBox, modelCallLimit, modelFallbackMiddleware, modelRetryMiddleware, ollama, ontologyLookupTool, parseSelect, parseSkillFile, parseStructured, piiMiddleware, policyFilterMiddleware, priceFor, printReport, proposeMappingTool, proposeShapes, proposeShapesTool, providerFromEnv, providerStrategy, quadsToJsonLd, readHandoffSignal, remoteSparqlTool, responseFormatJsonSchema, responseFormatName, retrievalTool, reviewOntology, reviewOntologyTool, runConformance, runEval, runJavascriptTool, runOrchestrated, runWithBudget, runWorkflow, scoreSkills, selectSnapshotFields, serializeMessages, serveFramework, sleep, sparqlRetriever, sparqlSelectTool, stampRetryable, summarizationMiddleware, supportsColor, supportsVision, system, textOf, todoListMiddleware, tokenize, toolCallLimitMiddleware, toolEmulatorMiddleware, toolResult, toolRetry, toolRetryMiddleware, toolStrategy, tracingEvents, trimDangling, usageCost, user, wireTextOf, withFileLock };
package/dist/index.js CHANGED
@@ -71,7 +71,7 @@ import {
71
71
  usageCost,
72
72
  user,
73
73
  wireTextOf
74
- } from "./chunk-VIGLIWEY.js";
74
+ } from "./chunk-2XXGDP7B.js";
75
75
 
76
76
  // src/config/index.ts
77
77
  import { existsSync } from "fs";
@@ -3781,6 +3781,9 @@ ${lines.join("\n")}` }];
3781
3781
  if (fresh.length) await this.store.add(fresh);
3782
3782
  }
3783
3783
  };
3784
+
3785
+ // src/index.ts
3786
+ import * as z13 from "zod";
3784
3787
  export {
3785
3788
  A2AClient,
3786
3789
  A2AServer,
@@ -3946,6 +3949,7 @@ export {
3946
3949
  usageCost,
3947
3950
  user,
3948
3951
  wireTextOf,
3949
- withFileLock
3952
+ withFileLock,
3953
+ z13 as z
3950
3954
  };
3951
3955
  //# sourceMappingURL=index.js.map