@theokit/agents 4.3.1 → 4.4.0

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 @@
1
+ {"version":3,"sources":["../src/errors.ts","../src/bridge/define-agent.ts","../src/bridge/compile-context-window.ts","../src/bridge/compile-skills.ts","../src/bridge/agent-compiler.ts","../src/bridge/agent-execution-context.ts","../src/bridge/compile-project-context.ts","../src/bridge/agent-sse-handler.ts","../src/bridge/agent-stream-events.ts","../src/bridge/agent-route-generator.ts","../src/bridge/event-translator.ts","../src/bridge/model-selection.ts","../src/bridge/think-tag-extractor.ts","../src/debug-log.ts","../src/bridge/sdk-adapter-create-options.ts","../src/bridge/tool-dialect-stripper.ts","../src/bridge/sdk-adapter.ts","../../presenter/src/agent-output-event.ts","../../presenter/src/presenter.ts","../../presenter/src/source/from-sdk.ts","../../presenter/src/presenters/ui-message-stream.ts","../../presenter/src/presenters/terminal.ts","../../presenter/src/presenters/json.ts","../src/bridge/present-ui-message-stream.ts","../src/bridge/agent-builder.ts","../src/bridge/hitl-plugin.ts","../src/bridge/agent-endpoint.ts","../src/guardrails/types.ts","../src/guardrails/detectors.ts","../src/guardrails/pipeline.ts","../src/guardrails/stream.ts","../src/loop/compaction-strategy.ts","../src/loop/loop-strategy.ts","../src/loop/reflection-strategy.ts","../src/bridge/delegation-types.ts","../src/loop/run-reflective-loop.ts","../src/loop/agent-runner.ts","../src/loop/goal-runner.ts","../src/bridge/agent-orchestrator.ts","../src/bridge/tool-hooks-plugin.ts","../src/bridge/api-error-handler.ts","../src/bridge/delegation-scoring.ts","../src/bridge/mcp-resolver.ts","../src/manifest/agent-manifest.ts","../src/theokit-plugin.ts"],"sourcesContent":["/**\n * Typed authoring failures for `@theokit/agents`.\n *\n * This module is still the leaf all internal layers import (`bridge/` + `capability/` both throw the\n * same typed error; keeping it here avoids the import cycle a home in `capability/capabilities.ts`\n * would close — `rules/architecture.md` § 2).\n *\n * M61 — there is now ONE `ConfigurationError`, not two. The layer used to define its own\n * (`extends Error`) while the SDK shipped a separate `ConfigurationError extends TheokitAgentError`;\n * the agent-builder imported the SDK's, so a `catch (e instanceof ConfigurationError)` caught one\n * path and silently missed the other. The layer now RE-EXPORTS the SDK's class, so authoring throws\n * from `@theokit/agents` and runtime throws from `@theokit/sdk` are the SAME class — `instanceof`\n * holds across the boundary in both directions. It gains the SDK's `{ code, cause, metadata }`\n * options (existing single-arg `new ConfigurationError('msg')` calls are unchanged — options are\n * optional) and stays `instanceof Error` (via `TheokitAgentError extends Error`). Decision in\n * `knowledge-base/adrs/0006-configuration-error-unification.md`.\n */\nexport { ConfigurationError } from '@theokit/sdk/errors'\n","/**\n * M2 (theokit-ai-first) — `defineAgent`, the zero-config imperative agent surface.\n *\n * ADR-B1: `defineAgent({...})` (default-exported from a top-level `agents/<name>.ts`) is\n * the canonical zero-config surface; the `@Agent` class decorator stays the advanced/DI\n * surface. Both compile to {@link CompiledAgentOptions} and run through the same SDK\n * runtime (`createSdkAgentStream`) — one runtime, two syntaxes.\n *\n * This module is PURE metadata (sdk-runtime.md / G2): `defineAgent` describes an agent, it\n * NEVER calls an LLM. It imports only `zod` (types) + the compiler shape — no `theokit`\n * core, preserving the agents → (nothing) dependency direction (G1).\n */\nimport type { CustomTool, InlineSkill, MemorySettings, SettingSource } from '@theokit/sdk'\nimport type { z } from 'zod'\n\nimport type { Guardrail } from '../guardrails/index.js'\nimport type { SkillsSelection } from '../skills-resolver.js'\nimport type { HumanInTheLoopOptions } from '../types.js'\nimport type { McpServersMap } from '../types.js'\nimport type { ReasoningEffort } from '../types.js'\n\nimport type { CompiledAgentOptions, CompiledTool } from './agent-compiler.js'\n\n/**\n * Brand tag for a `defineAgent` value. `Symbol.for` (global registry, not `Symbol()`) so\n * the brand survives duplicate module instances (dual-package / bundling) — the scanner's\n * brand-check then works regardless of which copy created the definition.\n */\nexport const AGENT_BRAND: unique symbol = Symbol.for('theokit.agent.definition')\n\n/** Config accepted by {@link defineAgent}. */\nexport interface DefineAgentConfig<TInput extends z.ZodType = z.ZodType> {\n /** Zod schema for the request body — lifted into the typed client (M2, {@link InferAgentInput}). */\n input?: TInput\n /** Model id (e.g. `claude-sonnet-4-6`). Falls back to the SDK default when omitted. */\n model?: string\n /** Static system prompt. */\n system?: string\n /** Extended-thinking effort. */\n reasoningEffort?: ReasoningEffort\n /**\n * Pre-built tools. Accepts the `@theokit/sdk` `CustomTool` that `defineAgentTool`\n * (theokit/server) and every `@theokit/sdk-tools` factory return (issue #81) — they are\n * normalized to the internal {@link CompiledTool} shape at compile time.\n */\n tools?: readonly CustomTool[]\n /**\n * M7 — run-context: an opaque, per-agent object forwarded to every tool handler's\n * `ctx.context` at run time (injected by the theokit adapter's tool wrapper). Set shared config\n * (e.g. `{ projectRoot }`) ONCE at the agent level instead of baking it into each tool\n * factory. Mirrors ai-sdk `experimental_context`, mastra `RuntimeContext`, and\n * openai-agents-js `RunContext`. Distinct from `@Agent`'s context-window `context`.\n */\n context?: Record<string, unknown>\n /**\n * M9 — guardrails: input/output guards applied at the framework boundary (ADR-0040 § D2).\n * Input guards run on the user message before the SDK runtime; a `block` fails the run fast.\n * Built-ins live in `@theokit/agents` (`promptInjectionDetector`, `piiDetector`, `costGuard`,\n * `unicodeNormalizer`, `outputModeration`).\n */\n guardrails?: readonly Guardrail[]\n /**\n * M14 — HITL approvals keyed by tool name. Each gated tool pauses the run and emits an\n * `approval_required` event until approved (reuses the same `compiled.hitl` wiring the `@Agent`\n * + `@HumanInTheLoop` path produces). A key that does not match a declared tool fails fast at\n * compile time.\n */\n approvals?: Record<string, HumanInTheLoopOptions>\n /**\n * M13 — skills selection: a static list (compiled straight to the SDK `skills.enabled`) OR a\n * per-request resolver `(ctx) => string[]` (carried on `compiled.skillsResolver`, resolved by the\n * request path against the run-context). Absent ⇒ the SDK enables every discovered skill.\n */\n skills?: SkillsSelection\n /**\n * theokit-file-based-config — opt into `.theokit/` file-based config (skills, subagents, hooks,\n * MCP, context, cron). The SDK discovers config from these roots under the app's `cwd`:\n * `\"project\"` = `<cwd>/.theokit/`, `\"user\"` = `~/.theokit/`. Absent ⇒ inline (code) config only.\n * SECURITY: enabling `\"project\"` enables shell-executing hooks from `.theokit/hooks.json` — this\n * is opt-in because `.theokit/` is the app's own repo (informed consent). The SDK owns discovery\n * + execution (G2 / ADR-0040); theokit only wires this into `Agent.create({ local.settingSources })`.\n */\n settingSources?: readonly SettingSource[]\n /**\n * M49 — durable memory (the SDK's `.theokit/memory/` subsystem: `Remember:` capture, MEMORY.md\n * store, auto-injected `<memory>` block, `memory_search`/`memory_get` tools). The shape is the\n * SDK's own `MemorySettings` — the canonical runtime contract. Projected into\n * `Agent.create({ memory })` by `assembleM8CreateOptions`.\n */\n memory?: MemorySettings\n /**\n * Code `Plugin` objects forwarded to `Agent.create({ plugins })` — EXTENSION units (tools,\n * commands, model providers, memory adapters). For lifecycle interception use {@link hooks}.\n */\n plugins?: readonly unknown[]\n /**\n * Lifecycle hooks keyed by `HookName` (`pre_tool_call` may veto via `{ block, message }`). Set by\n * the builder's `hooks()`; converted into a code plugin at `build()` and never reaching the SDK\n * under this name — the plugin is the TRANSPORT, this is the contract callers write against.\n */\n hooks?: Readonly<Record<string, unknown>>\n /**\n * MCP servers available to the agent — the builder-chain equivalent of the `@MCP` class\n * decorator. Each key is a server name; the value is the server configuration. Forwarded\n * unchanged to `Agent.create({ mcpServers })` (the SDK owns MCP execution). Absent ⇒ no MCP.\n */\n mcpServers?: McpServersMap\n}\n\n/**\n * A branded agent definition — the value {@link defineAgent} returns.\n *\n * `TTools` (M8) is a phantom type parameter carrying the tool-name union: the `AgentBuilder.create()` builder\n * threads its accumulated literal tool names here (`.build()` returns `AgentDefinition<TInput,\n * 'a' | 'b'>`), so the generated client (`.theokit/agents.d.ts`) can expose them via\n * {@link InferAgentToolNames}. `defineAgent` leaves it `string` (its tools array carries no literal\n * names). Never present at runtime.\n */\nexport type AgentDefinition<\n TInput extends z.ZodType = z.ZodType,\n TTools extends string = string,\n> = DefineAgentConfig<TInput> & {\n readonly [AGENT_BRAND]: true\n readonly __toolNames?: TTools\n}\n\n/** Infer the request type of an agent definition from its `input` Zod schema. */\nexport type InferAgentInput<T> =\n T extends AgentDefinition<infer S> ? (S extends z.ZodType ? z.infer<S> : never) : never\n\n/**\n * Infer the tool-name union of an agent definition (M8). Yields the literal union for agents built\n * with the `AgentBuilder.create()` builder (`'read_file' | 'count_lines'`), or `string` for `defineAgent` agents\n * whose tools array carries no literal names.\n */\nexport type InferAgentToolNames<T> = T extends AgentDefinition<z.ZodType, infer N> ? N : never\n\n/**\n * Define a zero-config agent. Identity/normalizer (like `defineRoute`) — returns the config\n * branded so the scanner recognizes it. Compilation is deferred to {@link compileAgentDefinition}.\n */\nexport function defineAgent<TInput extends z.ZodType = z.ZodType>(\n config: DefineAgentConfig<TInput>,\n): AgentDefinition<TInput> {\n return { ...config, [AGENT_BRAND]: true }\n}\n\n/** Brand-check: is `value` a {@link defineAgent} result? */\nexport function isAgentDefinition(value: unknown): value is AgentDefinition {\n return (\n typeof value === 'object' &&\n value !== null &&\n (value as unknown as Record<PropertyKey, unknown>)[AGENT_BRAND] === true\n )\n}\n\n/**\n * Normalize a pre-built `@theokit/sdk` {@link CustomTool} to the internal\n * {@link CompiledTool} shape (issue #81). `CustomTool.handler` takes a narrower\n * `Record<string, unknown>` input than `CompiledTool.handler`'s `unknown`, so it cannot be\n * assigned directly (contravariance); this thin wrapper bridges the parameter. Runtime-safe:\n * the SDK always calls a tool handler with the parsed input object.\n */\nfunction toCompiledTool(tool: CustomTool): CompiledTool {\n // M7 — forward the run-context `ctx` (2nd arg) to the underlying tool so `defineAgent({ context })`\n // reaches `ctx.context` in the handler (dropping it silently severs the context seam).\n // `CustomTool.handler` takes `Record<string, unknown>` as input; `CompiledTool.handler` takes the\n // wider `unknown`. Contravariance on the input parameter prevents direct assignment — `as unknown as`\n // is the SDK-boundary seam for this widening. Runtime-safe: SDK always passes a plain object for input.\n const handler = tool.handler as unknown as (\n input: unknown,\n ctx?: { signal?: AbortSignal; context?: unknown },\n ) => string | Promise<string>\n const compiled: CompiledTool = {\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema,\n handler: (input, ctx) => handler(input, ctx),\n }\n // Preserve SYMBOL-keyed metadata the SDK installs on a tool — notably the `@theokit/sdk/a2a` subagent\n // credential-inheritance sink (`Symbol.for(\"theokit.subagent.inheritCredentials\")`). Copying only the\n // four known fields drops it, so the SDK runtime can't hand the parent's `apiKey` down to a delegated\n // child → the child fails with `provider_unresolved` (\"(no response)\"). The wrapped handler still calls\n // the original tool's handler, so the sink (which mutates that handler's closure) stays effective.\n for (const sym of Object.getOwnPropertySymbols(tool)) {\n ;(compiled as unknown as Record<symbol, unknown>)[sym] = (\n tool as unknown as Record<symbol, unknown>\n )[sym]\n }\n return compiled\n}\n\n/**\n * Lower a definition to the SDK-ready {@link CompiledAgentOptions} — the same shape\n * `compileAgent` (decorator path) produces, so both surfaces converge on one runtime.\n */\nexport function compileAgentDefinition(def: AgentDefinition): CompiledAgentOptions {\n return {\n model: def.model,\n reasoningEffort: def.reasoningEffort,\n systemPrompt: def.system,\n tools: (def.tools ?? []).map(toCompiledTool),\n agents: {},\n stream: true,\n // M7 — run-context flows to CompiledAgentOptions.runContext (distinct from the\n // context-window `context` field the decorator path uses); absent ⇒ no key.\n ...(def.context !== undefined ? { runContext: def.context } : {}),\n // M9 — guardrails flow through unchanged; the runner applies them at the input boundary.\n ...(def.guardrails !== undefined ? { guardrails: def.guardrails } : {}),\n // M14 — HITL approvals compile into the same `hitl` map the decorator path produces.\n ...(def.approvals !== undefined ? { hitl: compileApprovals(def) } : {}),\n // M13 — skills: a static list → SDK skills.enabled; a resolver → carried for the request path.\n ...compileSkillsSelection(def.skills),\n // theokit-file-based-config — the declared `.theokit/` sources flow to the run path, which\n // projects them into `Agent.create({ local.settingSources })`; absent ⇒ inline config only.\n ...(def.settingSources !== undefined ? { settingSources: def.settingSources } : {}),\n // M49 — memory flows to the projection layer; `assembleM8CreateOptions` forwards it to Agent.create.\n ...(def.memory !== undefined ? { memory: def.memory } : {}),\n // Hooks are converted here — the layer EVERY path converges on — rather than on the builder, so\n // `defineAgent({ hooks })` cannot type-check and silently no-op. A lifecycle hook that is\n // declared but never registered is a security gate that does not gate.\n ...compileHooksAndPlugins(def),\n // MCP — builder/`defineAgent` servers converge on the same `mcpServers` field the `@MCP`\n // decorator path populates; the SDK adapter forwards it to `Agent.create({ mcpServers })`.\n ...(def.mcpServers !== undefined ? { mcpServers: def.mcpServers } : {}),\n }\n}\n\n/**\n * M13 — split a {@link SkillsSelection} into the compiled fields (static → `skills`, fn →\n * `skillsResolver`). A static array may mix filesystem skill NAMES (`string` → `skills.enabled`) with\n * inline `createSkill` objects (`InlineSkill` → `skills.inline`, injected into the `<skills>` block).\n */\n/**\n * Convert a `hooks` map into the code plugin that carries it, appended to any explicitly registered\n * plugins. Hooks and plugins are DIFFERENT concepts — a hook is a lifecycle interception point, a\n * plugin is an extension unit — but the SDK dispatches hooks through the plugin seam, so the map\n * needs a transport. Doing the conversion HERE (not on the builder) means every entry point that\n * reaches `defineAgent` gets it, so `hooks` can never be declared-but-dropped.\n */\nfunction compileHooksAndPlugins(def: AgentDefinition): { plugins?: readonly unknown[] } {\n const map = (def as { hooks?: Readonly<Record<string, unknown>> }).hooks\n const entries = Object.entries(map ?? {}).filter(([, h]) => typeof h === 'function')\n const explicit = def.plugins ?? []\n\n if (entries.length === 0) {\n return def.plugins !== undefined ? { plugins: def.plugins } : {}\n }\n\n // `kind: 'general'` is load-bearing — the SDK's `isCodePlugin()` drops any plugin without it and\n // no hook fires (proven against a real run; see the M26/M28 dispatch investigation).\n const plugin = {\n name: 'theokit-builder-hooks',\n version: '1.0.0',\n kind: 'general' as const,\n register(ctx: { on: (hook: string, handler: (c: never) => unknown) => void }): void {\n for (const [hookName, handler] of entries) {\n ctx.on(hookName, handler as (c: never) => unknown)\n }\n },\n }\n return { plugins: [...explicit, plugin] }\n}\n\nexport function compileSkillsSelection(\n skills: SkillsSelection | undefined,\n): Pick<CompiledAgentOptions, 'skills' | 'skillsResolver'> {\n if (skills === undefined) return {}\n if (typeof skills === 'function') return { skillsResolver: skills }\n const enabled: string[] = []\n const inline: InlineSkill[] = []\n for (const entry of skills) {\n if (typeof entry === 'string') enabled.push(entry)\n else inline.push(entry)\n }\n return {\n skills: { enabled, autoInject: true, ...(inline.length > 0 ? { inline } : {}) },\n }\n}\n\n/**\n * Build the HITL gate map from `defineAgent({ approvals })`, keyed by tool name — the same shape\n * `agent-endpoint.ts` consumes. Fails fast (error-handling.md) if an approval names a tool the\n * agent does not declare, so a typo is caught at compile time, not silently ignored at runtime.\n */\nfunction compileApprovals(def: AgentDefinition): Map<string, HumanInTheLoopOptions> {\n const toolNames = new Set((def.tools ?? []).map((t) => t.name))\n const gates = new Map<string, HumanInTheLoopOptions>()\n for (const [toolName, options] of Object.entries(def.approvals ?? {})) {\n if (!toolNames.has(toolName)) {\n throw new Error(\n `[@theokit/agents] defineAgent approval references unknown tool \"${toolName}\". ` +\n `Declared tools: ${[...toolNames].join(', ') || '(none)'}.`,\n )\n }\n gates.set(toolName, options)\n }\n return gates\n}\n","/**\n * M8-1 — compile `@ContextWindow` metadata into the SDK's `ContextSettings`.\n *\n * Per sdk-runtime.md, the SDK owns session/transcript storage + compaction.\n * The bridge therefore maps the one knob the SDK natively exposes as a budget —\n * `maxTokens` → `ContextSettings.maxTokens` — and reports the strategy knobs that\n * have NO native `AgentOptions` equivalent (`compactionStrategy`, `preserveLastN`,\n * `preserveToolResults`, `preserveSystemPrompt`). Those are surfaced as\n * `metadataOnlyKnobs` so the walk can emit an honest `metadata-only` warning\n * (ADR D2) instead of silently dropping them (G10 — honest enforcement).\n */\nimport type { ContextSettings } from '@theokit/sdk'\n\n/** How to compact the transcript when `maxTokens` is exceeded. */\nexport type ContextCompactionStrategy =\n | 'truncate-oldest'\n | 'summarize-oldest'\n | 'sliding-window'\n | 'priority-based'\n\n/**\n * M53 — declared here, with its conversion, instead of on the decorator being deleted.\n */\nexport interface ContextWindowOptions {\n /** Maximum tokens before compaction triggers. */\n maxTokens?: number\n /** How to compact when maxTokens is exceeded. */\n compactionStrategy?: ContextCompactionStrategy\n /** Always preserve the system prompt during compaction (default: true). */\n preserveSystemPrompt?: boolean\n /** Number of recent messages to always keep intact (default: 10). */\n preserveLastN?: number\n /** Keep all tool results even during compaction (default: true). */\n preserveToolResults?: boolean\n}\n\n/** `@ContextWindow` knobs with no native SDK `AgentOptions` mapping. */\nconst STRATEGY_KNOBS = [\n 'compactionStrategy',\n 'preserveLastN',\n 'preserveToolResults',\n 'preserveSystemPrompt',\n] as const\n\nexport interface CompiledContextWindow {\n /** SDK-shaped context budget passed to `Agent.create({ context })`. */\n context: ContextSettings\n /** Declared knobs the SDK does not expose — reported, never silently dropped. */\n metadataOnlyKnobs: string[]\n}\n\nexport function compileContextWindow(options: ContextWindowOptions): CompiledContextWindow {\n const context: ContextSettings = {}\n if (typeof options.maxTokens === 'number') {\n context.maxTokens = options.maxTokens\n }\n\n const opts = options as Record<string, unknown>\n const metadataOnlyKnobs = STRATEGY_KNOBS.filter((knob) => opts[knob] !== undefined)\n\n return { context, metadataOnlyKnobs }\n}\n","/**\n * M8-3 — compile `@Skills` metadata into the SDK's `SkillsSettings`.\n *\n * Per sdk-runtime.md: the bridge COMPILES decorator metadata into a format the\n * SDK accepts; the SDK is the runtime. `Agent.create({ skills })` natively\n * discovers `.theokit/skills/<name>/SKILL.md` files and injects the `<skills>`\n * block — so giving `@Skills` runtime is a pure shape translation, not a\n * reimplementation of discovery.\n *\n * Mapping (ADR D4):\n * - `{ include }` → `{ enabled: include, autoInject: true }`\n * - `{ autoDiscover: true }` → `{ autoInject: true }` (enabled omitted ⇒ the SDK\n * enables every discovered skill)\n */\nimport type { SkillsSettings } from '@theokit/sdk'\n\n/**\n * M53 — the options shape lives WITH its conversion now. It used to be declared on the decorator\n * that is being deleted, which would have taken a type the compiler needs down with it.\n */\nexport interface SkillsOptions {\n /** Skill names to include (resolved from `.theokit/skills/<name>/SKILL.md`). */\n include: string[]\n /** Auto-discover every skill under `.theokit/skills/` (default: false). */\n autoDiscover?: boolean\n}\n\nexport function compileSkills(options: SkillsOptions): SkillsSettings {\n if (options.autoDiscover) {\n return { autoInject: true }\n }\n return { enabled: options.include, autoInject: true }\n}\n","/**\n * Agent compiler — transforms decorator metadata into SDK calls.\n *\n * Per ADR D1: @Agent is a macro over Agent.create().\n * Per ADR D3: @Tool compiles to defineTool().\n *\n * EC-3: throws if toolbox instance is missing from the instances map.\n */\nimport type {\n ContextSettings,\n MemorySettings,\n SettingSource,\n SkillsSettings,\n SystemPromptResolver,\n} from '@theokit/sdk'\n\nimport { ConfigurationError } from '../errors.js'\nimport type { Guardrail } from '../guardrails/index.js'\nimport type { SkillsSelection } from '../skills-resolver.js'\nimport type {\n ApprovalOptions,\n BudgetOptions,\n CheckpointOptions,\n HumanInTheLoopOptions,\n McpServersMap,\n MemoryOptions,\n ProjectContextOptions,\n ReasoningEffort,\n ToolOptions,\n} from '../types.js'\n\n/**\n * M53 — the input shape `compileTools`/`compileHitlGates` consume, declared WITH them now that the\n * metadata walk that used to own it is gone. `ToolboxCapability` builds this from a class'\n * `static tools` declaration.\n */\n/** A guard/interceptor class token — identity only (the DI container instantiates it). */\nexport type ClassToken = abstract new (...args: never[]) => object\n\nexport interface ToolWalkResult {\n propertyKey: string | symbol\n config: ToolOptions\n guards: ClassToken[]\n approval?: ApprovalOptions\n capabilities?: string[]\n budget?: BudgetOptions\n trace: boolean\n audit: boolean\n /** HITL config when the tool is gated (M4); absent ⇒ not gated. */\n hitl?: HumanInTheLoopOptions\n}\n\nexport interface ToolboxWalkResult {\n /** The toolbox class — used as the identity key into `toolboxInstances`. */\n class: ClassToken\n namespace: string\n tools: ToolWalkResult[]\n guards: ClassToken[]\n}\n\n/** A tool method on a toolbox instance. */\ntype ToolHandler = (input: unknown) => string | Promise<string>\n\n/** Minimal interface matching defineTool() result shape. */\nexport interface CompiledTool {\n name: string\n description: string\n inputSchema: unknown\n /**\n * M7 — the optional 2nd `ctx` arg carries the SDK run context: `ctx.context` is the\n * `defineAgent({ context })` / per-run value, `ctx.signal` the abort signal. Optional so the\n * decorator `@Tool` handlers (which ignore it) stay assignable. The SDK calls the tool with\n * both args; a handler that needs run-context (e.g. a filesystem tool reading `projectRoot`)\n * reads `ctx?.context`.\n */\n handler: (\n input: unknown,\n ctx?: { signal?: AbortSignal; context?: unknown },\n ) => string | Promise<string>\n}\n\n/**\n * The charset `@theokit/sdk` accepts for a custom tool name.\n *\n * MIRROR of `@theokit/sdk@4.1.0 › validateToolName` (`TOOL_NAME_PATTERN`). The SDK does NOT export\n * the rule — it exists there as an internal constant plus prose in a JSDoc — so consuming it is\n * impossible and duplicating is the only option. The duplication is deliberate and alarmed: the\n * non-mocked contract suite (`tests/integration/tool-name-sdk-contract.test.ts`) exercises the real\n * `Agent.create`, so it fails the day the SDK tightens the rule.\n *\n * REVIEW TRIGGER (ADR D1): if the SDK ever exports `TOOL_NAME_PATTERN`/`validateToolName`, consume\n * it and delete this copy.\n */\nconst SDK_TOOL_NAME = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/\n\n/** Longest name {@link SDK_TOOL_NAME} admits (1 leading + 63) — split out so an overflow can say so. */\nconst SDK_TOOL_NAME_MAX_LENGTH = 64\n\n/** Same charset as {@link SDK_TOOL_NAME} but unbounded — tells \"too long\" apart from \"bad character\". */\nconst SDK_TOOL_NAME_CHARSET = /^[a-zA-Z][a-zA-Z0-9_-]*$/\n\n/**\n * Names the SDK refuses even when they match the charset. MIRROR of `RESERVED_TOOL_NAMES` plus the\n * `mcp_` prefix guard in the same function.\n *\n * This is the rule the #145 fix MISSED: it replicated the charset alone, so `namespace: 'mcp'`\n * minted `mcp_*`, passed our authoring check, and was rejected by `Agent.create` with\n * `tool_reserved_name` — the same defect class, by a different axis.\n */\nconst SDK_RESERVED_TOOL_NAMES: ReadonlySet<string> = new Set([\n 'shell',\n 'memory_search',\n 'memory_get',\n])\nconst SDK_RESERVED_TOOL_PREFIX = 'mcp_'\n\n/**\n * The runtime name the SDK loop reports in `pre_tool_call` — `namespace_tool` when a toolbox\n * declares a namespace, else the bare tool name.\n *\n * This function is the ONLY place a runtime name is minted, and it validates what it produces\n * (M55). Validating anywhere else leaves the gap #145 exposed twice: a caller that composes the\n * name itself, or a public entry point ({@link compileTools} is exported) that skips the check.\n * \"Validate where you mint\" is the invariant; both {@link compileTools} and {@link compileHitlGates}\n * key off this function, so the HITL gate map and the SDK tool registry cannot disagree on a name.\n *\n * SEPARATOR (theokit#145): `_`, not `.`. The dot is outside {@link SDK_TOOL_NAME}, so every\n * namespaced toolbox produced a name `Agent.create` REJECTS — a documented path that never once\n * worked against a real provider. Nothing caught it because the other suites mock the SDK.\n *\n * @throws ConfigurationError with a message naming the offending COMPOSED name — the parts often\n * look valid on their own, so echoing them back would send the author hunting in the wrong place.\n */\nexport function toolRuntimeName(namespace: string, toolName: string): string {\n // OUR rule, stricter than the SDK's, and deliberately so: `ns` + `''` mints \"ns_\", which passes\n // the charset and `Agent.create` ACCEPTS — a nonsense tool reaches the LLM. The SDK cannot know a\n // part was empty; at authoring time we can.\n if (toolName.trim().length === 0) {\n const where = namespace ? ` no namespace \"${namespace}\"` : ''\n throw new ConfigurationError(`tool: nome vazio${where} — declare um nome não vazio para a tool`)\n }\n\n const name = namespace ? `${namespace}_${toolName}` : toolName\n\n if (!SDK_TOOL_NAME.test(name)) {\n // Length is reported apart from charset: when the only problem is the total, a generic\n // \"must match /regex/\" sends the author looking for an invalid character that is not there.\n if (SDK_TOOL_NAME_CHARSET.test(name)) {\n throw new ConfigurationError(\n `tool: nome \"${name}\" tem comprimento ${name.length} — a composição ` +\n `namespace + \"_\" + tool excede o máximo de ${SDK_TOOL_NAME_MAX_LENGTH} que o SDK aceita`,\n )\n }\n throw new ConfigurationError(\n `tool: nome inválido \"${name}\" — deve casar ${String(SDK_TOOL_NAME)} ` +\n '(o SDK rejeita o resto; verifique o namespace e o nome da tool)',\n )\n }\n\n if (SDK_RESERVED_TOOL_NAMES.has(name) || name.startsWith(SDK_RESERVED_TOOL_PREFIX)) {\n throw new ConfigurationError(\n `tool: nome reservado \"${name}\" — o SDK reserva ` +\n `${[...SDK_RESERVED_TOOL_NAMES].join(', ')} e o prefixo \"${SDK_RESERVED_TOOL_PREFIX}\"`,\n )\n }\n\n return name\n}\n\n/**\n * Build the HITL gate map: runtime tool name → its `@HumanInTheLoop` config, for every gated tool.\n * The HITL plugin ({@link createHitlPlugin}) pauses the run only for tools present here. Empty map\n * ⇒ no gated tools ⇒ the non-HITL stream path (M2, byte-unchanged).\n */\nexport function compileHitlGates(\n toolboxes: ToolboxWalkResult[],\n): Map<string, HumanInTheLoopOptions> {\n const gates = new Map<string, HumanInTheLoopOptions>()\n for (const tb of toolboxes) {\n for (const tool of tb.tools) {\n if (tool.hitl) {\n gates.set(toolRuntimeName(tb.namespace, tool.config.name), tool.hitl)\n }\n }\n }\n return gates\n}\n\n/**\n * Compile @Tool metadata into tool definitions.\n *\n * @param toolboxes - Walked toolbox metadata\n * @param toolboxInstances - Map of Toolbox class → instantiated object (for `this` binding)\n */\nexport function compileTools(\n toolboxes: ToolboxWalkResult[],\n toolboxInstances: Map<ClassToken, object>,\n): CompiledTool[] {\n const tools: CompiledTool[] = []\n\n for (const tb of toolboxes) {\n // EC-3: guard against missing toolbox instance\n const instance = toolboxInstances.get(tb.class)\n if (!instance) {\n // M56 — typed, not a bare `Error`: the same module already throws `ConfigurationError` for\n // name validation, and `rules/error-handling.md` § 2 requires explicit typed errors so a\n // caller can distinguish an authoring mistake from an unexpected runtime failure.\n throw new ConfigurationError(\n `toolbox: ${tb.class.name} não foi instanciado — passe a instância em \\`toolboxInstances\\``,\n )\n }\n\n for (const tool of tb.tools) {\n const handler = (instance as unknown as Record<string | symbol, ToolHandler>)[\n tool.propertyKey\n ]\n if (typeof handler !== 'function') {\n throw new ConfigurationError(\n `toolbox: ${tb.class.name}.${String(tool.propertyKey)} não é um método ` +\n `(tool \"${tool.config.name}\")`,\n )\n }\n\n const name = toolRuntimeName(tb.namespace, tool.config.name)\n\n tools.push({\n name,\n description: tool.config.description,\n inputSchema: tool.config.input,\n handler: (input: unknown) => handler.call(instance, input),\n })\n }\n }\n\n return tools\n}\n\n/** Compiled sub-agent definition matching SDK AgentDefinition shape. */\nexport interface CompiledSubAgent {\n model?: string\n /**\n * V4-L.1: typed as the union for consistency with `AgentOptions.systemPrompt`,\n * so `compileSubAgents` carries whatever the sub-agent declared. Sub-agent\n * resolver EXECUTION is out of scope this slice (ADR D3): `compiled.agents` is\n * not spread into `Agent.create` by `createSdkAgentStream`; a resolver here is\n * carried, not invoked. Top-level agent resolvers are the supported path.\n */\n systemPrompt?: string | SystemPromptResolver\n}\n\n/** Compiled agent options ready for SDK Agent.create(). */\nexport interface CompiledAgentOptions {\n model?: string\n /** Extended-thinking effort; mapped to SDK ModelSelection.params. */\n reasoningEffort?: ReasoningEffort\n /** Opt-in `<think>`-tag extraction (M2); wraps the stream when true. */\n parseThinkTags?: boolean\n /** Opt-in tool-dialect stripping (theocode#32); strips leaked `<function=…></tool_call>` from text when true. */\n stripToolDialect?: boolean\n /** Opt-in leaked-dialect recovery (theokit#58); enables the SDK route's `extractToolCallsFromContent` so leaked tool calls EXECUTE when true. */\n recoverLeakedToolCalls?: boolean\n /** Static prompt OR a per-request {@link SystemPromptResolver} (V4-L.1, Axis-B). */\n systemPrompt?: string | SystemPromptResolver\n /**\n * theokit-file-based-config — opt-in `.theokit/` file-based config roots (`\"project\"`/`\"user\"`/…).\n * Projected into `Agent.create({ local: { settingSources } })` by `assembleM8CreateOptions`\n * (merged with `cwd`, decoupled from inline skills). Absent ⇒ inline (code) config only.\n */\n settingSources?: readonly SettingSource[]\n /** Code `Plugin` objects forwarded to `Agent.create({ plugins })` (lifecycle-hook seam). */\n plugins?: readonly unknown[]\n tools: CompiledTool[]\n agents: Record<string, CompiledSubAgent>\n memory?: MemoryOptions | MemorySettings\n skills?: SkillsSettings\n context?: ContextSettings\n /**\n * M7 — run-context injected into every tool handler's `ctx.context` by the theokit adapter\n * (`buildSdkTools` wrapper). Populated by `defineAgent({ context })` (functional surface).\n * NAME NOTE: distinct from the context-window `context` (`ContextSettings`) above — this is\n * per-run user data for tools, not token-budget config.\n */\n runContext?: Record<string, unknown>\n /** Raw @ProjectContext config; the adapter builds the (async) systemPrompt resolver from it. */\n projectContext?: ProjectContextOptions\n mcpServers?: McpServersMap\n maxIterations?: number\n timeoutMs?: number\n stream: boolean\n /**\n * HITL gate map (M4): runtime tool name → `@HumanInTheLoop` config. Absent/empty ⇒ no gated\n * tools. The harness (`mountAgent`) turns this into the `pre_tool_call` pause wiring.\n */\n hitl?: Map<string, HumanInTheLoopOptions>\n /**\n * `@Checkpoint` config (M4): when present the harness emits `checkpoint_saved` and selects the\n * durable SDK conversation storage (`storage: 'filesystem'`) so a same-`sessionId` request resumes.\n */\n checkpoint?: CheckpointOptions\n /**\n * M9 — guardrails: input/output guards applied at the framework boundary (ADR-0040 § D2).\n * Input guards run on the user message BEFORE the SDK runtime sees it (fail-fast on `block`).\n * They REUSE the runtime; they never reimplement it. Absent/empty ⇒ no guards.\n */\n guardrails?: readonly Guardrail[]\n /**\n * M13 — per-request skills resolver (from `defineAgent({ skills: (ctx) => [...] })`). The request\n * path resolves it against the run-context (`resolveEnabledSkills`) and sets `skills.enabled`\n * before the SDK runs. Not consumed by the SDK directly (it reads `skills`). Absent ⇒ no resolver.\n */\n skillsResolver?: SkillsSelection\n}\n","/**\n * AgentExecutionContext — extends http-decorators' ExecutionContext with agent-specific methods.\n *\n * Per ADR D2 (LSP): any guard that accepts ExecutionContext works unchanged with\n * AgentExecutionContext. Agent-specific guards can narrow via isAgentContext().\n */\nimport type { ExecutionContext } from '@theokit/http'\n\nimport type { AgentOptions, ToolOptions } from '../types.js'\n\nexport interface AgentRunInfo {\n id: string\n startedAt: Date\n}\n\nexport interface AgentExecutionContext extends ExecutionContext {\n /** The agent's scalar configuration. */\n getAgent(): AgentOptions\n /** The current run information. */\n getRun(): AgentRunInfo\n /** The tool being called, or null if in the main agent handler. */\n getToolCall(): ToolOptions | null\n /** Type guard — always true for AgentExecutionContext. */\n isAgentContext(): true\n}\n\n/** Create an AgentExecutionContext from a base ExecutionContext + agent state. */\nexport function createAgentExecutionContext(\n base: ExecutionContext,\n agent: AgentOptions,\n run: AgentRunInfo,\n toolCall?: ToolOptions,\n): AgentExecutionContext {\n return {\n getRequest: () => base.getRequest(),\n getUrl: () => base.getUrl(),\n getClass: () => base.getClass(),\n getMethodName: () => base.getMethodName(),\n getAgent: () => agent,\n getRun: () => run,\n getToolCall: () => toolCall ?? null,\n isAgentContext: () => true as const,\n }\n}\n\n/** Narrow an ExecutionContext to AgentExecutionContext if it is one. */\nexport function isAgentContext(ctx: ExecutionContext): ctx is AgentExecutionContext {\n return 'isAgentContext' in ctx && (ctx as AgentExecutionContext).isAgentContext()\n}\n","/**\n * M8-2 — compile `@ProjectContext` metadata into an SDK `SystemPromptResolver`.\n *\n * There is no native `AgentOptions` field that carries a repo map, so the bridge\n * composes the documented `systemPrompt` seam (`string | SystemPromptResolver`):\n * the resolver prepends `buildEnvContext` + `buildRepoMap` (`@theokit/sdk-tools`)\n * and the nearest `THEO.md` (`@theokit/sdk/project#readProjectInstructions`) to\n * the agent's base prompt (ADR D3). The SDK primitives are dynamically imported\n * so `@theokit/sdk-tools` stays an OPTIONAL peer — only loaded when a `@ProjectContext`\n * agent actually sends.\n *\n * Knobs with no primitive mapping (`indexStrategy`, `relevanceStrategy`,\n * `maxFilesInContext`, `includeExtensions`, `rootMarkers`) are reported via\n * {@link projectContextMetadataOnlyKnobs} so the walk warns honestly (G10).\n * Only `ignorePatterns` is forwarded (to `buildRepoMap`).\n */\nimport type { SystemPromptResolver } from '@theokit/sdk'\n\nimport type { ProjectContextOptions } from '../types.js'\n\n/** `@ProjectContext` knobs with no primitive mapping (reported, not executed). */\nconst UNMAPPED_KNOBS = [\n 'indexStrategy',\n 'relevanceStrategy',\n 'maxFilesInContext',\n 'includeExtensions',\n 'rootMarkers',\n] as const\n\nexport function projectContextMetadataOnlyKnobs(options: ProjectContextOptions): string[] {\n const opts = options as Record<string, unknown>\n return UNMAPPED_KNOBS.filter((knob) => opts[knob] !== undefined)\n}\n\n/**\n * Build a `SystemPromptResolver` that prepends env + repo map + project\n * instructions to `base`. `base` may itself be a {@link SystemPromptResolver}\n * (V4-L.1, ADR D2): it is resolved once with the same `promptCtx` and composed\n * (resolve-then-prepend). A failing base resolver propagates (fail-loud). When the\n * SDK provides no `cwd`, the resolver returns the resolved base unchanged (no\n * filesystem guess — keeps `packages/agents/src` free of direct Node `process`\n * access per G8; the repo map needs a real cwd).\n */\nexport function compileProjectContext(\n options: ProjectContextOptions,\n base?: string | SystemPromptResolver,\n): SystemPromptResolver {\n return async (promptCtx) => {\n const resolvedBase = typeof base === 'function' ? await base(promptCtx) : base\n const cwd = promptCtx.cwd\n if (!cwd) {\n return resolvedBase ?? ''\n }\n\n const { buildEnvContext, buildRepoMap } = await import('@theokit/sdk-tools')\n const { readProjectInstructions } = await import('@theokit/sdk/project')\n\n const env = buildEnvContext(cwd)\n const repoMap = buildRepoMap(cwd, { ignore: options.ignorePatterns })\n\n let instructions = ''\n try {\n instructions = (await readProjectInstructions(cwd)).content ?? ''\n } catch {\n // readProjectInstructions is best-effort: a missing/unreadable THEO.md must\n // never break a send. buildEnvContext/buildRepoMap are never-throw by contract.\n instructions = ''\n }\n\n return [env, repoMap, instructions, resolvedBase].filter(Boolean).join('\\n\\n')\n }\n}\n","/**\n * SSE streaming handler — Web Standard Response with ReadableStream.\n *\n * Per ADR D4: SSE is the v1 transport.\n * Per EC-2: uses ReadableStream with controller.enqueue() instead of res.write().\n * Works natively on Node, Bun, Deno, CF Workers.\n */\n\n/** Minimal event shape matching SDK's SDKMessage discriminated union. */\nexport interface StreamEvent {\n type: string\n [key: string]: unknown\n}\n\nconst encoder = new TextEncoder()\n\n/**\n * Create a Web Standard Response that streams SSE events.\n * Each event becomes: `event: {type}\\ndata: {json}\\n\\n`\n */\nexport function streamAgentResponse(\n eventStream: AsyncIterable<StreamEvent>,\n): Response {\n const stream = new ReadableStream({\n async start(controller) {\n let closed = false\n const safeEnqueue = (chunk: Uint8Array) => {\n if (closed) return\n try { controller.enqueue(chunk) } catch { closed = true }\n }\n try {\n for await (const event of eventStream) {\n if (closed) break // eslint-disable-line @typescript-eslint/no-unnecessary-condition -- mutated by safeEnqueue catch\n const data = JSON.stringify(event)\n const frame = `event: ${event.type}\\ndata: ${data}\\n\\n`\n safeEnqueue(encoder.encode(frame))\n }\n } catch (err) {\n if (!closed) { // eslint-disable-line @typescript-eslint/no-unnecessary-condition -- mutated by safeEnqueue catch\n const errorEvent = {\n type: 'error',\n error: { message: err instanceof Error ? err.message : 'Internal agent error' },\n }\n const frame = `event: error\\ndata: ${JSON.stringify(errorEvent)}\\n\\n`\n safeEnqueue(encoder.encode(frame))\n }\n } finally {\n controller.close()\n }\n },\n })\n\n return new Response(stream, {\n status: 200,\n headers: {\n 'content-type': 'text/event-stream',\n 'cache-control': 'no-cache',\n 'connection': 'keep-alive',\n },\n })\n}\n","/**\n * Typed discriminated union for agent SSE stream events.\n *\n * Every event has a `type` field for discrimination.\n * Clients narrow via `if (event.type === 'text_delta') event.content`.\n */\n\n/** Partial text content from the LLM. */\nexport interface TextDeltaEvent {\n type: 'text_delta'\n content: string\n}\n\n/** Agent started a tool call. */\nexport interface ToolCallEvent {\n type: 'tool_call'\n callId: string\n toolName: string\n input: unknown\n}\n\n/**\n * Tool-call arguments streaming in incrementally (theokit-sdk#70). Emitted repeatedly as the\n * model generates a tool call's args, BEFORE they are committed. The same `callId` correlates to\n * the later `tool_call` (args committed) and `tool_result`. Consumers opt in to render tool-input\n * progressively; those that don't simply ignore this variant (it never replaces `tool_call`).\n */\nexport interface PartialToolCallEvent {\n type: 'partial_tool_call'\n callId: string\n toolName: string\n input: unknown\n}\n\n/** Tool execution completed. */\nexport interface ToolResultEvent {\n type: 'tool_result'\n callId: string\n toolName: string\n output: string\n durationMs: number\n isError: boolean\n}\n\n/** Extended thinking / reasoning (when model supports it). */\nexport interface ThinkingEvent {\n type: 'thinking'\n content: string\n}\n\n/** Agent loop iteration. */\nexport interface IterationEvent {\n type: 'iteration'\n step: number\n totalSteps: number | null\n}\n\n/** Human approval required before proceeding. */\nexport interface ApprovalRequiredEvent {\n type: 'approval_required'\n callId: string\n toolName: string\n question: string\n input?: unknown\n callbackUrl: string\n timeoutMs: number\n /** M20 — JSON-schema descriptor of the custom payload the approver may attach (optional). */\n payloadSchema?: Record<string, unknown>\n}\n\n/** Agent encountered an error. */\nexport interface ErrorEvent {\n type: 'error'\n code: string\n message: string\n retryable: boolean\n}\n\n/** Agent completed with a final result. */\nexport interface DoneEvent {\n type: 'done'\n result: string\n usage: {\n inputTokens: number\n outputTokens: number\n totalTokens: number\n /** V4-O: SDK reasoning/cache token buckets (0 when the provider omits them). */\n reasoningTokens?: number\n cacheReadTokens?: number\n cacheWriteTokens?: number\n }\n durationMs: number\n /** Total cost in USD for this agent run (EC-2: added for budget tracking). */\n cost?: number\n}\n\n/**\n * Per-turn usage the translator attaches to the ai-sdk `finish` chunk's `messageMetadata`, so it\n * lands on the reconstructed assistant `UIMessage.metadata` on the client (via `readUIMessageStream`)\n * with NO extra header/store wiring. It is the seam that lets a surface (a TUI status bar, a web\n * cost meter) show real tokens/cost for the turn it just streamed. Mirrors `DoneEvent`'s usage/cost\n * (the authoritative totals the SDK reports at turn end) plus the wall-clock `durationMs`.\n */\nexport interface AgentTurnMetadata {\n usage: DoneEvent['usage']\n /** Total cost in USD for the turn (present iff the SDK reported it). */\n cost?: number\n durationMs: number\n}\n\n/** Agent run started. */\nexport interface RunStartedEvent {\n type: 'run_started'\n runId: string\n agentName: string\n model?: string\n}\n\n/** Artifact generation started (code, document, diagram). */\nexport interface ArtifactStartEvent {\n type: 'artifact_start'\n artifactId: string\n mimeType: string\n filename?: string\n metadata?: Record<string, unknown>\n}\n\n/** Artifact content chunk (streamable artifacts). */\nexport interface ArtifactChunkEvent {\n type: 'artifact_chunk'\n artifactId: string\n chunk: string\n isLast: boolean\n}\n\n/** Real-time state update from @Observable channels. */\nexport interface StateUpdateEvent {\n type: 'state_update'\n channel: string\n data: unknown\n}\n\n/** Checkpoint saved (resumable agents). */\nexport interface CheckpointSavedEvent {\n type: 'checkpoint_saved'\n checkpointId: string\n step: number\n resumeToken: string\n}\n\n/** File edit produced by a code assistant tool. */\nexport interface FileEditEvent {\n type: 'file_edit'\n file: string\n format: 'search-replace' | 'unified-diff' | 'full-file' | 'line-range'\n search?: string\n replace?: string\n content?: string\n diff?: string\n startLine?: number\n endLine?: number\n}\n\n/** Discriminated union of all agent stream events. */\nexport type AgentStreamEvent =\n | RunStartedEvent\n | TextDeltaEvent\n | ToolCallEvent\n | PartialToolCallEvent\n | ToolResultEvent\n | ThinkingEvent\n | IterationEvent\n | ApprovalRequiredEvent\n | ArtifactStartEvent\n | ArtifactChunkEvent\n | StateUpdateEvent\n | CheckpointSavedEvent\n | FileEditEvent\n | ErrorEvent\n | DoneEvent\n\n/** Type guard helpers. */\nexport function isTextDelta(e: AgentStreamEvent): e is TextDeltaEvent {\n return e.type === 'text_delta'\n}\nexport function isToolCall(e: AgentStreamEvent): e is ToolCallEvent {\n return e.type === 'tool_call'\n}\nexport function isPartialToolCall(e: AgentStreamEvent): e is PartialToolCallEvent {\n return e.type === 'partial_tool_call'\n}\nexport function isToolResult(e: AgentStreamEvent): e is ToolResultEvent {\n return e.type === 'tool_result'\n}\nexport function isDone(e: AgentStreamEvent): e is DoneEvent {\n return e.type === 'done'\n}\nexport function isError(e: AgentStreamEvent): e is ErrorEvent {\n return e.type === 'error'\n}\nexport function isApprovalRequired(e: AgentStreamEvent): e is ApprovalRequiredEvent {\n return e.type === 'approval_required'\n}\n","/**\n * Auto-generate HTTP routes from @Agent metadata — Web Standard.\n *\n * Per ADR D5: an agent's `route` auto-generates two endpoints:\n * - POST {route}/chat — send message, receive SSE stream\n * - GET {route}/runs/:runId — get run status/result\n *\n * Routes are convention-based, generated at registration time.\n */\nimport type { CompiledAgentOptions } from './agent-compiler.js'\nimport { streamAgentResponse, type StreamEvent } from './agent-sse-handler.js'\n\nexport interface AgentRoute {\n method: 'POST' | 'GET'\n path: string\n handler: (request: Request) => Promise<Response>\n}\n\nexport interface AgentRouteContext {\n /**\n * M53 — only the mounting `route` was ever read from the walk, so the generator declares that\n * instead of the whole `AgentWalkResult` (which chained it to the decorator metadata walk).\n * `AgentWalkResult` satisfies this structurally, so the decorator path is unchanged.\n */\n walkResult: { route: string }\n compiledOptions: CompiledAgentOptions\n createRun: (message: string, sessionId: string) => AsyncIterable<StreamEvent>\n getRun?: (runId: string) => Promise<{ id: string; status: string; result?: string } | null>\n}\n\n/** Generate HTTP routes for a single agent. Returns Web Standard handlers. */\nexport function generateAgentRoutes(ctx: AgentRouteContext): AgentRoute[] {\n const { walkResult, createRun, getRun } = ctx\n const basePath = walkResult.route.replace(/\\/$/, '')\n const routes: AgentRoute[] = []\n\n routes.push({\n method: 'POST',\n path: `${basePath}/chat`,\n handler: async (request) => {\n let body: Record<string, unknown> | null = null\n try {\n body = (await request.json()) as Record<string, unknown>\n } catch {\n /* empty */\n }\n\n const message = body?.message\n if (typeof message !== 'string' || message.length === 0) {\n return new Response(\n JSON.stringify({ error: { code: 'BAD_REQUEST', message: 'message field required' } }),\n { status: 400, headers: { 'content-type': 'application/json' } },\n )\n }\n\n const rawSessionId = body?.sessionId\n const sessionId = typeof rawSessionId === 'string' ? rawSessionId : `session-${Date.now()}`\n return streamAgentResponse(createRun(message, sessionId))\n },\n })\n\n if (getRun) {\n routes.push({\n method: 'GET',\n path: `${basePath}/runs/:runId`,\n handler: async (request) => {\n const url = new URL(request.url)\n const runId = url.pathname.split('/').pop() ?? ''\n const run = await getRun(runId)\n if (!run) {\n return new Response(\n JSON.stringify({ error: { code: 'NOT_FOUND', message: `Run ${runId} not found` } }),\n { status: 404, headers: { 'content-type': 'application/json' } },\n )\n }\n return new Response(JSON.stringify(run), {\n status: 200,\n headers: { 'content-type': 'application/json' },\n })\n },\n })\n }\n\n return routes\n}\n","/**\n * Translates @theokit/sdk SDKMessage events → TheoKit AgentStreamEvent.\n *\n * The SDK yields SDKMessage (system/assistant/tool_call/thinking/status).\n * TheoKit devtools + SSE handler expect AgentStreamEvent (run_started/text_delta/tool_call/done).\n * This module bridges the two — Adapter pattern (per sdk-integration-blueprint ADR-D2).\n */\nimport type { InteractionUpdate } from '@theokit/sdk'\n\nimport type { StreamEvent } from './agent-sse-handler.js'\n\n/** Minimal SDK message shape — duck-typed to avoid hard import of @theokit/sdk types. */\nexport interface SdkMessage {\n type: string\n [key: string]: unknown\n}\n\n/** Safely coerce unknown value to string. */\nfunction asString(value: unknown, fallback: string): string {\n if (typeof value === 'string') return value\n return fallback\n}\n\n/**\n * Serialize a tool's `result` into the `string` wire contract of ToolResultEvent.output (#41).\n * String passthrough; null/undefined → fallback; otherwise JSON (String() on throw — BigInt/circular).\n */\nfunction serializeToolOutput(value: unknown, fallback: string): string {\n if (typeof value === 'string') return value\n if (value === undefined || value === null) return fallback\n try {\n return JSON.stringify(value)\n } catch {\n // JSON.stringify throws on BigInt and circular refs. Preserve a BigInt's real value;\n // for anything non-serializable (circular object) base-to-string is uninformative, so\n // return the fallback rather than '[object Object]'.\n return typeof value === 'bigint' ? value.toString() : fallback\n }\n}\n\nfunction translateSystemEvent(msg: SdkMessage, runId: string): StreamEvent[] {\n return [\n {\n type: 'run_started',\n runId,\n agentName: asString(msg.agent_id, 'agent'),\n model: asString(msg.model, 'unknown'),\n },\n ]\n}\n\nfunction translateAssistantEvent(msg: SdkMessage): StreamEvent[] {\n const events: StreamEvent[] = []\n // Real SDKAssistantMessage (messages.ts:58): content lives at msg.message.content.\n const message = msg.message as { content?: unknown } | undefined\n const content = message?.content\n if (!Array.isArray(content)) return events\n\n for (const block of content) {\n const b = block as { type: string; text?: string; name?: string; input?: unknown; id?: string }\n if (b.type === 'text' && b.text) {\n events.push({ type: 'text_delta', content: b.text })\n }\n if (b.type === 'tool_use') {\n events.push({\n type: 'tool_call',\n callId: b.id ?? `tc-${Date.now()}`,\n toolName: b.name ?? 'unknown',\n input: b.input ?? {},\n })\n }\n }\n return events\n}\n\nfunction translateToolCallEvent(msg: SdkMessage): StreamEvent[] {\n // Real SDKToolUseMessage (messages.ts:89): call_id (not id), status running|completed|error,\n // tool output in `result` (no separate `error` field).\n const status = msg.status as string\n const callId = asString(msg.call_id, `tc-${Date.now()}`)\n const toolName = asString(msg.name, 'unknown')\n if (status === 'completed') {\n return [\n {\n type: 'tool_result',\n callId,\n toolName,\n output: serializeToolOutput(msg.result, ''),\n durationMs: 0,\n isError: false,\n },\n ]\n }\n if (status === 'error') {\n return [\n {\n type: 'tool_result',\n callId,\n toolName,\n output: serializeToolOutput(msg.result, 'Tool failed'),\n durationMs: 0,\n isError: true,\n },\n ]\n }\n if (status === 'running') {\n // #42: emit a tool_call at tool start so the UI shows the running card with its args.\n // theokit#58: the real SDKToolUseMessage carries the args in `args` (run-D22b53SU.d.ts:486;\n // live TC-DIAG confirmed `args={\"command\":…}`); `input`/`arguments` were never the SDK field\n // and resolved to `{}`, blanking the tool card. Read `args` first, keep the others as\n // defensive cross-shape fallbacks (error-handling.md).\n return [\n { type: 'tool_call', callId, toolName, input: msg.args ?? msg.input ?? msg.arguments ?? {} },\n ]\n }\n return [] // unknown status → no event\n}\n\nfunction translateStatusEvent(msg: SdkMessage): StreamEvent[] {\n // Real SDKStatusMessage (messages.ts:106): status is UPPERCASE cloud-run lifecycle;\n // error text (when present) is in `msg.message`. FINISHED/CANCELLED are terminal-clean;\n // ERROR/EXPIRED are terminal-failure (must surface — fail-loud, Unbreakable Rule 8);\n // CREATING/RUNNING are in-progress.\n const s = msg.status as string\n if (s === 'FINISHED' || s === 'CANCELLED') {\n return [\n {\n type: 'done',\n result: '',\n usage: { inputTokens: 0, outputTokens: 0, totalTokens: 0 },\n durationMs: 0,\n cost: 0,\n },\n ]\n }\n if (s === 'ERROR' || s === 'EXPIRED') {\n return [\n {\n type: 'error',\n code: 'AGENT_ERROR',\n message: asString(msg.message, 'Agent error'),\n retryable: false,\n },\n ]\n }\n return []\n}\n\n/**\n * Translate a single SDK message to zero or more TheoKit stream events.\n * Returns an array because one SDK message may map to multiple TheoKit events.\n */\nexport function translateSdkEvent(msg: SdkMessage, runId: string): StreamEvent[] {\n switch (msg.type) {\n case 'system':\n return translateSystemEvent(msg, runId)\n case 'assistant':\n return translateAssistantEvent(msg)\n case 'tool_call':\n return translateToolCallEvent(msg)\n case 'thinking':\n // Real SDKThinkingMessage (messages.ts:73): reasoning text is in msg.text.\n return [{ type: 'thinking', content: asString(msg.text, '') }]\n case 'status':\n return translateStatusEvent(msg)\n default:\n return [] // Unknown message types silently ignored\n }\n}\n\n/**\n * #44 — Translate ONE real-time `onDelta` `InteractionUpdate` to zero or more StreamEvents, in\n * arrival order. This is the chronological path: routing `tool-call-started/completed` (and\n * `thinking-delta`) through `onDelta` — alongside `text-delta` — keeps tool/text/thinking\n * interleaved in true model order, instead of all-text-then-all-tools (the run.stream() buffer is\n * post-completion). Shapes per @theokit/sdk types/updates.ts: `ToolCall { callId, name, args?, result? }`.\n * `partial-tool-call` is surfaced as a DISTINCT `partial_tool_call` event (theokit-sdk#70) so\n * consumers can stream tool-input; it never duplicates `tool_call` (different lifecycle points).\n * Reuses `serializeToolOutput` for the tool-result `output` wire contract (#41 / DRY).\n */\nexport function translateInteractionUpdate(update: InteractionUpdate): StreamEvent[] {\n switch (update.type) {\n case 'text-delta':\n return update.text ? [{ type: 'text_delta', content: update.text }] : []\n case 'thinking-delta':\n return update.text ? [{ type: 'thinking', content: update.text }] : []\n case 'tool-call-started':\n return [\n {\n type: 'tool_call',\n callId: update.callId,\n toolName: update.toolCall.name,\n input: update.toolCall.args ?? {},\n },\n ]\n case 'partial-tool-call':\n // theokit-sdk#70 — surface the incremental args so consumers can stream tool-input.\n // A DISTINCT event type (not another `tool_call`): the partial fills the arg-streaming\n // window that `tool-call-started` (args committed) closes — it never duplicates `tool_call`.\n return [\n {\n type: 'partial_tool_call',\n callId: update.callId,\n toolName: update.toolCall.name,\n input: update.toolCall.args ?? {},\n },\n ]\n case 'tool-call-completed':\n return [\n {\n type: 'tool_result',\n callId: update.callId,\n toolName: update.toolCall.name,\n output: serializeToolOutput(update.toolCall.result, ''),\n durationMs: 0,\n isError: false,\n },\n ]\n default:\n return [] // thinking-completed, token-delta, step-*, etc. — not surfaced\n }\n}\n","/**\n * Model-selection mapping (M1 reasoning-visibility) — the single site that turns a\n * provider-agnostic `ReasoningEffort` into the SDK `ModelSelection`. Kept in its own small module\n * (not inside `sdk-adapter.ts`) so the adapter stays under the G6 500-LoC budget and the helper has\n * a focused home (per the plan's T1.1 \"or a small sibling\").\n */\nimport type { ModelSelection } from '@theokit/sdk'\n\nimport type { ReasoningEffort } from '../types.js'\n\n/**\n * Build the SDK `ModelSelection` for a model id + optional reasoning effort. With no (or empty)\n * effort it returns the bare `{ id }` — byte-identical to the prior behavior (backward-compat). With\n * an effort it adds the canonical reasoning param `{ id: 'thinking', value: effort }`. Pure.\n */\nexport function buildModelSelection(modelId: string, effort?: ReasoningEffort): ModelSelection {\n if (!effort) return { id: modelId }\n return { id: modelId, params: [{ id: 'thinking', value: effort }] }\n}\n","/**\n * `<think>`-tag reasoning extractor (M2 reasoning-visibility) — bridge middleware.\n *\n * Converts inline `<think>…</think>` in the assistant TEXT stream into `thinking` segments, so\n * models that emit reasoning as inline tags (qwen3-coder / deepseek-class) surface reasoning the\n * same way native-reasoning providers do (M1's `reasoningEffort`). Two exports:\n * - `createThinkTagExtractor` — the pure incremental splitter (handles a tag straddling a chunk\n * boundary); the testable core.\n * - `extractThinkTagStream` — a StreamEvent transform that applies the extractor to `text_delta`\n * events and passes every other event through unchanged (Phase 2).\n *\n * Opt-in: wired into `createSdkAgentStream` only when `parseThinkTags` is set (Phase 3) — default\n * off, because a code assistant can legitimately emit literal `<think>` in answer/code text.\n *\n * Reference patterns: Aider `reasoning_tags.py`, Vercel AI SDK `extract-reasoning-middleware.ts`\n * (blueprint `code-assistant-reasoning-ux` ADR-3).\n */\nimport type { StreamEvent } from './agent-sse-handler.js'\n\n/** The de-facto inline-reasoning tag (qwen/deepseek). Single change point if a second tag ever appears. */\nconst TAG = 'think'\nconst OPEN = `<${TAG}>`\nconst CLOSE = `</${TAG}>`\n\n/** A typed slice of the text stream: ordinary `text` vs extracted `thinking`. */\nexport interface Segment {\n kind: 'text' | 'thinking'\n content: string\n}\n\n/**\n * The length of the longest suffix of `s` that is a (proper) prefix of `delim` — i.e. how many\n * trailing chars of `s` could still grow into `delim` on the next chunk. A full match is never\n * counted here (the caller resolves full matches via `indexOf` first), so the search caps at\n * `delim.length - 1`. Returns 0 when the tail cannot extend to the delimiter (EC-1: a buffered\n * prefix like `<think` followed by `ers>` is NOT held — it is flushed as text).\n */\nfunction heldPrefixLength(s: string, delim: string): number {\n const max = Math.min(s.length, delim.length - 1)\n for (let k = max; k >= 1; k--) {\n if (s.slice(s.length - k) === delim.slice(0, k)) return k\n }\n return 0\n}\n\n/**\n * A pure, stateful, incremental `<think>` splitter. Feed it text chunks via `write`; it returns the\n * segments it can resolve so far, holding back only a tail that is still a viable prefix of the\n * active delimiter (so a tag split across two chunks is recognized). Call `end()` once the stream\n * is done to flush any buffered tail (a truncated `<think>` with no close is flushed as `thinking`,\n * so reasoning is never silently dropped).\n *\n * One instance per stream (per round); never shared — there is no cross-instance state.\n */\nexport function createThinkTagExtractor(): {\n write: (chunk: string) => Segment[]\n end: () => Segment[]\n} {\n let mode: 'text' | 'thinking' = 'text'\n let buffer = ''\n\n const write = (chunk: string): Segment[] => {\n buffer += chunk\n const out: Segment[] = []\n // Resolve every full delimiter currently in the buffer; stop when only a partial prefix remains.\n for (;;) {\n const delim = mode === 'text' ? OPEN : CLOSE\n const idx = buffer.indexOf(delim)\n if (idx !== -1) {\n const content = buffer.slice(0, idx)\n if (content) out.push({ kind: mode, content })\n buffer = buffer.slice(idx + delim.length)\n mode = mode === 'text' ? 'thinking' : 'text'\n continue\n }\n // No full delimiter: emit everything except a tail that could still become the delimiter.\n const keep = heldPrefixLength(buffer, delim)\n const emit = buffer.slice(0, buffer.length - keep)\n if (emit) out.push({ kind: mode, content: emit })\n buffer = buffer.slice(buffer.length - keep)\n break\n }\n return out\n }\n\n const end = (): Segment[] => {\n if (!buffer) return []\n const seg: Segment = { kind: mode, content: buffer }\n buffer = ''\n return [seg]\n }\n\n return { write, end }\n}\n\n/** Map an extractor segment to its StreamEvent (`thinking` segment → thinking event, else text_delta). */\nfunction segmentToEvent(seg: Segment): StreamEvent {\n return seg.kind === 'thinking'\n ? { type: 'thinking', content: seg.content }\n : { type: 'text_delta', content: seg.content }\n}\n\n/**\n * Stream transform: convert inline `<think>…</think>` carried in `text_delta` events into `thinking`\n * events, passing every other event (native `thinking`, `tool_call`, `done`, `error`, …) through\n * unchanged. A fresh extractor per call ⇒ per-stream (per-round) state; the extractor's mode persists\n * across interleaved non-text events (a reasoning block split by a tool call is not corrupted). On\n * source end, the extractor is flushed so a truncated `<think>` is still surfaced (as `thinking`).\n *\n * Non-string `text_delta.content` is passed through untouched (defensive — never throws). The\n * `end()` flush runs in a `finally`, so a buffered unclosed `<think>` is surfaced as `thinking`\n * even when the source errors mid-stream (the flushed segments are delivered before the error\n * re-propagates) — never silently dropped (Unbreakable Rule 8: fail loud, lose nothing).\n */\nexport async function* extractThinkTagStream(\n source: AsyncIterable<StreamEvent>,\n): AsyncGenerator<StreamEvent> {\n const extractor = createThinkTagExtractor()\n try {\n for await (const event of source) {\n if (event.type === 'text_delta' && typeof event.content === 'string') {\n for (const seg of extractor.write(event.content)) yield segmentToEvent(seg)\n } else {\n yield event\n }\n }\n } finally {\n for (const seg of extractor.end()) yield segmentToEvent(seg)\n }\n}\n","/**\n * Opt-in debug logging for agent-run runtime metrics (the wiring-triad \"runtime metric\" pillar).\n *\n * These metrics are observable proof the decorators fired, but emitting them to stdout unconditionally\n * corrupts any stdout consumer — a `@theokit/tui` Ink render, a piped log, a JSON pipeline (G9: no\n * unconditional `console.*` in production paths). Gate them behind `THEOKIT_DEBUG` so the observability is\n * preserved (set `THEOKIT_DEBUG=1` to see the M7/M8/mainloop wiring metrics) while the default is silent.\n */\nexport function debugLog(marker: string, data: Record<string, unknown>): void {\n const flag = process.env.THEOKIT_DEBUG\n if (flag !== undefined && flag !== '' && flag !== '0' && flag !== 'false') {\n // eslint-disable-next-line no-console -- this IS the debug channel, gated by THEOKIT_DEBUG\n console.debug(marker, data)\n }\n}\n","/**\n * SDK-adapter create-options projection — extracted from `sdk-adapter.ts` (G6 file-size split).\n *\n * Two pure helpers the streaming adapter uses to talk to the SDK:\n * - `assembleM8CreateOptions` projects the compiled `@Agent` decorator fields into `Agent.create()`\n * arguments (the single compile site is `agent-compiler.ts`, per sdk-runtime.md);\n * - `realUsageDone` builds the terminal `done` StreamEvent from the SDK `RunResult`.\n */\nimport type { ContextSettings, SkillsSettings, SystemPromptResolver } from '@theokit/sdk'\nimport type { MemorySettings } from '@theokit/sdk'\n\nimport type { McpServersMap } from '../types.js'\n\nimport type { CompiledAgentOptions } from './agent-compiler.js'\nimport type { StreamEvent } from './agent-sse-handler.js'\nimport { compileProjectContext } from './compile-project-context.js'\n\n/** Extra `Agent.create()` options compiled from the M8 declarative decorators. */\ninterface M8CreateOptions {\n skills?: SkillsSettings\n context?: ContextSettings\n systemPrompt?: string | SystemPromptResolver\n /** SDK local options: settings source for SKILL.md discovery (EC-1) + per-run cwd (V4-L.2). */\n local?: { settingSources?: string[]; cwd?: string; baseDir?: string }\n plugins?: readonly unknown[]\n /** #89 — `@MCP` servers forwarded to `Agent.create({ mcpServers })` (the SDK owns execution). */\n mcpServers?: McpServersMap\n /** M49 — durable-memory settings forwarded to `Agent.create({ memory })` (SDK MemorySettings). */\n memory?: MemorySettings\n}\n\n/**\n * Project the M8 fields from `CompiledAgentOptions` into `Agent.create()` arguments. Only the async\n * `@ProjectContext` resolver is built here (it does I/O, so the compiler keeps it raw). `applied`\n * lists which decorators contributed, for the observability log (wiring triad — runtime metric).\n */\nexport function assembleM8CreateOptions(compiled: CompiledAgentOptions): {\n options: M8CreateOptions\n applied: string[]\n} {\n const options: M8CreateOptions = {}\n const applied: string[] = []\n const base = compiled.systemPrompt\n\n if (compiled.skills) {\n options.skills = compiled.skills\n applied.push('skills')\n }\n // theokit-file-based-config — project `.theokit/` discovery sources into `local`, DECOUPLED from\n // inline skills (an agent may want hooks/mcp/subagents/context/cron with no inline skill). cwd is\n // merged downstream (`sdk-adapter.ts` overrides.cwd → app root via `mount-agent.ts`); never dropped.\n // Code `Plugin` objects (e.g. `createToolHooksPlugin`) — registered directly by the runtime\n // (`extractCodePlugins`); this is the fluent builder's only route to the SDK lifecycle-hook seam.\n if (compiled.plugins) {\n options.plugins = compiled.plugins\n applied.push('plugins')\n }\n const settingSources = resolveSettingSources(compiled)\n if (settingSources) {\n options.local = { ...options.local, settingSources }\n applied.push('settingSources')\n }\n if (compiled.context) {\n options.context = compiled.context\n applied.push('context')\n }\n if (compiled.projectContext) {\n options.systemPrompt = compileProjectContext(compiled.projectContext, base)\n applied.push('projectContext')\n } else if (base !== undefined) {\n options.systemPrompt = base\n }\n // #89 — forward the compiled `@MCP` servers to `Agent.create`. Without this the decorator was\n // inert (metadata compiled but never reaching the SDK runtime — same class as the HITL\n // `kind:'general'` bug). The SDK owns MCP server execution; this is pure adapter projection.\n if (compiled.mcpServers && Object.keys(compiled.mcpServers).length > 0) {\n options.mcpServers = compiled.mcpServers\n applied.push('mcpServers')\n }\n // M49 — forward memory to `Agent.create` (same inert-decorator class as #89: the field compiled\n // but never projected, so the SDK's whole memory subsystem was unreachable). Builder path carries\n // the SDK `MemorySettings` verbatim; the legacy decorator shape (no `enabled`) normalizes to the\n // minimal opt-in — declaring `@Memory()` means the author wants memory ON.\n if (compiled.memory !== undefined) {\n if ('enabled' in compiled.memory) {\n options.memory = compiled.memory\n } else {\n // Legacy decorator shape ({provider, embeddings, fts, scope, maxFacts}) — those knobs have no\n // SDK counterpart yet, so they are DISCARDED on normalization. Loud, never silent (M49 review\n // F8): the author asked for e.g. maxFacts and must know it is not honored.\n const dropped = Object.keys(compiled.memory)\n if (dropped.length > 0) {\n process.stderr.write(\n `[theokit-agents] @Memory decorator options not yet mapped to the SDK (${dropped.join(', ')}) — memory enabled with defaults\\n`,\n )\n }\n options.memory = { enabled: true }\n }\n applied.push('memory')\n }\n\n return { options, applied }\n}\n\n/**\n * theokit-file-based-config — resolve the SDK `local.settingSources`:\n * - an explicit, NON-EMPTY `.settingSources([...])` wins (EC-5), empty `[]` ⇒ unset (EC-3);\n * - else an agent that declares inline skills falls back to `['project']` (back-compat);\n * - else `undefined` (inline config only — no disk discovery).\n */\nfunction resolveSettingSources(compiled: CompiledAgentOptions): string[] | undefined {\n const explicit = compiled.settingSources\n if (explicit && explicit.length > 0) return [...explicit]\n if (compiled.skills) return ['project']\n return undefined\n}\n\n/**\n * V4-N.1: build the terminal `done` event from the SDK `RunResult` (real per-run token usage +\n * cost). Extracted from the stream generator to keep its complexity within budget (G6).\n */\nexport function realUsageDone(\n result: {\n result?: string\n usage?: {\n inputTokens?: number\n outputTokens?: number\n // V4-O: optional reasoning/cache buckets from the SDK TokenUsage.\n reasoningTokens?: number\n cacheReadTokens?: number\n cacheWriteTokens?: number\n }\n cost?: { amount?: number }\n },\n t0: number,\n): StreamEvent {\n const u = result.usage\n const inputTokens = u?.inputTokens ?? 0\n const outputTokens = u?.outputTokens ?? 0\n return {\n type: 'done',\n result: result.result ?? '',\n // V4-O: forward the SDK reasoning/cache buckets (0 when the provider omits them) so a\n // consumer keeps full per-turn usage through the loop into DelegationResult (passthrough — ADR D1).\n usage: {\n inputTokens,\n outputTokens,\n totalTokens: inputTokens + outputTokens,\n reasoningTokens: u?.reasoningTokens ?? 0,\n cacheReadTokens: u?.cacheReadTokens ?? 0,\n cacheWriteTokens: u?.cacheWriteTokens ?? 0,\n },\n durationMs: Date.now() - t0,\n cost: result.cost?.amount ?? 0,\n }\n}\n","/**\n * Tool-dialect stripper (theocode#32) — bridge middleware.\n *\n * Neutralizes a model that leaks its Hermes tool-call dialect — `<function=NAME>…</function></tool_call>`\n * XML — into the assistant TEXT stream instead of emitting native `tool_calls` (qwen3-coder class). The\n * leaked block is STRIPPED out of the visible text; it is NEVER parsed back into a tool call (parsing a\n * provider-broken channel re-introduces the no-progress spin closed in theokit#53). Two exports:\n * - `createToolDialectStripper` — the pure incremental splitter (handles the OPEN `<function=` and the\n * CLOSE `</tool_call>` each straddling a chunk boundary); the testable core.\n * - `stripToolDialectStream` — a StreamEvent transform that applies the stripper to `text_delta` events\n * and passes every other event through unchanged.\n *\n * Opt-in: wired into `createSdkAgentStream` only when `stripToolDialect` is set — default off, because a\n * code assistant can legitimately emit a literal `<function=` substring in answer/code text.\n *\n * Sibling of `think-tag-extractor.ts` (same incremental-splitter shape): the only deltas are the\n * delimiter (a two-string OPEN…CLOSE pair, not a single `<think>` tag) and the disposition of matched\n * content (dropped, not re-routed to a `thinking` segment).\n *\n * Accepted best-effort limit (EC-5): if a leaked block's parameter value contains the literal substring\n * `</tool_call>`, the scanner closes at that inner occurrence and the trailing real `</function></tool_call>`\n * re-emits as text. This errs toward showing MORE text (never silently drops), matching the lossless\n * contract — same class as the think-tag scanner being fooled by `<thinkers>`-shaped content. Pinned by\n * `tool-dialect-stripper.test.ts:test_stripper_embedded_close_early_closes_then_text`.\n */\nimport type { StreamEvent } from './agent-sse-handler.js'\n\n/** The Hermes leak's open marker. Single change-point if a second tool-dialect opener ever appears. */\nconst OPEN = '<function='\n/** The Hermes leak's close marker — the whole `<function=…>` block is dropped up to and including this. */\nconst CLOSE = '</tool_call>'\n\n/** A typed slice of the surviving (non-leaked) text stream. Dropped leak content yields no segment. */\nexport interface Segment {\n kind: 'text'\n content: string\n}\n\n/**\n * The length of the longest suffix of `s` that is a (proper) prefix of `delim` — i.e. how many trailing\n * chars of `s` could still grow into `delim` on the next chunk. A full match is resolved by `indexOf`\n * first, so the search caps at `delim.length - 1`. Returns 0 when the tail cannot extend to the delimiter.\n */\nfunction heldPrefixLength(s: string, delim: string): number {\n const max = Math.min(s.length, delim.length - 1)\n for (let k = max; k >= 1; k--) {\n if (s.slice(s.length - k) === delim.slice(0, k)) return k\n }\n return 0\n}\n\n/**\n * A pure, stateful, incremental tool-dialect splitter. Feed it text chunks via `write`; it returns the\n * surviving text segments, dropping any resolved `<function=…></tool_call>` block and holding back only a\n * tail that is still a viable prefix of the active delimiter (so a delimiter split across two chunks is\n * recognized). Call `end()` once the stream is done: an UNCLOSED leak (saw `<function=`, never saw\n * `</tool_call>`) is flushed as text — lossless, never silently dropped (Unbreakable Rule 8).\n *\n * One instance per stream (per run); never shared — there is no cross-instance state.\n */\nexport function createToolDialectStripper(): {\n write: (chunk: string) => Segment[]\n end: () => Segment[]\n} {\n let mode: 'text' | 'stripping' = 'text'\n let buffer = ''\n // Accumulates the dropped-so-far leak content (including the OPEN marker) so an unclosed leak can be\n // flushed losslessly on end(). Reset to '' the moment a full OPEN…CLOSE pair resolves.\n let pendingLeak = ''\n\n const write = (chunk: string): Segment[] => {\n buffer += chunk\n const out: Segment[] = []\n for (;;) {\n if (mode === 'text') {\n const idx = buffer.indexOf(OPEN)\n if (idx !== -1) {\n const content = buffer.slice(0, idx)\n if (content) out.push({ kind: 'text', content })\n pendingLeak = OPEN\n buffer = buffer.slice(idx + OPEN.length)\n mode = 'stripping'\n continue\n }\n const keep = heldPrefixLength(buffer, OPEN)\n const emit = buffer.slice(0, buffer.length - keep)\n if (emit) out.push({ kind: 'text', content: emit })\n buffer = buffer.slice(buffer.length - keep)\n break\n }\n // stripping: scan for CLOSE, dropping everything in between (accumulated into pendingLeak).\n const idx = buffer.indexOf(CLOSE)\n if (idx !== -1) {\n buffer = buffer.slice(idx + CLOSE.length)\n pendingLeak = ''\n mode = 'text'\n continue\n }\n const keep = heldPrefixLength(buffer, CLOSE)\n pendingLeak += buffer.slice(0, buffer.length - keep)\n buffer = buffer.slice(buffer.length - keep)\n break\n }\n return out\n }\n\n const end = (): Segment[] => {\n // Lossless: an unclosed leak (still in stripping mode) flushes pendingLeak + the held CLOSE-prefix\n // as text; a held OPEN-prefix in text mode flushes as text. Never silently drop unconfirmed content.\n const leftover = mode === 'stripping' ? pendingLeak + buffer : buffer\n buffer = ''\n pendingLeak = ''\n return leftover ? [{ kind: 'text', content: leftover }] : []\n }\n\n return { write, end }\n}\n\n/**\n * Stream transform: strip a leaked `<function=…></tool_call>` Hermes tool-call dialect out of `text_delta`\n * events, passing every other event (native `thinking`, `tool_call`, `done`, `error`, `status`, …) through\n * unchanged. A fresh stripper per call ⇒ per-stream (per-round) state; the stripper's mode persists across\n * interleaved non-text events. Non-string `text_delta.content` is passed through untouched (defensive —\n * never coerced). The `end()` flush runs in a `finally`, so a buffered unclosed leak is surfaced as text\n * even when the source errors mid-stream (delivered before the error re-propagates) — Rule 8: lose nothing.\n */\nexport async function* stripToolDialectStream(\n source: AsyncIterable<StreamEvent>,\n): AsyncGenerator<StreamEvent> {\n const stripper = createToolDialectStripper()\n try {\n for await (const event of source) {\n if (event.type === 'text_delta' && typeof event.content === 'string') {\n for (const seg of stripper.write(event.content)) {\n yield { type: 'text_delta', content: seg.content }\n }\n } else {\n yield event\n }\n }\n } finally {\n for (const seg of stripper.end()) {\n yield { type: 'text_delta', content: seg.content }\n }\n }\n}\n","/**\n * SDK Adapter — bridges @theokit/agents decorators → @theokit/sdk runtime.\n *\n * Per rule sdk-runtime.md (INQUEBRÁVEL): @theokit/sdk is the ONLY agent runtime.\n * This adapter replaces llm-runner.ts (which called OpenRouter API directly).\n *\n * Flow: @Agent decorator → compileAgent() → createSdkAgentStream() → SDK Agent.create() → Run.stream()\n */\nimport type {\n AgentDefinition,\n BudgetTracker,\n CustomTool,\n InlineSkill,\n InteractionUpdate,\n Plugin,\n PluginsSettings,\n ProviderRoutingSettings,\n SendOptions,\n} from '@theokit/sdk'\n\nimport { debugLog } from '../debug-log.js'\nimport type { ReasoningEffort } from '../types.js'\n\nimport type { CompiledAgentOptions, CompiledTool } from './agent-compiler.js'\nimport type { StreamEvent } from './agent-sse-handler.js'\nimport {\n compileAgentDefinition,\n type AgentDefinition as TheokitAgentDefinition,\n} from './define-agent.js'\nimport {\n translateInteractionUpdate,\n translateSdkEvent,\n type SdkMessage,\n} from './event-translator.js'\nimport { buildModelSelection } from './model-selection.js'\nimport { assembleM8CreateOptions, realUsageDone } from './sdk-adapter-create-options.js'\nimport { extractThinkTagStream } from './think-tag-extractor.js'\nimport { stripToolDialectStream } from './tool-dialect-stripper.js'\n\n/**\n * Per-request overrides forwarded into `Agent.create` (V4-L.2 + V4-L.3). Bundled into\n * one object (rather than positional params) so the per-request surface can grow without\n * a parameter explosion. Each field is Axis-A SWAP — a value the app holds at call time.\n */\n/**\n * A multimodal image for a send turn — the SDK's `SDKImage` shape, typed locally because `@theokit/sdk`\n * is an optional peer (dynamic import). Either a URL or inline base64 `{ data, mimeType }`.\n */\nexport type BridgeImage = { url: string } | { data: string; mimeType: string }\n\nexport interface RuntimeOverrides {\n /** Overrides the model for this call (`?? compiled.model ?? default`). */\n model?: string\n /**\n * M35 (multimodal) — images to send alongside the text. When present, the SDK send switches from the\n * plain-string form to the structured `{ text, images }` form (`SDKUserMessage`). Absent ⇒ the\n * string path is byte-unchanged (back-compat).\n */\n images?: readonly BridgeImage[]\n /**\n * Per-run extended-thinking effort (`?? compiled.reasoningEffort`). Mapped to the SDK\n * `ModelSelection.params` so the provider produces reasoning (surfaced as `thinking` StreamEvents).\n */\n reasoningEffort?: ReasoningEffort\n /**\n * Per-run opt-in (`?? compiled.parseThinkTags`): when true, wrap the event stream with the M2\n * `<think>`-tag extractor so inline `<think>…</think>` text becomes `thinking` StreamEvents.\n */\n parseThinkTags?: boolean\n /**\n * Per-run opt-in (`?? compiled.stripToolDialect`): when true, strip a leaked Hermes\n * `<function=…></tool_call>` tool-call dialect out of the assistant text stream (theocode#32).\n */\n stripToolDialect?: boolean\n /**\n * Per-run opt-in (`?? compiled.recoverLeakedToolCalls`): when true, enable the SDK chat route's\n * `extractToolCallsFromContent` so a leaked Hermes `<function=…></tool_call>` dialect is recovered\n * and EXECUTED (theokit#58). Sibling of {@link stripToolDialect}; has effect only when {@link providers}\n * routes a provider.\n */\n recoverLeakedToolCalls?: boolean\n /** Per-run cwd → `Agent.create({ local: { cwd } })` → `SystemPromptContext.cwd`. */\n cwd?: string\n /**\n * M7 — per-run run-context override (`?? compiled.runContext`). Injected into every tool\n * handler's `ctx.context` by `buildSdkTools`. Lets a single request override the agent-level\n * `defineAgent({ context })` (mirrors `model`/`cwd`).\n */\n runContext?: Record<string, unknown>\n /**\n * Per-run plugins (e.g. permission gate selected by request mode). Accepts EITHER\n * named-plugin discovery settings (`{ enabled: [...] }`) OR an array of code `Plugin`\n * objects, forwarded RAW through the duck-typed `Agent.create` bridge (mirrors the\n * @theokit/sdk `AgentOptions.plugins` widen).\n */\n plugins?: PluginsSettings | readonly Plugin[]\n /** Per-run provider routing. */\n providers?: ProviderRoutingSettings\n /** Per-run sub-agent definitions (opts-only; `compiled.agents` stays deferred — ADR D3). */\n agents?: Record<string, AgentDefinition>\n /** Per-run SDK budget tracker (inner tool-loop cap; distinct from the loop's USD `budget`). */\n budgetTracker?: BudgetTracker\n /**\n * SDK 4.0 (SE40) — root of the native Claude-shaped `.jsonl` session transcript the SDK writes\n * automatically (`<baseDir>/projects/<encoded-cwd>/<agentId>.jsonl`). The framework threads the\n * app's project root here (see `mount-agent`) so sessions persist per-app; unset ⇒ SDK default\n * (`~/.theokit`). Replaces the removed pluggable `conversationStorage` — persistence is now the\n * SDK's native transcript, not a swappable adapter.\n */\n baseDir?: string\n /**\n * V4-Q: pre-built SDK `CustomTool[]` forwarded RAW to `Agent.create.tools` (appended after the\n * compiled tools), bypassing `defineTool` (which requires a Zod schema). Lets an app whose tools\n * come from imperative SDK factories supply them without the `@Tool` compile path.\n */\n sdkTools?: readonly CustomTool[]\n}\n\n/**\n * theokit#58: clone provider routing with `extractToolCallsFromContent` enabled on every route, so the\n * SDK recovers a leaked Hermes `<function=…></tool_call>` dialect that would otherwise be lost. The SDK\n * reads the flag off the chat route (routes[0]); marking all routes is fail-open — a non-leaking route\n * is unaffected (recovery only fires on a finish with ZERO native tool_calls carrying the dialect).\n */\nfunction withLeakedDialectRecovery(providers: ProviderRoutingSettings): ProviderRoutingSettings {\n return {\n ...providers,\n routes: providers.routes.map((route) => ({ ...route, extractToolCallsFromContent: true })),\n }\n}\n\n/**\n * Project the V4-L.3 per-request fields into the `Agent.create` extra surface (absent ⇒ no\n * key). Extracted from the stream generator to keep its cyclomatic complexity within budget (G6).\n * theokit#58: per-run `recoverLeakedToolCalls` (overrides compiled) opts the routed provider into\n * SDK leaked-dialect recovery by cloning the routes with `extractToolCallsFromContent`.\n */\nfunction buildExtraCreateOptions(\n overrides: RuntimeOverrides,\n compiled: CompiledAgentOptions,\n): Record<string, unknown> {\n const recoverLeakedToolCalls =\n overrides.recoverLeakedToolCalls ?? compiled.recoverLeakedToolCalls ?? false\n const extra: Record<string, unknown> = {}\n // A per-run plugin override (e.g. the HITL gate) must NOT silently drop the agent's own code plugins:\n // `extra` is spread AFTER the assembled options, so a bare assignment clobbered `compiled.plugins`\n // and every `createToolHooksPlugin` hook was lost whenever HITL was active. Concatenate when both\n // sides are arrays; keep the previous replace semantics for the legacy `{ enabled }` object form.\n if (overrides.plugins !== undefined) {\n // `Array.isArray` narrows to `any[]`, losing the element type — a local guard keeps it.\n const asArray = (v: unknown): readonly unknown[] | undefined =>\n Array.isArray(v) ? (v as readonly unknown[]) : undefined\n const overrideList = asArray(overrides.plugins)\n const compiledList = asArray(compiled.plugins)\n extra.plugins =\n overrideList !== undefined && compiledList !== undefined\n ? [...compiledList, ...overrideList]\n : overrides.plugins\n }\n if (overrides.providers !== undefined) {\n extra.providers = recoverLeakedToolCalls\n ? withLeakedDialectRecovery(overrides.providers)\n : overrides.providers\n }\n if (overrides.agents !== undefined) extra.agents = overrides.agents\n if (overrides.budgetTracker !== undefined) extra.budgetTracker = overrides.budgetTracker\n return extra\n}\n\n/** The `@theokit/sdk` `Agent` surface the adapter drives (dynamic-import shape, kept minimal). */\ninterface SdkAgentApi {\n getOrCreate: (\n id: string,\n opts: Record<string, unknown>,\n ) => Promise<{\n // #40: the SDK token-streams ONLY via send's onDelta callback (proven empirically);\n // run.stream() yields complete messages. The adapter merges both.\n send: (\n msg: string,\n // onDelta receives `{ update: InteractionUpdate }`; toolChoice gates tools for this send.\n opts?: {\n onDelta?: (d: { update: InteractionUpdate }) => void\n toolChoice?: 'auto' | 'none' | 'required'\n },\n ) => Promise<{\n stream: () => AsyncGenerator<SdkMessage>\n // V4-N.1: the SDK Run's terminal await — carries the real per-run token usage + cost.\n // V4-O: usage also carries optional reasoning/cache buckets (forwarded by realUsageDone).\n wait: () => Promise<{\n result?: string\n usage?: {\n inputTokens?: number\n outputTokens?: number\n reasoningTokens?: number\n cacheReadTokens?: number\n cacheWriteTokens?: number\n }\n cost?: { amount?: number }\n }>\n }>\n dispose: () => Promise<void>\n }>\n}\n\n/** The resolved `@theokit/sdk` runtime symbols the adapter needs, bound after the dynamic import. */\ninterface SdkRuntime {\n Agent: SdkAgentApi\n defineTool: (spec: {\n name: string\n description: string\n inputSchema: unknown\n handler: CustomTool['handler']\n }) => unknown\n /**\n * SE23 — optional `skill_read` tool factory. Absent on SDKs older than it shipped; guarded with `in`\n * at load so an older peer degrades gracefully (inline skills still list in the `<skills>` block, they\n * just aren't auto-readable). Used to auto-wire reading for `defineAgent({ skills: [inlineSkill] })`.\n */\n defineSkillReadTool?: (skills: readonly InlineSkill[]) => unknown\n}\n\n/**\n * Dynamically import `@theokit/sdk` (optional peer dep) and bind the runtime symbols; `null` when it\n * is not installed (the caller emits `SDK_NOT_INSTALLED`). SDK 4.0 (SE40) writes the session transcript\n * natively — there is no pluggable storage to load; persistence is automatic (see `local.baseDir`).\n */\nasync function loadSdkRuntime(): Promise<SdkRuntime | null> {\n try {\n const sdk = await import('@theokit/sdk')\n // SE36 (SDK v3.0) — the public factories became `X.create()`: `defineTool`→`Tool.create`,\n // `defineSkillReadTool`→`SkillReadTool.create`. Guard on the VALUE (not `'…' in sdk`) so a peer\n // that omits `SkillReadTool` degrades gracefully instead of calling `.create` on `undefined`.\n const skillReadTool = 'SkillReadTool' in sdk ? sdk.SkillReadTool : undefined\n return {\n Agent: sdk.Agent as unknown as SdkAgentApi,\n // `.bind` keeps the static factory callable when detached from `sdk.Tool` (it takes no `this`,\n // but binding is explicit + satisfies unbound-method rather than relying on that).\n defineTool: sdk.Tool.create.bind(sdk.Tool) as unknown as SdkRuntime['defineTool'],\n ...(skillReadTool ? { defineSkillReadTool: (skills) => skillReadTool.create(skills) } : {}),\n }\n } catch (err) {\n console.warn('[theokit] @theokit/sdk import failed:', err)\n return null\n }\n}\n\n/** #40: tagged item flowing through the merge queue — an incremental delta or a complete SDK message. */\ntype MergeItem = { kind: 'delta'; event: StreamEvent } | { kind: 'sdk'; msg: SdkMessage }\n\n/** Minimal single-producer/single-consumer async queue (#40 — merge onDelta tokens with run.stream()). */\ninterface AsyncQueue<T> {\n push: (item: T) => void\n close: () => void\n [Symbol.asyncIterator]: () => AsyncIterator<T>\n}\n\nfunction createAsyncQueue<T>(): AsyncQueue<T> {\n const items: T[] = []\n let wake: (() => void) | null = null\n let closed = false\n return {\n push(item: T) {\n items.push(item)\n if (wake) {\n wake()\n wake = null\n }\n },\n close() {\n closed = true\n if (wake) {\n wake()\n wake = null\n }\n },\n async *[Symbol.asyncIterator]() {\n for (;;) {\n while (items.length > 0) {\n const next = items.shift()\n if (next !== undefined) yield next\n }\n if (closed) return\n await new Promise<void>((resolve) => {\n wake = resolve\n })\n }\n },\n }\n}\n\n/**\n * #44 dedup state — text/thinking by category flag (no per-event id); tool by callId Set, so a\n * `run.stream()` tool result whose callId onDelta only reported as `tool-call-started` (e.g. a tool\n * ERROR surfaced only via the stream) is NOT suppressed. `sawError` short-circuits the real-usage done.\n */\ninterface MergeState {\n sawTextDelta: boolean\n sawThinkingDelta: boolean\n emittedToolCallIds: Set<string>\n emittedToolResultIds: Set<string>\n sawError: boolean\n}\n\n/** Read a StreamEvent's `callId` as a string (the union is index-typed `unknown`). */\nfunction streamCallId(ev: StreamEvent): string {\n return typeof ev.callId === 'string' ? ev.callId : ''\n}\n\n/**\n * #44 — skip a run.stream() content event ONLY when onDelta already drove that exact (category, id).\n * Tool dedup is keyed by callId; an empty/missing callId never matches (returns false) so two distinct\n * id-less tool events cannot collide and wrongly suppress each other (favours a visible double-emit\n * over silent loss — fail-loud).\n */\nfunction isDuplicatedByDelta(ev: StreamEvent, state: MergeState): boolean {\n if (ev.type === 'text_delta') return state.sawTextDelta\n if (ev.type === 'thinking') return state.sawThinkingDelta\n if (ev.type === 'tool_call') {\n const id = streamCallId(ev)\n return id !== '' && state.emittedToolCallIds.has(id)\n }\n if (ev.type === 'tool_result') {\n const id = streamCallId(ev)\n return id !== '' && state.emittedToolResultIds.has(id)\n }\n return false\n}\n\n/**\n * #44: merge real-time content events (queued via onDelta — text/tool/thinking in chronological\n * arrival order) with the complete SDK messages from `run.stream()`. Deltas are yielded as they\n * arrive; the pump opens `run.stream()` (post-completion) for structural events (`run_started`/`done`)\n * + the no-onDelta fallback, deduped per-category (`isDuplicatedByDelta`) so nothing double-emits.\n * The `done` SDK event stays suppressed (real-usage `done` emitted by the caller after `run.wait()`);\n * errors set `state.sawError`. `openStream` is a thunk so the consumer drains CONCURRENTLY with\n * `send()` (the run only resolves after the loop completes). Extracted to keep the generator within G6.\n */\nasync function* mergeDeltaStream(\n queue: AsyncQueue<MergeItem>,\n openStream: () => Promise<AsyncGenerator<SdkMessage>>,\n runId: string,\n state: MergeState,\n): AsyncGenerator<StreamEvent> {\n // The catch is attached AT CREATION (not deferred to `await pump`): the consumer loop below is\n // paced by the external puller (SSE backpressure), so a send()/stream() rejection could otherwise\n // sit unhandled across macrotask gaps and crash the process (Node unhandledRejection). The captured\n // error is re-thrown after the drain so it still surfaces in the caller's try/catch as one error event.\n let pumpError: { thrown: unknown } | undefined\n const pump = (async () => {\n try {\n const stream = await openStream()\n for await (const msg of stream) queue.push({ kind: 'sdk', msg })\n } finally {\n queue.close()\n }\n })().catch((thrown: unknown) => {\n pumpError = { thrown }\n })\n // #47-followup — stream ALL deltas (text / tool / thinking) LIVE in arrival order. The tool\n // lifecycle (`tool-call-started` + `tool-call-completed`) is now emitted via `onDelta` from the SDK's\n // tool-dispatch, which runs BETWEEN LLM rounds — so a tool call and its result arrive in the queue at\n // their true chronological position, BEFORE the post-tool answer text. That removes the need to HOLD\n // the answer (the earlier #47 fix), which had regressed text-ONLY turns to batch-at-completion. The\n // `run.stream()` (pump) replay of the same tool call/result is deduped by callId (`isDuplicatedByDelta`\n // + the sink's `emittedTool*Ids`), so nothing double-renders and text streams token-by-token again.\n for await (const item of queue) {\n if (item.kind === 'delta') {\n yield item.event\n continue\n }\n for (const out of translateSdkEvent(item.msg, runId)) {\n if (out.type === 'done') continue // suppressed; the real-usage done is emitted by the caller\n if (isDuplicatedByDelta(out, state)) continue // #44 per-category/callId dedup vs onDelta\n if (out.type === 'error') state.sawError = true\n yield out\n }\n }\n await pump // settled (handled at creation); re-throw any captured error into the generator's try/catch\n if (pumpError) throw pumpError.thrown\n}\n\n/**\n * #44 — build the onDelta sink: a fresh per-run dedup `MergeState` + the callback that routes every\n * content update (text/tool/thinking) into the merge queue in chronological arrival order, recording\n * per-category flags + per-callId Sets so the run.stream() fallback is deduped without losing\n * stream-only tool results. Extracted to keep `createSdkAgentStream` within the function-size budget.\n */\nfunction createDeltaSink(queue: AsyncQueue<MergeItem>): {\n state: MergeState\n onDelta: (d: { update: InteractionUpdate }) => void\n} {\n const state: MergeState = {\n sawTextDelta: false,\n sawThinkingDelta: false,\n emittedToolCallIds: new Set<string>(),\n emittedToolResultIds: new Set<string>(),\n sawError: false,\n }\n const onDelta = (d: { update: InteractionUpdate }) => {\n for (const event of translateInteractionUpdate(d.update)) {\n if (event.type === 'text_delta') state.sawTextDelta = true\n else if (event.type === 'thinking') state.sawThinkingDelta = true\n else if (event.type === 'tool_call') {\n const id = streamCallId(event)\n if (id !== '') state.emittedToolCallIds.add(id)\n } else if (event.type === 'tool_result') {\n const id = streamCallId(event)\n if (id !== '') state.emittedToolResultIds.add(id)\n }\n queue.push({ kind: 'delta', event })\n }\n }\n return { state, onDelta }\n}\n\n/**\n * Resolve the per-run opt-in text-transform flags, each `override ?? compiled ?? false` (mirrors `model`).\n */\nfunction resolveTextTransformFlags(\n compiled: CompiledAgentOptions,\n overrides: RuntimeOverrides,\n): { parseThinkTags: boolean; stripToolDialect: boolean } {\n return {\n parseThinkTags: overrides.parseThinkTags ?? compiled.parseThinkTags ?? false,\n stripToolDialect: overrides.stripToolDialect ?? compiled.stripToolDialect ?? false,\n }\n}\n\n/**\n * Compose the opt-in text-stream transforms over the merged event stream, in fixed order:\n * `<think>`-tag extraction (M2) first, then tool-dialect stripping (theocode#32) on the post-think\n * `text_delta`. Both default off ⇒ the merged stream is returned unchanged (byte-identical).\n */\nfunction applyTextTransforms(\n events: AsyncIterable<StreamEvent>,\n opts: { parseThinkTags: boolean; stripToolDialect: boolean },\n): AsyncIterable<StreamEvent> {\n let out = opts.parseThinkTags ? extractThinkTagStream(events) : events\n if (opts.stripToolDialect) out = stripToolDialectStream(out)\n return out\n}\n\n/**\n * A tool whose `inputSchema` is a live Zod schema (from `@Tool({ input })`) needs the SDK's\n * `defineTool` to lower it to JSON Schema + wrap parsing. A tool whose `inputSchema` is already a\n * JSON-Schema object (from `defineAgentTool`, which pre-converts via `z.toJSONSchema`) is ALREADY an\n * SDK-ready `CustomTool` and MUST be appended raw — re-running it through `defineTool` (which reads\n * Zod internals like `.def`) crashes. Every Zod schema exposes `.parse`; a JSON-Schema object does not.\n */\nfunction hasZodInputSchema(schema: unknown): boolean {\n return typeof (schema as { parse?: unknown } | null | undefined)?.parse === 'function'\n}\n\n/**\n * M7 — wrap a tool handler so it receives the run-context as `ctx.context`, injected from a closure\n * over `runContext`. theokit owns the run-context concern (the `defineAgent({ context })` /\n * `AgentBuilder.create().context()` API is theokit's), so it injects it at THIS adapter layer instead of relying\n * on the SDK to forward it — decoupling the framework from the SDK's tool-call internals. The\n * incoming `ctx.signal` (from the SDK) is preserved; `context` is set to the agent's run-context.\n */\nfunction withRunContext(\n handler: CustomTool['handler'],\n runContext: unknown,\n): CustomTool['handler'] {\n // Forward the FULL ctx (SE12 `messages` transcript projection + `signal` + any future\n // field) and override ONLY `context` with the run value. Dropping `messages` here would\n // silently break a tool that reads the turn transcript — so spread, don't cherry-pick.\n return (input, ctx) => handler(input, { ...ctx, context: runContext })\n}\n\n/**\n * Build the SDK tool list: `@Tool`s (Zod `inputSchema`) lowered via `defineTool`; `defineAgentTool`\n * results (already SDK-ready `CustomTool`s with a JSON-Schema `inputSchema`) and any pre-built\n * `sdkTools` appended RAW — must NOT re-run through `defineTool` (V4-Q). Extracted for G6.\n *\n * When `runContext` is set, every tool handler is wrapped to receive it as `ctx.context` (M7);\n * `undefined` ⇒ handlers are passed through unwrapped (byte-identical to pre-M7).\n */\nfunction buildSdkTools(\n compiledTools: CompiledTool[],\n defineTool: (spec: {\n name: string\n description: string\n inputSchema: unknown\n handler: CustomTool['handler']\n }) => unknown,\n extraSdkTools: readonly CustomTool[] = [],\n runContext?: unknown,\n): unknown[] {\n const has = runContext !== undefined\n return [\n ...compiledTools.map((t) => {\n if (hasZodInputSchema(t.inputSchema)) {\n return defineTool({\n name: t.name,\n description: t.description,\n inputSchema: t.inputSchema,\n handler: has ? withRunContext(t.handler, runContext) : t.handler,\n })\n }\n // Already an SDK-ready CustomTool (JSON-Schema inputSchema) — forward RAW (same reference)\n // unless a run-context must be injected into its handler.\n return has ? { ...t, handler: withRunContext(t.handler, runContext) } : t\n }),\n ...extraSdkTools.map((t) =>\n has ? { ...t, handler: withRunContext(t.handler, runContext) } : t,\n ),\n ]\n}\n\n/**\n * Creates an agent stream factory using @theokit/sdk as the runtime.\n *\n * Returns a function that, given a message + sessionId, yields TheoKit\n * AgentStreamEvent via the SDK's Agent.create() + Run.stream() pipeline.\n */\nexport function createSdkAgentStream(\n compiled: CompiledAgentOptions,\n compiledTools: CompiledTool[],\n apiKey: string,\n overrides: RuntimeOverrides = {},\n) {\n const model = overrides.model ?? compiled.model ?? 'openai/gpt-4o-mini'\n // M1 reasoning-visibility: per-run effort overrides the compiled @Agent effort (mirrors `model`).\n const reasoningEffort = overrides.reasoningEffort ?? compiled.reasoningEffort\n // Per-run opt-in text-stream transforms (each overrides the compiled @Agent flag, mirrors `model`):\n // parseThinkTags (M2, <think> extraction), stripToolDialect (theocode#32, leaked-dialect strip).\n const { parseThinkTags, stripToolDialect } = resolveTextTransformFlags(compiled, overrides)\n // M7 — run-context resolved once per stream: per-run override wins over the agent-level\n // `defineAgent({ context })`; injected into every tool's `ctx.context` by buildSdkTools.\n const runContext = overrides.runContext ?? compiled.runContext\n // SDK 4.0 (SE40): history persists across the loop's rounds via the SDK's native `.jsonl` transcript\n // (keyed by `sessionId`/`agentId` under `local.baseDir`). No theokit-side store — the SDK owns it.\n\n // `factoryOpts.disableTools` (step-cap force-close) → `tool_choice:\"none\"` at send-time.\n const factory = (\n message: string,\n sessionId: string,\n factoryOpts?: { disableTools?: boolean },\n ): AsyncIterable<StreamEvent> => ({\n async *[Symbol.asyncIterator]() {\n const runId = `run-${Date.now()}`\n const t0 = Date.now()\n\n // Dynamic import — @theokit/sdk is optional peer dep (null ⇒ not installed).\n const rt = await loadSdkRuntime()\n if (!rt) {\n yield {\n type: 'error',\n code: 'SDK_NOT_INSTALLED',\n message: 'Install @theokit/sdk: pnpm add @theokit/sdk',\n retryable: false,\n }\n return\n }\n\n // M7 — pass the resolved run-context so every tool handler receives it as `ctx.context`.\n const sdkTools = buildSdkTools(compiledTools, rt.defineTool, overrides.sdkTools, runContext)\n\n // Auto-wire `skill_read` for inline skills (`defineAgent({ skills: [inlineSkill] })`). An inline\n // skill lists in the `<skills>` block by name + description only — its body is unreachable to the\n // model without the `skill_read` tool, so registering an inline skill implies wanting it readable.\n // One `.skills([...])` call thus both registers AND makes the skill readable. Dedup: skip when the\n // app already declared a `skill_read` (an explicit `defineSkillReadTool` wins). Graceful: skip when\n // the loaded SDK predates `defineSkillReadTool` (inline skills still list, just not auto-readable).\n const inlineSkills = compiled.skills?.inline\n if (\n inlineSkills !== undefined &&\n inlineSkills.length > 0 &&\n rt.defineSkillReadTool !== undefined &&\n !compiledTools.some((t) => t.name === 'skill_read')\n ) {\n sdkTools.push(rt.defineSkillReadTool(inlineSkills))\n }\n // Wiring triad pillar (c) — M7 run-context metric: observable proof that context injection is active.\n let runContextSource: string\n if (overrides.runContext !== undefined) {\n runContextSource = 'per-run'\n } else if (compiled.runContext !== undefined) {\n runContextSource = 'agent-level'\n } else {\n runContextSource = 'none'\n }\n debugLog('[THEO_AGENT_M7_RUN_CONTEXT]', {\n source: runContextSource,\n keys: runContext !== undefined ? Object.keys(runContext) : [],\n })\n\n try {\n yield* streamSdkAgent(rt, compiled, sdkTools, {\n apiKey,\n model,\n reasoningEffort,\n overrides,\n parseThinkTags,\n stripToolDialect,\n sessionId,\n message,\n factoryOpts,\n runId,\n t0,\n })\n } catch (err) {\n yield {\n type: 'error',\n code: 'SDK_ERROR',\n message: err instanceof Error ? err.message : 'SDK agent error',\n retryable: false,\n }\n }\n },\n })\n\n // The resolved model is the one silent fallback in this path that matters: a caller passing the\n // wrong argument shape (as the HTTP app builder did) gets `openai/gpt-4o-mini` with no error and\n // no way to tell. Exposing it makes the resolution observable — and testable.\n return Object.assign(factory, { resolvedModel: model })\n}\n\ninterface StreamSdkAgentOpts {\n apiKey: string\n model: string\n reasoningEffort: string | undefined\n overrides: RuntimeOverrides\n parseThinkTags: boolean\n stripToolDialect: boolean\n sessionId: string\n message: string\n factoryOpts: { disableTools?: boolean } | undefined\n runId: string\n t0: number\n}\n\n/**\n * Inner streaming kernel (G6 extraction): creates the SDK agent, runs the send+stream loop,\n * and disposes. Errors propagate to the outer generator's catch. The `finally` inside guarantees\n * disposal even when `run.wait()` rejects (V4-N.1).\n */\nasync function* streamSdkAgent(\n rt: SdkRuntime,\n compiled: CompiledAgentOptions,\n sdkTools: unknown[],\n opts: StreamSdkAgentOpts,\n): AsyncGenerator<StreamEvent> {\n const { Agent } = rt\n const {\n apiKey,\n model,\n reasoningEffort,\n overrides,\n parseThinkTags,\n stripToolDialect,\n sessionId,\n message,\n factoryOpts,\n runId,\n t0,\n } = opts\n\n // Project the compiled M8 decorator fields into native Agent.create args.\n const { options: m8, applied } = assembleM8CreateOptions(compiled)\n if (overrides.cwd !== undefined) m8.local = { ...m8.local, cwd: overrides.cwd }\n // SDK 4.0 (SE40): root the native session transcript at the framework-resolved app root when known\n // (mount-agent threads it), so sessions persist per-app; unset ⇒ SDK default (`~/.theokit`).\n if (overrides.baseDir !== undefined) m8.local = { ...m8.local, baseDir: overrides.baseDir }\n const extra = buildExtraCreateOptions(overrides, compiled)\n if (applied.length > 0) {\n // Wiring triad — runtime metric: observable proof the decorators fired (opt-in via THEOKIT_DEBUG).\n debugLog('[THEO_AGENT_M8_RUNTIME_APPLIED]', {\n skills: applied.includes('skills'),\n contextWindow: applied.includes('context'),\n projectContext: applied.includes('projectContext'),\n })\n }\n\n // V4-N.1: declared before try so `finally` can dispose even when `run.wait()` rejects.\n const agent = await Agent.getOrCreate(sessionId, {\n apiKey,\n model: buildModelSelection(model, reasoningEffort),\n tools: sdkTools,\n ...m8,\n ...extra,\n })\n try {\n // #44: chronological token streaming via onDelta + merge queue (see createDeltaSink).\n const queue = createAsyncQueue<MergeItem>()\n const { state, onDelta } = createDeltaSink(queue)\n const sendOptions: SendOptions = { onDelta }\n if (factoryOpts?.disableTools === true) sendOptions.toolChoice = 'none'\n // M35 — when images are present, use the SDK's structured `SDKUserMessage { text, images }` form so\n // the model receives them alongside the text; otherwise the plain-string form is unchanged (back-compat).\n const sendInput =\n overrides.images && overrides.images.length > 0\n ? { text: message, images: overrides.images }\n : message\n const sendPromise = agent.send(sendInput as typeof message, sendOptions)\n const openStream = async () => (await sendPromise).stream()\n const merged = mergeDeltaStream(queue, openStream, runId, state)\n for await (const event of applyTextTransforms(merged, { parseThinkTags, stripToolDialect })) {\n yield event\n }\n // V4-N.1: ONE real-usage `done` after run.wait(); errors short-circuit it.\n if (!state.sawError) {\n yield realUsageDone(await (await sendPromise).wait(), t0)\n }\n } finally {\n await agent.dispose()\n }\n}\n\n/**\n * The minimal `SDKAgent` surface a serving host needs (ACP checks `agentId: string` + `send: fn`).\n * `Agent.getOrCreate` returns the real SDK agent — this alias just types what {@link toAgentFactory}\n * hands back without re-exporting the full `@theokit/sdk` `Agent` type.\n */\nexport interface SdkAgentHandle {\n readonly agentId: string\n send: (msg: string, opts?: unknown) => unknown\n dispose: () => Promise<void>\n}\n\n/**\n * #12 — bridge a builder/`defineAgent` {@link TheokitAgentDefinition} to a real `SDKAgent` FACTORY,\n * so surfaces that require an `SDKAgent` (or `(sessionId) => SDKAgent`) — notably `theokit acp`,\n * whose entry default-export must be one — can serve an agent defined with the `AgentBuilder.create()` chain.\n *\n * The factory reuses the SAME projection the streaming path uses (`compileAgentDefinition` → tools /\n * model / `assembleM8CreateOptions`), so the served agent has identical tools, model, system prompt,\n * skills, and `mcpServers`. Keyed per `sessionId` via `Agent.getOrCreate` (matches the run path).\n *\n * NOTE: HITL approvals (`.approval(...)`) are driven by the framework's streaming runner, not by\n * `Agent.create`; a raw `SDKAgent` from this factory does not auto-pause gated tools — the serving\n * surface (e.g. the ACP client) owns approval. Tools still execute; they are simply not HITL-gated here.\n */\nexport function toAgentFactory(\n def: TheokitAgentDefinition,\n opts: { apiKey: string; overrides?: RuntimeOverrides },\n): (sessionId: string) => Promise<SdkAgentHandle> {\n const compiled = compileAgentDefinition(def)\n const overrides = opts.overrides ?? {}\n const model = overrides.model ?? compiled.model ?? 'openai/gpt-4o-mini'\n const reasoningEffort = overrides.reasoningEffort ?? compiled.reasoningEffort\n const runContext = overrides.runContext ?? compiled.runContext\n return async (sessionId: string): Promise<SdkAgentHandle> => {\n const rt = await loadSdkRuntime()\n if (!rt) {\n throw new Error(\n '[@theokit/agents] @theokit/sdk is not installed — run: pnpm add @theokit/sdk',\n )\n }\n const sdkTools = buildSdkTools(compiled.tools, rt.defineTool, overrides.sdkTools, runContext)\n // Auto-wire `skill_read` for inline skills (mirror createSdkAgentStream) so an inline skill's\n // body stays reachable to the model when this factory serves the agent.\n const inlineSkills = compiled.skills?.inline\n if (\n inlineSkills !== undefined &&\n inlineSkills.length > 0 &&\n rt.defineSkillReadTool !== undefined &&\n !compiled.tools.some((t) => t.name === 'skill_read')\n ) {\n sdkTools.push(rt.defineSkillReadTool(inlineSkills))\n }\n const { options: m8 } = assembleM8CreateOptions(compiled)\n if (overrides.cwd !== undefined) m8.local = { ...m8.local, cwd: overrides.cwd }\n if (overrides.baseDir !== undefined) m8.local = { ...m8.local, baseDir: overrides.baseDir }\n const extra = buildExtraCreateOptions(overrides, compiled)\n const agent = await rt.Agent.getOrCreate(sessionId, {\n apiKey: opts.apiKey,\n model: buildModelSelection(model, reasoningEffort),\n tools: sdkTools,\n ...m8,\n ...extra,\n })\n return agent as unknown as SdkAgentHandle\n }\n}\n","/**\n * `AgentOutputEvent` — the canonical, normalized agent-output event (M49).\n *\n * This is the **narrow waist** of theokit's presentation layer: ONE normalized event that every SOURCE\n * (the SDK's `SDKMessage` / `InteractionUpdate`) is translated INTO, and that every `Presenter`\n * (web `UIMessageStream`, terminal ANSI, JSON API) is translated OUT of. Without it you get N×M\n * translators — the current duplication where the web path and the terminal path each re-translate the\n * SDK independently and drift. The variants are derived from the SDK's own event discriminants (source\n * side), NOT from any single surface's wire format, so no surface leaks into the contract.\n *\n * @public\n */\nexport type AgentOutputEvent =\n | AgentTextEvent\n | AgentReasoningEvent\n | AgentToolCallEvent\n | AgentPartialToolCallEvent\n | AgentToolResultEvent\n | AgentErrorEvent\n | AgentFinishEvent\n | AgentStatusEvent\n\n/** Assistant text output (streamed or whole). */\nexport interface AgentTextEvent {\n readonly type: 'text'\n readonly text: string\n}\n\n/** Model reasoning / thinking content (distinct from user-visible text). */\nexport interface AgentReasoningEvent {\n readonly type: 'reasoning'\n readonly text: string\n}\n\n/** A tool invocation with its (committed) input — the args the model decided on. */\nexport interface AgentToolCallEvent {\n readonly type: 'tool-call'\n readonly callId: string\n readonly name: string\n readonly input: unknown\n}\n\n/**\n * Incremental tool input as the model streams the args (theokit-sdk#70) — a DISTINCT lifecycle point\n * from `tool-call` (args committed). Consumers that stream tool-input render the progressive args; those\n * that don't may ignore it. Never duplicates `tool-call`.\n */\nexport interface AgentPartialToolCallEvent {\n readonly type: 'partial-tool-call'\n readonly callId: string\n readonly name: string\n readonly input: unknown\n}\n\n/** The result of a tool invocation, keyed by the same `callId`. `isError` marks a failed tool. */\nexport interface AgentToolResultEvent {\n readonly type: 'tool-result'\n readonly callId: string\n readonly name: string\n readonly result: unknown\n readonly isError?: boolean\n}\n\n/** A run-level error (typed message + optional code). */\nexport interface AgentErrorEvent {\n readonly type: 'error'\n readonly message: string\n readonly code?: string\n}\n\n/** Terminal event of a turn: the run finished. `usage` carries token accounting when available. */\nexport interface AgentFinishEvent {\n readonly type: 'finish'\n readonly reason?: string\n readonly usage?: { readonly totalTokens?: number }\n}\n\n/** A lifecycle status transition (e.g. goal `active` → `completed`), surface-agnostic. */\nexport interface AgentStatusEvent {\n readonly type: 'status'\n readonly status: string\n readonly detail?: string\n}\n\n/** The stable set of variant discriminants — useful for exhaustiveness and registry keys. */\nexport const AGENT_OUTPUT_EVENT_TYPES = [\n 'text',\n 'reasoning',\n 'tool-call',\n 'partial-tool-call',\n 'tool-result',\n 'error',\n 'finish',\n 'status',\n] as const\n\nexport type AgentOutputEventType = (typeof AGENT_OUTPUT_EVENT_TYPES)[number]\n\n// --- type guards (discriminate a canonical event without a manual `switch`) ---\n\nexport const isTextEvent = (e: AgentOutputEvent): e is AgentTextEvent => e.type === 'text'\nexport const isReasoningEvent = (e: AgentOutputEvent): e is AgentReasoningEvent =>\n e.type === 'reasoning'\nexport const isToolCallEvent = (e: AgentOutputEvent): e is AgentToolCallEvent =>\n e.type === 'tool-call'\nexport const isPartialToolCallEvent = (e: AgentOutputEvent): e is AgentPartialToolCallEvent =>\n e.type === 'partial-tool-call'\nexport const isToolResultEvent = (e: AgentOutputEvent): e is AgentToolResultEvent =>\n e.type === 'tool-result'\nexport const isErrorEvent = (e: AgentOutputEvent): e is AgentErrorEvent => e.type === 'error'\nexport const isFinishEvent = (e: AgentOutputEvent): e is AgentFinishEvent => e.type === 'finish'\nexport const isStatusEvent = (e: AgentOutputEvent): e is AgentStatusEvent => e.type === 'status'\n","import type { AgentOutputEvent } from './agent-output-event.js'\n\n/**\n * `Presenter<TOut>` — the Strategy that turns the canonical {@link AgentOutputEvent} into ONE surface's\n * output (M49). Web (`UIMessageStream`), terminal (ANSI), and JSON API are peer implementations; each\n * consumes the SAME canonical event, so a source is translated once and every surface reuses it.\n *\n * The contract is **per-event, driven by the caller**: the host loops the event stream and calls\n * `present(event)` for each, so it can INTERLEAVE a presenter's pure-output chunks with framework chunks\n * (HITL approval, checkpoints, done-metadata — `@theokit/agents`) in true model order (ADR-4). Optional\n * `start()` / `finish()` bracket the stream for stateful surfaces (the web stream's `start` framing and\n * its open-block close + `finish`). A stateful presenter (web) holds its open-block state internally and\n * is therefore instantiated **per stream**; stateless presenters (terminal/json) may be singletons.\n *\n * @public\n */\nexport interface Presenter<TOut> {\n /** Stable surface key (`\"ui-message-stream\" | \"terminal\" | \"json\" | …`) — the registry resolves by it. */\n readonly surface: string\n /** Optional opening framing emitted once before any event (e.g. the web stream's `{ type: 'start' }`). */\n start?(): TOut[]\n /** Translate one canonical event into zero or more surface chunks (may maintain internal stream state). */\n present(event: AgentOutputEvent): TOut[]\n /** Optional closing framing emitted once after the last event (e.g. close the open block + `finish`). */\n finish?(): TOut[]\n}\n\n/** Thrown when a surface key is resolved but no presenter is registered for it (fail-fast, typed). */\nexport class UnknownPresenterError extends Error {\n override readonly name = 'UnknownPresenterError'\n constructor(surface: string, known: readonly string[]) {\n super(\n `No presenter registered for surface \"${surface}\". Known: ${known.join(', ') || '(none)'}.`,\n )\n }\n}\n\n/**\n * A registry of presenters keyed by surface. Lets a single agent run be driven through any registered\n * surface without the caller hard-wiring a concrete presenter (Open/Closed — add a surface by registering,\n * not by editing a switch).\n *\n * @public\n */\nexport class PresenterRegistry {\n readonly #presenters = new Map<string, Presenter<unknown>>()\n\n /** Register (or replace) the presenter for its surface. Returns `this` for fluent wiring. */\n register(presenter: Presenter<unknown>): this {\n this.#presenters.set(presenter.surface, presenter)\n return this\n }\n\n /** Whether a presenter is registered for `surface`. */\n has(surface: string): boolean {\n return this.#presenters.has(surface)\n }\n\n /** The registered surface keys. */\n surfaces(): string[] {\n return [...this.#presenters.keys()]\n }\n\n /** Resolve the presenter for `surface`, or throw {@link UnknownPresenterError} (never returns undefined). */\n resolve<TOut>(surface: string): Presenter<TOut> {\n const p = this.#presenters.get(surface)\n if (p === undefined) throw new UnknownPresenterError(surface, this.surfaces())\n return p as Presenter<TOut>\n }\n}\n","import type { InteractionUpdate } from '@theokit/sdk'\n\nimport type { AgentOutputEvent } from '../agent-output-event.js'\n\n/**\n * `fromSdk` (M49) — the SINGLE source translator: `@theokit/sdk` output → the canonical\n * {@link AgentOutputEvent}. Every presenter (web / terminal / json) consumes the result, so the SDK is\n * parsed ONCE instead of each surface re-translating it (the duplication this layer removes).\n *\n * Ported faithfully from `@theokit/agents/bridge/event-translator.ts` (the proven web-path logic), but\n * emitting the NARROW pure-output event: framework concerns (run-lifecycle, HITL approval, checkpoints,\n * devtools artifacts) are NOT SDK output and are layered by `@theokit/agents` on top (ADR-4), so they are\n * intentionally NOT produced here.\n */\n\n/** Minimal SDK message shape — duck-typed to avoid a hard import of every SDK message subtype. */\nexport interface SdkMessage {\n readonly type: string\n readonly [key: string]: unknown\n}\n\n/** Safely coerce an unknown value to a string, else the fallback. */\nfunction asString(value: unknown, fallback: string): string {\n return typeof value === 'string' ? value : fallback\n}\n\n/**\n * Serialize a tool's `result` for the canonical `tool-result.result`. String passthrough; null/undefined →\n * fallback; otherwise JSON. `JSON.stringify` throws on BigInt / circular refs — preserve a BigInt's real\n * value, else fall back (never `[object Object]`). Mirrors event-translator's `serializeToolOutput` (#41).\n */\nfunction serializeToolResult(value: unknown, fallback: string): string {\n if (typeof value === 'string') return value\n if (value === undefined || value === null) return fallback\n try {\n return JSON.stringify(value)\n } catch {\n return typeof value === 'bigint' ? value.toString() : fallback\n }\n}\n\nfunction fromAssistant(msg: SdkMessage): AgentOutputEvent[] {\n const events: AgentOutputEvent[] = []\n const content = (msg.message as { content?: unknown } | undefined)?.content\n if (!Array.isArray(content)) return events\n for (const block of content) {\n const b = block as { type: string; text?: string; name?: string; input?: unknown; id?: string }\n if (b.type === 'text' && b.text) events.push({ type: 'text', text: b.text })\n if (b.type === 'tool_use') {\n events.push({\n type: 'tool-call',\n callId: b.id ?? `tc-${Date.now()}`,\n name: b.name ?? 'unknown',\n input: b.input ?? {},\n })\n }\n }\n return events\n}\n\nfunction fromToolUse(msg: SdkMessage): AgentOutputEvent[] {\n const status = msg.status as string\n const callId = asString(msg.call_id, `tc-${Date.now()}`)\n const name = asString(msg.name, 'unknown')\n if (status === 'completed') {\n return [\n {\n type: 'tool-result',\n callId,\n name,\n result: serializeToolResult(msg.result, ''),\n isError: false,\n },\n ]\n }\n if (status === 'error') {\n return [\n {\n type: 'tool-result',\n callId,\n name,\n result: serializeToolResult(msg.result, 'Tool failed'),\n isError: true,\n },\n ]\n }\n if (status === 'running') {\n // Tool start — emit the committed call so the UI shows the running card. The SDK carries args in\n // `args` (theokit#58; `input`/`arguments` were never the field); keep the others as defensive fallbacks.\n return [\n { type: 'tool-call', callId, name, input: msg.args ?? msg.input ?? msg.arguments ?? {} },\n ]\n }\n return []\n}\n\nfunction fromStatus(msg: SdkMessage): AgentOutputEvent[] {\n // SDKStatusMessage: UPPERCASE cloud-run lifecycle. FINISHED/CANCELLED → finish (terminal-clean);\n // ERROR/EXPIRED → error (terminal-failure, fail-loud). CREATING/RUNNING → in-progress (no output).\n const s = msg.status as string\n if (s === 'FINISHED' || s === 'CANCELLED') return [{ type: 'finish', reason: s.toLowerCase() }]\n if (s === 'ERROR' || s === 'EXPIRED') {\n return [{ type: 'error', message: asString(msg.message, 'Agent error'), code: 'AGENT_ERROR' }]\n }\n return []\n}\n\n/** Translate ONE buffered SDK message (`run.stream()`) to zero or more canonical output events. */\nexport function fromSdkMessage(msg: SdkMessage): AgentOutputEvent[] {\n switch (msg.type) {\n case 'assistant':\n return fromAssistant(msg)\n case 'tool_call':\n return fromToolUse(msg)\n case 'thinking':\n return [{ type: 'reasoning', text: asString(msg.text, '') }]\n case 'status':\n return fromStatus(msg)\n // `system` / run-lifecycle is framework framing, not pure output — intentionally skipped (ADR-4).\n default:\n return []\n }\n}\n\n/**\n * Translate ONE real-time `onDelta` {@link InteractionUpdate} to zero or more canonical output events, in\n * arrival order — the chronological path that keeps text / tool / thinking interleaved in true model order.\n * `partial-tool-call` is surfaced distinctly (theokit-sdk#70); it never duplicates `tool-call`.\n */\nexport function fromInteractionUpdate(update: InteractionUpdate): AgentOutputEvent[] {\n switch (update.type) {\n case 'text-delta':\n return update.text ? [{ type: 'text', text: update.text }] : []\n case 'thinking-delta':\n return update.text ? [{ type: 'reasoning', text: update.text }] : []\n case 'tool-call-started':\n return [\n {\n type: 'tool-call',\n callId: update.callId,\n name: update.toolCall.name,\n input: update.toolCall.args ?? {},\n },\n ]\n case 'partial-tool-call':\n return [\n {\n type: 'partial-tool-call',\n callId: update.callId,\n name: update.toolCall.name,\n input: update.toolCall.args ?? {},\n },\n ]\n case 'tool-call-completed':\n return [\n {\n type: 'tool-result',\n callId: update.callId,\n name: update.toolCall.name,\n result: serializeToolResult(update.toolCall.result, ''),\n isError: false,\n },\n ]\n default:\n return []\n }\n}\n","import type { UIMessageChunk } from 'ai'\n\nimport type { AgentOutputEvent } from '../agent-output-event.js'\nimport type { Presenter } from '../presenter.js'\n\n/**\n * `UIMessageStreamPresenter` (M49) — the web surface: the canonical {@link AgentOutputEvent} → the Vercel\n * ai-sdk `UIMessageStream` (`UIMessageChunk`), consumed by `useChat` / assistant-ui.\n *\n * Ported faithfully from `@theokit/agents/bridge/ui-message-stream-translator.ts` (the M1 web path) with\n * ZERO behavior change for the pure-output events. Framework chunks (HITL `tool-approval-request`,\n * `data-checkpoint`) are NOT emitted here — they ride on `@theokit/agents` framework events and are\n * composed by the agents web handler around this presenter (ADR-4).\n *\n * STATEFUL (open-block state machine) → instantiate ONE per stream. The host brackets the stream with\n * {@link start} / {@link finish} and drives {@link present} per event, interleaving framework chunks.\n *\n * Chunk sequences (unchanged):\n * text run: start → text-start{id} → text-delta{id,delta}* → text-end{id} → finish\n * reasoning run: start → reasoning-start{id} → reasoning-delta{id,delta}* → reasoning-end{id} → finish\n * tool run: start → tool-input-available{callId,name,input} → tool-output-available{callId,output} → finish\n *\n * @public\n */\nexport interface TurnMetadata {\n readonly usage?: {\n readonly inputTokens?: number\n readonly outputTokens?: number\n readonly totalTokens?: number\n }\n readonly durationMs?: number\n readonly cost?: number\n}\n\nexport interface UIMessageStreamPresenterOptions {\n /** A single shared id for every text block — injected for deterministic tests (D3). */\n readonly textId: string\n}\n\nexport class UIMessageStreamPresenter implements Presenter<UIMessageChunk> {\n readonly surface = 'ui-message-stream'\n readonly #textId: string\n #openBlock: 'text' | 'reasoning' | null = null\n #reasoningId: string | null = null\n readonly #seen = new Set<string>()\n\n constructor(options: UIMessageStreamPresenterOptions) {\n this.#textId = options.textId\n }\n\n /** Emit the opening `start` chunk (exactly once, before any event). */\n start(): UIMessageChunk[] {\n return [{ type: 'start' }]\n }\n\n present(event: AgentOutputEvent): UIMessageChunk[] {\n switch (event.type) {\n case 'text':\n return this.#emitTextDelta(event.text)\n case 'reasoning':\n return this.#emitReasoningDelta(event.text)\n case 'tool-call':\n return [\n ...this.#closeOpenBlock(),\n ...this.#emitToolCall(event.callId, event.name, event.input),\n ]\n case 'tool-result':\n return [\n ...this.#closeOpenBlock(),\n ...this.#emitToolResult(event.callId, event.name, event.result, event.isError ?? false),\n ]\n case 'error':\n // Surface the failure as an ai-sdk error chunk (fail-clear); the host stops and calls finish().\n return [{ type: 'error', errorText: event.message }]\n // `partial-tool-call` streams incremental args — the current web path emits no chunk for it\n // (args are shown on the committed `tool-call`); `finish` / `status` are handled by finish()/host.\n default:\n return []\n }\n }\n\n /**\n * Close any open text/reasoning block and emit the terminal `finish` chunk. When `metadata` is given\n * (a clean run's turn totals from the framework `done`), it rides `messageMetadata`; otherwise the\n * finish is bare (error/abort turns), byte-identical to the original translator.\n */\n finish(metadata?: TurnMetadata): UIMessageChunk[] {\n const out = this.#closeOpenBlock()\n out.push(metadata ? { type: 'finish', messageMetadata: metadata } : { type: 'finish' })\n return out\n }\n\n /**\n * Close any open text/reasoning block WITHOUT finishing the stream. The host calls this before\n * interleaving a framework chunk (HITL approval / checkpoint) that must not appear inside an open text\n * block — mirroring the original translator's `closeOpenBlock` before those chunks. Idempotent.\n */\n closeBlock(): UIMessageChunk[] {\n return this.#closeOpenBlock()\n }\n\n /**\n * Whether a `callId` has already been introduced (a `tool-call` or a synthesized `tool-input`). The host\n * uses this so a framework `approval_required` reuses the EC-1 synthesize-input-first rule exactly once.\n */\n hasSeen(callId: string): boolean {\n return this.#seen.has(callId)\n }\n\n /** Mark a `callId` as introduced (the host synthesized its `tool-input` for a framework chunk). */\n markSeen(callId: string): void {\n this.#seen.add(callId)\n }\n\n // --- internal open-block state machine (verbatim from the original translator) ---\n\n #closeOpenBlock(): UIMessageChunk[] {\n const out: UIMessageChunk[] = []\n if (this.#openBlock === 'text') {\n out.push({ type: 'text-end', id: this.#textId })\n } else if (this.#openBlock === 'reasoning' && this.#reasoningId) {\n out.push({ type: 'reasoning-end', id: this.#reasoningId })\n }\n this.#openBlock = null\n this.#reasoningId = null\n return out\n }\n\n #emitTextDelta(content: string): UIMessageChunk[] {\n const out: UIMessageChunk[] = []\n if (this.#openBlock !== 'text') {\n out.push(...this.#closeOpenBlock(), { type: 'text-start', id: this.#textId })\n this.#openBlock = 'text'\n }\n out.push({ type: 'text-delta', id: this.#textId, delta: content })\n return out\n }\n\n #emitReasoningDelta(content: string): UIMessageChunk[] {\n const out: UIMessageChunk[] = []\n let reasoningId = this.#openBlock === 'reasoning' ? this.#reasoningId : null\n if (reasoningId === null) {\n out.push(...this.#closeOpenBlock())\n reasoningId = crypto.randomUUID()\n this.#reasoningId = reasoningId\n out.push({ type: 'reasoning-start', id: reasoningId })\n this.#openBlock = 'reasoning'\n }\n out.push({ type: 'reasoning-delta', id: reasoningId, delta: content })\n return out\n }\n\n #emitToolCall(callId: string, name: string, input: unknown): UIMessageChunk[] {\n this.#seen.add(callId)\n return [\n { type: 'tool-input-available', toolCallId: callId, toolName: name, input, dynamic: true },\n ]\n }\n\n #emitToolResult(\n callId: string,\n name: string,\n result: unknown,\n isError: boolean,\n ): UIMessageChunk[] {\n const out: UIMessageChunk[] = []\n if (!this.#seen.has(callId)) {\n this.#seen.add(callId)\n out.push({\n type: 'tool-input-available',\n toolCallId: callId,\n toolName: name,\n input: {},\n dynamic: true,\n })\n }\n // The canonical tool-result carries a serialized string `result` (from `fromSdk`).\n const output = typeof result === 'string' ? result : ''\n if (isError) {\n out.push({ type: 'tool-output-error', toolCallId: callId, errorText: output })\n } else {\n out.push({ type: 'tool-output-available', toolCallId: callId, output })\n }\n return out\n }\n}\n","import type { AgentOutputEvent } from '../agent-output-event.js'\nimport type { Presenter } from '../presenter.js'\n\n/**\n * `TerminalPresenter` (M50) — the terminal surface: the canonical {@link AgentOutputEvent} → plain rows\n * ready for a TTY. Peer of the web `UIMessageStreamPresenter`, sourced from the SAME canonical event, so a\n * terminal agent (exec / CLI / TUI) never re-translates the SDK.\n *\n * Returns DATA (`TerminalRow[]`), never a pre-painted string blob: the row carries its `kind` so an Ink /\n * blessed / raw-TTY renderer decides styling (SRP — format here, render there). ANSI is opt-in via\n * `{ ansi: true }` for consumers that write straight to a stream.\n *\n * @public\n */\nexport interface TerminalRow {\n /** Semantic kind — the renderer maps it to a style. */\n readonly kind:\n | 'text'\n | 'reasoning'\n | 'tool'\n | 'tool-result'\n | 'tool-error'\n | 'error'\n | 'status'\n | 'finish'\n /** The line content (already one-line-safe; no trailing newline). */\n readonly text: string\n}\n\nexport interface TerminalPresenterOptions {\n /** Wrap rows in ANSI colors (default `false` — the renderer usually styles). */\n readonly ansi?: boolean\n /** Max width for inlined tool input/result previews (default 88). */\n readonly maxPreview?: number\n}\n\nconst ANSI: Record<TerminalRow['kind'], string> = {\n text: '',\n reasoning: '\\x1b[2m', // dim\n tool: '\\x1b[36m', // cyan\n 'tool-result': '\\x1b[2m',\n 'tool-error': '\\x1b[31m', // red\n error: '\\x1b[31m',\n status: '\\x1b[35m', // magenta\n finish: '\\x1b[2m',\n}\nconst RESET = '\\x1b[0m'\n\n/** One-line, width-capped preview of an arbitrary value (tool input/result). */\nfunction preview(value: unknown, max: number): string {\n const raw = typeof value === 'string' ? value : safeJson(value)\n const flat = raw.replace(/\\s+/g, ' ').trim()\n return flat.length > max ? `${flat.slice(0, max - 1)}…` : flat\n}\n\nfunction safeJson(value: unknown): string {\n if (value === undefined || value === null) return ''\n try {\n return JSON.stringify(value)\n } catch {\n return typeof value === 'bigint' ? value.toString() : ''\n }\n}\n\n/** Build an optional ` (code)` / ` — detail` suffix without nesting template literals. */\nfunction suffix(open: string, value: string | undefined, close: string): string {\n return value === undefined ? '' : open + value + close\n}\n\nexport class TerminalPresenter implements Presenter<TerminalRow> {\n readonly surface = 'terminal'\n readonly #ansi: boolean\n readonly #max: number\n\n constructor(options: TerminalPresenterOptions = {}) {\n this.#ansi = options.ansi ?? false\n this.#max = options.maxPreview ?? 88\n }\n\n present(event: AgentOutputEvent): TerminalRow[] {\n switch (event.type) {\n case 'text':\n return event.text.length > 0 ? [this.#row('text', event.text)] : []\n case 'reasoning':\n return event.text.length > 0 ? [this.#row('reasoning', `\\u00b7 ${event.text}`)] : []\n case 'tool-call':\n return [this.#row('tool', `\\u23fa ${event.name}(${preview(event.input, this.#max)})`)]\n case 'tool-result':\n return [this.#toolResult(event.isError === true, preview(event.result, this.#max))]\n case 'error':\n return [this.#row('error', `\\u2716 ${event.message}${suffix(' (', event.code, ')')}`)]\n case 'status':\n return [\n this.#row('status', `\\u25cf ${event.status}${suffix(' \\u2014 ', event.detail, '')}`),\n ]\n case 'finish':\n return [this.#row('finish', this.#finishText(event.reason, event.usage?.totalTokens))]\n // `partial-tool-call` streams incremental args — the committed `tool-call` renders them.\n default:\n return []\n }\n }\n\n #toolResult(isError: boolean, body: string): TerminalRow {\n return this.#row(isError ? 'tool-error' : 'tool-result', ` \\u23bf ${body}`)\n }\n\n #finishText(reason: string | undefined, tokens: number | undefined): string {\n const r = suffix(' ', reason, '')\n const t = tokens === undefined ? '' : ` \\u00b7 ${tokens} tokens`\n return `<<${r}${t} >>`\n }\n\n #row(kind: TerminalRow['kind'], text: string): TerminalRow {\n return { kind, text: this.#ansi && ANSI[kind] !== '' ? `${ANSI[kind]}${text}${RESET}` : text }\n }\n}\n","import type { AgentOutputEvent } from '../agent-output-event.js'\nimport type { Presenter } from '../presenter.js'\n\n/**\n * `JsonPresenter` (M51) — the API / programmatic surface: the canonical {@link AgentOutputEvent} → a\n * stable, machine-readable JSON record. Third peer of the web (`UIMessageStreamPresenter`) and terminal\n * (`TerminalPresenter`) surfaces, proving the contract generalizes: ONE canonical event, N surfaces.\n *\n * Consumers (a `--json` CLI, a webhook, a log sink) read FIELDS, never regex over rendered UI strings.\n * The record keeps the canonical discriminant under `type` and is namespaced with `agent.` so it can be\n * multiplexed onto a shared JSONL stream without colliding with a host's own event names.\n *\n * @public\n */\nexport interface JsonRecord {\n /** Namespaced canonical discriminant, e.g. `agent.text` / `agent.tool-call`. */\n readonly type: string\n readonly [key: string]: unknown\n}\n\nexport interface JsonPresenterOptions {\n /** Prefix for the `type` field (default `\"agent.\"`). Pass `\"\"` for bare discriminants. */\n readonly namespace?: string\n}\n\nexport class JsonPresenter implements Presenter<JsonRecord> {\n readonly surface = 'json'\n readonly #ns: string\n\n constructor(options: JsonPresenterOptions = {}) {\n this.#ns = options.namespace ?? 'agent.'\n }\n\n present(event: AgentOutputEvent): JsonRecord[] {\n // The canonical event IS already a flat, typed record — the JSON surface only namespaces the\n // discriminant and passes the payload through verbatim (no lossy re-shaping).\n const { type, ...payload } = event\n return [{ type: `${this.#ns}${type}`, ...payload }]\n }\n}\n","\nimport { UIMessageStreamPresenter } from '@theokit/presenter'\nimport type { AgentOutputEvent } from '@theokit/presenter'\nimport type { UIMessageChunk } from 'ai'\n\nimport type { AgentStreamEvent, AgentTurnMetadata, DoneEvent } from './agent-stream-events.js'\n\n/**\n * M49 — the web surface, composed over `@theokit/presenter`. Replaces the inline `translateToUIMessageStream`.\n *\n * The PURE-OUTPUT variants of `AgentStreamEvent` map to the canonical `AgentOutputEvent` and are rendered\n * by the shared {@link UIMessageStreamPresenter} (the single source of the UIMessageChunk state machine,\n * reused by every surface). The FRAMEWORK variants that only the web/devtools path has — HITL\n * `approval_required`, `checkpoint_saved` — are composed INLINE here (ADR-4: they are not pure agent\n * output, so they never entered the presenter's canonical event). Behavior is byte-identical to the\n * original translator (proven by `present-ui-message-stream.test.ts`).\n */\n\n/** Map a pure-output `AgentStreamEvent` to the canonical event, or `null` for framework/no-output variants. */\nfunction toAgentOutputEvent(e: AgentStreamEvent): AgentOutputEvent | null {\n switch (e.type) {\n case 'text_delta':\n return { type: 'text', text: e.content }\n case 'thinking':\n return { type: 'reasoning', text: e.content }\n case 'tool_call':\n return { type: 'tool-call', callId: e.callId, name: e.toolName, input: e.input }\n case 'tool_result':\n return {\n type: 'tool-result',\n callId: e.callId,\n name: e.toolName,\n result: e.output,\n isError: e.isError,\n }\n default:\n return null\n }\n}\n\n/** Project the `done` event's authoritative totals into the finish chunk's metadata (unchanged from M1). */\nfunction doneToMetadata(event: DoneEvent): AgentTurnMetadata {\n return event.cost === undefined\n ? { usage: event.usage, durationMs: event.durationMs }\n : { usage: event.usage, durationMs: event.durationMs, cost: event.cost }\n}\n\nexport async function* presentUIMessageStream(\n events: AsyncIterable<AgentStreamEvent>,\n opts: { textId: string },\n): AsyncGenerator<UIMessageChunk, void, unknown> {\n const presenter = new UIMessageStreamPresenter({ textId: opts.textId })\n yield { type: 'start' }\n let turnMetadata: AgentTurnMetadata | undefined\n try {\n for await (const event of events) {\n const output = toAgentOutputEvent(event)\n if (output !== null) {\n yield* presenter.present(output)\n continue\n }\n if (event.type === 'approval_required') {\n // A framework chunk must not sit inside an open text/reasoning block — close it first (as the\n // original translator did), then synthesize the tool-input (EC-1) once, then the approval.\n yield* presenter.closeBlock()\n if (!presenter.hasSeen(event.callId)) {\n presenter.markSeen(event.callId)\n yield {\n type: 'tool-input-available',\n toolCallId: event.callId,\n toolName: event.toolName,\n input: event.input ?? {},\n dynamic: true,\n }\n }\n yield { type: 'tool-approval-request', approvalId: event.callId, toolCallId: event.callId }\n continue\n }\n if (event.type === 'checkpoint_saved') {\n yield* presenter.closeBlock()\n yield {\n type: 'data-checkpoint',\n data: {\n checkpointId: event.checkpointId,\n resumeToken: event.resumeToken,\n step: event.step,\n },\n transient: true,\n }\n continue\n }\n if (event.type === 'error') {\n yield { type: 'error', errorText: event.message }\n break\n }\n if (event.type === 'done') {\n turnMetadata = doneToMetadata(event)\n break\n }\n // run_started, iteration, partial_tool_call, artifact_*, state_update, file_edit → no web chunk.\n }\n } catch (err) {\n yield { type: 'error', errorText: String(err) }\n }\n yield* presenter.finish(turnMetadata)\n}\n","/**\n * M8 — `AgentBuilder.create()`, the fluent agent builder with accumulative **type-state**.\n *\n * `AgentBuilder.create().context<C>().tool(t).model(id).system(s).build()` accumulates type parameters the way\n * the most-loved TS DX does (tRPC `t.procedure.input().query()`, Zod, Hono) and resolves to the\n * **SAME branded `AgentDefinition`** that {@link defineAgent} produces — one runtime, N syntaxes\n * (ADR-B1). The value is entirely at the type level; `.build()` delegates to `defineAgent`, so\n * convergence with the `defineAgent` / `@Agent` surfaces is by construction.\n *\n * Compile-time guarantees (proven by `tests/type/agent-builder.test-d.ts`):\n * - `.build()` is a compile error when `.model()` was never called (UnsetMarker technique — tRPC\n * `utils.ts:2-4` / `procedureBuilder.ts:362-379`).\n * - `.tool(t)` is a compile error when the tool declares a required run-context ⊄ the agent's `C`.\n * - tool names accumulate into a union type parameter (`TTools`).\n *\n * PURE metadata (sdk-runtime.md / G2): the builder describes an agent, it NEVER calls an LLM.\n */\nimport type { CustomTool, SettingSource, MemorySettings } from '@theokit/sdk'\nimport type { z } from 'zod'\n\nimport type { Guardrail } from '../guardrails/index.js'\nimport type { SkillsSelection } from '../skills-resolver.js'\nimport type { HumanInTheLoopOptions } from '../types.js'\nimport type { McpServersMap } from '../types.js'\nimport type { ReasoningEffort } from '../types.js'\n\nimport { defineAgent, type AgentDefinition, type DefineAgentConfig } from './define-agent.js'\n\n/**\n * A required-but-unset builder field. Branded (a literal intersected with a unique brand) so no\n * ordinary value can satisfy it — the terminal-method guards below key off it. tRPC's UnsetMarker.\n */\ntype UnsetMarker = 'theokit.unset' & { readonly __brand: 'theokit.unset' }\n\n/**\n * Compile-error carriers. When a guarded method's precondition fails, its signature demands an\n * argument of one of these types, which the caller cannot supply — the labeled tuple element\n * surfaces the reason in the error. (Idiomatic gate for zero-arg terminal methods.)\n */\ninterface MissingModelError {\n readonly __theokitError: 'call .model(id) before .build()'\n}\ninterface ToolContextError<TRequired> {\n readonly __theokitError: 'this tool requires a run-context not provided via .context()'\n readonly required: TRequired\n}\n\n/** The agent context before `.context()` is called — satisfies only tools with no requirement. */\ntype EmptyContext = Record<never, never>\n\n/**\n * A tool that MAY declare, at the type level, the run-context shape it needs. A plain\n * {@link CustomTool} (`TRequired = unknown`) is satisfied by any agent context. Build one that\n * carries a literal name + optional required-context via {@link ContextualTool.of}.\n */\nexport interface ContextualTool<\n TName extends string = string,\n TRequired = unknown,\n> extends CustomTool {\n readonly name: TName\n /** Phantom — never present at runtime; carries the required run-context type for `.tool()`. */\n readonly __requiredContext?: TRequired\n}\n\n/**\n * Static factory for {@link ContextualTool}. M57: OO surface (`ContextualTool.of(...)`) aligned with\n * the SDK's `X.create()` shape — was the free `contextualTool(...)` function. `ContextualTool` is a\n * TYPE (the interface above) and a VALUE (this const) at once, the same dual-space pattern the SDK\n * uses for `Tool`/`Agent`. No instance state, so the factory is `static`-style (`of`), not `create`.\n */\nexport const ContextualTool = {\n /**\n * Tag a {@link CustomTool} with a literal name (so `.tool()` can accumulate the tool-name union)\n * and, optionally, a required run-context type. The `requiredContext` argument is a type-only\n * witness — pass `undefined as C` or a sample value; it is never read at runtime.\n */\n of<TName extends string, TRequired = unknown>(\n tool: CustomTool & { name: TName },\n _requiredContext?: TRequired,\n ): ContextualTool<TName, TRequired> {\n return tool\n },\n}\n\n/**\n * The fluent builder. Each method returns a NEW builder type with the relevant type parameter\n * advanced (immutable chaining). Runtime state is a plain {@link DefineAgentConfig} accumulator.\n */\nexport interface AgentBuilder<\n TInput extends z.ZodType | UnsetMarker = UnsetMarker,\n TModel extends string | UnsetMarker = UnsetMarker,\n TContext = EmptyContext,\n TTools extends string = never,\n> {\n /** Set the request schema (lifted into the typed client via {@link AgentDefinition}). */\n input<S extends z.ZodType>(schema: S): AgentBuilder<S, TModel, TContext, TTools>\n /**\n * Set the model id. Required before `.build()`. COMPILE ERROR when called twice — the argument\n * type collapses to `never` once the model is set (tRPC's set-once technique).\n */\n model(\n id: TModel extends UnsetMarker ? string : never,\n ): AgentBuilder<TInput, string, TContext, TTools>\n /** Set the static system prompt. */\n system(prompt: string): AgentBuilder<TInput, TModel, TContext, TTools>\n /** Set the extended-thinking effort. */\n reasoningEffort(effort: ReasoningEffort): AgentBuilder<TInput, TModel, TContext, TTools>\n /** Set the run-context (M7) — the object every tool handler receives as `ctx.context`. */\n context<C extends Record<string, unknown>>(value: C): AgentBuilder<TInput, TModel, C, TTools>\n /**\n * Add a tool. Accumulates its name into `TTools`. COMPILE ERROR when the tool declares a\n * required run-context (`ContextualTool<_, TRequired>`) that the agent's `TContext` does not\n * satisfy — set it first with `.context()`.\n */\n tool<TName extends string, TRequired>(\n tool: ContextualTool<TName, TRequired>,\n ...guard: TContext extends TRequired ? [] : [error: ToolContextError<TRequired>]\n ): AgentBuilder<TInput, TModel, TContext, TTools | TName>\n /** M9 — add one input/output guardrail (appends). Runs at the framework boundary before the SDK. */\n guardrail(g: Guardrail): AgentBuilder<TInput, TModel, TContext, TTools>\n /** M9 — set the full guardrail list (replaces any previously added). */\n guardrails(gs: readonly Guardrail[]): AgentBuilder<TInput, TModel, TContext, TTools>\n /** M14 — gate one tool behind a HITL approval (merges into the approvals map, keyed by tool name). */\n approval(\n toolName: TTools extends never ? string : TTools,\n options: HumanInTheLoopOptions,\n ): AgentBuilder<TInput, TModel, TContext, TTools>\n /** M14 — set the full approvals map (replaces any previously added). */\n approvals(\n map: Record<string, HumanInTheLoopOptions>,\n ): AgentBuilder<TInput, TModel, TContext, TTools>\n /**\n * M13 — the skills the agent can consult mid-turn: a static list OR a per-request\n * resolver `(ctx) => string[]`. Each entry is a `createSkill(...)` object OR a\n * filesystem skill NAME (a string) — mix freely.\n *\n * Progressive disclosure (cheap by default): every turn the SDK lists each skill's\n * name + description in a `<skills>` block (so the model KNOWS the skill exists) AND\n * auto-provisions a `skill_read` tool the model calls to load the full body ON DEMAND\n * (so a long procedure only enters the prompt when it is actually needed).\n */\n skills(selection: SkillsSelection): AgentBuilder<TInput, TModel, TContext, TTools>\n /**\n * theokit-file-based-config — opt into `.theokit/` file-based config (skills, subagents, hooks,\n * MCP, context, cron), discovered by the SDK from the app root (`\"project\"` = `<cwd>/.theokit/`,\n * `\"user\"` = `~/.theokit/`). Unset ⇒ inline (code) config only. SECURITY: `\"project\"` enables\n * shell-executing hooks from `.theokit/hooks.json` — opt-in because `.theokit/` is your own repo.\n */\n settingSources(sources: readonly SettingSource[]): AgentBuilder<TInput, TModel, TContext, TTools>\n /**\n * M49 — enable the SDK's durable memory for this agent (`.theokit/memory/` in the run cwd:\n * `Remember:` capture with secret redaction, auto-injected recall, memory tools). Takes the SDK's\n * `MemorySettings` verbatim — `{ enabled: true }` is the minimal opt-in.\n */\n memory(settings: MemorySettings): AgentBuilder<TInput, TModel, TContext, TTools>\n /**\n * Attach LIFECYCLE HOOKS in code, keyed by `HookName` — the builder-chain seam for intercepting\n * the agent loop. `pre_tool_call` may VETO a tool by returning `{ block: true, message }` before\n * it runs; the other events are observational.\n *\n * ```ts\n * AgentBuilder.create().hooks({\n * pre_tool_call: (c) => guard(c.name) ? undefined : { block: true, message: 'not allowed' },\n * on_session_start: () => log('session up'),\n * })\n * ```\n *\n * A hook is delivered internally as a code plugin, but that is TRANSPORT, not the contract — use\n * this instead of hand-wrapping a plugin, so the caller expresses interception rather than\n * assembling plumbing. Call once — a later call replaces the map. Composes with\n * {@link AgentBuilder.plugins}: hooks and plugins are additive, not exclusive.\n */\n hooks(map: Readonly<Record<string, unknown>>): AgentBuilder<TInput, TModel, TContext, TTools>\n /**\n * Register code `Plugin` objects for this agent — the builder-chain equivalent of\n * `Agent.create({ plugins })`. A plugin is an EXTENSION UNIT: it can register tools and commands,\n * or supply a model provider / memory adapter (`kind: 'general' | 'model-provider' | 'memory'`).\n *\n * For lifecycle interception prefer {@link AgentBuilder.hooks} — a hook needs a plugin only as its\n * transport, and `plugins()` makes the caller assemble that transport by hand. Reach for this when\n * you genuinely have a plugin (a provider, a memory adapter, a tool-registering extension).\n */\n plugins(list: readonly unknown[]): AgentBuilder<TInput, TModel, TContext, TTools>\n /**\n * Declare MCP (Model Context Protocol) servers available to this agent — the builder-chain\n * equivalent of the `@MCP` class decorator. Each key is a server name; the value is its config\n * (`command` / `args` / `env` / `cwd`). Forwarded to `Agent.create({ mcpServers })`; the SDK owns\n * MCP execution. Call once — a later call replaces the map.\n */\n mcp(servers: McpServersMap): AgentBuilder<TInput, TModel, TContext, TTools>\n /**\n * Apply a reusable partial chain (Spring-Boot-style composition). `preset` receives the current\n * builder and returns an advanced one; its accumulated type-state flows through.\n */\n use<TResult>(\n preset: (builder: AgentBuilder<TInput, TModel, TContext, TTools>) => TResult,\n ): TResult\n /**\n * Resolve to the branded {@link AgentDefinition} — the SAME value `defineAgent` returns.\n * COMPILE ERROR when `.model()` was never called.\n */\n build(\n ...guard: TModel extends UnsetMarker ? [error: MissingModelError] : []\n ): AgentDefinition<TInput extends z.ZodType ? TInput : z.ZodType, TTools>\n /** Phantom — lets type tests read the accumulated tool-name union. Never present at runtime. */\n readonly __toolNames?: TTools\n}\n\n/**\n * Build the runtime accumulator. The public method signatures carry the type-state generics + the\n * compile-time guards; the runtime cannot track generics, so the object is bridged to the typed\n * interface once here (the single, documented type-state impl seam — same technique tRPC uses).\n */\nfunction makeBuilder(config: DefineAgentConfig): AgentBuilder {\n const runtime = {\n input: (schema: z.ZodType) => makeBuilder({ ...config, input: schema }),\n model: (id: string) => makeBuilder({ ...config, model: id }),\n system: (prompt: string) => makeBuilder({ ...config, system: prompt }),\n reasoningEffort: (effort: ReasoningEffort) =>\n makeBuilder({ ...config, reasoningEffort: effort }),\n context: (value: Record<string, unknown>) => makeBuilder({ ...config, context: value }),\n tool: (tool: CustomTool) => makeBuilder({ ...config, tools: [...(config.tools ?? []), tool] }),\n guardrail: (g: Guardrail) =>\n makeBuilder({ ...config, guardrails: [...(config.guardrails ?? []), g] }),\n guardrails: (gs: readonly Guardrail[]) => makeBuilder({ ...config, guardrails: gs }),\n approval: (toolName: string, options: HumanInTheLoopOptions) =>\n makeBuilder({ ...config, approvals: { ...(config.approvals ?? {}), [toolName]: options } }),\n approvals: (map: Record<string, HumanInTheLoopOptions>) =>\n makeBuilder({ ...config, approvals: map }),\n skills: (selection: SkillsSelection) => makeBuilder({ ...config, skills: selection }),\n settingSources: (sources: readonly SettingSource[]) =>\n makeBuilder({ ...config, settingSources: sources }),\n memory: (settings: MemorySettings) => makeBuilder({ ...config, memory: settings }),\n hooks: (map: Readonly<Record<string, unknown>>) => makeBuilder({ ...config, hooks: map }),\n plugins: (list: readonly unknown[]) => makeBuilder({ ...config, plugins: list }),\n mcp: (servers: McpServersMap) => makeBuilder({ ...config, mcpServers: servers }),\n use: (preset: (b: unknown) => unknown) => preset(runtime),\n build: () => defineAgent(config),\n }\n return runtime as unknown as AgentBuilder\n}\n\n/**\n * Static entry point for the fluent builder. M57: OO surface (`AgentBuilder.create()`) aligned with\n * the SDK's `X.create()` shape — was the free `agent()` function. `AgentBuilder` is a TYPE (the\n * generic interface above) and a VALUE (this const) at once; in type position the interface wins, in\n * value position the const wins — no collision, the same dual-space pattern the SDK uses for `Agent`.\n */\nexport const AgentBuilder = {\n /**\n * Start a fluent agent definition. Chain `.model()` (required) + `.context()` / `.system()` /\n * `.input()` / `.tool()` / `.use()`, then `.build()` to get the branded {@link AgentDefinition}.\n */\n create(): AgentBuilder {\n return makeBuilder({})\n },\n}\n","/**\n * M4 (theokit-ai-first) — the HITL producer: a `pre_tool_call` plugin that pauses the SDK run\n * for a human-in-the-loop tool approval.\n *\n * ADR 0038: this is the ADAPTER seam — it makes the shipped-but-dead `@HumanInTheLoop` decorator\n * FUNCTIONAL by wiring the SDK's OWN async `pre_tool_call` veto hook (which the SDK loop `await`s,\n * so returning a pending Promise genuinely PAUSES the run) to a human approval. It calls no LLM,\n * dispatches no tool, and runs no second loop — the SDK owns all of that.\n *\n * Flow: gated tool about to run → emit an `ApprovalRequiredEvent` (which the translator maps to\n * the ai-sdk `tool-approval-request` chunk) → `await awaitApproval(approvalId)` (resolved by the\n * out-of-band approve route) → allow (`undefined`) or veto (`{ block, message }`, which the SDK\n * surfaces as a tool result the model self-corrects on).\n */\nimport type { HumanInTheLoopOptions } from '../types.js'\n\nimport type { ApprovalRequiredEvent } from './agent-stream-events.js'\n\n/** Minimal shapes mirrored from `@theokit/sdk` (type-only — no runtime import, keeps the SDK peer optional). */\ninterface PreToolCallContext {\n name: string\n args: Record<string, unknown>\n agentId: string\n runId: string\n}\ninterface PreToolCallVeto {\n block: true\n message: string\n}\ninterface PluginContext {\n on(hook: string, handler: (ctx: PreToolCallContext) => unknown): void\n}\ninterface HitlPlugin {\n name: string\n /** SDK `BasePlugin.version` — required by the `@theokit/sdk` Plugin contract. */\n version: string\n /**\n * SDK Plugin discriminator. MUST be `'general'` — the SDK's `isCodePlugin()` gate drops any plugin\n * object lacking `kind: 'general'`, so a `register()`-only object never fires (the HITL veto would\n * silently NOT pause the run). Regression guard for the M14 latent E2E bug.\n */\n kind: 'general'\n register(ctx: PluginContext): void\n}\n\n/**\n * M20 — a settled HITL decision. Structural mirror of the harness's `ApprovalDecision` (the agents\n * package must not import from `theokit` — dependency direction). `awaitApproval` may resolve a bare\n * boolean (legacy) OR this object; the plugin normalizes both.\n */\nexport interface HitlDecision {\n approved: boolean\n reason?: string\n payload?: unknown\n}\n\n/** Injected wiring — the harness (mount-agent) supplies these; the plugin stays pure. */\nexport interface HitlWiring {\n /** Tool name → its `@HumanInTheLoop` config. A tool absent here is NOT gated. */\n gated: Map<string, HumanInTheLoopOptions>\n /** Push the approval-required event into the agent stream (the translator emits the chunk). */\n emit: (event: ApprovalRequiredEvent) => void\n /**\n * Await the human decision for `approvalId`; resolves approve/deny (or timeout). M20 — may resolve\n * a bare boolean (legacy) OR a {@link HitlDecision} carrying an approver `reason` + `payload`.\n */\n awaitApproval: (\n approvalId: string,\n opts: HumanInTheLoopOptions,\n toolName: string,\n ) => Promise<boolean | HitlDecision>\n}\n\n/**\n * Build the HITL `pre_tool_call` plugin. Gated tools pause for approval; others pass through.\n * The returned object is a `@theokit/sdk` `Plugin` (structural — `definePlugin` is an identity).\n */\nexport function createHitlPlugin(wiring: HitlWiring): HitlPlugin {\n return {\n name: 'theokit-hitl',\n version: '1.0.0',\n // `kind: 'general'` is load-bearing — without it the SDK's isCodePlugin() drops this plugin and\n // the HITL veto never fires (the run would proceed WITHOUT waiting for human approval).\n kind: 'general',\n register(ctx) {\n ctx.on('pre_tool_call', async (c): Promise<PreToolCallVeto | undefined> => {\n const opts = wiring.gated.get(c.name)\n if (!opts) return undefined // not gated — allow\n const approvalId = crypto.randomUUID()\n wiring.emit({\n type: 'approval_required',\n callId: approvalId,\n toolName: c.name,\n question: opts.question,\n input: c.args,\n callbackUrl: `approve/${approvalId}`,\n timeoutMs: opts.timeout ?? 300_000,\n // M20 — carry the declared custom-payload schema so the UI knows what to collect.\n ...(opts.payloadSchema !== undefined ? { payloadSchema: opts.payloadSchema } : {}),\n })\n const raw = await wiring.awaitApproval(approvalId, opts, c.name)\n // M20 — normalize the legacy boolean and the decision object to one shape.\n const decision: HitlDecision = typeof raw === 'boolean' ? { approved: raw } : raw\n if (decision.approved) return undefined\n // On denial, surface the approver's reason + payload to the model so it can self-correct.\n let message = `Tool '${c.name}' denied by human approver`\n if (decision.reason) message += `: ${decision.reason}`\n if (decision.payload !== undefined) {\n message += ` (payload: ${JSON.stringify(decision.payload)})`\n }\n return { block: true, message }\n })\n },\n }\n}\n","/**\n * M2 (theokit-ai-first) — the file-convention runtime bridge.\n *\n * Turns a loaded `agents/<name>.ts` module into the M0/M1 canonical `UIMessageStream`:\n *\n * module (defineAgent value | @Agent class) ──compileAgentModule──▶ CompiledAgentOptions\n * CompiledAgentOptions ──createSdkAgentStream──▶ AgentStreamEvent* ──translate──▶ UIMessageChunk*\n *\n * Both agent surfaces converge here (ADR-B1): a `defineAgent` value lowers via\n * `compileAgentDefinition`, an `@Agent`-decorated class lowers via `compileAgent`\n * (which requires the full `@MainLoop` decoration — its existing errors surface for\n * DI-heavy classes). Neither runs an LLM directly — `@theokit/sdk` stays the sole\n * runtime (G2 / sdk-runtime.md); this module only wires its output onto the wire.\n */\nimport type { UIMessageChunk } from 'ai'\n\nimport { type CompiledAgentOptions } from './agent-compiler.js'\nimport type { StreamEvent } from './agent-sse-handler.js'\nimport type { AgentStreamEvent } from './agent-stream-events.js'\nimport { compileAgentDefinition, isAgentDefinition } from './define-agent.js'\nimport { createHitlPlugin, type HitlWiring } from './hitl-plugin.js'\nimport { presentUIMessageStream } from './present-ui-message-stream.js'\nimport { createSdkAgentStream, type RuntimeOverrides } from './sdk-adapter.js'\n\n/** Thrown when an `agents/` file default-exports neither a `defineAgent` value nor an `@Agent` class. */\nexport class AgentDefinitionError extends Error {\n constructor(source: string) {\n super(\n `[@theokit/agents] ${source}: an agents/ file must default-export a ` +\n `defineAgent(...) value or an @Agent-decorated class.`,\n )\n this.name = 'AgentDefinitionError'\n }\n}\n\n/** Unwrap a module namespace `{ default: X }` to `X`; pass a bare value through. */\nfunction extractDefaultExport(mod: unknown): unknown {\n if (typeof mod === 'object' && mod !== null && 'default' in mod) {\n return mod.default\n }\n return mod\n}\n\n/**\n * Compile a loaded `agents/` module to SDK-ready options. Accepts a `defineAgent` value\n * (zero-config surface) OR an `@Agent`-decorated class (advanced surface). `source` labels\n * the fail-fast error (typically the file path).\n *\n * For a class agent, its `@Mixin(...)` toolboxes are gathered (the declared tool-association\n * mechanism, same as `app.ts`/`theokit-plugin.ts`) and instantiated with a no-arg `new` — the\n * zero-config file convention has no DI container. This is what makes a `@HumanInTheLoop`-gated\n * tool on a mixin actually gate through the M2 endpoint (M4): its config reaches `compiled.hitl`.\n */\n/** A capability-built waist: has the two collection fields `applyCapabilities` always seeds. */\nfunction isCompiledAgentOptions(value: unknown): value is CompiledAgentOptions {\n if (typeof value !== 'object' || value === null) return false\n const v = value as Record<string, unknown>\n return Array.isArray(v.tools) && typeof v.agents === 'object' && v.agents !== null\n}\n\nexport function compileAgentModule(mod: unknown, source = 'agent module'): CompiledAgentOptions {\n const def = extractDefaultExport(mod)\n if (isAgentDefinition(def)) {\n return compileAgentDefinition(def)\n }\n // M53 — the decorated-class branch is gone with the decorators. An agent module now default-exports\n // either a `defineAgent(...)` definition or a capability-built `CompiledAgentOptions`.\n if (isCompiledAgentOptions(def)) return def\n throw new AgentDefinitionError(source)\n}\n\n/**\n * Bridge the SDK stream (typed loosely as `StreamEvent`) to the strict `AgentStreamEvent`\n * union the translator consumes. `createSdkAgentStream` yields `AgentStreamEvent`-shaped\n * values (its `type` IS the union tag) — this is the single sanctioned narrowing boundary\n * (G3: via `unknown`); the translator ignores any variant it does not map.\n */\nasync function* asAgentStream(\n events: AsyncIterable<StreamEvent>,\n): AsyncGenerator<AgentStreamEvent> {\n // The two unions do not structurally overlap (StreamEvent's index signature vs the\n // discriminated AgentStreamEvent), so tsc requires the `unknown` hop; this is the one\n // sanctioned narrowing point (the runtime values ARE AgentStreamEvents — same producer).\n for await (const e of events) yield e as unknown as AgentStreamEvent\n}\n\n/**\n * A minimal single-consumer async queue for merging the SDK event stream with the HITL\n * plugin's out-of-band `approval_required` events (M4). Both the SDK-stream pump and the\n * plugin's `emit` push here; the translator drains it. When a gated tool pauses the SDK run\n * (the awaited `pre_tool_call` hook), the pump blocks with no SDK events — but the plugin's\n * approval event is already queued, so the client sees the approval request while paused.\n */\nclass EventQueue<T> {\n #items: T[] = []\n #resolvers: ((v: IteratorResult<T>) => void)[] = []\n #closed = false\n push(item: T): void {\n if (this.#closed) return\n const r = this.#resolvers.shift()\n if (r) r({ value: item, done: false })\n else this.#items.push(item)\n }\n close(): void {\n this.#closed = true\n for (const r of this.#resolvers.splice(0)) r({ value: undefined as never, done: true })\n }\n async *drain(): AsyncGenerator<T> {\n for (;;) {\n if (this.#items.length > 0) {\n yield this.#items.shift() as T\n continue\n }\n if (this.#closed) return\n const next = await new Promise<IteratorResult<T>>((resolve) => this.#resolvers.push(resolve))\n if (next.done) return\n yield next.value\n }\n }\n}\n\n/**\n * Append a `checkpoint_saved` event just before the terminal `done` (M4). The translator breaks on\n * `done`, so the checkpoint MUST precede it to reach the wire. `resumeToken` is the `sessionId` a\n * follow-up request replays through the SDK conversation storage. On a run that ends without a clean\n * `done` (e.g. error — the translator already broke), the trailing emit is inert. The SDK genuinely\n * persisted the turns via its conversation storage; this is the resume-handle signal, not a new store.\n */\nasync function* appendCheckpointSaved(\n source: AsyncGenerator<AgentStreamEvent>,\n sessionId: string,\n): AsyncGenerator<AgentStreamEvent> {\n let emitted = false\n const checkpoint = (): AgentStreamEvent => ({\n type: 'checkpoint_saved',\n checkpointId: crypto.randomUUID(),\n step: 0,\n resumeToken: sessionId,\n })\n for await (const ev of source) {\n if (ev.type === 'done' && !emitted) {\n emitted = true\n yield checkpoint()\n }\n yield ev\n }\n if (!emitted) yield checkpoint()\n}\n\n/** HITL wiring supplied by the harness (mount-agent): the gated-tool map + the approval resolver. */\ninterface StreamHitlOptions {\n gated: HitlWiring['gated']\n awaitApproval: HitlWiring['awaitApproval']\n}\n\ninterface StreamAgentOptions {\n message: string\n sessionId: string\n /** M35 (multimodal) — images to send alongside the text. Absent ⇒ the string send path is unchanged. */\n images?: RuntimeOverrides['images']\n /** Enable human-in-the-loop tool approval (M4). Absent ⇒ the M2 non-HITL path, byte-unchanged. */\n hitl?: StreamHitlOptions\n /**\n * theokit-file-based-config (EC-1) — the app root `cwd` the SDK resolves `.theokit/` against when\n * `settingSources` is active. The framework boundary (`mountAgent`) threads its resolved\n * `projectRoot` here so discovery points at the app root, NOT `process.cwd()`. Absent ⇒ no `local.cwd`.\n */\n cwd?: RuntimeOverrides['cwd']\n /**\n * SDK 4.0 (SE40) — root of the native `.jsonl` session transcript. The framework boundary\n * (`mountAgent`) threads the resolved app root here so sessions persist per-app; absent ⇒ the SDK\n * default (`~/.theokit`).\n */\n baseDir?: RuntimeOverrides['baseDir']\n /**\n * The request's abort signal (M4). On client disconnect, the HITL merge queue is closed so the\n * detached SDK pump stops buffering (bounded memory) and the client stream terminates at once.\n * The paused SDK run itself is released by the approval timeout, not instantly — a durable-store\n * follow-up. The non-HITL path is pull-based and already tears down on the consumer's return.\n */\n signal?: AbortSignal\n}\n\n/**\n * Run a compiled agent and yield the M0/M1 `UIMessageStream` chunks. `apiKey` is resolved by the\n * caller (`resolveProvider`). One `textId` per run (G8: `crypto.randomUUID`). When `hitl` is\n * supplied (M4), a HITL `pre_tool_call` plugin pauses the run for gated tools — the pause is the\n * SDK's own awaited hook, never a second loop (ADR 0038).\n */\nexport function streamAgentUIMessages(\n compiled: CompiledAgentOptions,\n apiKey: string,\n input: StreamAgentOptions,\n): AsyncGenerator<UIMessageChunk> {\n const textId = crypto.randomUUID()\n const overrides: RuntimeOverrides = {}\n // theokit-file-based-config (EC-1) — thread the app-root cwd so the adapter merges it into\n // `local.cwd` (sdk-adapter `overrides.cwd`), pointing `.theokit/` discovery at the app root.\n if (input.cwd !== undefined) overrides.cwd = input.cwd\n // SDK 4.0 (SE40) — thread the app-root session dir so the SDK writes the native transcript per-app.\n if (input.baseDir !== undefined) overrides.baseDir = input.baseDir\n // M35 (multimodal) — thread images so the adapter sends the structured `{ text, images }` form.\n if (input.images !== undefined) overrides.images = input.images\n\n let source: AsyncGenerator<AgentStreamEvent>\n if (!input.hitl || input.hitl.gated.size === 0) {\n // M2 non-HITL path — unchanged.\n const events = createSdkAgentStream(\n compiled,\n compiled.tools,\n apiKey,\n overrides,\n )(input.message, input.sessionId)\n source = asAgentStream(events)\n } else {\n // M4 HITL path — inject the plugin + merge its approval events with the SDK stream.\n const queue = new EventQueue<AgentStreamEvent>()\n // On client disconnect, stop buffering into the detached pump's queue (bounded memory) and\n // terminate the client stream at once; `EventQueue.push` no-ops once closed.\n input.signal?.addEventListener(\n 'abort',\n () => {\n queue.close()\n },\n { once: true },\n )\n const plugin = createHitlPlugin({\n gated: input.hitl.gated,\n emit: (e) => {\n queue.push(e)\n },\n awaitApproval: input.hitl.awaitApproval,\n })\n const sdkStream = createSdkAgentStream(compiled, compiled.tools, apiKey, {\n ...overrides,\n // The HITL plugin is a structural @theokit/sdk Plugin (createHitlPlugin returns the\n // { name, register } shape); the RuntimeOverrides.plugins union is widened at the SDK edge.\n plugins: [plugin] as unknown as RuntimeOverrides['plugins'],\n })(input.message, input.sessionId)\n // Pump the SDK stream into the shared queue; close when it ends. A thrown SDK stream (e.g.\n // dispose() rejecting) is SURFACED as an `error` event into the queue — never a `void`-IIFE\n // unhandled rejection (mirrors sdk-adapter's mergeDeltaStream capture), so the client still gets\n // a well-formed error chunk + a terminated stream instead of a silent clean end.\n void (async () => {\n try {\n for await (const e of sdkStream) queue.push(e as unknown as AgentStreamEvent)\n } catch (err) {\n queue.push({\n type: 'error',\n code: 'SDK_STREAM_ERROR',\n message: err instanceof Error ? err.message : String(err),\n retryable: false,\n })\n } finally {\n queue.close()\n }\n })()\n source = queue.drain()\n }\n\n // M4 @Checkpoint: emit `checkpoint_saved` (→ `data-checkpoint`) ONLY when the agent opted into a\n // durable checkpoint (`@Checkpoint({ storage: 'filesystem' })`) — the theokit-side signal that the\n // client may resume. SDK 4.0 (SE40) persists EVERY session to the native `.jsonl` transcript, so\n // resume is available under the hood; this gate keeps the pre-4.0 emit contract unchanged (G10:\n // don't retroactively promise a resume handle the agent never asked to advertise).\n const durableCheckpoint = compiled.checkpoint?.storage === 'filesystem'\n const events = durableCheckpoint ? appendCheckpointSaved(source, input.sessionId) : source\n return presentUIMessageStream(events, { textId })\n}\n","/**\n * M9 (theokit-ai-first) — guardrail contract + typed errors.\n *\n * ADR-0040 § D2: guardrails are a HOME/BOUNDARY concern (filter user input before the SDK,\n * filter model output before the client). They REUSE the SDK runtime — this module makes zero\n * LLM calls. A guard reports one of three actions; the pipeline (`pipeline.ts`) enforces them.\n */\n\n/** What a guard decided for a piece of text. */\nexport type GuardrailAction = 'allow' | 'block' | 'redact'\n\n/**\n * The result of a single guard check.\n * - `allow` — text passes untouched.\n * - `block` — the pipeline throws {@link GuardrailViolationError}; the run stops fail-fast.\n * - `redact` — the pipeline replaces the text with {@link GuardrailResult.text} and continues.\n */\nexport interface GuardrailResult {\n action: GuardrailAction\n /** Human-readable reason — required in spirit for `block`, surfaced in the thrown error. */\n reason?: string\n /** The transformed text — present (and used) only when `action === 'redact'`. */\n text?: string\n}\n\n/**\n * A guardrail. A guard MAY inspect input (before the model), output (after the model), or both.\n * A guard that omits a phase hook is skipped for that phase.\n */\nexport interface Guardrail {\n readonly name: string\n checkInput?(text: string): GuardrailResult | Promise<GuardrailResult>\n checkOutput?(text: string): GuardrailResult | Promise<GuardrailResult>\n}\n\n/** Which boundary phase a violation happened in. */\nexport type GuardrailPhase = 'input' | 'output'\n\n/** Thrown (fail-fast) when a guard returns `action: 'block'`. Typed per error-handling.md. */\nexport class GuardrailViolationError extends Error {\n constructor(\n public readonly guardName: string,\n public readonly phase: GuardrailPhase,\n public readonly reason: string,\n ) {\n super(`Guardrail \"${guardName}\" blocked ${phase}: ${reason}`)\n this.name = 'GuardrailViolationError'\n }\n}\n\n/** Thrown when {@link costGuard}'s cumulative token budget is exceeded. */\nexport class CostBudgetExceededError extends Error {\n constructor(\n public readonly usedTokens: number,\n public readonly maxTokens: number,\n ) {\n super(`Cost budget exceeded: ${usedTokens} > ${maxTokens} tokens`)\n this.name = 'CostBudgetExceededError'\n }\n}\n","/**\n * M9 (theokit-ai-first) — built-in guardrail detectors.\n *\n * Each factory returns a {@link Guardrail}. None call an LLM (G2 / sdk-runtime.md):\n * `outputModeration` takes an INJECTED predicate so the provider call (if any) lives in the\n * consumer's code, never in `packages/`.\n */\nimport { CostBudgetExceededError, type Guardrail, type GuardrailResult } from './types.js'\n\n/** Rough token estimate — ~4 chars/token (documented heuristic; exact counting is provider-specific). */\nexport function estimateTokens(text: string): number {\n return Math.ceil(text.length / 4)\n}\n\n/**\n * Known prompt-injection / jailbreak trigger phrases (lowercased). Matched via normalized\n * substring (not regex) — ReDoS-free by construction, since the guard runs on UNTRUSTED input\n * (security is never traded for terseness — parsimony-ladder § Never on the chopping block).\n */\nconst INJECTION_PHRASES: readonly string[] = [\n 'previous instructions', // \"ignore/disregard [all|the] previous instructions\"\n 'disregard the above',\n 'you are now dan',\n 'system prompt', // \"reveal your/the system prompt\"\n 'no restrictions',\n 'without restrictions',\n 'no rules',\n 'override your',\n]\n\nexport interface PromptInjectionOptions {\n /** Additional project-specific trigger phrases (compared lowercased, substring). */\n extra?: readonly string[]\n}\n\n/** Collapse whitespace + lowercase so spacing/casing tricks do not evade the phrase match. */\nfunction normalizeForMatch(text: string): string {\n return text.toLowerCase().replace(/\\s+/g, ' ')\n}\n\n/** Blocks input containing a known injection trigger phrase. */\nexport function promptInjectionDetector(options: PromptInjectionOptions = {}): Guardrail {\n const phrases = [...INJECTION_PHRASES, ...(options.extra ?? []).map((p) => p.toLowerCase())]\n return {\n name: 'prompt-injection',\n checkInput(text): GuardrailResult {\n const normalized = normalizeForMatch(text)\n for (const phrase of phrases) {\n if (normalized.includes(phrase)) {\n return { action: 'block', reason: `prompt injection phrase matched: \"${phrase}\"` }\n }\n }\n return { action: 'allow' }\n },\n }\n}\n\n// PII patterns. CPF (Brazilian): 11 digits, optionally punctuated. Email + international phone.\nconst CPF = /\\b\\d{3}\\.?\\d{3}\\.?\\d{3}-?\\d{2}\\b/g\nconst EMAIL = /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b/g\n// A run of 9–15 digit-ish characters (single bounded quantifier — ReDoS-safe, low complexity).\nconst PHONE = /\\+?\\d[\\d\\s()-]{7,13}\\d/g\n\nexport interface PiiOptions {\n /** When true (default), matched PII is replaced with `[REDACTED]`. */\n redact?: boolean\n /** Placeholder token. Default `[REDACTED]`. */\n placeholder?: string\n}\n\n/** Redacts CPF, email and phone numbers from input. */\nexport function piiDetector(options: PiiOptions = {}): Guardrail {\n const placeholder = options.placeholder ?? '[REDACTED]'\n return {\n name: 'pii',\n checkInput(text): GuardrailResult {\n let redacted = text\n // Order matters: email before phone (an email's digits must not be eaten by PHONE).\n redacted = redacted.replace(EMAIL, placeholder)\n redacted = redacted.replace(CPF, placeholder)\n redacted = redacted.replace(PHONE, placeholder)\n if (redacted === text) return { action: 'allow' }\n return { action: 'redact', text: redacted, reason: 'PII detected and redacted' }\n },\n }\n}\n\n// Zero-width + bidi-override control characters used to hide/obfuscate text.\n// U+200B–U+200D (zero-width space/ZWNJ/ZWJ), U+FEFF (ZWNBSP/BOM), U+202A–U+202E (bidi\n// embeddings/overrides), U+2066–U+2069 (bidi isolates). Escapes (not literals) keep lint clean.\nconst OBFUSCATION_CHARS = /[\\u200B-\\u200D\\uFEFF\\u202A-\\u202E\\u2066-\\u2069]/g\n\n/** NFKC-normalizes and strips zero-width / RTL-override characters. */\nexport function unicodeNormalizer(): Guardrail {\n return {\n name: 'unicode-normalizer',\n checkInput(text): GuardrailResult {\n const cleaned = text.normalize('NFKC').replace(OBFUSCATION_CHARS, '')\n if (cleaned === text) return { action: 'allow' }\n return { action: 'redact', text: cleaned, reason: 'obfuscation characters normalized' }\n },\n }\n}\n\nexport interface CostGuardOptions {\n /** Cumulative input-token budget per guard instance (per session — one guard per run). */\n maxTokens: number\n}\n\n/**\n * Enforces a cumulative input-token budget. Stateful: one instance accumulates across the calls\n * it sees within a run. Throws {@link CostBudgetExceededError} fail-fast when exceeded.\n */\nexport function costGuard(options: CostGuardOptions): Guardrail {\n let used = 0\n return {\n name: 'cost-guard',\n // Returns a Promise explicitly (not `async`) so a budget breach REJECTS uniformly — never a\n // sync throw — safe for direct callers and for the pipeline's `await g.checkInput()`.\n checkInput(text): Promise<GuardrailResult> {\n used += estimateTokens(text)\n if (used > options.maxTokens) {\n return Promise.reject(new CostBudgetExceededError(used, options.maxTokens))\n }\n return Promise.resolve({ action: 'allow' })\n },\n }\n}\n\nexport interface OutputModerationOptions {\n /**\n * Injected predicate — returns `true` when the text is prohibited. The provider call (OpenAI\n * moderation API, a classifier, etc.) lives HERE, in consumer code — never inside `packages/`\n * (G2). Keeps the module runtime-free.\n */\n moderate: (text: string) => boolean | Promise<boolean>\n}\n\n/** Blocks model output the injected predicate flags as prohibited. */\nexport function outputModeration(options: OutputModerationOptions): Guardrail {\n return {\n name: 'output-moderation',\n async checkOutput(text): Promise<GuardrailResult> {\n const flagged = await options.moderate(text)\n return flagged\n ? { action: 'block', reason: 'output flagged by moderation predicate' }\n : { action: 'allow' }\n },\n }\n}\n","/**\n * M9 (theokit-ai-first) — the guardrail pipeline: apply guards in order at a boundary phase.\n *\n * Fail-fast (error-handling.md): a `block` throws {@link GuardrailViolationError} immediately.\n * A `redact` threads the transformed text into the next guard. Independent of the SDK runtime —\n * this runs at the framework boundary, before/after the SDK does its work.\n */\nimport { type Guardrail, GuardrailViolationError } from './types.js'\n\n/**\n * Run every guard's `checkInput` in order against `text`. Returns the (possibly redacted) text.\n * Throws {@link GuardrailViolationError} on the first `block`. Guards without `checkInput` are skipped.\n */\nexport async function runInputGuards(text: string, guards: readonly Guardrail[]): Promise<string> {\n let current = text\n for (const g of guards) {\n if (!g.checkInput) continue\n const r = await g.checkInput(current)\n if (r.action === 'block') {\n throw new GuardrailViolationError(g.name, 'input', r.reason ?? 'blocked')\n }\n if (r.action === 'redact' && r.text !== undefined) current = r.text\n }\n return current\n}\n\n/**\n * Run every guard's `checkOutput` in order against `text`. Returns the (possibly redacted) text.\n * Throws {@link GuardrailViolationError} on the first `block`. Guards without `checkOutput` are skipped.\n */\nexport async function runOutputGuards(text: string, guards: readonly Guardrail[]): Promise<string> {\n let current = text\n for (const g of guards) {\n if (!g.checkOutput) continue\n const r = await g.checkOutput(current)\n if (r.action === 'block') {\n throw new GuardrailViolationError(g.name, 'output', r.reason ?? 'blocked')\n }\n if (r.action === 'redact' && r.text !== undefined) current = r.text\n }\n return current\n}\n","/**\n * M9 — apply output guards to a stream (ADR-0040 § D2).\n *\n * Generic over the event type (no dependency on the bridge's `StreamEvent` — keeps this module\n * pure per G1). When any guard defines `checkOutput`, the stream is BUFFERED: every event is held,\n * the accumulated text is moderated, and only on pass are the events replayed. A `block` throws\n * {@link GuardrailViolationError} BEFORE any event reaches the client — the honest \"blocked before\n * reaching the client\" semantics. Streaming is traded for safety only when an output guard exists;\n * with none, this is a transparent pass-through (streaming preserved).\n */\nimport { runOutputGuards } from './pipeline.js'\nimport type { Guardrail } from './types.js'\n\n/**\n * Wrap `inner`, moderating its accumulated text output.\n *\n * @param inner the source stream (yields events, returns a result).\n * @param guards the guardrails; only those with `checkOutput` participate.\n * @param extractText pulls the human-visible text out of an event (return `undefined` for non-text).\n */\nexport async function* moderateOutputStream<E, R>(\n inner: AsyncGenerator<E, R>,\n guards: readonly Guardrail[],\n extractText: (event: E) => string | undefined,\n): AsyncGenerator<E, R> {\n const hasOutputGuard = guards.some((g) => g.checkOutput != null)\n // Fast path: nothing to moderate — pass through, streaming preserved.\n if (!hasOutputGuard) return yield* inner\n\n const buffered: E[] = []\n let accumulated = ''\n let step = await inner.next()\n while (!step.done) {\n const event = step.value\n const text = extractText(event)\n if (text !== undefined) accumulated += text\n buffered.push(event)\n step = await inner.next()\n }\n\n // Moderate the FULL output before emitting anything — throws on block.\n await runOutputGuards(accumulated, guards)\n\n for (const event of buffered) yield event\n return step.value\n}\n","/**\n * TranscriptCompactionStrategy — a named, callable transcript-compaction authoring layer\n * (Strategy pattern, V4-F). Mirrors `ReflectionStrategy`/`LoopStrategy`: interface\n * + zod config schema + a `'token-budget'` default + `resolveCompactionStrategy`.\n *\n * The `'token-budget'` strategy DELEGATES to the SDK's `compactTranscript` (ADR D2 /\n * G2 / sdk-runtime.md — the SDK owns the algorithm; agents owns the named interface;\n * no reimplementation). Per ADR D1 it is CALLABLE by the app (exposed as\n * `AgentRunner.compaction`), NOT auto-invoked by the reflective loop — the SDK owns\n * per-turn context, so the app decides WHEN to compact and supplies the `summarize`\n * callback (its own LLM). EC-6: consumers whose transcript rows carry roles outside\n * the SDK's `CompressibleMessage` union (e.g. `'tool'`) cast at the call site, exactly\n * as the SDK's own type contract requires.\n *\n * referencia: knowledge-base/references/mastra compaction (named strategy over a budget).\n */\nimport { compactTranscript, type CompressibleMessage } from '@theokit/sdk/compaction'\nimport { z } from 'zod'\n\nexport type { CompressibleMessage }\n\n/** Token budget mirrored from theocode's proven `DEFAULT_KEEP_TOKENS` (server/lib/compaction.ts). */\nexport const DEFAULT_KEEP_TOKENS = 8000\n\n/**\n * App-supplied summarizer: collapse the older window into one turn (the app's LLM).\n * Signature matches the SDK `compactTranscript` contract — receives the older window\n * AND the (optionally overridden) summary template.\n */\nexport type Summarize = (\n older: CompressibleMessage[],\n template: string,\n) => Promise<CompressibleMessage>\n\n/**\n * Per-call options for {@link TranscriptCompactionStrategy.compact} — a faithful\n * pass-through of the SDK `CompactTranscriptOptions` knobs the app controls. Defaults\n * are the SDK's, EXCEPT `failSafe` which defaults `true` here: a thrown `summarize`\n * returns the ORIGINAL transcript + a structured warn instead of losing it — compaction\n * is an optimization, never a cause of data loss (error-handling discipline). The app\n * passes `failSafe: false` to opt into fail-fast propagation.\n */\nexport interface CompactionCallOptions {\n /** Override the strategy's configured `keepTokens` for this call. */\n readonly keepTokens?: number\n /** Summarize the older window; if omitted, the SDK drops it (its documented contract). */\n readonly summarize?: Summarize\n /** Checkpoint marker (SDK default when omitted). */\n readonly marker?: string\n /** Summary template passed to `summarize` (SDK default when omitted). */\n readonly summaryTemplate?: string\n /** When true (DEFAULT here), a thrown `summarize` returns the original transcript + a warn. */\n readonly failSafe?: boolean\n}\n\n/** A named, callable compaction strategy. Pure of I/O except the delegated SDK call. */\nexport interface TranscriptCompactionStrategy {\n /** Strategy identifier (e.g. `'token-budget'`). */\n readonly name: string\n /** The configured token budget (from `@Compaction` / `.compaction()` / default). */\n readonly keepTokens: number\n /**\n * Compact `messages` to the (optionally overridden) token budget via the SDK's\n * `compactTranscript`. Returns the compacted transcript; never mutates the input.\n */\n compact(\n messages: CompressibleMessage[],\n options?: CompactionCallOptions,\n ): Promise<CompressibleMessage[]>\n}\n\n/**\n * Serializable config for a TranscriptCompactionStrategy (SSoT per type-safety.md / G3).\n * `keepTokens` is REQUIRED for `'token-budget'` (EC-2 / G10 — no silent degradation\n * to the SDK's turn-count `keepRecent` default; the strategy is named for token budget).\n */\nexport const compactionStrategyConfigSchema = z.object({\n name: z.literal('token-budget'),\n keepTokens: z.number().int().positive(),\n})\n\nexport type CompactionStrategyConfig = z.infer<typeof compactionStrategyConfigSchema>\n\n/**\n * Resolve a `@Compaction` / `.compaction()` declaration to a concrete strategy.\n * Throws (Zod) on an unknown name or a missing/invalid `keepTokens` (EC-2/EC-5 —\n * fail-fast, mirrors `resolveLoopStrategy`). The returned strategy's `compact`\n * delegates to `compactTranscript`, defaulting `keepTokens` to the configured value.\n */\nexport function resolveCompactionStrategy(\n name: string,\n config: { keepTokens?: number },\n): TranscriptCompactionStrategy {\n const cfg = compactionStrategyConfigSchema.parse({ name, keepTokens: config.keepTokens })\n return {\n name: cfg.name,\n keepTokens: cfg.keepTokens,\n compact: (messages, options) =>\n compactTranscript(messages, {\n keepTokens: options?.keepTokens ?? cfg.keepTokens,\n summarize: options?.summarize,\n marker: options?.marker,\n summaryTemplate: options?.summaryTemplate,\n // Default-safe: a thrown summarize keeps the transcript (app opts out via failSafe:false).\n failSafe: options?.failSafe ?? true,\n }),\n }\n}\n\n/**\n * The default `'token-budget'` strategy (what `@Compaction('token-budget')` without\n * an explicit budget resolves to). Carries {@link DEFAULT_KEEP_TOKENS}; the app may\n * override per call via `compact(messages, { keepTokens })`.\n */\nexport const tokenBudgetCompactionStrategy: TranscriptCompactionStrategy =\n resolveCompactionStrategy('token-budget', { keepTokens: DEFAULT_KEEP_TOKENS })\n","/**\n * LoopStrategy — the per-round terminal-decision contract that gives runtime to\n * `@MainLoop({ strategy })`.\n *\n * V4-A proved `@MainLoop`'s `strategy` field was metadata-only (declared +\n * compiled, never executed). This module is the foundation Phase 2's\n * `runReflectiveLoop` branches on. Modeled on Mastra's `agentic-loop`/`stopWhen`\n * (inverted) + `maxSteps` ceiling — NOT Spring's per-call Advisor (plan ADR D1).\n * Config is Zod-validated so an invalid `maxIterations` fails fast at resolve\n * time, never as a silent infinite loop at runtime (plan ADR D3).\n *\n * referencia: knowledge-base/references/mastra agentic-loop/index.ts (stopWhen + maxSteps).\n */\nimport { z } from 'zod'\n\n/** Why a single round ended (or, for the V4-D terminals, why the whole loop ended). */\nexport type LoopFinishReason =\n | 'tool-calls'\n | 'stop'\n | 'length'\n | 'error'\n // V4-D outer-loop terminals — set by runReflectiveLoop, not derived from a single round:\n | 'step_limit' // hit the maxIterations ceiling while the round still wanted to continue\n | 'no_progress' // the agent repeated the same round signature for K consecutive rounds\n\n/** Value object describing one round's result. */\nexport interface LoopOutcome {\n /** Why the round ended (the continuation signal). */\n readonly finishReason: LoopFinishReason\n /** 1-indexed round number that just completed. */\n readonly round: number\n /** Tool calls executed during the round (V4-N: `id` correlates the call to its result). */\n readonly toolCalls: readonly { id: string; name: string; input: unknown; output: string }[]\n /** Accumulated assistant text for the round. */\n readonly responseText: string\n}\n\n/** The terminal-decision contract. `shouldContinue` is the inverted `stopWhen`. */\nexport interface LoopStrategy {\n /**\n * The strategy name, surfaced in `finalize`/logs. M54 relaxes this from\n * `MainLoopMeta['strategy']` to `string` so a caller-injected `.loopStrategy(custom)` can name\n * itself freely — the three built-ins keep their names, but the seam is no longer union-locked.\n * The INTERNAL resolution (`loopStrategyConfigSchema`) still validates the three built-in names\n * via `z.enum`; a custom never passes through it (it enters by the seam, not by name).\n */\n readonly name: string\n /** Hard ceiling on rounds — guarantees termination (enforced by the runner since M54). */\n readonly maxIterations: number\n /** True ⇒ re-enter for another round; false ⇒ terminate. The runner caps it at `maxIterations`. */\n shouldContinue(outcome: LoopOutcome): boolean\n}\n\n/** Default round ceiling when `@MainLoop` declares no `maxIterations` (EC-3: finite, never Infinity). */\nexport const DEFAULT_MAX_ITERATIONS = 8\n\n/** The ceiling contract every strategy must satisfy: a finite integer ≥ 1. SSoT for the rule. */\nconst maxIterationsSchema = z.number().int().min(1)\n\n/** Serializable config for a LoopStrategy. SSoT per type-safety.md (ADR D3). */\nexport const loopStrategyConfigSchema = z.object({\n name: z.enum(['simple-chat', 'plan-act-reflect', 'react']),\n maxIterations: maxIterationsSchema,\n})\n\n/**\n * M54 — validate a CUSTOM strategy's ceiling at authoring time (`AgentRunnerBuilder.loopStrategy`).\n * The three built-ins get this rule for free via {@link loopStrategyConfigSchema}; a custom bypasses\n * that path, and `maxIterations: Infinity` (or `NaN`/`0`/negative/non-integer) would defeat the\n * runner's `round < maxIterations` ceiling — an infinite loop, the exact failure the seam must not\n * reopen. Fail fast, typed, at the boundary (`rules/error-handling.md` § 2).\n *\n * @throws {Error} when `maxIterations` is not a finite integer ≥ 1, with a message naming the value.\n */\nexport function assertValidCustomLoopStrategy(strategy: LoopStrategy): void {\n const result = maxIterationsSchema.safeParse(strategy.maxIterations)\n if (!result.success) {\n throw new Error(\n `loopStrategy: maxIterations inválido (${String(strategy.maxIterations)}) — ` +\n 'deve ser um inteiro finito ≥ 1 (senão o teto round < maxIterations nunca termina)',\n )\n }\n}\n\nexport type LoopStrategyConfig = z.infer<typeof loopStrategyConfigSchema>\n\n/**\n * Map a `@MainLoop` strategy + ceiling to a concrete {@link LoopStrategy}.\n *\n * - `simple-chat` ⇒ exactly one round (`shouldContinue` always false).\n * - `react` ⇒ continue while the round ended on `tool-calls` AND the ceiling has not been reached\n * (`round < maxIterations`) — the reflection is `noop` (no feedback), so the strategy IS the gate.\n * - `plan-act-reflect` ⇒ DEFER continuation to the reflection (V4-S): `shouldContinue` is\n * `round < maxIterations`, so the loop continues iff the (custom) `ReflectionStrategy` returns\n * `continue: true` within the ceiling — letting a reflection extend even a terminal (`stop`)\n * round (e.g. \"you answered without editing — make the edit now\"). Backward-compatible with the\n * default `ladderReflectionStrategy`, which itself returns `continue: true` only on `tool-calls`,\n * so the observable behavior with the shipped ladder is unchanged.\n *\n * Throws (Zod) when `maxIterations < 1` — fail fast, never a silent infinite loop.\n */\nexport function resolveLoopStrategy(\n // M54 (D2): accepts `string`, but `loopStrategyConfigSchema` (`z.enum`) still admits ONLY the three\n // built-in names — an unknown name throws here (fail-fast), never resolving. A custom strategy\n // never reaches this function; it enters through `AgentRunnerBuilder.loopStrategy(obj)`.\n strategy: string,\n maxIterations: number = DEFAULT_MAX_ITERATIONS,\n): LoopStrategy {\n const cfg = loopStrategyConfigSchema.parse({ name: strategy, maxIterations })\n\n if (cfg.name === 'simple-chat') {\n return { name: cfg.name, maxIterations: cfg.maxIterations, shouldContinue: () => false }\n }\n\n if (cfg.name === 'plan-act-reflect') {\n // V4-S: defer to the reflection — the ceiling is the only hard bound; the ReflectionStrategy\n // decides whether to continue (so a custom strategy can extend a terminal round).\n return {\n name: cfg.name,\n maxIterations: cfg.maxIterations,\n shouldContinue: (outcome: LoopOutcome): boolean => outcome.round < cfg.maxIterations,\n }\n }\n\n return {\n name: cfg.name,\n maxIterations: cfg.maxIterations,\n shouldContinue: (outcome: LoopOutcome): boolean =>\n outcome.finishReason === 'tool-calls' && outcome.round < cfg.maxIterations,\n }\n}\n","/**\n * ReflectionStrategy — composes INTO the loop between rounds (the loop calls\n * `reflect()` then `LoopStrategy.shouldContinue()`).\n *\n * `'plan-act-reflect'` resolves to the `'ladder'` default shipped here; a custom\n * strategy may be supplied (OCP — plan Drawback #2). `reflect()` is pure (no\n * I/O, no LLM) — it inspects the round's outcome and returns feedback to inject\n * into the next round's prompt plus a `continue` hint. The hard round ceiling\n * lives in `LoopStrategy.shouldContinue` (maxIterations), NOT here.\n *\n * referencia: knowledge-base/references/mastra agentic-loop/index.ts (onIterationComplete → { feedback, continue }).\n */\nimport { z } from 'zod'\n\nimport type { LoopOutcome } from './loop-strategy.js'\n\n/** Result of reflecting on a completed round. */\nexport interface ReflectionResult {\n /** Optional text prepended to the next round's prompt. */\n readonly feedback?: string\n /** Hint: should the loop reflect-and-continue? (the ceiling still bounds it) */\n readonly continue: boolean\n}\n\n/**\n * V4-K: a per-run mutable scratch bag threaded to every `reflect()` call within one\n * `runReflectiveLoopStream` run, so a STATEFUL strategy can accumulate cumulative state\n * (counters, one-shot flags) across rounds. The framework owns the lifecycle (creates\n * one per run, passes the SAME ref each round) but writes NOTHING into it — the strategy\n * owns the contents. Generic by design: the framework cannot know app semantics (e.g.\n * what an \"edit\" is). A consumer narrows it locally (`ctx as MyState`).\n */\nexport type ReflectionContext = Record<string, unknown>\n\n/** Pluggable between-round reflection. Pure — never performs I/O. */\nexport interface ReflectionStrategy {\n /** Strategy identifier (e.g. `'ladder'`). */\n readonly name: string\n /**\n * Inspect the round outcome; return feedback + continue hint. `ctx` (V4-K) is the\n * per-run mutable scratch — optional for backward compatibility (shipped strategies\n * ignore it; stateful custom strategies accumulate in it across rounds).\n */\n reflect(outcome: LoopOutcome, ctx?: ReflectionContext): ReflectionResult\n}\n\n/** Serializable config for a ReflectionStrategy. SSoT per type-safety.md (ADR D3). */\nexport const reflectionStrategyConfigSchema = z.object({\n name: z.string().min(1),\n})\n\nexport type ReflectionStrategyConfig = z.infer<typeof reflectionStrategyConfigSchema>\n\n/**\n * The default `'ladder'` reflection (what `'plan-act-reflect'` resolves to).\n *\n * Continues with bounded templated feedback while the round ended on\n * `tool-calls`; terminates on any terminal `finishReason` (`stop`/`error`/\n * `length`). The feedback is a short fixed template (bounded — EC-5; context\n * growth is the SDK's responsibility, not the loop's).\n */\nexport const ladderReflectionStrategy: ReflectionStrategy = {\n name: 'ladder',\n reflect(outcome: LoopOutcome): ReflectionResult {\n if (outcome.finishReason === 'tool-calls') {\n return {\n feedback: `Tool results received (round ${outcome.round}). Reflect on whether the goal is met; if not, refine the approach and continue.`,\n continue: true,\n }\n }\n return { continue: false }\n },\n}\n\n/**\n * No-op reflection for `'react'` (multi-round WITHOUT reflection feedback).\n *\n * Returns `{ continue: true }` (no feedback) so the round-continuation decision\n * is delegated entirely to `LoopStrategy.shouldContinue` (i.e. `react` loops\n * while `finishReason === 'tool-calls'` under the ceiling). NOTE: the plan's\n * pseudo-code (Files-to-edit) sketched `{ continue: false }`, which would make\n * `react` single-shot — that contradicts the plan's own Deep Dives (\"`react`\n * still multi-rounds while finishReason==='tool-calls'\"); `continue: true` is\n * the behavior the resolved react LoopStrategy requires.\n */\nexport const noopReflectionStrategy: ReflectionStrategy = {\n name: 'noop',\n reflect(): ReflectionResult {\n return { continue: true }\n },\n}\n","/**\n * Shared delegation value types + typed errors.\n *\n * Extracted from `agent-orchestrator.ts` so BOTH the orchestrator (`delegate`)\n * and the loop driver (`loop/run-reflective-loop.ts`) can import them WITHOUT a\n * cycle (orchestrator → loop → delegation-types; orchestrator → delegation-types;\n * delegation-types has only a TYPE-ONLY import of `LoopFinishReason` (erased at\n * runtime → no runtime edge; `loop-strategy.ts` is a leaf importing only zod, so\n * no cycle — Acyclic Dependencies Principle, G1).\n * `agent-orchestrator.ts` re-exports these for backward compatibility.\n */\nimport type { LoopFinishReason } from '../loop/loop-strategy.js'\n\nexport interface DelegationResult {\n response: string\n toolCalls: { id: string; name: string; input: unknown; output: string }[]\n cost: number\n tokens: number\n /** V4-N: split token usage accumulated across rounds (`tokens` stays as the total). Absent for the single-shot path. */\n tokensInput?: number\n tokensOutput?: number\n /** V4-O: reasoning/cache token buckets accumulated across rounds (0 on any loop-driven run; the loop seeds them). Optional for type compat. */\n reasoningTokens?: number\n cacheReadTokens?: number\n cacheWriteTokens?: number\n /** Rounds the reflective loop ran (set by `runReflectiveLoop`; absent for the single-shot path). */\n rounds?: number\n /**\n * The loop's terminal reason (set by `runReflectiveLoop`): `'stop'`/`'length'` natural end,\n * `'step_limit'` (hit maxIterations), `'no_progress'` (stuck). Absent for the single-shot path. (V4-D)\n */\n finishReason?: LoopFinishReason\n}\n\nexport class BudgetExceededError extends Error {\n constructor(\n public readonly agentName: string,\n public readonly actualCost: number,\n public readonly budgetLimit: number,\n ) {\n super(\n `Agent \"${agentName}\" exceeded budget: $${actualCost.toFixed(4)} > $${budgetLimit.toFixed(4)}`,\n )\n this.name = 'BudgetExceededError'\n }\n}\n\nexport class DelegationError extends Error {\n constructor(\n public readonly agentName: string,\n public readonly cause: unknown,\n ) {\n super(\n `Delegation to agent \"${agentName}\" failed: ${cause instanceof Error ? cause.message : String(cause)}`,\n )\n this.name = 'DelegationError'\n }\n}\n","/**\n * runReflectiveLoop — the multi-round reflective driver that gives `@MainLoop`\n * its runtime (closes the metadata-only gap, V4-A / plan ADR D2).\n *\n * Per round it consumes ONE SDK stream turn (the model call stays in the SDK —\n * the factory is `createSdkAgentStream(...)`, injected for testability), derives\n * a {@link LoopOutcome}, asks the {@link ReflectionStrategy} for feedback, then\n * the {@link LoopStrategy} whether to continue. Bounded by `maxIterations`\n * (forced terminal at the ceiling — never an infinite loop). The bridge owns the\n * loop; the SDK owns the model call (sdk-runtime.md / ADR 0031 — no second runtime).\n *\n * `runReflectiveLoop` is INTERNAL (not re-exported from the package barrel,\n * Drawback #4) — consumed by `delegate()` (T2.2) and `AgentRunner` (T3.1).\n *\n * referencia: knowledge-base/references/mastra agent.ts (re-enter the loop with feedback).\n */\n// V4-P: type-only import (erased at runtime) so the loop stays SDK-optional; the `withRetry`\n// VALUE is dynamic-imported inside consumeOneRound only when `retry` is configured.\nimport type { RetryOptions } from '@theokit/sdk/retry'\n\nimport type { StreamEvent } from '../bridge/agent-sse-handler.js'\nimport {\n BudgetExceededError,\n type DelegationResult,\n DelegationError,\n} from '../bridge/delegation-types.js'\nimport { debugLog } from '../debug-log.js'\n\nimport type { LoopFinishReason, LoopOutcome, LoopStrategy } from './loop-strategy.js'\nimport type { ReflectionContext, ReflectionStrategy } from './reflection-strategy.js'\n\n/** One SDK stream turn: `createSdkAgentStream(...)` returns this shape. */\n/**\n * Opens one round's SDK stream. `opts.disableTools` (step-cap force-close) asks the factory to\n * gate tools OFF for THIS round (the SDK adapter maps it to `tool_choice:\"none\"` at send-time, so a\n * cached agent — whose tools can't be un-registered — is still forced to a text summary). Optional +\n * ignored by injected test factories ⇒ backward-compatible.\n */\nexport type RoundStreamFactory = (\n message: string,\n sessionId: string,\n opts?: { disableTools?: boolean },\n) => AsyncIterable<StreamEvent>\n\n/** Per-round inputs bundled to keep helper signatures within the parameter budget (G6). */\ninterface RoundInputs {\n factory: RoundStreamFactory\n prompt: string\n sessionId: string\n signal: AbortSignal | undefined\n retry: RetryOptions | undefined\n}\n\n/** Strategies + options for {@link runReflectiveLoop}. */\ninterface RunReflectiveLoopConfig {\n /** The terminal-decision strategy (resolved from `@MainLoop.strategy`). */\n readonly loop: LoopStrategy\n /** Between-round reflection (default `'ladder'` for `'plan-act-reflect'`). */\n readonly reflection: ReflectionStrategy\n /** Cumulative USD budget across ALL rounds (EC-4). Exceeding throws BudgetExceededError. */\n readonly budget?: number\n /** Cancellation — when aborted, the loop stops re-entering and advancing the in-flight stream. */\n readonly signal?: AbortSignal\n /** Name surfaced in typed errors. */\n readonly agentName?: string\n /**\n * V4-P: per-round transient retry. When set, the START of each round (factory creation + first\n * event, before any event is yielded → no re-applied edit) is wrapped in the SDK `withRetry`.\n * Absent ⇒ single attempt (backward-compatible). Default `isRetryable` is the SDK `isTransientError`.\n */\n readonly retry?: RetryOptions\n}\n\nfunction asString(value: unknown, fallback: string): string {\n return typeof value === 'string' ? value : fallback\n}\n\nfunction asNumber(value: unknown, fallback: number): number {\n return typeof value === 'number' ? value : fallback\n}\n\n/** Consecutive no-progress rounds before terminating with `'no_progress'` (K=2 tolerates one retry — V4-D). */\nconst NO_PROGRESS_THRESHOLD = 2\n\n/** Runtime metric key (wiring triad — G10): observable proof the loop ran, with terminal + round count. */\nconst MAINLOOP_METRIC = '[THEO_AGENT_MAINLOOP_RUNTIME_APPLIED]'\n\n/** The \"still working\" continuation signal — a tool-using turn re-enters the loop. */\nconst TOOL_CALLS: LoopFinishReason = 'tool-calls'\n\n/** Final-round graceful-degradation hint (V4-D step_limit — modeled on opencode MAX_STEPS_PROMPT). */\nconst STEP_LIMIT_HINT =\n 'This is your final round — do not call any more tools; summarize the work done so far and list any remaining tasks.'\n\n/**\n * Deterministic JSON: object keys are emitted in sorted order so two semantically\n * equal tool inputs serialize identically regardless of key insertion order (a\n * stuck-loop detector must not be fooled by re-ordered keys — review NF, robustness).\n */\nfunction stableStringify(value: unknown): string {\n if (value === undefined) return 'undefined'\n if (value === null || typeof value !== 'object') return JSON.stringify(value)\n if (Array.isArray(value)) return `[${value.map(stableStringify).join(',')}]`\n const obj = value as Record<string, unknown>\n const entries = Object.keys(obj)\n .sort((a, b) => a.localeCompare(b))\n .map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`)\n return `{${entries.join(',')}}`\n}\n\n/**\n * A round's progress fingerprint = its tool-call set ONLY (name+input, SORTED so call\n * ORDER is irrelevant — EC-3; input keys canonicalized so KEY order is irrelevant too).\n * Two consecutive rounds with an equal signature made no new progress. The assistant\n * narration text is DELIBERATELY excluded (theokit#53): a model that re-runs identical\n * tool calls while rephrasing its prose (\"…e executá-lo.\" → \"Agora vou executar…\") would\n * otherwise evade the detector and spin. Mirrors opencode's `doom_loop`, which compares\n * tool name + JSON.stringify(input) and nothing else. Tool `output` is also excluded:\n * repeating the same call is no-progress even if the result text wobbles. (V4-D, ADR D2)\n */\nfunction roundSignature(toolCalls: readonly { name: string; input: unknown }[]): string {\n return toolCalls\n .map((tc) => `${tc.name}:${stableStringify(tc.input)}`)\n .sort((a, b) => a.localeCompare(b))\n .join(',')\n}\n\n/**\n * The loop's terminal reason: `'step_limit'` when the round wanted to continue\n * (tool-calls + reflection continue) but the `maxIterations` ceiling stopped it;\n * otherwise the round's own natural reason (`'stop'`/`'length'`). (V4-D, ADR D1)\n */\nfunction terminalReason(\n reflectionContinue: boolean,\n roundReason: LoopFinishReason,\n round: number,\n maxIterations: number,\n): LoopFinishReason {\n if (reflectionContinue && roundReason === TOOL_CALLS && round >= maxIterations)\n return 'step_limit'\n // A tool-using round that terminates BELOW the ceiling means a (custom) reflection chose to\n // stop while the turn could have continued — surface 'stop', never leak the per-round\n // 'tool-calls' signal as the loop's terminal reason (review NF; shipped ladder/noop never hit this).\n if (roundReason === TOOL_CALLS) return 'stop'\n return roundReason\n}\n\n/**\n * Default round-2+ continuation when the reflection produced no feedback (V4-M): the\n * persisted session (getOrCreate, sdk-adapter) already holds the prior turns, so a short\n * nudge is enough — re-sending the original task would duplicate it in the session.\n */\nconst CONTINUE_PROMPT =\n 'Continue from the prior turns above; finish the task and give a final answer.'\n\n/**\n * Build the round's prompt. V4-M: rounds carry conversation via the persisted SDK session,\n * so round 1 sends the original `message`; rounds 2+ send the reflection `feedback` (or a\n * default continuation) WITHOUT re-sending `message`. Final-round summary hint preserved (V4-D).\n */\nfunction buildPrompt(\n round: number,\n maxIterations: number,\n message: string,\n feedback: string | undefined,\n): string {\n const hint = round === maxIterations ? `${STEP_LIMIT_HINT}\\n\\n` : ''\n // Round 1 sends the original task; rounds 2+ rely on the persisted session (V4-M) and send\n // ONLY the reflection block (tag preserved) or a default continuation — never re-sending `message`.\n const continuation = feedback ? `[reflection] ${feedback}` : CONTINUE_PROMPT\n const body = round === 1 ? message : continuation\n return hint + body\n}\n\n/**\n * Consume one round, normalizing a RAW stream/iterator exception (not an `error` event —\n * e.g. the SDK dynamic import rejecting) into a typed `DelegationError` (M2). Typed errors\n * (`BudgetExceededError`/`DelegationError`) propagate unchanged.\n */\nasync function* consumeRoundOrThrow(\n inputs: RoundInputs,\n agentName: string,\n): AsyncGenerator<StreamEvent, RoundResult> {\n try {\n return yield* consumeOneRound(\n inputs.factory,\n inputs.prompt,\n inputs.sessionId,\n inputs.signal,\n inputs.retry,\n )\n } catch (err) {\n if (err instanceof BudgetExceededError || err instanceof DelegationError) throw err\n throw new DelegationError(agentName, err)\n }\n}\n\n/**\n * V4-N/V4-O: fold one round's usage into the accumulator — cost + total/split tokens (V4-N) and\n * the reasoning/cache buckets (V4-O). Extracted from the loop body to keep its complexity within\n * budget (G6); the optional `acc` fields default to 0 before adding.\n */\nfunction accumulateUsage(acc: DelegationResult, r: RoundResult): void {\n acc.cost += r.cost\n acc.tokens += r.tokens\n acc.tokensInput = (acc.tokensInput ?? 0) + r.tokensInput\n acc.tokensOutput = (acc.tokensOutput ?? 0) + r.tokensOutput\n acc.reasoningTokens = (acc.reasoningTokens ?? 0) + r.reasoningTokens\n acc.cacheReadTokens = (acc.cacheReadTokens ?? 0) + r.cacheReadTokens\n acc.cacheWriteTokens = (acc.cacheWriteTokens ?? 0) + r.cacheWriteTokens\n}\n\n/** Stamp the terminal state on the accumulator + emit the runtime metric (DRY for the 2 exit points). */\nfunction finalize(\n acc: DelegationResult,\n round: number,\n reason: LoopFinishReason,\n strategyName: string,\n): DelegationResult {\n acc.rounds = round\n acc.finishReason = reason\n debugLog(MAINLOOP_METRIC, { strategy: strategyName, rounds: round, terminal: reason })\n return acc\n}\n\n/** One round's accumulated facts + the signals needed to derive `finishReason`. */\ninterface RoundResult {\n responseText: string\n toolCalls: { id: string; name: string; input: unknown; output: string }[]\n cost: number\n tokens: number\n tokensInput: number\n tokensOutput: number\n // V4-O: reasoning/cache token buckets folded from the done event.\n reasoningTokens: number\n cacheReadTokens: number\n cacheWriteTokens: number\n finishReason: LoopFinishReason\n errorMessage: string\n}\n\n/**\n * Derive the round's terminal signal from the events seen this round.\n *\n * Precedence (B1 — the load-bearing fix):\n * 1. error event ⇒ 'error'\n * 2. explicit done.finishReason==='tool-calls' ⇒ 'tool-calls' (if a future SDK adapter sets it)\n * 3. ANY tool_result seen ⇒ 'tool-calls' — the turn USED TOOLS (\"still working\"), so the\n * outer reflective loop should reflect + re-prompt. The real `@theokit/sdk` adapter ALWAYS\n * appends a terminal `done` WITHOUT finishReason after a turn (sdk-adapter.ts / event-translator.ts);\n * letting that `done` short-circuit a tool-using turn to 'stop' is exactly what made the loop\n * dead in production (single-round). tool_result therefore OUTRANKS the bare done. Bounded by\n * `maxIterations` so it can never spin.\n * 4. otherwise (pure-answer `done`, text-only, or empty round) ⇒ 'stop' (terminal). EC-1: a\n * degenerate/empty round defaults to 'stop', NEVER 'tool-calls'.\n *\n * This is an honest heuristic: the SDK runs the inner tool loop to completion per turn, so the\n * outer loop treats a tool-using turn as \"continue/reflect\" and a pure-text answer as \"done\".\n */\nfunction deriveFinishReason(signals: {\n sawError: boolean\n sawDone: boolean\n doneFinishReason: string\n sawToolResult: boolean\n}): LoopFinishReason {\n if (signals.sawError) return 'error'\n if (signals.sawDone && signals.doneFinishReason === TOOL_CALLS) return TOOL_CALLS\n if (signals.sawToolResult) return TOOL_CALLS\n return 'stop'\n}\n\n/** Mutable round signals used to derive the round's {@link LoopFinishReason}. */\ninterface RoundSignals {\n sawError: boolean\n sawDone: boolean\n doneFinishReason: string\n sawToolResult: boolean\n}\n\n/** V4-N: push a faithful `{id,name,input,output}` toolCall, correlating input from the tool_call. */\nfunction pushToolResult(\n event: StreamEvent,\n r: RoundResult,\n callInputs: Map<string, { name: string; input: unknown }>,\n): void {\n const id = asString(event.callId, '')\n const call = callInputs.get(id)\n r.toolCalls.push({\n id,\n name: call?.name ?? asString(event.toolName, 'unknown'),\n // Prefer the correlated tool_call input (real SDK shape); fall back to an input on the\n // result event itself (some streams/tests carry it there), else {}.\n input: call?.input ?? event.input ?? {},\n output: asString(event.output, ''),\n })\n}\n\n/** V4-N: fold a `done` event's cost + split/total token usage into the round (V4-O: + buckets). */\nfunction applyDone(event: StreamEvent, r: RoundResult): void {\n r.cost = asNumber(event.cost, 0)\n const usage = event.usage as\n | {\n totalTokens?: number\n inputTokens?: number\n outputTokens?: number\n reasoningTokens?: number\n cacheReadTokens?: number\n cacheWriteTokens?: number\n }\n | undefined\n r.tokens = usage?.totalTokens ?? 0\n r.tokensInput = usage?.inputTokens ?? 0\n r.tokensOutput = usage?.outputTokens ?? 0\n // V4-O: fold the reasoning/cache buckets (0 when the provider/adapter omits them).\n r.reasoningTokens = usage?.reasoningTokens ?? 0\n r.cacheReadTokens = usage?.cacheReadTokens ?? 0\n r.cacheWriteTokens = usage?.cacheWriteTokens ?? 0\n}\n\n/**\n * Fold ONE stream event into the round accumulator (V4-N: extracted from `consumeOneRound`\n * to keep its complexity within budget — G6).\n */\nfunction accumulateEvent(\n event: StreamEvent,\n r: RoundResult,\n signals: RoundSignals,\n callInputs: Map<string, { name: string; input: unknown }>,\n): void {\n if (event.type === 'text_delta' && typeof event.content === 'string') {\n r.responseText += event.content\n } else if (event.type === 'tool_call') {\n callInputs.set(asString(event.callId, ''), {\n name: asString(event.toolName, 'unknown'),\n input: event.input ?? {},\n })\n } else if (event.type === 'tool_result') {\n signals.sawToolResult = true\n pushToolResult(event, r, callInputs)\n } else if (event.type === 'done') {\n signals.sawDone = true\n signals.doneFinishReason = asString(event.finishReason, '')\n applyDone(event, r)\n } else if (event.type === 'error') {\n signals.sawError = true\n r.errorMessage = asString((event as { message?: unknown }).message, 'Unknown agent error')\n }\n}\n\n/**\n * Consume exactly one SDK stream turn and derive its {@link LoopFinishReason}.\n * V4-D-stream: an async generator — it `yield`s each event to the consumer LIVE\n * (so SSE-first apps see tokens/tool-calls incrementally) AND returns the\n * aggregated {@link RoundResult} as the generator's return value.\n */\n/**\n * V4-P: open the round's stream + read its first event. When `retry` is set, the whole START\n * (creation + first `next()`) is wrapped in the SDK `withRetry` (dynamic-imported to keep the\n * loop SDK-optional) — a transient before any event is yielded is recovered without re-applying\n * an edit. Once the first event is obtained, the caller iterates WITHOUT retry.\n */\nasync function startRound(\n factory: RoundStreamFactory,\n prompt: string,\n sessionId: string,\n signal: AbortSignal | undefined,\n retry: RetryOptions | undefined,\n): Promise<{ it: AsyncIterator<StreamEvent>; first: IteratorResult<StreamEvent> }> {\n const open = async () => {\n const it = factory(prompt, sessionId)[Symbol.asyncIterator]()\n try {\n return { it, first: await it.next() }\n } catch (err) {\n // The first event threw — release THIS attempt's iterator (run its finally → SDK dispose)\n // before `withRetry` opens a fresh stream, so a failed retry attempt leaks nothing.\n await it.return?.(undefined)\n throw err\n }\n }\n if (!retry) return open()\n // SE36 (SDK v3.0) — `withRetry` became `Retry.create`; same call shape.\n const { Retry } = await import('@theokit/sdk/retry')\n return Retry.create(open, { ...retry, signal: retry.signal ?? signal })\n}\n\nasync function* consumeOneRound(\n factory: RoundStreamFactory,\n prompt: string,\n sessionId: string,\n signal: AbortSignal | undefined,\n retry: RetryOptions | undefined,\n): AsyncGenerator<StreamEvent, RoundResult> {\n const r: RoundResult = {\n responseText: '',\n toolCalls: [],\n cost: 0,\n tokens: 0,\n tokensInput: 0,\n tokensOutput: 0,\n reasoningTokens: 0,\n cacheReadTokens: 0,\n cacheWriteTokens: 0,\n finishReason: 'stop',\n errorMessage: '',\n }\n const signals: RoundSignals = {\n sawError: false,\n sawDone: false,\n doneFinishReason: '',\n sawToolResult: false,\n }\n // V4-N: the tool-call `input` (command/args) lives ONLY on the `tool_call` event; the\n // `output` on the paired `tool_result`. Correlate by callId so toolCalls is faithful.\n const callInputs = new Map<string, { name: string; input: unknown }>()\n\n // V4-P: the round START (creation + first event) is retried when `retry` is set; once an\n // event is yielded we iterate without retry (a mid-stream throw may have applied an edit).\n const { it, first } = await startRound(factory, prompt, sessionId, signal, retry)\n let next = first\n while (!next.done) {\n if (signal?.aborted) {\n // Cancellation: release the underlying iterator (parity with `for await`'s `.return()`\n // on break — runs the factory generator's `finally`, e.g. the SDK adapter's dispose).\n await it.return?.(undefined)\n break\n }\n yield next.value // V4-D-stream: surface the event to the consumer before accumulating\n accumulateEvent(next.value, r, signals, callInputs)\n next = await it.next()\n }\n\n r.finishReason = deriveFinishReason(signals)\n return r\n}\n\n/**\n * Step-cap force-close: on the ceiling round (`round === maxIterations`) wrap the factory so it is\n * called with `disableTools: true` (the adapter maps it to `tool_choice:\"none\"` at send-time),\n * forcing the model to emit the closing summary STEP_LIMIT_HINT requests instead of more tool calls.\n * Below the ceiling, the factory is returned unchanged. NOT exported (M55): its only caller is\n * `runReflectiveLoopStream` below — a stray `export` used to leak it and split that function's JSDoc.\n */\nfunction ceilingRoundFactory(\n factory: RoundStreamFactory,\n round: number,\n maxIterations: number,\n): RoundStreamFactory {\n if (round !== maxIterations) return factory\n return (m, s) => factory(m, s, { disableTools: true })\n}\n\n/**\n * Drive the reflective loop to a terminal {@link DelegationResult}.\n *\n * Terminates when: the reflection/strategy says stop, the `maxIterations` ceiling\n * is reached (via `loop.shouldContinue`), the signal aborts, or a degenerate round\n * resolves to `stop`. Throws `DelegationError` on a mid-round error event\n * (fail-fast, typed) and `BudgetExceededError` when cumulative cost crosses `budget`.\n */\nexport async function* runReflectiveLoopStream(\n factory: RoundStreamFactory,\n message: string,\n sessionId: string,\n config: RunReflectiveLoopConfig,\n): AsyncGenerator<StreamEvent, DelegationResult> {\n const {\n loop,\n reflection,\n budget = Number.POSITIVE_INFINITY,\n signal,\n agentName = loop.name,\n retry,\n } = config\n const acc: DelegationResult = {\n response: '',\n toolCalls: [],\n cost: 0,\n tokens: 0,\n tokensInput: 0,\n tokensOutput: 0,\n reasoningTokens: 0,\n cacheReadTokens: 0,\n cacheWriteTokens: 0,\n rounds: 0,\n }\n // V4-K: one mutable scratch bag per run, threaded to every reflect() so a stateful\n // strategy accumulates across rounds. The framework writes NOTHING into it.\n const reflectionContext: ReflectionContext = {}\n let round = 1\n let feedback: string | undefined\n let prevSig: string | undefined // V4-D: prior round's progress signature (no_progress detection)\n let stuck = 0 // V4-D: consecutive no-progress rounds\n\n while (!signal?.aborted) {\n const prompt = buildPrompt(round, loop.maxIterations, message, feedback)\n const roundFactory = ceilingRoundFactory(factory, round, loop.maxIterations)\n const r = yield* consumeRoundOrThrow(\n { factory: roundFactory, prompt, sessionId, signal, retry },\n agentName,\n )\n\n acc.response += r.responseText\n acc.toolCalls.push(...r.toolCalls)\n accumulateUsage(acc, r)\n\n if (r.finishReason === 'error') throw new DelegationError(agentName, r.errorMessage)\n if (Number.isFinite(budget) && acc.cost > budget) {\n throw new BudgetExceededError(agentName, acc.cost, budget)\n }\n\n // V4-D no_progress: only on would-continue rounds (EC-1: stop/error/length/empty already\n // terminate with their own reason), evaluated BEFORE the ceiling (EC-4: the earlier signal wins).\n // Require ≥1 tool call: a TOOL_CALLS round with an empty tool-call set (reachable only via the\n // dormant deriveFinishReason path 2 — done.finishReason==='tool-calls' with no tool_result) has\n // an empty signature; without this guard two such rounds would collide ('' === '') into a false\n // no_progress (theokit#53 review, architecture+tests LOW). An empty round made no tool progress\n // to compare — skip it (don't accumulate or reset).\n if (r.finishReason === TOOL_CALLS && r.toolCalls.length > 0) {\n const sig = roundSignature(r.toolCalls)\n stuck = sig === prevSig ? stuck + 1 : 0\n if (stuck >= NO_PROGRESS_THRESHOLD) return finalize(acc, round, 'no_progress', loop.name)\n prevSig = sig\n }\n\n const outcome: LoopOutcome = {\n finishReason: r.finishReason,\n round,\n toolCalls: r.toolCalls,\n responseText: r.responseText,\n }\n const reflectionResult = reflection.reflect(outcome, reflectionContext)\n // M54 — the `round < loop.maxIterations` term makes the ceiling the RUNNER's guarantee, not each\n // strategy's convention. Redundant for the three built-ins (they already embed it in\n // `shouldContinue`, so the whole expression is unchanged — zero-behavior), determinative for a\n // custom `.loopStrategy()` that never returns false: without it such a strategy loops forever.\n if (\n !(reflectionResult.continue && loop.shouldContinue(outcome) && round < loop.maxIterations)\n ) {\n const reason = terminalReason(\n reflectionResult.continue,\n r.finishReason,\n round,\n loop.maxIterations,\n )\n return finalize(acc, round, reason, loop.name)\n }\n\n feedback = reflectionResult.feedback\n round += 1\n }\n\n // Aborted before (re-)entering a round. L1: record the rounds that DID run\n // (round is 1-indexed and points at the next round, so `round - 1` ran).\n acc.rounds = round - 1\n return acc\n}\n\n/**\n * Collect-mode wrapper (backward-compatible): drains {@link runReflectiveLoopStream}\n * and returns ONLY the aggregated {@link DelegationResult}. `delegate()` and\n * `AgentRunner.run()` use this; streaming-first consumers use the generator directly.\n */\nexport async function runReflectiveLoop(\n factory: RoundStreamFactory,\n message: string,\n sessionId: string,\n config: RunReflectiveLoopConfig,\n): Promise<DelegationResult> {\n const gen = runReflectiveLoopStream(factory, message, sessionId, config)\n let res = await gen.next()\n while (!res.done) res = await gen.next()\n return res.value\n}\n","/**\n * AgentRunner — the imperative twin of `@MainLoop` (plan ADR D4, V4-B).\n *\n * `AgentRunner.fromSpec(spec).reflection().stream().build()` resolves the loop strategy from\n * an already-compiled spec (the capability-authored agent). `delegate()` shares the same runtime.\n * `build()` is the compile boundary (no I/O, no IoC — standalone, mirrors\n * Spring's `ChatClient.builder(...).build()`); `stream()`/`run()` do the I/O via\n * `runReflectiveLoopStream` (the SAME loop `delegate()` drains — DRY, ADR 0031).\n * V4-D-stream: `stream()` yields events live (SSE-first); `run()` drains it to a result.\n *\n * referencia: knowledge-base/references/spring-ai DefaultChatClientBuilder.java (build() returns standalone).\n */\nimport type {\n AgentDefinition,\n BudgetTracker,\n CustomTool,\n Plugin,\n PluginsSettings,\n ProviderRoutingSettings,\n} from '@theokit/sdk'\nimport type { RetryOptions } from '@theokit/sdk/retry'\n\nimport type { CompiledAgentOptions, CompiledTool } from '../bridge/agent-compiler.js'\nimport type { StreamEvent } from '../bridge/agent-sse-handler.js'\nimport type { DelegationResult } from '../bridge/delegation-types.js'\nimport { createSdkAgentStream } from '../bridge/sdk-adapter.js'\nimport { moderateOutputStream, runInputGuards } from '../guardrails/index.js'\nimport type { MainLoopMeta, ReasoningEffort } from '../types.js'\n\nimport {\n resolveCompactionStrategy,\n type TranscriptCompactionStrategy,\n} from './compaction-strategy.js'\nimport {\n assertValidCustomLoopStrategy,\n type LoopStrategy,\n resolveLoopStrategy,\n} from './loop-strategy.js'\nimport {\n ladderReflectionStrategy,\n noopReflectionStrategy,\n type ReflectionStrategy,\n} from './reflection-strategy.js'\nimport { type RoundStreamFactory, runReflectiveLoopStream } from './run-reflective-loop.js'\n\n/** Options for {@link AgentRunner.run}. */\nexport interface AgentRunnerRunOptions {\n /** LLM API key. */\n readonly apiKey: string\n /** Session id override (default: a fresh isolated id). */\n readonly sessionId?: string\n /** Cumulative USD budget across rounds. */\n readonly budget?: number\n /** Cancellation — aborts stop the reflective loop from re-entering. */\n readonly signal?: AbortSignal\n /**\n * V4-J: per-run tool override. When provided, REPLACES the build-time\n * `compiled.tools` for this call only (e.g. a consumer that selects tools by\n * request mode/permission). Absent ⇒ the agent's compiled tools (unchanged).\n */\n readonly tools?: readonly CompiledTool[]\n /**\n * V4-L.2 (Axis-A SWAP): per-run model override. Merge-over-compiled —\n * `opts.model ?? compiled.model ?? default`. Absent ⇒ the compiled model.\n */\n readonly model?: string\n /**\n * M1 (Axis-A SWAP): per-run extended-thinking effort. Merge-over-compiled —\n * `opts.reasoningEffort ?? compiled.reasoningEffort` (resolved in the adapter, single site).\n * Mapped to the SDK `ModelSelection.params` so the provider reasons (surfaced as `thinking`\n * StreamEvents). Absent ⇒ the compiled reasoning effort (or none).\n */\n readonly reasoningEffort?: ReasoningEffort\n /**\n * M2 (Axis-A SWAP): per-run opt-in to convert inline `<think>…</think>` text into `thinking`\n * events. Merge-over-compiled (`opts.parseThinkTags ?? compiled.parseThinkTags ?? false`). For\n * models that emit reasoning as inline tags (qwen/deepseek) instead of a native reasoning param.\n */\n readonly parseThinkTags?: boolean\n /**\n * theocode#32 (Axis-A SWAP): per-run opt-in to strip a leaked Hermes `<function=…></tool_call>`\n * tool-call dialect out of the text stream. Merge-over-compiled\n * (`opts.stripToolDialect ?? compiled.stripToolDialect ?? false`). For models (qwen/qwen3-coder)\n * that leak tool calls as text instead of native `tool_calls`.\n */\n readonly stripToolDialect?: boolean\n /**\n * theokit#58 (Axis-A SWAP): per-run opt-in to RECOVER a leaked Hermes `<function=…></tool_call>`\n * tool-call dialect so the call EXECUTES (enables the SDK route's `extractToolCallsFromContent`).\n * Merge-over-compiled (`opts.recoverLeakedToolCalls ?? compiled.recoverLeakedToolCalls ?? false`).\n * Sibling of {@link stripToolDialect} (display-only); typically enabled together. Has effect only\n * when {@link providers} routes a provider.\n */\n readonly recoverLeakedToolCalls?: boolean\n /**\n * V4-L.2 (Axis-A SWAP): per-run working directory, forwarded into\n * `Agent.create({ local: { cwd } })` so the SDK populates `SystemPromptContext.cwd`\n * (read by a `SystemPromptResolver` / `@ProjectContext`). Absent ⇒ no `local.cwd`.\n */\n readonly cwd?: string\n /**\n * SDK 4.0 (SE40): per-run root of the native `.jsonl` session transcript, forwarded into\n * `Agent.create({ local: { baseDir } })`. Absent ⇒ the SDK default (`~/.theokit`).\n */\n readonly baseDir?: string\n /**\n * V4-L.2 (Axis-A SWAP): per-run loop-ceiling override. When provided, the loop\n * strategy is re-resolved with this ceiling for this call only (zod-validated —\n * `< 1` throws, never a silent unbounded loop). Absent ⇒ the build-time ceiling.\n */\n readonly maxIterations?: number\n /**\n * V4-L.3 (Axis-A SWAP): per-run plugins (e.g. permission gate by request mode).\n * Accepts EITHER named-plugin discovery settings (`{ enabled: [...] }`) OR an\n * array of code `Plugin` objects (`[permissionPlugin, cachePlugin]`). Both are\n * forwarded RAW through the duck-typed `Agent.create` bridge to the SDK runtime,\n * which accepts either form (mirrors the @theokit/sdk `AgentOptions.plugins` widen).\n */\n readonly plugins?: PluginsSettings | readonly Plugin[]\n /** V4-L.3 (Axis-A SWAP): per-run provider routing. */\n readonly providers?: ProviderRoutingSettings\n /** V4-L.3 (Axis-A SWAP): per-run sub-agent definitions (opts-only; @SubAgents stays deferred). */\n readonly agents?: Record<string, AgentDefinition>\n /**\n * V4-L.3 (Axis-A SWAP): per-run SDK budget tracker — caps the INNER SDK tool-loop per\n * send. Distinct from {@link AgentRunnerRunOptions.budget} (the OUTER reflective-loop USD ceiling).\n */\n readonly budgetTracker?: BudgetTracker\n /**\n * V4-Q: pre-built SDK `CustomTool[]` forwarded RAW to `Agent.create.tools` (appended after the\n * agent's compiled tools), bypassing `defineTool`. For an app whose tools come from imperative\n * SDK factories (no `@Tool` compile path / no recoverable Zod schema). Distinct from `tools`\n * (which REPLACES the compiled `CompiledTool[]`).\n */\n readonly sdkTools?: readonly CustomTool[]\n /**\n * V4-R: inject the per-round stream factory, driving the reflective loop with a caller-provided\n * stream INSTEAD of the SDK adapter (tests / custom transport). When set, the SDK-create options\n * (`tools`/`sdkTools`/`model`/`cwd`/`plugins`/...) are NOT used for this call — the consumer owns\n * the stream. Absent ⇒ `createSdkAgentStream` (the default runtime).\n */\n readonly streamFactory?: RoundStreamFactory\n /**\n * V4-P: per-round transient retry. When set, the START of each reflective round (factory\n * creation + first event, before any event is yielded) is wrapped in the SDK `withRetry` —\n * a 429/5xx/network blip is recovered without re-applying an edit. Absent ⇒ single attempt.\n * Default `isRetryable` is the SDK `isTransientError`.\n */\n readonly retry?: RetryOptions\n}\n\n/**\n * A built, runnable agent. Construct via {@link AgentRunner.fromSpec} — the\n * constructor takes already-resolved state and is an internal detail.\n */\n/** Already-resolved state handed to the {@link AgentRunner} constructor (internal). */\ninterface AgentRunnerState {\n readonly compiled: CompiledAgentOptions\n readonly agentName: string\n /** The resolved terminal-decision strategy (parity with `delegate()`). */\n readonly loopStrategy: LoopStrategy\n /**\n * M54 — true when `loopStrategy` came from `.loopStrategy(custom)` rather than a built-in name.\n * A custom must NOT be re-resolved by name (its name is outside the `z.enum`); a per-run\n * `maxIterations` override applies to it as a runner ceiling instead (see `stream`). Optional and\n * defaults to `false`: a state built directly (tests, `delegate()`) is a by-name built-in.\n */\n readonly loopStrategyIsCustom?: boolean\n /** The resolved between-round reflection (default or `.reflection(custom)` override). */\n readonly reflectionStrategy: ReflectionStrategy\n /** Recorded streaming preference (see {@link AgentRunner.streamEnabled}). */\n readonly streamEnabled: boolean\n /** The resolved compaction strategy, or `undefined` when none is declared (EC-4). */\n readonly compaction?: TranscriptCompactionStrategy\n}\n\nexport class AgentRunner {\n private readonly compiled: CompiledAgentOptions\n private readonly agentName: string\n /** The resolved terminal-decision strategy (parity with `delegate()`). */\n readonly loopStrategy: LoopStrategy\n /** M54 — whether {@link loopStrategy} is a caller-injected custom (see {@link AgentRunnerState}). */\n private readonly loopStrategyIsCustom: boolean\n /** The resolved between-round reflection (default or `.reflection(custom)` override). */\n readonly reflectionStrategy: ReflectionStrategy\n /**\n * Recorded streaming preference. The reflective loop currently always streams via\n * the SDK `Run.stream()`; a non-streaming collect mode is future work — the flag is\n * captured + exposed here, not yet branched on (honest per G10: documented, not a\n * silent no-op).\n */\n readonly streamEnabled: boolean\n /**\n * V4-F: the resolved compaction strategy (from `@Compaction` or `.compaction()`),\n * or `undefined` when neither is declared — compaction is opt-in (EC-4). CALLABLE\n * by the app (ADR D1: `runner.compaction?.compact(messages, { summarize })`); the\n * reflective loop does NOT auto-invoke it (the SDK owns per-turn context).\n */\n readonly compaction?: TranscriptCompactionStrategy\n\n constructor(state: AgentRunnerState) {\n this.compiled = state.compiled\n this.agentName = state.agentName\n this.loopStrategy = state.loopStrategy\n this.loopStrategyIsCustom = state.loopStrategyIsCustom ?? false\n this.reflectionStrategy = state.reflectionStrategy\n this.streamEnabled = state.streamEnabled\n this.compaction = state.compaction\n }\n\n /** Start a fluent builder from an already-compiled spec. */\n static fromSpec(spec: AgentRunnerSpec): AgentRunnerBuilder {\n return new AgentRunnerBuilder(spec)\n }\n\n /**\n * V4-D-stream: stream the agent's events LIVE across the reflective loop, returning\n * the aggregated {@link DelegationResult} as the generator's return value. This is the\n * on-ramp for streaming-first apps (SSE) — `runReflectiveLoopStream` yields every\n * round's events before the loop terminates. `streamEnabled` is honored: when the\n * builder set `.stream(false)`, callers should use {@link run} instead.\n */\n stream(\n message: string,\n opts: AgentRunnerRunOptions,\n ): AsyncGenerator<StreamEvent, DelegationResult> {\n // M9 — apply input guardrails at the boundary BEFORE the SDK runtime sees the message.\n // A `block` throws GuardrailViolationError fail-fast; a `redact` rewrites the message.\n // Absent/empty guard list ⇒ no wrapper, zero overhead (identity path).\n const guardrails = this.compiled.guardrails\n if (guardrails && guardrails.length > 0) {\n // Arrow captures `this` lexically (no `const self = this` aliasing) for the generator below.\n const runUnguarded = (m: string): AsyncGenerator<StreamEvent, DelegationResult> =>\n this.streamUnguarded(m, opts)\n return (async function* guarded(): AsyncGenerator<StreamEvent, DelegationResult> {\n const safe = await runInputGuards(message, guardrails)\n // Output guards moderate the accumulated text before it reaches the client (M9).\n // `moderateOutputStream` is a transparent pass-through when no output guard is present.\n return yield* moderateOutputStream(runUnguarded(safe), guardrails, (e) =>\n e.type === 'text_delta' && typeof e.content === 'string' ? e.content : undefined,\n )\n })()\n }\n return this.streamUnguarded(message, opts)\n }\n\n /** The core stream path, after input guardrails have run (M9). */\n private streamUnguarded(\n message: string,\n opts: AgentRunnerRunOptions,\n ): AsyncGenerator<StreamEvent, DelegationResult> {\n // V4-J: per-run tool override replaces compiled.tools for this call only.\n const tools = opts.tools ? [...opts.tools] : this.compiled.tools\n // Re-resolve the ceiling per call (see {@link resolvePerRunLoop} for the M54 D4 rules).\n const loop = this.resolvePerRunLoop(opts.maxIterations)\n // V4-R: a caller-injected factory drives the loop directly (tests / custom transport); absent ⇒\n // the SDK adapter. V4-L.2 + V4-L.3 (Axis-A SWAP): the per-request overrides forwarded to Agent.create.\n // `model` resolves against compiled.model in the adapter (single resolution site).\n const streamFactory =\n opts.streamFactory ??\n createSdkAgentStream(this.compiled, tools, opts.apiKey, {\n model: opts.model,\n reasoningEffort: opts.reasoningEffort, // M1: per-run extended-thinking effort\n parseThinkTags: opts.parseThinkTags, // M2: per-run <think>-tag extraction opt-in\n stripToolDialect: opts.stripToolDialect, // theocode#32: per-run tool-dialect strip opt-in\n recoverLeakedToolCalls: opts.recoverLeakedToolCalls, // theokit#58: per-run leaked-dialect recovery opt-in\n cwd: opts.cwd,\n baseDir: opts.baseDir,\n plugins: opts.plugins,\n providers: opts.providers,\n agents: opts.agents,\n budgetTracker: opts.budgetTracker,\n sdkTools: opts.sdkTools, // V4-Q: pre-built SDK tools forwarded raw\n })\n const sessionId = opts.sessionId ?? `runner-${crypto.randomUUID()}`\n return runReflectiveLoopStream(streamFactory, message, sessionId, {\n loop,\n reflection: this.reflectionStrategy,\n budget: opts.budget,\n agentName: this.agentName,\n signal: opts.signal,\n retry: opts.retry, // V4-P: per-round transient retry (opt-in)\n })\n }\n\n /** Run the agent to a terminal result via the shared reflective loop (collect mode). */\n /**\n * Apply a per-call `maxIterations` override (M54 D4). A custom strategy must NOT be re-resolved by\n * name — its name is outside the `z.enum`, which would throw — and its `shouldContinue` closure\n * must survive; since the runner enforces the ceiling via `round < loop.maxIterations` (T1.1),\n * overriding just that field bounds a custom without touching its logic. A built-in keeps the\n * by-name re-resolution (zod fail-loud on `< 1`) — unchanged, zero-behavior.\n */\n private resolvePerRunLoop(maxIterations: number | undefined): LoopStrategy {\n if (maxIterations == null) return this.loopStrategy\n if (this.loopStrategyIsCustom) {\n // Preserve the prototype: a class-based strategy carries `shouldContinue` on its prototype, and\n // an object-literal spread (`{ ...loop }`) copies only OWN enumerable props — dropping the method\n // and crashing the run. `Object.create` + `assign` keeps the prototype chain, overriding only the\n // ceiling field (M54 review F-2; ADR-0004 D4 promised the custom's shouldContinue survives).\n const base = this.loopStrategy\n return Object.assign(Object.create(Object.getPrototypeOf(base) as object), base, {\n maxIterations,\n }) as LoopStrategy\n }\n return resolveLoopStrategy(this.loopStrategy.name, maxIterations)\n }\n\n async run(message: string, opts: AgentRunnerRunOptions): Promise<DelegationResult> {\n const gen = this.stream(message, opts)\n let res = await gen.next()\n while (!res.done) res = await gen.next()\n return res.value\n }\n}\n\n/**\n * M53 — what the runner actually needs in order to run: an already-compiled agent plus the two\n * loop knobs. It used to derive all of this from `walkAgentMetadata`, which chained the runner to\n * the decorator surface. `strategy` and `compaction` are the two non-waist channels ADR 0002 keeps\n * (the builder's `.compaction()` already outranked the decorator; this just names the input).\n */\n/**\n * The already-compiled agent the runner executes. Field-compatible with `SubAgentSpec` on purpose —\n * one spec drives both `AgentRunner.fromSpec` and `delegate`.\n */\ninterface AgentRunnerSpec {\n readonly name: string\n readonly compiled: CompiledAgentOptions\n readonly strategy?: MainLoopMeta['strategy']\n readonly maxIterations?: number\n readonly compaction?: { name: string; keepTokens?: number }\n}\n\n/** Fluent builder — accumulates config; `build()` is the compile boundary. */\nexport class AgentRunnerBuilder {\n private reflectionOverride?: ReflectionStrategy\n private streamEnabled = true\n private compactionOverride?: { name: string; keepTokens?: number }\n private loopStrategyOverride?: LoopStrategy\n\n constructor(private readonly spec: AgentRunnerSpec) {}\n\n /** Override the default reflection strategy (OCP — plan Drawback #2). No arg ⇒ keep default. */\n reflection(strategy?: ReflectionStrategy): this {\n if (strategy) this.reflectionOverride = strategy\n return this\n }\n\n /**\n * M54 — inject a custom terminal-decision strategy (the fourth OCP axis, alongside\n * `.reflection()`/`.compaction()`/`streamFactory`). WINS over the strategy the spec's name would\n * resolve to, exactly as `.compaction()` outranks the spec. The runner caps ANY strategy at\n * `custom.maxIterations` (T1.1), so a `shouldContinue: () => true` still terminates — never an\n * infinite loop.\n *\n * @example\n * ```ts\n * // Stop as soon as the confidence in the last round crosses 0.9, else run to the ceiling.\n * const stopWhenConfident: LoopStrategy = {\n * name: 'confident',\n * maxIterations: 8,\n * shouldContinue: (o) => !o.responseText.includes('confidence: high'),\n * }\n * AgentRunner.fromSpec(spec).loopStrategy(stopWhenConfident).build()\n * ```\n */\n loopStrategy(custom: LoopStrategy): this {\n // Fail fast at authoring: a custom bypasses the built-ins' zod ceiling check, and a non-finite\n // or `< 1` ceiling would make the runner's `round < maxIterations` guard never fire (M54).\n assertValidCustomLoopStrategy(custom)\n this.loopStrategyOverride = custom\n return this\n }\n\n /** Record the streaming preference (see {@link AgentRunner.streamEnabled}). */\n stream(enabled = true): this {\n this.streamEnabled = enabled\n return this\n }\n\n /**\n * V4-F: declare the compaction strategy (e.g. `.compaction('token-budget', { keepTokens: 8000 })`).\n * Resolved + validated at {@link build} (EC-5 — fail-fast there, not here). This builder\n * call WINS over a `@Compaction` decorator on the same agent (EC-1 — explicit override).\n */\n compaction(name: string, options: { keepTokens?: number } = {}): this {\n this.compactionOverride = { name, keepTokens: options.keepTokens }\n return this\n }\n\n /** Resolve strategies from the spec — the compile→execute boundary (no I/O). */\n build(): AgentRunner {\n const { spec } = this\n // `'simple-chat'` is the default when the spec declares no strategy.\n const strategy = spec.strategy ?? 'simple-chat'\n // M54: `.loopStrategy(custom)` WINS over the spec's name-derived strategy (same precedence as\n // `.compaction()`). `loopStrategyIsCustom` flows to the runner so a per-run `maxIterations`\n // override applies to a custom as a ceiling instead of re-resolving it by name (D4).\n const loopStrategyIsCustom = this.loopStrategyOverride !== undefined\n const loopStrategy =\n this.loopStrategyOverride ?? resolveLoopStrategy(strategy, spec.maxIterations)\n const reflectionStrategy =\n this.reflectionOverride ??\n (strategy === 'plan-act-reflect' ? ladderReflectionStrategy : noopReflectionStrategy)\n // V4-F: builder override WINS over whatever the spec declares (EC-1); undefined when neither\n // declares it (EC-4 — opt-in). resolveCompactionStrategy fails fast (EC-5/EC-2).\n const compactionDecl = this.compactionOverride ?? spec.compaction\n const compaction = compactionDecl\n ? resolveCompactionStrategy(compactionDecl.name, { keepTokens: compactionDecl.keepTokens })\n : undefined\n return new AgentRunner({\n compiled: spec.compiled,\n agentName: spec.name,\n loopStrategy,\n loopStrategyIsCustom,\n reflectionStrategy,\n streamEnabled: this.streamEnabled,\n compaction,\n })\n }\n}\n","import { runGoalLoop } from '@theokit/sdk'\nimport type { GoalEvent, GoalLoopAgent, GoalOptions, GoalResult } from '@theokit/sdk'\n\n// M59 — the goal domain's types travel WITH `GoalRunner` (the layer owns the whole goal surface now):\n// a consumer types against `GoalRunner` — `run(): AsyncGenerator<GoalEvent, GoalResult>`, the\n// `GoalLoopAgent` it binds, the `GoalOptions` it takes — entirely from `@theokit/agents`, never\n// reaching back to `@theokit/sdk`.\nexport type { GoalEvent, GoalLoopAgent, GoalOptions, GoalResult } from '@theokit/sdk'\n\n/**\n * M59 — `GoalRunner`, the OO twin of the SDK's free `runGoalLoop`, parallel to {@link AgentRunner}.\n *\n * The SDK ships goal orchestration as a free function: `runGoalLoop(agent, goal, options, deps)` drives\n * a goal to completion (Codex states + token budget, an LLM judge as the completion oracle), streaming\n * `GoalEvent`s and resolving a `GoalResult`. This class imposes the layer's OO shape on it so the\n * consumer authors `new GoalRunner(agent).run(goal, options)` instead of a bare function call — the same\n * `SDK → Theokit → AgentBuilder` boundary the M58 barrels established, here ENRICHING (a contract) an\n * orchestration primitive rather than passing a pure one through.\n *\n * It DELEGATES, never reimplements (parsimony Rung 9): `run` forwards verbatim to `runGoalLoop`, so the\n * emitted `GoalEvent` stream and the final `GoalResult` are identical to calling the SDK directly. The\n * parity test pins that by construction.\n */\n\n/** The optional 4th arg of `runGoalLoop` (the SDK's internal `RunUntilDeps` — judge/clock overrides). */\nexport type GoalRunnerDeps = Parameters<typeof runGoalLoop>[3]\n\nexport class GoalRunner {\n constructor(private readonly agent: GoalLoopAgent) {}\n\n /**\n * Drive `goal` to completion against the bound agent. Returns the SAME async generator `runGoalLoop`\n * returns — yielding `GoalEvent`s, resolving a `GoalResult`. `deps` (judge/clock overrides) threads\n * straight through; a test seam for the judge lives there, exactly as on the free function.\n */\n run(\n goal: string,\n options?: GoalOptions,\n deps?: GoalRunnerDeps,\n ): AsyncGenerator<GoalEvent, GoalResult, void> {\n return runGoalLoop(this.agent, goal, options, deps)\n }\n}\n","/**\n * Multi-agent orchestration runtime.\n *\n * Provides `delegate()` — a function that lets a parent agent invoke a\n * sub-agent and receive its result. Handles budget clamping (D4), tool sharing,\n * toolbox auto-instantiation (EC-1), and routes the resolved `@MainLoop` strategy\n * through `runReflectiveLoop` — the SAME driver `AgentRunner.run()` uses, so both\n * on-ramps are one runtime (ADR D4). `simple-chat` ⇒ `shouldContinue:()=>false`\n * ⇒ exactly one round; `react`/`plan-act-reflect` ⇒ multi-round reflective loop.\n */\nimport type {\n AgentDefinition,\n BudgetTracker,\n CustomTool,\n PluginsSettings,\n ProviderRoutingSettings,\n} from '@theokit/sdk'\nimport type { RetryOptions } from '@theokit/sdk/retry'\n\nimport {\n ladderReflectionStrategy,\n noopReflectionStrategy,\n type ReflectionStrategy,\n resolveLoopStrategy,\n} from '../loop/index.js'\nimport { type RoundStreamFactory, runReflectiveLoop } from '../loop/run-reflective-loop.js'\nimport type { MainLoopMeta } from '../types.js'\n\nimport type { CompiledAgentOptions, CompiledTool } from './agent-compiler.js'\nimport { type DelegationResult, DelegationError } from './delegation-types.js'\nimport { createSdkAgentStream } from './sdk-adapter.js'\n\n// Re-export the delegation value types for backward compatibility — they moved\n// to delegation-types.js to break the orchestrator↔loop import cycle (G1).\nexport { BudgetExceededError, type DelegationResult, DelegationError } from './delegation-types.js'\n\nexport interface DelegateOptions {\n /** Max USD for this sub-agent call. */\n budget?: number\n /** Parent's remaining budget (for clamping). */\n parentBudgetRemaining?: number\n /** Parent's tools (for sharing — sub-agent inherits these). */\n parentTools?: CompiledTool[]\n /** LLM API key (inherited from parent). */\n apiKey?: string\n /** Session ID override (default: crypto.randomUUID for isolation). */\n sessionId?: string\n /** Cancellation — aborts stop the reflective loop from re-entering. */\n signal?: AbortSignal\n // V4-T: per-run config parity with `AgentRunnerRunOptions` — a sub-agent inherits the parent's\n // runtime config (all optional; absent ⇒ today's behavior). Each field is already accepted by\n // `createSdkAgentStream`'s `RuntimeOverrides` / the loop's `RunReflectiveLoopConfig`.\n /** Per-run model override (`?? SubAgent @Agent model`). */\n model?: string\n /** Per-run working directory → `Agent.create({ local: { cwd } })`. */\n cwd?: string\n /** Per-run plugins (e.g. a read-only permission gate for an explore sub-agent). */\n plugins?: PluginsSettings\n /** Per-run provider routing (e.g. OpenRouter). */\n providers?: ProviderRoutingSettings\n /** Per-run sub-agent definitions. */\n agents?: Record<string, AgentDefinition>\n /** Per-run SDK budget tracker (inner tool-loop cap). */\n budgetTracker?: BudgetTracker\n /** Per-run pre-built SDK tools forwarded raw (V4-Q). */\n sdkTools?: readonly CustomTool[]\n /** Per-round transient retry (V4-P). */\n retry?: RetryOptions\n /** Custom between-round reflection (default: ladder for `plan-act-reflect`, else noop). */\n reflection?: ReflectionStrategy\n /** Per-run loop-ceiling override (`?? SubAgent @MainLoop maxIterations`). */\n maxIterations?: number\n // M12 — delegation observability hooks (ADR-0040 § D2). Observability over the EXISTING\n // primitive; no new orchestration engine. `abortSignal` propagation already lives in `signal`.\n /**\n * Called BEFORE the sub-agent runs. Returns the input the sub-agent will receive — return\n * `ctx.input` unchanged, or a rewritten string (e.g. inject a persona). A transform, not a veto.\n */\n onDelegationStart?: (ctx: { subAgent: string; input: string }) => string | Promise<string>\n /**\n * Called AFTER the sub-agent completes. Returns the result the supervisor sees — return\n * `ctx.result` unchanged, or a transformed one (e.g. redact, score, re-wrap).\n */\n onDelegationComplete?: (ctx: {\n subAgent: string\n result: DelegationResult\n }) => DelegationResult | Promise<DelegationResult>\n /**\n * Injected stream factory (parity with `AgentRunnerRunOptions.streamFactory`) — drives the loop\n * directly instead of the SDK adapter (tests / custom transport). Absent ⇒ `createSdkAgentStream`.\n */\n streamFactory?: RoundStreamFactory\n}\n\n/** Validate API key and throw DelegationError if missing. */\nfunction requireApiKey(opts: DelegateOptions, agentName: string): string {\n const apiKey = opts.apiKey ?? ''\n if (!apiKey) {\n throw new DelegationError(agentName, 'No API key provided. Pass apiKey in DelegateOptions.')\n }\n return apiKey\n}\n\n/** Merge parent tools with sub-agent tools (sub wins on collision). */\nfunction mergeTools(parentTools: CompiledTool[], subTools: CompiledTool[]): CompiledTool[] {\n const subToolNames = new Set(subTools.map((t) => t.name))\n const inherited = parentTools.filter((t) => !subToolNames.has(t.name))\n return [...inherited, ...subTools]\n}\n\n/**\n * Delegate a task to a sub-agent and collect its result.\n *\n * - Budget clamping: `min(parentBudgetRemaining, budget)` (D4)\n * - Tool sharing: parent tools merged with sub-agent tools (sub wins on collision)\n * - Toolbox auto-instantiation: sub-agent toolboxes instantiated without DI (EC-1)\n * - Session isolation: each delegation gets a unique session ID (EC-4)\n * - `@MainLoop` strategy runtime: routes through `runReflectiveLoop` (the same loop\n * `AgentRunner.run` uses — one runtime for both on-ramps, ADR D4). The runtime\n * metric (`THEO_AGENT_MAINLOOP_RUNTIME_APPLIED`) + typed-error + cumulative budget\n * all live in the shared driver, so they fire identically on both paths.\n */\n/**\n * What `delegate` needs from a sub-agent: a name and already-compiled options (built by\n * `applyCapabilities`). Compatible with {@link AgentRunnerSpec} — one spec drives both on-ramps.\n */\nexport interface SubAgentSpec {\n readonly name: string\n readonly compiled: CompiledAgentOptions\n /** Loop strategy (`@MainLoop({ strategy })`); absent ⇒ the same `'simple-chat'` default. */\n readonly strategy?: MainLoopMeta['strategy']\n /** Loop ceiling (`@MainLoop({ maxIterations })`); a per-run override still wins. */\n readonly maxIterations?: number\n}\n\nexport async function delegate(\n spec: SubAgentSpec,\n message: string,\n opts: DelegateOptions = {},\n): Promise<DelegationResult> {\n const apiKey = requireApiKey(opts, spec.name)\n\n // M12 — onDelegationStart: let the supervisor rewrite the input before the sub-agent runs.\n const effectiveMessage = opts.onDelegationStart\n ? await opts.onDelegationStart({ subAgent: spec.name, input: message })\n : message\n\n const { compiled } = spec\n\n // 2. Merge parent tools + clamp budget (D4)\n const allTools = mergeTools(opts.parentTools ?? [], compiled.tools)\n const budget = Math.min(opts.budget ?? Infinity, opts.parentBudgetRemaining ?? Infinity)\n\n // 3. Build the stream factory (the model call stays in the SDK — ADR 0031) + session.\n // V4-T: forward the per-run config (parity with AgentRunner.stream); model opt wins over the\n // decorator; absent fields ⇒ no key (byte-identical to the pre-V4-T `{ model }`-only override).\n // M12 — an injected factory (tests / custom transport) wins; absent ⇒ the SDK adapter.\n const streamFactory =\n opts.streamFactory ??\n createSdkAgentStream(compiled, allTools, apiKey, {\n model: opts.model ?? compiled.model,\n cwd: opts.cwd,\n plugins: opts.plugins,\n providers: opts.providers,\n agents: opts.agents,\n budgetTracker: opts.budgetTracker,\n sdkTools: opts.sdkTools,\n })\n const sessionId = opts.sessionId ?? `sub-${crypto.randomUUID()}`\n\n // 4. Resolve the @MainLoop strategy + reflection, then run the shared reflective loop.\n // V4-T: per-run maxIterations override (parity with AgentRunner.stream); absent ⇒ decorator ceiling.\n const loopStrategy = resolveLoopStrategy(\n spec.strategy ?? 'simple-chat',\n opts.maxIterations ?? spec.maxIterations,\n )\n // V4-T: a custom reflection wins; absent ⇒ the strategy-derived default (ladder/noop).\n const reflection =\n opts.reflection ??\n (loopStrategy.name === 'plan-act-reflect' ? ladderReflectionStrategy : noopReflectionStrategy)\n const result = await runReflectiveLoop(streamFactory, effectiveMessage, sessionId, {\n loop: loopStrategy,\n reflection,\n budget,\n agentName: spec.name,\n signal: opts.signal,\n retry: opts.retry, // V4-T: per-round transient retry (V4-P) on the delegate path\n })\n\n // M12 — onDelegationComplete: let the supervisor transform the result before it returns.\n if (opts.onDelegationComplete) {\n return await opts.onDelegationComplete({ subAgent: spec.name, result })\n }\n return result\n}\n","/**\n * M10 (theokit-ai-first) — createToolHooksPlugin: `beforeToolCall` / `afterToolCall` observability.\n *\n * ADR-0040 § D2: a HOME/BOUNDARY plugin over the SDK's OWN `pre_tool_call` / `post_tool_call` /\n * `pre_llm_call` / `post_llm_call` / `pre_user_send` hooks (mirrors {@link createHitlPlugin}). It\n * calls no LLM, dispatches no tool, runs no second loop — the SDK owns the run. `beforeToolCall`\n * may VETO a call; `afterToolCall` observes the result.\n *\n * M19 — `processInput` completes the input side of the processor pipeline, wired to the SDK\n * `pre_user_send` hook. NOTE (honest ceiling): the SDK does NOT let a plugin mutate the raw\n * prompt/stream; `pre_user_send` lets a handler INJECT derived context (`recalledContext`) BEFORE\n * the model. So `processInput` receives the prompt and returns an optional string, which the SDK\n * injects as a `<memory-context>` block ahead of the prompt. The api-error side of M19 lives in\n * `./api-error-handler` (a sibling factory — the SDK owns retry and exposes no error hook).\n */\n\n/** A tool call about to run (mirrored from the SDK `pre_tool_call` context — type-only). */\nexport interface BeforeToolCallContext {\n name: string\n args: Record<string, unknown>\n}\n/** A veto returned from `beforeToolCall` — blocks the tool; the SDK surfaces `message` to the model. */\nexport interface ToolCallVeto {\n block: true\n message: string\n}\n/** A completed tool call (mirrored from the SDK `post_tool_call` context — type-only). */\nexport interface AfterToolCallContext {\n name: string\n result: unknown\n}\n\nexport interface ToolHooks {\n /** Observe (and optionally VETO) every tool call before it runs. Return a veto or nothing. */\n beforeToolCall?: (\n ctx: BeforeToolCallContext,\n ) => ToolCallVeto | undefined | Promise<ToolCallVeto | undefined>\n /** Observe every tool call's result after it runs. */\n afterToolCall?: (ctx: AfterToolCallContext) => void | Promise<void>\n /**\n * M10 — observe every LLM turn BEFORE it runs (SDK `pre_llm_call`). Observability only — the\n * SDK's LLM-call context carries `{ agentId, runId, iteration }`, not the mutable request body.\n */\n beforeLLMCall?: (ctx: LLMCallContext) => void | Promise<void>\n /** M10 — observe every LLM turn AFTER it completes (SDK `post_llm_call`). Observability only. */\n afterLLMCall?: (ctx: LLMCallContext) => void | Promise<void>\n /**\n * M19 — pre-process the user input BEFORE the model runs (SDK `pre_user_send`). Receives the\n * prompt; return a string to INJECT as derived context ahead of it (the SDK wraps it in a\n * `<memory-context>` block), or `undefined` to inject nothing. The SDK does not expose raw-prompt\n * mutation to plugins, so this is additive, not a rewrite of the caller's stream.\n */\n processInput?: (ctx: ProcessInputContext) => string | undefined | Promise<string | undefined>\n}\n\n/** Context of the input seam (mirrors the SDK `PreUserSendContext`). */\nexport interface ProcessInputContext {\n prompt: string\n agentId: string\n runId: string\n}\n\n/** Context of an LLM turn (mirrors the SDK `LlmCallContext` for `pre_llm_call`/`post_llm_call`). */\nexport interface LLMCallContext {\n agentId: string\n runId: string\n /** 0-based iteration index of the current turn, when available. */\n iteration?: number\n}\n\n/**\n * Minimal SDK hook context (type-only — no runtime import, keeps the SDK peer optional). Tool hooks\n * carry `name`/`args`/`result`; LLM hooks carry `iteration`. All optional so one shape covers both.\n */\nexport interface ToolHookRawContext {\n agentId: string\n runId: string\n name?: string\n args?: Record<string, unknown>\n result?: unknown\n iteration?: number\n /** M19 — the user prompt, present on the `pre_user_send` seam. */\n prompt?: string\n}\nexport interface ToolHooksPluginContext {\n on(hook: string, handler: (ctx: ToolHookRawContext) => unknown): void\n}\nexport interface ToolHooksPlugin {\n name: string\n /** SDK `BasePlugin.version` — required by the `@theokit/sdk` Plugin contract. */\n version: string\n /**\n * SDK Plugin discriminator. MUST be `'general'` — the SDK's `isCodePlugin()` gate filters out any\n * plugin object lacking `kind: 'general'` (a `register()`-only object is silently dropped and its\n * hooks NEVER fire). Regression guard for the M10/M19 latent E2E bug.\n */\n kind: 'general'\n register(ctx: ToolHooksPluginContext): void\n}\n\n/**\n * Build the tool-hooks plugin. Registers ONLY the hooks provided (inert when none) so it adds no\n * overhead unless used. The returned object is a structural `@theokit/sdk` `Plugin`.\n */\nexport function createToolHooksPlugin(hooks: ToolHooks): ToolHooksPlugin {\n return {\n name: 'theokit-tool-hooks',\n version: '1.0.0',\n // `kind: 'general'` is load-bearing — without it the SDK's isCodePlugin() drops this plugin and\n // no hook fires (M10/M19 latent bug, proven via a real OpenRouter run).\n kind: 'general',\n register(ctx) {\n const { beforeToolCall, afterToolCall, beforeLLMCall, afterLLMCall, processInput } = hooks\n if (beforeToolCall) {\n ctx.on('pre_tool_call', (c) => beforeToolCall({ name: c.name ?? '', args: c.args ?? {} }))\n }\n if (afterToolCall) {\n ctx.on('post_tool_call', (c) => afterToolCall({ name: c.name ?? '', result: c.result }))\n }\n if (beforeLLMCall) {\n ctx.on('pre_llm_call', (c) =>\n beforeLLMCall({ agentId: c.agentId, runId: c.runId, iteration: c.iteration }),\n )\n }\n if (afterLLMCall) {\n ctx.on('post_llm_call', (c) =>\n afterLLMCall({ agentId: c.agentId, runId: c.runId, iteration: c.iteration }),\n )\n }\n if (processInput) {\n // M19 — map the returned string to the SDK's `pre_user_send` result ({ recalledContext }).\n ctx.on('pre_user_send', async (c) => {\n const injected = await processInput({\n prompt: c.prompt ?? '',\n agentId: c.agentId,\n runId: c.runId,\n })\n return injected !== undefined && injected.length > 0\n ? { recalledContext: injected }\n : undefined\n })\n }\n },\n }\n}\n","/**\n * M19 (theokit-ai-first) — `processApiError`: app-level fallback around an agent run.\n *\n * ADR-0040 § D2 + sdk-runtime.md: the `@theokit/sdk` runtime OWNS the LLM call AND its own\n * retry/backoff, and exposes NO api-error hook to plugins. This module is therefore NOT a plugin —\n * it is a thin app-boundary wrapper (the M19 DoD explicitly allows \"a sibling factory\"). It\n * RE-INVOKES the caller's run thunk on error; it never calls an LLM, never dispatches a tool, never\n * reimplements retry inside the loop (G2). The SDK's internal retry runs first; this handles what\n * survives it — a second, app-owned fallback layer (the M19 top-risk note: \"app-level fallback, not\n * a second retry loop\" inside the SDK).\n */\n\n/** What the app decides after seeing an API error. */\nexport interface ApiErrorDecision<R = unknown> {\n /** Re-invoke the run thunk once more. Ignored past `maxAttempts`. */\n retry?: boolean\n /**\n * A value to return INSTEAD of rethrowing, when `retry` is false/absent. Lets the app degrade\n * gracefully (e.g. a canned response) rather than surface the raw provider error.\n */\n fallback?: R\n}\n\n/** Context handed to the app's error handler for each failed attempt (1-based). */\nexport interface ApiErrorContext {\n error: unknown\n /** 1-based attempt number that just failed. */\n attempt: number\n}\n\nexport interface ApiErrorPolicy<R = unknown> {\n /** Called once per failed attempt. Return `{ retry: true }` to try again, or a `{ fallback }`. */\n processApiError: (ctx: ApiErrorContext) => ApiErrorDecision<R> | Promise<ApiErrorDecision<R>>\n /**\n * Hard cap on total attempts (defaults to 3). A backstop so a handler that always returns\n * `{ retry: true }` cannot loop forever (mirrors the SDK's own bounded retry philosophy).\n */\n maxAttempts?: number\n}\n\nconst DEFAULT_MAX_ATTEMPTS = 3\n\n/**\n * Run `thunk`, applying the app's `processApiError` policy on failure. Returns the run's value on\n * success, the policy's `fallback` when it declines to retry with one, or rethrows the last error.\n *\n * `thunk` is typically `() => agent.send(msg).then((r) => r.wait())` — a whole SDK run. On retry the\n * thunk is re-invoked from scratch (a fresh run), never resumed mid-loop.\n */\nexport async function runWithApiErrorHandling<R>(\n thunk: () => Promise<R>,\n policy: ApiErrorPolicy<R>,\n): Promise<R> {\n const maxAttempts = policy.maxAttempts ?? DEFAULT_MAX_ATTEMPTS\n let attempt = 0\n // Loop bounded by maxAttempts; each iteration is one full run attempt.\n for (;;) {\n attempt += 1\n try {\n return await thunk()\n } catch (error) {\n const decision = await policy.processApiError({ error, attempt })\n if (decision.retry && attempt < maxAttempts) continue\n if (!decision.retry && 'fallback' in decision && decision.fallback !== undefined) {\n return decision.fallback\n }\n throw error\n }\n }\n}\n\n/**\n * Build a reusable guard bound to one policy. `const guard = createApiErrorHandler({ ... })` then\n * `guard(() => agent.send(m).then((r) => r.wait()))` — the same policy applied to many runs.\n */\nexport function createApiErrorHandler<R = unknown>(\n policy: ApiErrorPolicy<R>,\n): (thunk: () => Promise<R>) => Promise<R> {\n return (thunk) => runWithApiErrorHandling(thunk, policy)\n}\n","/**\n * M25 (theokit-ai-first) — background delegation + task-completion scoring.\n *\n * Two THIN wrappers over the M12 `delegate` (ADR 0038/0040): no new orchestration engine, no second\n * loop, no new store. `delegateBackground` kicks off a sub-agent without blocking the supervisor and\n * hands back a handle to await later. `delegateWithScoring` runs `delegate`, scores the result with\n * an injected scorer, and re-delegates with the scorer's feedback until it passes or `maxRounds` is\n * hit. The `delegate` implementation is injectable (`delegateFn`) so this is testable without a\n * SubAgent class or an LLM — and so it NEVER re-implements the delegation runtime.\n */\nimport { delegate, type DelegateOptions, type SubAgentSpec } from './agent-orchestrator.js'\nimport type { DelegationResult } from './delegation-types.js'\n\n/** The delegation primitive both wrappers drive. Defaults to the M12 {@link delegate}. */\nexport type DelegateFn = (\n subAgent: SubAgentSpec,\n message: string,\n opts?: DelegateOptions,\n) => Promise<DelegationResult>\n\n/** A running background delegation the supervisor can await/poll later. */\nexport interface BackgroundDelegation {\n /** Await the sub-agent's result (or rejection). Idempotent — returns the same settled promise. */\n wait(): Promise<DelegationResult>\n /** Whether the underlying delegation has resolved or rejected. */\n settled(): boolean\n}\n\n/**\n * Start a sub-agent WITHOUT blocking the supervisor. Returns immediately with a handle; the\n * supervisor keeps working and calls `wait()` when it needs the result. A thin async wrapper over\n * `delegate` — not a scheduler (Top-risk 1). Rejections are still observable via `wait()`.\n */\nexport function delegateBackground(\n subAgent: SubAgentSpec,\n message: string,\n opts: DelegateOptions & { delegateFn?: DelegateFn } = {},\n): BackgroundDelegation {\n const { delegateFn = delegate, ...delegateOpts } = opts\n let isSettled = false\n const promise = delegateFn(subAgent, message, delegateOpts).finally(() => {\n isSettled = true\n })\n // Swallow the unhandled-rejection warning: the rejection surfaces through wait().\n promise.catch(() => undefined)\n return {\n wait: () => promise,\n settled: () => isSettled,\n }\n}\n\n/** A scorer's verdict on a sub-agent result. `feedback` is fed back into the next round on failure. */\nexport interface ScoreVerdict {\n pass: boolean\n /** Optional numeric score (0..1) for logging/telemetry. */\n score?: number\n /** Guidance appended to the next delegation when `pass` is false. */\n feedback?: string\n}\n\n/** Scores a sub-agent result. Opt-in (Top-risk 2) — the caller supplies it, and pays its cost. */\nexport type Scorer = (result: DelegationResult) => ScoreVerdict | Promise<ScoreVerdict>\n\n/** The outcome of a scored delegation: the final result plus the per-round verdict trail. */\nexport interface ScoredDelegation {\n result: DelegationResult\n /** Rounds actually run (1..maxRounds). */\n rounds: number\n /** Whether the final round passed the scorer. */\n passed: boolean\n /** The verdict from each round, in order. */\n verdicts: ScoreVerdict[]\n}\n\nconst DEFAULT_MAX_ROUNDS = 3\n\n/** Default: append the scorer feedback under a `Feedback:` header for the next round. */\nfunction defaultFeedbackTemplate(message: string, feedback: string): string {\n return `${message}\\n\\nFeedback from the reviewer (address this): ${feedback}`\n}\n\n/**\n * Run `delegate`, score the result, and re-delegate with the scorer's feedback until it passes or\n * `maxRounds` is reached. Each round is ONE `delegate` call — no second loop, no new store. Returns\n * the final result (passing, or the last attempt) with the per-round verdict trail.\n */\nexport async function delegateWithScoring(\n subAgent: SubAgentSpec,\n message: string,\n opts: DelegateOptions & {\n scorer: Scorer\n maxRounds?: number\n delegateFn?: DelegateFn\n feedbackTemplate?: (message: string, feedback: string) => string\n },\n): Promise<ScoredDelegation> {\n const {\n scorer,\n maxRounds: maxRoundsOpt = DEFAULT_MAX_ROUNDS,\n delegateFn = delegate,\n feedbackTemplate = defaultFeedbackTemplate,\n ...delegateOpts\n } = opts\n // Clamp to ≥ 1 so at least one delegate call always runs (guarantees a result).\n const maxRounds = Math.max(1, maxRoundsOpt)\n\n const verdicts: ScoreVerdict[] = []\n let currentMessage = message\n let lastResult: DelegationResult | undefined\n\n for (let round = 1; round <= maxRounds; round++) {\n const result = await delegateFn(subAgent, currentMessage, delegateOpts)\n lastResult = result\n const verdict = await scorer(result)\n verdicts.push(verdict)\n if (verdict.pass) {\n return { result, rounds: round, passed: true, verdicts }\n }\n // Failed — fold the feedback into the next round's message (if any feedback was given).\n if (verdict.feedback) currentMessage = feedbackTemplate(message, verdict.feedback)\n }\n\n // Exhausted maxRounds without passing — return the last attempt honestly (passed: false).\n // The clamped `maxRounds >= 1` guarantees at least one delegate call — but assert it instead of\n // asserting the type away: if the invariant ever breaks, fail loudly rather than return undefined.\n if (lastResult === undefined) {\n throw new Error('[@theokit/agents] delegateWithScoring: no round ran (maxRounds < 1)')\n }\n return {\n result: lastResult,\n rounds: maxRounds,\n passed: false,\n verdicts,\n }\n}\n","/**\n * M24 (ADR-0041) — MCP follow-ups, framework-side layer over the `@MCP` config (ADR-0040 § D2).\n *\n * Three home/boundary helpers that compose with the existing `@MCP` / `defineAgent` surfaces — the\n * SDK still owns MCP server EXECUTION (`Agent.create({ mcpServers })`); these only shape the config:\n * - `resolveMcpServers` — per-request resolver so multi-tenant apps hand different MCP creds to\n * different callers (mirrors the M13 skills resolver);\n * - `mcpRegistry` — build a server config for a known MCP registry (Composio / mcp.run);\n * - `mcpToolApprovals` — mark MCP tools for approval, producing the M14 `approvals` entries so a\n * gated MCP tool routes through the (E2E-proven) HITL flow.\n */\nimport type { HumanInTheLoopOptions } from '../types.js'\nimport type { McpServersMap } from '../types.js'\n\n/** The request context handed to an MCP resolver (the M7 run-context — opaque per-request data). */\nexport type McpRequestContext = Record<string, unknown>\n\n/**\n * How the MCP server set is chosen:\n * - a map — static `@MCP`-style config.\n * - a function — resolved per request from the {@link McpRequestContext} (sync or async).\n */\nexport type McpSelection =\n | McpServersMap\n | ((ctx: McpRequestContext) => McpServersMap | Promise<McpServersMap>)\n\n/**\n * Resolve the MCP servers for a request. Returns `undefined` when no selection is given. Fails fast\n * if a resolver returns a non-object (error-handling.md). Multi-tenant apps pass a function that\n * reads per-user credentials from `ctx`.\n */\nexport async function resolveMcpServers(\n selection: McpSelection | undefined,\n ctx: McpRequestContext,\n): Promise<McpServersMap | undefined> {\n if (selection === undefined) return undefined\n if (typeof selection !== 'function') return selection\n const resolved: unknown = await selection(ctx)\n if (typeof resolved !== 'object' || resolved === null) {\n throw new Error('[@theokit/agents] MCP resolver must return an McpServersMap object')\n }\n return resolved as McpServersMap\n}\n\n/** Config for {@link mcpRegistry}. `registry` selects a known provider. */\nexport interface McpRegistryConfig {\n registry: 'composio' | 'mcp.run'\n /** The registry API key (kept in the server's env, never logged). */\n apiKey: string\n /** Composio: the app toolkits to expose (e.g. `['github', 'slack']`). */\n apps?: string[]\n /** mcp.run: the profile to connect. */\n profile?: string\n}\n\n/**\n * Build an {@link McpServersMap} for a known MCP registry. Emits an `npx`-launched server config with\n * the API key in `env`. Documented registries: **Composio** (`@composio/mcp`) and **mcp.run**\n * (`@mcp.run/cli`). Other registries are wired manually via a raw `@MCP` entry.\n */\nexport function mcpRegistry(config: McpRegistryConfig): McpServersMap {\n // Compare as a string so an out-of-union value (JS callers) reaches the fail-fast branch.\n const registry: string = config.registry\n if (registry === 'composio') {\n const apps = config.apps ?? []\n return {\n composio: {\n command: 'npx',\n args: ['-y', '@composio/mcp', ...(apps.length > 0 ? ['--apps', apps.join(',')] : [])],\n env: { COMPOSIO_API_KEY: config.apiKey },\n },\n }\n }\n if (registry === 'mcp.run') {\n return {\n 'mcp.run': {\n command: 'npx',\n args: [\n '-y',\n '@mcp.run/cli',\n 'serve',\n ...(config.profile ? ['--profile', config.profile] : []),\n ],\n env: { MCP_RUN_API_KEY: config.apiKey },\n },\n }\n }\n throw new Error(\n `mcpRegistry: unknown registry ${JSON.stringify(registry)} (supported: 'composio', 'mcp.run').`,\n )\n}\n\n/** An MCP tool's approval spec: full {@link HumanInTheLoopOptions} or a bare question string. */\nexport type McpApprovalSpec = HumanInTheLoopOptions | string\n\n/**\n * Mark MCP tools for human approval (`requireToolApproval`). Returns the `Record<toolName,\n * HumanInTheLoopOptions>` shape the M14 `defineAgent({ approvals })` map consumes — so a gated MCP\n * tool routes through the same (E2E-proven) HITL flow as a native gated tool. A bare string is\n * shorthand for `{ question }`.\n */\nexport function mcpToolApprovals(\n specs: Record<string, McpApprovalSpec>,\n): Record<string, HumanInTheLoopOptions> {\n const out: Record<string, HumanInTheLoopOptions> = {}\n for (const [tool, spec] of Object.entries(specs)) {\n out[tool] = typeof spec === 'string' ? { question: spec } : spec\n }\n return out\n}\n","/**\n * Agent manifest generator — build-time JSON describing all agents, tools, guards, policies.\n *\n * Feeds: theokit agents list/inspect, TheoCloud deploy, UI agent consoles.\n */\n/**\n * M53 — the manifest's OWN input contract, listing exactly the members it reads. It used to take an\n * `AgentWalkResult`, which chained the manifest to the decorator metadata walk that M53 deletes.\n *\n * `AgentWalkResult` satisfies this structurally, so the decorator path keeps working unchanged while\n * the migration is in flight; once the walk is gone, the capability path builds this directly. The\n * point is that the manifest never needed the whole walk — only these members.\n */\nexport interface AgentManifestSource {\n readonly agentConfig: { name: string; model?: string; stream?: boolean }\n readonly route: string\n readonly mainLoop: { propertyKey: string | symbol; strategy: string }\n readonly guards: readonly { name: string }[]\n readonly interceptors: readonly { name: string }[]\n readonly toolboxes: readonly {\n namespace?: string\n tools: readonly {\n config: { name: string; description: string; risk?: string }\n approval?: unknown\n capabilities?: string[]\n trace: boolean\n audit: boolean\n }[]\n }[]\n readonly gateway?: { platforms: string[]; sessionStrategy?: string }\n readonly subAgentClasses: readonly { name: string }[]\n readonly memory?: { provider?: string; embeddings?: boolean; fts?: boolean; scope?: string }\n readonly skills?: { include?: string[] }\n readonly mcpServers?: Record<string, unknown>\n}\n\nexport interface AgentManifest {\n version: '1.0'\n generatedAt: string\n agents: AgentManifestEntry[]\n}\n\nexport interface AgentManifestEntry {\n name: string\n route: string\n model?: string\n stream: boolean\n mainLoop: {\n method: string\n strategy: string\n }\n guards: string[]\n interceptors: string[]\n tools: AgentManifestTool[]\n gateway?: {\n platforms: string[]\n sessionStrategy: string\n }\n subAgents: string[]\n memory?: { provider: string; embeddings: boolean; fts: boolean; scope: string }\n skills?: string[]\n mcpServers?: string[]\n}\n\nexport interface AgentManifestTool {\n name: string\n description: string\n risk?: string\n approval: boolean\n capabilities?: string[]\n trace: boolean\n audit: boolean\n}\n\n/**\n * Generate a serializable agent manifest from an {@link AgentManifestSource} per agent.\n * All Function references are converted to string names for JSON safety.\n */\nexport function generateAgentManifest(sources: AgentManifestSource[]): AgentManifest {\n return {\n version: '1.0',\n generatedAt: new Date().toISOString(),\n agents: sources.map((r) => ({\n name: r.agentConfig.name,\n route: r.route,\n model: r.agentConfig.model,\n stream: r.agentConfig.stream ?? true,\n mainLoop: {\n method: String(r.mainLoop.propertyKey),\n strategy: r.mainLoop.strategy,\n },\n guards: r.guards.map((g) => g.name),\n interceptors: r.interceptors.map((i) => i.name),\n tools: r.toolboxes.flatMap((tb) =>\n tb.tools.map((t) => ({\n name: tb.namespace ? `${tb.namespace}.${t.config.name}` : t.config.name,\n description: t.config.description,\n risk: t.config.risk,\n approval: t.approval !== undefined,\n capabilities: t.capabilities,\n trace: t.trace,\n audit: t.audit,\n })),\n ),\n gateway: r.gateway\n ? {\n platforms: r.gateway.platforms,\n sessionStrategy: r.gateway.sessionStrategy ?? 'per-user',\n }\n : undefined,\n subAgents: r.subAgentClasses.map((cls) => cls.name),\n memory: r.memory\n ? {\n provider: r.memory.provider ?? 'built-in',\n embeddings: r.memory.embeddings ?? false,\n fts: r.memory.fts ?? false,\n scope: r.memory.scope ?? 'per-user',\n }\n : undefined,\n skills: r.skills?.include,\n mcpServers: r.mcpServers ? Object.keys(r.mcpServers) : undefined,\n })),\n }\n}\n","/**\n * agentsPlugin() — TheoKit dev-server plugin for agent routes.\n *\n * Mirrors httpDecoratorsPlugin() pattern. Registers agent HTTP endpoints\n * (POST /chat, GET /runs/:id) via the TheoKit plugin hook system.\n *\n * Per ADR D6: structural { name, register } shape (no compile-time theokit dep).\n */\n\nimport { type CompiledAgentOptions } from './bridge/agent-compiler.js'\nimport { generateAgentRoutes, type AgentRoute } from './bridge/agent-route-generator.js'\nimport type { StreamEvent } from './bridge/agent-sse-handler.js'\n\n/**\n * An agent the plugin mounts: its name, route and already-compiled options (from `applyCapabilities`).\n */\nexport interface PluginAgentEntry {\n readonly name: string\n readonly route: string\n readonly compiled: CompiledAgentOptions\n}\n\n/** Route/name identity used to detect duplicate agent routes. */\nexport interface RouteIdentity {\n readonly route: string\n readonly agentConfig: { name: string }\n}\n\n/** Fail fast on two agents mounting the same route. */\nfunction validateUniqueRoutes(results: readonly RouteIdentity[]): void {\n const seen = new Map<string, string>()\n for (const r of results) {\n const existing = seen.get(r.route)\n if (existing !== undefined) {\n throw new Error(\n `[@theokit/agents] Duplicate agent route '${r.route}': ` +\n `both '${existing}' and '${r.agentConfig.name}' declare it.`,\n )\n }\n seen.set(r.route, r.agentConfig.name)\n }\n}\n\nexport interface AgentsPluginOptions {\n /** Agents to mount: prepared entries built by `applyCapabilities`. */\n agents: PluginAgentEntry[]\n /** Factory that creates agent runs — bridges to SDK Agent.create() + agent.send(). */\n createRunFactory?: (\n compiled: CompiledAgentOptions,\n ) => (message: string, sessionId: string) => AsyncIterable<StreamEvent>\n}\n\ninterface PluginApp {\n addHook(name: string, fn: (ctx: { request: Request }) => Promise<Response | undefined>): void\n}\n\n/**\n * Create a TheoKit plugin that mounts agent routes.\n * Web Standard Request/Response — runtime-agnostic.\n */\nexport function agentsPlugin(opts: AgentsPluginOptions) {\n let routes: CompiledRoute[] | null = null\n\n return {\n name: '@theokit/agents',\n\n register(app: PluginApp) {\n app.addHook('onRequest', async (pluginCtx) => {\n routes ??= initRoutes(opts)\n\n const request = pluginCtx.request\n const url = new URL(request.url)\n const method = request.method.toUpperCase()\n\n const matched = matchRoute(routes, method, url.pathname)\n if (!matched) return // fall through\n\n return matched.handler(request)\n })\n },\n }\n}\n\n/** Initialize routes from agent metadata (once). */\nfunction initRoutes(opts: AgentsPluginOptions): CompiledRoute[] {\n const allRoutes: AgentRoute[] = []\n const routeIdentities: RouteIdentity[] = []\n\n for (const entry of opts.agents) {\n routeIdentities.push({ route: entry.route, agentConfig: { name: entry.name } })\n\n const createRun = opts.createRunFactory\n ? opts.createRunFactory(entry.compiled)\n : defaultCreateRun(entry.compiled)\n\n allRoutes.push(\n ...generateAgentRoutes({\n walkResult: { route: entry.route },\n compiledOptions: entry.compiled,\n createRun,\n }),\n )\n }\n\n validateUniqueRoutes(routeIdentities)\n return compileRoutePatterns(allRoutes)\n}\n\n/** Default run factory — returns a mock stream when SDK not wired. */\nfunction defaultCreateRun(compiled: CompiledAgentOptions) {\n return async function* (_message: string, _sessionId: string): AsyncGenerator<StreamEvent> {\n await Promise.resolve() // yield to event loop for async contract\n yield {\n type: 'run_started',\n runId: `run-${Date.now()}`,\n agentName: compiled.model ?? 'unknown',\n }\n yield {\n type: 'error',\n code: 'SDK_NOT_WIRED',\n message:\n 'No createRunFactory provided — wire @theokit/sdk Agent.create() to enable real agent execution.',\n retryable: false,\n }\n }\n}\n\ninterface CompiledRoute extends AgentRoute {\n regex?: RegExp\n}\n\n/** Pre-compile route patterns for efficient matching. */\nfunction compileRoutePatterns(routes: AgentRoute[]): CompiledRoute[] {\n return routes.map((r) => {\n if (!r.path.includes(':')) return r\n const regexSource = r.path.replace(/:[^/]+/g, '[^/]+')\n return { ...r, regex: RegExp(`^${regexSource}$`) }\n })\n}\n\n/** Simple route matcher — checks method + path prefix. */\nfunction matchRoute(\n routes: CompiledRoute[],\n method: string,\n pathname: string,\n): CompiledRoute | undefined {\n return routes.find((r) => {\n if (r.method !== method) return false\n if (r.regex) return r.regex.test(pathname)\n return r.path === pathname\n })\n}\n"],"mappings":";;;;;AAiBA,SAASA,0BAA0B;;;ACW5B,IAAMC,cAA6BC,uBAAOC,IAAI,0BAAA;AAiH9C,SAASC,YACdC,QAAiC;AAEjC,SAAO;IAAE,GAAGA;IAAQ,CAACJ,WAAAA,GAAc;EAAK;AAC1C;AAJgBG;AAOT,SAASE,kBAAkBC,OAAc;AAC9C,SACE,OAAOA,UAAU,YACjBA,UAAU,QACTA,MAAkDN,WAAAA,MAAiB;AAExE;AANgBK;AAehB,SAASE,eAAeC,MAAgB;AAMtC,QAAMC,UAAUD,KAAKC;AAIrB,QAAMC,WAAyB;IAC7BC,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AO,QAAOzD,EAAEyD,MAAMG,KAAKpC,QAAAA;AACjC,WAAOxB,EAAEqD,SAAS7B;EACpB,CAAA;AACF;AAVSD;","names":["ConfigurationError","AGENT_BRAND","Symbol","for","defineAgent","config","isAgentDefinition","value","toCompiledTool","tool","handler","compiled","name","description","inputSchema","input","ctx","sym","Object","getOwnPropertySymbols","compileAgentDefinition","def","model","reasoningEffort","systemPrompt","system","tools","map","agents","stream","context","undefined","runContext","guardrails","approvals","hitl","compileApprovals","compileSkillsSelection","skills","settingSources","memory","compileHooksAndPlugins","mcpServers","hooks","entries","filter","h","explicit","plugins","length","plugin","version","kind","register","hookName","on","skillsResolver","enabled","inline","entry","push","autoInject","toolNames","Set","t","gates","Map","toolName","options","has","Error","join","set","STRATEGY_KNOBS","compileContextWindow","options","context","maxTokens","opts","metadataOnlyKnobs","filter","knob","undefined","compileSkills","options","autoDiscover","autoInject","enabled","include","SDK_TOOL_NAME","SDK_TOOL_NAME_MAX_LENGTH","SDK_TOOL_NAME_CHARSET","SDK_RESERVED_TOOL_NAMES","Set","SDK_RESERVED_TOOL_PREFIX","toolRuntimeName","namespace","toolName","trim","length","where","ConfigurationError","name","test","String","has","startsWith","join","compileHitlGates","toolboxes","gates","Map","tb","tool","tools","hitl","set","config","compileTools","toolboxInstances","instance","get","class","handler","propertyKey","push","description","inputSchema","input","call","createAgentExecutionContext","base","agent","run","toolCall","getRequest","getUrl","getClass","getMethodName","getAgent","getRun","getToolCall","isAgentContext","ctx","UNMAPPED_KNOBS","projectContextMetadataOnlyKnobs","options","opts","filter","knob","undefined","compileProjectContext","base","promptCtx","resolvedBase","cwd","buildEnvContext","buildRepoMap","readProjectInstructions","env","repoMap","ignore","ignorePatterns","instructions","content","Boolean","join","encoder","TextEncoder","streamAgentResponse","eventStream","stream","ReadableStream","start","controller","closed","safeEnqueue","chunk","enqueue","event","data","JSON","stringify","frame","type","encode","err","errorEvent","error","message","Error","close","Response","status","headers","isTextDelta","e","type","isToolCall","isPartialToolCall","isToolResult","isDone","isError","isApprovalRequired","generateAgentRoutes","ctx","walkResult","createRun","getRun","basePath","route","replace","routes","push","method","path","handler","request","body","json","message","length","Response","JSON","stringify","error","code","status","headers","rawSessionId","sessionId","Date","now","streamAgentResponse","url","URL","runId","pathname","split","pop","run","asString","value","fallback","serializeToolOutput","undefined","JSON","stringify","toString","translateSystemEvent","msg","runId","type","agentName","agent_id","model","translateAssistantEvent","events","message","content","Array","isArray","block","b","text","push","callId","id","Date","now","toolName","name","input","translateToolCallEvent","status","call_id","output","result","durationMs","isError","args","arguments","translateStatusEvent","s","usage","inputTokens","outputTokens","totalTokens","cost","code","retryable","translateSdkEvent","translateInteractionUpdate","update","toolCall","buildModelSelection","modelId","effort","id","params","value","TAG","OPEN","CLOSE","heldPrefixLength","s","delim","max","Math","min","length","k","slice","createThinkTagExtractor","mode","buffer","write","chunk","out","idx","indexOf","content","push","kind","keep","emit","end","seg","segmentToEvent","type","extractThinkTagStream","source","extractor","event","debugLog","marker","data","flag","process","env","THEOKIT_DEBUG","undefined","console","debug","assembleM8CreateOptions","compiled","options","applied","base","systemPrompt","skills","push","plugins","settingSources","resolveSettingSources","local","context","projectContext","compileProjectContext","undefined","mcpServers","Object","keys","length","memory","dropped","process","stderr","write","join","enabled","explicit","realUsageDone","result","t0","u","usage","inputTokens","outputTokens","type","totalTokens","reasoningTokens","cacheReadTokens","cacheWriteTokens","durationMs","Date","now","cost","amount","OPEN","CLOSE","heldPrefixLength","s","delim","max","Math","min","length","k","slice","createToolDialectStripper","mode","buffer","pendingLeak","write","chunk","out","idx","indexOf","content","push","kind","keep","emit","end","leftover","stripToolDialectStream","source","stripper","event","type","seg","withLeakedDialectRecovery","providers","routes","map","route","extractToolCallsFromContent","buildExtraCreateOptions","overrides","compiled","recoverLeakedToolCalls","extra","plugins","undefined","asArray","v","Array","isArray","overrideList","compiledList","agents","budgetTracker","loadSdkRuntime","sdk","skillReadTool","SkillReadTool","Agent","defineTool","Tool","create","bind","defineSkillReadTool","skills","err","console","warn","createAsyncQueue","items","wake","closed","push","item","close","Symbol","asyncIterator","length","next","shift","Promise","resolve","streamCallId","ev","callId","isDuplicatedByDelta","state","type","sawTextDelta","sawThinkingDelta","id","emittedToolCallIds","has","emittedToolResultIds","mergeDeltaStream","queue","openStream","runId","pumpError","pump","stream","msg","kind","catch","thrown","event","out","translateSdkEvent","sawError","createDeltaSink","Set","onDelta","d","translateInteractionUpdate","update","add","resolveTextTransformFlags","parseThinkTags","stripToolDialect","applyTextTransforms","events","opts","extractThinkTagStream","stripToolDialectStream","hasZodInputSchema","schema","parse","withRunContext","handler","runContext","input","ctx","context","buildSdkTools","compiledTools","extraSdkTools","t","inputSchema","name","description","createSdkAgentStream","apiKey","model","reasoningEffort","factory","message","sessionId","factoryOpts","Date","now","t0","rt","code","retryable","sdkTools","inlineSkills","inline","some","runContextSource","debugLog","source","keys","Object","streamSdkAgent","Error","assign","resolvedModel","options","m8","applied","assembleM8CreateOptions","cwd","local","baseDir","includes","contextWindow","projectContext","agent","getOrCreate","buildModelSelection","tools","sendOptions","disableTools","toolChoice","sendInput","images","text","sendPromise","send","merged","realUsageDone","wait","dispose","toAgentFactory","def","compileAgentDefinition","UnknownPresenterError","Error","name","surface","known","join","PresenterRegistry","Map","register","presenter","set","has","surfaces","keys","resolve","p","get","undefined","asString","value","fallback","serializeToolResult","JSON","stringify","toString","fromAssistant","msg","events","content","message","Array","isArray","block","b","type","text","push","callId","id","Date","now","input","fromToolUse","status","call_id","result","isError","args","arguments","fromStatus","s","reason","toLowerCase","code","fromSdkMessage","fromInteractionUpdate","update","toolCall","UIMessageStreamPresenter","Set","options","textId","start","present","event","errorText","finish","metadata","out","messageMetadata","closeBlock","hasSeen","markSeen","add","delta","reasoningId","crypto","randomUUID","toolCallId","toolName","dynamic","output","ANSI","reasoning","tool","error","RESET","preview","max","raw","safeJson","flat","replace","trim","length","slice","suffix","open","close","TerminalPresenter","ansi","maxPreview","detail","usage","totalTokens","body","tokens","r","t","kind","JsonPresenter","namespace","payload","toAgentOutputEvent","e","type","text","content","callId","name","toolName","input","result","output","isError","doneToMetadata","event","cost","undefined","usage","durationMs","presentUIMessageStream","events","opts","presenter","UIMessageStreamPresenter","textId","turnMetadata","present","closeBlock","hasSeen","markSeen","toolCallId","dynamic","approvalId","data","checkpointId","resumeToken","step","transient","errorText","message","err","String","finish","ContextualTool","of","tool","_requiredContext","makeBuilder","config","runtime","input","schema","model","id","system","prompt","reasoningEffort","effort","context","value","tools","guardrail","g","guardrails","gs","approval","toolName","options","approvals","map","skills","selection","settingSources","sources","memory","settings","hooks","plugins","list","mcp","servers","mcpServers","use","preset","build","defineAgent","AgentBuilder","create","createHitlPlugin","wiring","name","version","kind","register","ctx","on","c","opts","gated","get","undefined","approvalId","crypto","randomUUID","emit","type","callId","toolName","question","input","args","callbackUrl","timeoutMs","timeout","payloadSchema","raw","awaitApproval","decision","approved","message","reason","payload","JSON","stringify","block","AgentDefinitionError","Error","source","name","extractDefaultExport","mod","default","isCompiledAgentOptions","value","v","Array","isArray","tools","agents","compileAgentModule","def","isAgentDefinition","compileAgentDefinition","asAgentStream","events","e","EventQueue","push","item","r","shift","done","close","splice","undefined","drain","length","next","Promise","resolve","appendCheckpointSaved","sessionId","emitted","checkpoint","type","checkpointId","crypto","randomUUID","step","resumeToken","ev","streamAgentUIMessages","compiled","apiKey","input","textId","overrides","cwd","baseDir","images","hitl","gated","size","createSdkAgentStream","message","queue","signal","addEventListener","once","plugin","createHitlPlugin","emit","awaitApproval","sdkStream","plugins","err","code","String","retryable","durableCheckpoint","storage","presentUIMessageStream","GuardrailViolationError","Error","guardName","phase","reason","name","CostBudgetExceededError","usedTokens","maxTokens","estimateTokens","text","Math","ceil","length","INJECTION_PHRASES","normalizeForMatch","toLowerCase","replace","promptInjectionDetector","options","phrases","extra","map","p","name","checkInput","normalized","phrase","includes","action","reason","CPF","EMAIL","PHONE","piiDetector","placeholder","redacted","OBFUSCATION_CHARS","unicodeNormalizer","cleaned","normalize","costGuard","used","maxTokens","Promise","reject","CostBudgetExceededError","resolve","outputModeration","checkOutput","flagged","moderate","runInputGuards","text","guards","current","g","checkInput","r","action","GuardrailViolationError","name","reason","undefined","runOutputGuards","checkOutput","moderateOutputStream","inner","guards","extractText","hasOutputGuard","some","g","checkOutput","buffered","accumulated","step","next","done","event","value","text","undefined","push","runOutputGuards","compactTranscript","z","DEFAULT_KEEP_TOKENS","compactionStrategyConfigSchema","z","object","name","literal","keepTokens","number","int","positive","resolveCompactionStrategy","config","cfg","parse","compact","messages","options","compactTranscript","summarize","marker","summaryTemplate","failSafe","tokenBudgetCompactionStrategy","z","DEFAULT_MAX_ITERATIONS","maxIterationsSchema","z","number","int","min","loopStrategyConfigSchema","object","name","enum","maxIterations","assertValidCustomLoopStrategy","strategy","result","safeParse","success","Error","String","resolveLoopStrategy","cfg","parse","shouldContinue","outcome","round","finishReason","z","reflectionStrategyConfigSchema","object","name","string","min","ladderReflectionStrategy","reflect","outcome","finishReason","feedback","round","continue","noopReflectionStrategy","BudgetExceededError","Error","agentName","actualCost","budgetLimit","toFixed","name","DelegationError","cause","message","String","asString","value","fallback","asNumber","NO_PROGRESS_THRESHOLD","MAINLOOP_METRIC","TOOL_CALLS","STEP_LIMIT_HINT","stableStringify","undefined","JSON","stringify","Array","isArray","map","join","obj","entries","Object","keys","sort","a","b","localeCompare","k","roundSignature","toolCalls","tc","name","input","terminalReason","reflectionContinue","roundReason","round","maxIterations","CONTINUE_PROMPT","buildPrompt","message","feedback","hint","continuation","body","consumeRoundOrThrow","inputs","agentName","consumeOneRound","factory","prompt","sessionId","signal","retry","err","BudgetExceededError","DelegationError","accumulateUsage","acc","r","cost","tokens","tokensInput","tokensOutput","reasoningTokens","cacheReadTokens","cacheWriteTokens","finalize","reason","strategyName","rounds","finishReason","debugLog","strategy","terminal","deriveFinishReason","signals","sawError","sawDone","doneFinishReason","sawToolResult","pushToolResult","event","callInputs","id","callId","call","get","push","toolName","output","applyDone","usage","totalTokens","inputTokens","outputTokens","accumulateEvent","type","content","responseText","set","errorMessage","startRound","open","it","Symbol","asyncIterator","first","next","return","Retry","create","Map","done","aborted","ceilingRoundFactory","m","s","disableTools","runReflectiveLoopStream","config","loop","reflection","budget","Number","POSITIVE_INFINITY","response","reflectionContext","prevSig","stuck","roundFactory","isFinite","length","sig","outcome","reflectionResult","reflect","continue","shouldContinue","runReflectiveLoop","gen","res","AgentRunner","compiled","agentName","loopStrategy","loopStrategyIsCustom","reflectionStrategy","streamEnabled","compaction","state","fromSpec","spec","AgentRunnerBuilder","stream","message","opts","guardrails","length","runUnguarded","m","streamUnguarded","guarded","safe","runInputGuards","moderateOutputStream","e","type","content","undefined","tools","loop","resolvePerRunLoop","maxIterations","streamFactory","createSdkAgentStream","apiKey","model","reasoningEffort","parseThinkTags","stripToolDialect","recoverLeakedToolCalls","cwd","baseDir","plugins","providers","agents","budgetTracker","sdkTools","sessionId","crypto","randomUUID","runReflectiveLoopStream","reflection","budget","signal","retry","base","Object","assign","create","getPrototypeOf","resolveLoopStrategy","name","run","gen","res","next","done","value","reflectionOverride","compactionOverride","loopStrategyOverride","strategy","custom","assertValidCustomLoopStrategy","enabled","options","keepTokens","build","ladderReflectionStrategy","noopReflectionStrategy","compactionDecl","resolveCompactionStrategy","runGoalLoop","GoalRunner","agent","run","goal","options","deps","runGoalLoop","requireApiKey","opts","agentName","apiKey","DelegationError","mergeTools","parentTools","subTools","subToolNames","Set","map","t","name","inherited","filter","has","delegate","spec","message","effectiveMessage","onDelegationStart","subAgent","input","compiled","allTools","tools","budget","Math","min","Infinity","parentBudgetRemaining","streamFactory","createSdkAgentStream","model","cwd","plugins","providers","agents","budgetTracker","sdkTools","sessionId","crypto","randomUUID","loopStrategy","resolveLoopStrategy","strategy","maxIterations","reflection","ladderReflectionStrategy","noopReflectionStrategy","result","runReflectiveLoop","loop","signal","retry","onDelegationComplete","createToolHooksPlugin","hooks","name","version","kind","register","ctx","beforeToolCall","afterToolCall","beforeLLMCall","afterLLMCall","processInput","on","c","args","result","agentId","runId","iteration","injected","prompt","undefined","length","recalledContext","DEFAULT_MAX_ATTEMPTS","runWithApiErrorHandling","thunk","policy","maxAttempts","attempt","error","decision","processApiError","retry","fallback","undefined","createApiErrorHandler","delegateBackground","subAgent","message","opts","delegateFn","delegate","delegateOpts","isSettled","promise","finally","catch","undefined","wait","settled","DEFAULT_MAX_ROUNDS","defaultFeedbackTemplate","feedback","delegateWithScoring","scorer","maxRounds","maxRoundsOpt","feedbackTemplate","Math","max","verdicts","currentMessage","lastResult","round","result","verdict","push","pass","rounds","passed","Error","resolveMcpServers","selection","ctx","undefined","resolved","Error","mcpRegistry","config","registry","apps","composio","command","args","length","join","env","COMPOSIO_API_KEY","apiKey","profile","MCP_RUN_API_KEY","JSON","stringify","mcpToolApprovals","specs","out","tool","spec","Object","entries","question","generateAgentManifest","sources","version","generatedAt","Date","toISOString","agents","map","r","name","agentConfig","route","model","stream","mainLoop","method","String","propertyKey","strategy","guards","g","interceptors","i","tools","toolboxes","flatMap","tb","t","namespace","config","description","risk","approval","undefined","capabilities","trace","audit","gateway","platforms","sessionStrategy","subAgents","subAgentClasses","cls","memory","provider","embeddings","fts","scope","skills","include","mcpServers","Object","keys","validateUniqueRoutes","results","seen","Map","r","existing","get","route","undefined","Error","agentConfig","name","set","agentsPlugin","opts","routes","register","app","addHook","pluginCtx","initRoutes","request","url","URL","method","toUpperCase","matched","matchRoute","pathname","handler","allRoutes","routeIdentities","entry","agents","push","createRun","createRunFactory","compiled","defaultCreateRun","generateAgentRoutes","walkResult","compiledOptions","compileRoutePatterns","_message","_sessionId","Promise","resolve","type","runId","Date","now","agentName","model","code","message","retryable","map","path","includes","regexSource","replace","regex","RegExp","find","test"]}