@theokit/sdk 4.41.0 → 4.41.1

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.
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../src/agent-builder.ts","../src/internal/auth/api-key-validator.ts","../src/internal/runtime/config/default-model.ts","../src/agent-generate.ts","../src/internal/env.ts","../src/internal/ids.ts","../src/internal/runtime/model-selection.ts","../src/internal/plugins/enabled-names.ts","../src/internal/runtime/registry/agent-registry-store.ts","../src/internal/runtime/registry/agent-registry.ts","../src/internal/runtime/system-prompt/system-prompt.ts","../src/internal/cloud-agent/cloud-config-serializer.ts","../src/internal/runtime/fixtures/fixture-events.ts","../src/internal/memory/migration.ts","../src/internal/runtime/memory/memory-store.ts","../src/internal/runtime/fixtures/fixture-scripts.ts","../src/internal/runtime/fixtures/fixture-responder.ts","../src/internal/runtime/fixtures/fixture-run-base.ts","../src/internal/cloud-agent/cloud-run.ts","../src/internal/cloud-agent/real-cloud-run.ts","../src/internal/cloud-agent/cloud-agent.ts","../src/internal/cloud-agent/cloud-tool-parity.ts","../src/internal/personality/store.ts","../src/internal/plugins/context.ts","../src/internal/plugins/manager.ts","../src/internal/runtime/lifecycle/spawn-collect.ts","../src/internal/runtime/hooks/hooks-executor.ts","../src/internal/runtime/memory/memory-path-selector.ts","../src/internal/runtime/lifecycle/context-budget-event.ts","../src/internal/runtime/lifecycle/post-run-lifecycle.ts","../src/define-tool.ts","../src/internal/runtime/reasoning/native-reasoning.ts","../src/internal/runtime/skills/skills-manager.ts","../src/internal/runtime/system-prompt/local-assembly.ts","../src/internal/runtime/system-prompt/safe-call.ts","../src/internal/runtime/system-prompt/sources/active-memory-provider.ts","../src/internal/runtime/system-prompt/sources/base-provider.ts","../src/internal/runtime/system-prompt/sources/context-provider.ts","../src/internal/runtime/system-prompt/sources/memory-provider.ts","../src/internal/runtime/system-prompt/sources/reasoning-provider.ts","../src/internal/runtime/system-prompt/sources/skills-provider.ts","../src/internal/runtime/system-prompt/pipeline.ts","../src/internal/runtime/validation/validate-agent-options.ts","../src/internal/telemetry/span-names.ts","../src/internal/telemetry/safe-require.ts","../src/internal/telemetry/adapters/arize.ts","../src/internal/telemetry/adapters/braintrust.ts","../src/internal/telemetry/adapters/datadog.ts","../src/internal/telemetry/adapters/langfuse.ts","../src/internal/telemetry/adapters/langsmith.ts","../src/internal/telemetry/adapters/posthog.ts","../src/internal/telemetry/adapters/sentry.ts","../src/internal/telemetry/adapter-registry.ts","../src/internal/telemetry/tracer.ts","../src/internal/runtime/config/providers-manager.ts","../src/internal/persistence/markdown-config-loader.ts","../src/internal/runtime/context/context-loaders.ts","../src/internal/runtime/context/context-aggregator.ts","../src/internal/runtime/context/context-import-resolver.ts","../src/internal/runtime/context/context-glob.ts","../src/internal/runtime/context/context-yaml-lite.ts","../src/internal/runtime/context/context-mdc-parser.ts","../src/internal/runtime/context/context-rules-frontmatter.ts","../src/internal/runtime/context/context-discovery-runner.ts","../src/internal/runtime/context/context-frontmatter.ts","../src/internal/runtime/context/context-manager.ts","../src/internal/runtime/plugins/plugin-frontmatter.ts","../src/internal/runtime/plugins/plugins-manager.ts","../src/internal/local-agent/local-agent-bootstrap.ts","../src/internal/runtime/registry/run-registry.ts","../src/internal/local-agent/local-run.ts","../src/internal/budget/tracker/budget.ts","../src/internal/runtime/validation/validate-response.ts","../src/internal/agent-loop/budget-gate.ts","../src/internal/agent-loop/doom-loop-tracker.ts","../src/internal/budget/usage-accumulator.ts","../src/internal/agent-loop/live-events.ts","../src/internal/agent-loop/message-builders.ts","../src/internal/agent-loop/loop-context-init.ts","../src/internal/tool-dispatch/strip-think.ts","../src/internal/agent-loop/loop-llm-stream.ts","../src/internal/agent-loop/loop-thinking-steps.ts","../src/internal/tool-dispatch/repair-middleware.ts","../src/tool-error.ts","../src/internal/runtime/tools/shell-tool.ts","../src/internal/agent-loop/tool-executors.ts","../src/internal/agent-loop/tool-timeout.ts","../src/internal/agent-loop/tool-dispatch.ts","../src/internal/agent-loop/tool-result-guard.ts","../src/internal/budget/pricing-data.json","../src/internal/budget/pricing-registry.ts","../src/internal/budget/compute-cost.ts","../src/internal/agent-loop/usage-and-cost.ts","../src/internal/agent-loop/loop.ts","../src/internal/llm/fallback-client.ts","../src/internal/mcp/client.ts","../src/internal/providers/register-plugin-providers.ts","../src/internal/local-agent/mcp-pool.ts","../src/internal/tool-registry/personality-filter.ts","../src/internal/local-agent/real-local-run-tools.ts","../src/internal/local-agent/real-local-run.ts","../src/internal/local-agent/local-agent-dispatch.ts","../src/internal/local-agent/local-agent-invalidate.ts","../src/internal/runtime/registry/live-agent-registry.ts","../src/internal/local-agent/local-agent-lifecycle.ts","../src/internal/memory/storage/transcript-store.ts","../src/internal/memory/active-memory.ts","../src/internal/memory/active-memory-cache.ts","../src/internal/memory/adapters/azure-openai-embedding.ts","../src/internal/memory/adapters/cohere-embedding.ts","../src/internal/memory/adapters/deepinfra-embedding.ts","../src/internal/memory/adapters/gemini-embedding.ts","../src/internal/memory/adapters/jina-embedding.ts","../src/internal/memory/adapters/mistral-embedding.ts","../src/internal/memory/adapters/ollama-embedding.ts","../src/internal/memory/adapters/openai-embedding.ts","../src/internal/memory/adapters/openrouter-embedding.ts","../src/internal/memory/adapters/voyage-embedding.ts","../src/internal/memory/adapters/catalog.ts","../src/internal/memory/storage/reader.ts","../src/internal/memory/tools.ts","../src/internal/local-agent/local-agent-memory.ts","../src/internal/local-agent/local-agent-memory-direct.ts","../src/internal/local-agent/local-agent-memory-provider.ts","../src/internal/personality/types.ts","../src/internal/personality/registry.ts","../src/internal/personality/switch.ts","../src/internal/local-agent/local-agent-personality-extensions.ts","../src/internal/local-agent/local-agent-runtime-extensions.ts","../src/internal/runtime/concurrency/abort-utils.ts","../src/internal/runtime/lifecycle/wrap-completion-check-run.ts","../src/internal/runtime/processors/run-processors.ts","../src/internal/runtime/processors/tripwire-run.ts","../src/internal/runtime/processors/wrap-output-run.ts","../src/internal/local-agent/local-agent-memory-hooks.ts","../src/internal/local-agent/local-agent-send.ts","../src/internal/local-agent/local-agent-task-wrap.ts","../src/internal/local-agent/local-agent.ts","../src/agent-helpers.ts","../src/agent.ts"],"names":["randomUUID","ConfigurationError","join","agents","readVersionedJson","withCwdMutex","writeVersionedJson","diag","serializeCloud","serializeAgents","serializeProviders","serializeMemory","access","readFile","appendFactToMarkdown","unlink","legacyMemoryJsonPath","memoryMdPath","readFacts","redactSecrets","appendFact","getConfiguredBaseUrl","NetworkError","parseSseStream","data","isFixtureApiKey","validateArtifactPath","PathTraversalError","UnknownAgentError","UnsupportedRunOperationError","SCHEMA_VERSION","warnOnce","mkdir","dirname","withFileLock","atomicWriteJson","getTheokitHome","resolveChildEnv","spawn","loadHookConfig","resolveEffectiveContextWindow","getCatalogModelInfo","CONTEXT_WINDOW_MARGIN","CONTEXT_WINDOW_FLOOR","persistTurnToTranscript","flushSessionWrites","appendSessionMessage","emitRunEvent","buildDefaultSummarizer","writeSessionSummary","sanitizeToolInput","toJsonSchema","z","discoverSkills","stripSkillFrontmatter","escapeBlockBody","buildSkillsBlock","createRequire","registeredHere","parseSimpleYaml","stat","readdir","resolvePath","homedir","isAbsolute","splitFrontmatter","findGitRoot","DEFAULT_DISCOVERY_SPECS","walkUpForFile","walkUpForGlob","path","relative","existsSync","readWorkspaceDir","safePathJoin","TheokitAgentError","mapWithConcurrency","checkToolWhitelist","safe","renderToolResultContentText","isPatchedModelKey","parseModelId","decision","tryFirstEvent","relayStream","registered","registerProvider","subAgentToolsFromDefinitions","registerBuiltins","getProviderProfile","inferProviderFromApiKey","detectPrimaryProvider","resolveProviderChain","withToolWhitelist","withInheritedSubAgentCredentials","getSessionMessages","shouldUseRealLocalRuntime","entry","discardSession","loadSubagents","memoryDir","finalized","createHash","createOpenAiCompatibleRuntime","DIMENSION_BY_MODEL","IndexManager","warned","CircuitBreaker","currentPersonalityContext","warnPersonalitySwitchInsideFork","clearSession","AgentDisposedError","submit","FsSessionStore","extractCodePlugins","hydrateSession","defaultBaseDir","expandTilde","AuthenticationError","httpRequest","discoverProviderPlugins","AgentRunError","coerceToKnownAgentRunErrorCode","enqueueSessionWrite","setAgentFacade"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCO,IAAM,eAAN,MAAmB;AAAA,EAChB,OAA8B,EAAC;AAAA,EACtB,IAAA;AAAA,EAEjB,YAAY,IAAA,EAAyB;AACnC,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AAAA,EACd;AAAA;AAAA,EAGA,MAAM,CAAA,EAAkC;AACtC,IAAA,IAAA,CAAK,KAAK,KAAA,GAAQ,CAAA;AAClB,IAAA,OAAO,IAAA;AAAA,EACT;AAAA,EACA,OAAO,CAAA,EAAiB;AACtB,IAAA,IAAA,CAAK,KAAK,MAAA,GAAS,CAAA;AACnB,IAAA,OAAO,IAAA;AAAA,EACT;AAAA,EACA,KAAK,CAAA,EAAiB;AACpB,IAAA,IAAA,CAAK,KAAK,IAAA,GAAO,CAAA;AACjB,IAAA,OAAO,IAAA;AAAA,EACT;AAAA,EACA,aAAa,CAAA,EAAwC;AACnD,IAAA,IAAA,CAAK,KAAK,YAAA,GAAe,CAAA;AACzB,IAAA,OAAO,IAAA;AAAA,EACT;AAAA,EACA,MAAM,CAAA,EAAuB;AAC3B,IAAA,IAAA,CAAK,KAAK,KAAA,GAAQ,CAAA;AAClB,IAAA,OAAO,IAAA;AAAA,EACT;AAAA,EACA,MAAM,CAAA,EAAuB;AAC3B,IAAA,IAAA,CAAK,KAAK,KAAA,GAAQ,CAAA;AAClB,IAAA,OAAO,IAAA;AAAA,EACT;AAAA,EACA,OAAO,CAAA,EAAyB;AAC9B,IAAA,IAAA,CAAK,KAAK,MAAA,GAAS,CAAA;AACnB,IAAA,OAAO,IAAA;AAAA,EACT;AAAA,EACA,MAAM,CAAA,EAAuB;AAC3B,IAAA,IAAA,CAAK,KAAK,KAAA,GAAQ,CAAA;AAClB,IAAA,OAAO,IAAA;AAAA,EACT;A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AA,CAAQ,KAAA;AAC7B,EAAA,MAAM,KAAA,GACJ,IAAI,KAAA,EAAO,EAAA,KAAO,OAAO,QAAA,KAAa,QAAA,GAAW,QAAA,GAAW,QAAA,EAAU,EAAA,CAAA,IAAO,SAAA;AAC/E,EAAA,MAAM,EAAE,cAAA,EAAAX,eAAAA,EAAe,GAAI,MAAM,OAAO,iCAA4C,CAAA;AACpF,EAAA,MAAM,EAAE,gBAAAG,eAAAA,EAAgB,WAAA,EAAAC,cAAY,GAAI,MAAM,OAC5C,mCACF,CAAA;AACA,EAAA,MAAM,OAAA,GACJ,GAAA,CAAI,OAAA,CAAQ,KAAA,EAAO,OAAA,KAAY,MAAA,GAC3BA,YAAAA,CAAY,GAAA,CAAI,OAAA,CAAQ,KAAA,CAAM,OAAO,CAAA,GACrCD,eAAAA,EAAe;AACrB,EAAA,OAAO,EAAE,GAAA,EAAK,KAAA,EAAO,KAAA,EAAO,IAAIH,gBAAe,EAAE,OAAA,EAAS,GAAA,EAAK,CAAA,EAAE;AACnE","file":"chunk-F5DSDDBY.cjs","sourcesContent":["import type {\n AgentDefinition,\n AgentOptions,\n CloudOptions,\n CustomTool,\n LocalOptions,\n MemorySettings,\n ModelSelection,\n SDKAgent,\n SkillsSettings,\n SystemPromptResolver,\n} from \"./types/agent.js\";\nimport type { ContextSettings } from \"./types/context.js\";\nimport type { McpServerConfig } from \"./types/mcp.js\";\nimport type { PluginsSettings, ProviderRoutingSettings } from \"./types/providers.js\";\n\n/**\n * Terminal-method callbacks injected by `Agent.builder()` so that\n * `agent-builder.ts` does NOT need a static import of `Agent` — keeps the\n * dependency graph acyclic (G6).\n *\n * @internal\n */\ninterface AgentBuilderDeps {\n create: (options: AgentOptions) => Promise<SDKAgent>;\n getOrCreate: (agentId: string, options: AgentOptions) => Promise<SDKAgent>;\n}\n\n/**\n * Fluent builder for {@link AgentOptions}. Chainable setters mutate internal\n * state and return `this`. Three terminals:\n *\n * - `.build()` — synchronous snapshot (shallow clone) of accumulated options.\n * - `.create()` — calls the injected `create` (Agent.create).\n * - `.getOrCreate(agentId)` — calls the injected `getOrCreate` (Agent.getOrCreate).\n *\n * Validation runs inside the terminals via `validateAgentOptions`. See ADR D25.\n *\n * @public\n */\nexport class AgentBuilder {\n private opts: Partial<AgentOptions> = {};\n private readonly deps: AgentBuilderDeps | undefined;\n\n constructor(deps?: AgentBuilderDeps) {\n this.deps = deps;\n }\n\n /** SE8 — accepts a bare-string id shorthand (`\"openai/gpt-4o-mini\"`) or a {@link ModelSelection}. */\n model(m: string | ModelSelection): this {\n this.opts.model = m;\n return this;\n }\n apiKey(k: string): this {\n this.opts.apiKey = k;\n return this;\n }\n name(n: string): this {\n this.opts.name = n;\n return this;\n }\n systemPrompt(p: string | SystemPromptResolver): this {\n this.opts.systemPrompt = p;\n return this;\n }\n local(l: LocalOptions): this {\n this.opts.local = l;\n return this;\n }\n cloud(c: CloudOptions): this {\n this.opts.cloud = c;\n return this;\n }\n memory(m: MemorySettings): this {\n this.opts.memory = m;\n return this;\n }\n tools(t: CustomTool[]): this {\n this.opts.tools = t;\n return this;\n }\n mcpServers(s: Record<string, McpServerConfig>): this {\n this.opts.mcpServers = s;\n return this;\n }\n agents(a: Record<string, AgentDefinition>): this {\n this.opts.agents = a;\n return this;\n }\n context(c: ContextSettings): this {\n this.opts.context = c;\n return this;\n }\n providers(p: ProviderRoutingSettings): this {\n this.opts.providers = p;\n return this;\n }\n plugins(p: PluginsSettings): this {\n this.opts.plugins = p;\n return this;\n }\n skills(s: SkillsSettings): this {\n this.opts.skills = s;\n return this;\n }\n agentId(id: string): this {\n this.opts.agentId = id;\n return this;\n }\n\n /**\n * Synchronous snapshot of the accumulated options. Returns a SHALLOW CLONE\n * so external mutation of the result doesn't pollute the builder state (EC-2).\n */\n build(): AgentOptions {\n return { ...this.opts } as AgentOptions;\n }\n\n /**\n * Validate + create a fresh agent. Delegates to `Agent.create` via the\n * injected `deps.create`. Throws if the builder was instantiated without\n * deps (i.e., direct `new AgentBuilder()` instead of `Agent.builder()`).\n */\n create(): Promise<SDKAgent> {\n if (this.deps === undefined) {\n return Promise.reject(\n new Error(\n \"AgentBuilder.create() requires Agent.builder() entry — direct construction has no terminals.\",\n ),\n );\n }\n return this.deps.create(this.build());\n }\n\n /**\n * Resume an existing agent or create one if the ID is unknown. Delegates to\n * `Agent.getOrCreate` via the injected `deps.getOrCreate` (ADR D22).\n */\n getOrCreate(agentId: string): Promise<SDKAgent> {\n if (this.deps === undefined) {\n return Promise.reject(\n new Error(\n \"AgentBuilder.getOrCreate() requires Agent.builder() entry — direct construction has no terminals.\",\n ),\n );\n }\n return this.deps.getOrCreate(agentId, this.build());\n }\n}\n","/**\n * T1.3 — API key boundary validation.\n *\n * `validateApiKeyShape(key, provider?)` runs at the create-agent boundary\n * and rejects malformed inputs early (whitespace-only strings, sub-16-char\n * fragments, embedded whitespace, missing-prefix shapes for providers that\n * stamp a known prefix). The check is shape-only — it does NOT make a\n * round-trip to the provider; live validation still happens at the first\n * `fetch` against the provider URL.\n *\n * Exempted from shape validation:\n * - fixture keys (prefix `theo_test_`) — used by SDK consumers' fixture-mode tests.\n * - local-runtime mock key `\"local\"` — used by Ollama / LMStudio / llama.cpp\n * sibling profiles (ADRs D182/D188/D189) whose `authType` is `\"none\"`.\n *\n * @internal\n */\n\nconst FIXTURE_KEY_PREFIX = \"theo_test_\";\n/**\n * The sentinel key that forces the local runtime without a real provider\n * credential. Exported so callers threading an explicit `apiKey` into the\n * provider router can skip it (it is not a real credential). @internal\n */\nexport const LOCAL_RUNTIME_MOCK_KEY = \"local\";\nconst MIN_KEY_LENGTH = 16;\n\ninterface ProviderPrefixHint {\n /** Substring (case-sensitive) that legitimate keys for this provider start with. */\n prefix: string;\n /** Provider canonical name used by the boundary helper for error messages. */\n provider: string;\n}\n\nconst KNOWN_PROVIDER_PREFIXES: ProviderPrefixHint[] = [\n { provider: \"openai\", prefix: \"sk-\" },\n { provider: \"anthropic\", prefix: \"sk-ant-\" },\n { provider: \"openrouter\", prefix: \"sk-or-\" },\n];\n\nexport interface ApiKeyValidationFailure {\n readonly malformed: true;\n readonly reason:\n | \"empty\"\n | \"whitespace_only\"\n | \"too_short\"\n | \"embedded_whitespace\"\n | \"missing_known_prefix\";\n readonly message: string;\n}\n\nexport interface ApiKeyValidationOk {\n readonly malformed: false;\n}\n\nexport type ApiKeyValidationResult = ApiKeyValidationOk | ApiKeyValidationFailure;\n\nexport interface ValidateApiKeyOptions {\n /** Provider name (lowercase) for prefix sanity check. */\n provider?: string;\n /**\n * When `false`, only OBVIOUSLY-malformed inputs (empty, whitespace-only,\n * < 4 chars) are rejected. Set when the caller knows the value is just an\n * identifier (e.g., `shouldUseRealLocalRuntime` mode where the real HTTP\n * call uses an env credential instead of this `apiKey`).\n *\n * When `true` (default), the full shape check applies: 16-char minimum,\n * provider-prefix sanity, no embedded whitespace.\n */\n strict?: boolean;\n}\n\n/**\n * Validate the shape of an API key. Returns a discriminated result; the\n * boundary caller (`agent.ts createLocalAgent` / `createCloudAgent`) throws\n * `AuthenticationError({code:\"malformed_api_key\"})` on failure.\n */\nexport function validateApiKeyShape(\n key: string | undefined,\n options: ValidateApiKeyOptions | string = {},\n): ApiKeyValidationResult {\n // Back-compat: legacy callers pass a bare `provider` string as 2nd arg.\n const opts: ValidateApiKeyOptions = typeof options === \"string\" ? { provider: options } : options;\n const tier1 = checkTier1(key);\n if (tier1.malformed) return tier1;\n // Tier 1 succeeded → key is a non-empty string ≥ 4 chars; narrow it.\n const validKey = key as string;\n if (validKey.startsWith(FIXTURE_KEY_PREFIX) || validKey === LOCAL_RUNTIME_MOCK_KEY) {\n return { malformed: false };\n }\n if (opts.strict === false) return { malformed: false };\n return checkTier2(validKey, opts.provider);\n}\n\nfunction checkTier1(key: string | undefined): ApiKeyValidationResult {\n if (key === undefined || key.length === 0) {\n return { malformed: true, reason: \"empty\", message: \"API key is empty.\" };\n }\n if (key.trim().length === 0) {\n return {\n malformed: true,\n reason: \"whitespace_only\",\n message: \"API key contains only whitespace.\",\n };\n }\n if (key.length < 4) {\n return {\n malformed: true,\n reason: \"too_short\",\n message: `API key must be at least 4 chars (got ${key.length}).`,\n };\n }\n return { malformed: false };\n}\n\nfunction checkTier2(key: string, provider: string | undefined): ApiKeyValidationResult {\n if (key.length < MIN_KEY_LENGTH) {\n return {\n malformed: true,\n reason: \"too_short\",\n message: `API key must be at least ${MIN_KEY_LENGTH} chars (got ${key.length}).`,\n };\n }\n if (/\\s/.test(key)) {\n return {\n malformed: true,\n reason: \"embedded_whitespace\",\n message: \"API key contains embedded whitespace.\",\n };\n }\n return checkProviderPrefix(key, provider);\n}\n\nfunction checkProviderPrefix(key: string, provider: string | undefined): ApiKeyValidationResult {\n if (provider === undefined) return { malformed: false };\n const hint = KNOWN_PROVIDER_PREFIXES.find((p) => p.provider === provider.toLowerCase());\n if (hint === undefined) return { malformed: false };\n if (!key.startsWith(hint.prefix)) {\n return {\n malformed: true,\n reason: \"missing_known_prefix\",\n message: `API key for provider \"${hint.provider}\" expected to start with \"${hint.prefix}\".`,\n };\n }\n return { malformed: false };\n}\n","/**\n * Default agentic model id used when callers create an agent without\n * explicitly setting `model`. Picked from OpenRouter's free tier so a fresh\n * SDK install with `OPENROUTER_API_KEY` set works out-of-the-box. Has solid\n * tool-calling for agentic flows (memory tools, MCP, hooks, subagents).\n *\n * Override per-agent via `Agent.create({ model: { id: \"...\" } })` or\n * per-send via `agent.send(msg, { model: { id: \"...\" } })`. Real\n * provider-side model selection is determined by the API key chosen — this\n * id is the label embedded in run metadata + the value forwarded when the\n * runtime hits OpenRouter directly.\n *\n * @internal\n */\nexport const DEFAULT_AGENTIC_MODEL_ID = \"google/gemini-2.0-flash-001\";\n","/**\n * SE9 — integrated structured output: `agent.generate(input, { output })` runs the\n * agent's NORMAL tool loop (the user's tools run first) and then coerces the final\n * answer into a Zod schema, returning a validated, inferred-typed object.\n *\n * This is SUGAR over `generateObject` (ADR D33) — it does NOT fork the\n * synthetic-forced-tool machinery. Phase 1 is the user's own `agent.send()` run;\n * phase 2 reuses `generateObjectImpl` over the run's final answer.\n *\n * @public\n */\n\nimport type { z as ZodNamespace, ZodType } from \"zod\";\n\nimport { DEFAULT_AGENTIC_MODEL_ID } from \"./internal/runtime/config/default-model.js\";\nimport type { LocalOptions, ModelSelection, SDKAgent } from \"./types/agent.js\";\n// SE9 — GenerateOptions/GenerateRunResult live in types/run.ts (co-located with\n// SendOptions/RunResult they extend) so the SDKAgent interface doesn't import this\n// runtime module — breaking the type cycle. Re-exported for ergonomic import.\nimport type { GenerateOptions, GenerateRunResult, RunResult, SDKUserMessage } from \"./types/run.js\";\n\nexport type { GenerateOptions, GenerateRunResult } from \"./types/run.js\";\n\n/**\n * Shared implementation for `LocalAgent.generate` / `CloudAgent.generate`.\n * @internal\n */\nexport async function agentGenerate<T extends ZodType>(\n agent: SDKAgent,\n agentModel: string | ModelSelection | undefined,\n agentApiKey: string | undefined,\n agentLocal: LocalOptions | undefined,\n input: string | SDKUserMessage,\n options: GenerateOptions<T>,\n): Promise<GenerateRunResult<ZodNamespace.infer<T>>> {\n const { output, maxRetries, errorStrategy, ...sendOptions } = options;\n\n // Phase 1 — the user's own tool loop.\n const run = await agent.send(input, sendOptions);\n const result = await run.wait();\n\n // Reuse generateObject's implementation + error taxonomy. Dynamic import keeps\n // this a runtime edge, not a static one (generate-object takes its agent factory\n // as a callback, so it never edges back here — the graph stays acyclic).\n const { generateObjectImpl, GenerateObjectError } = await import(\"./generate-object.js\");\n\n // A run that did not FINISH with a text answer has nothing to structure.\n const answer = structurableAnswerOrThrow(result, GenerateObjectError);\n\n // Phase 2 — structure the final answer via the forced synthetic output tool.\n // The transient structuring agent is created through the public-facade DI seam\n // (`getAgentFacade()`) rather than a direct `import(\"./agent.js\")` — the same\n // inversion `LocalAgent.fork` / eval / cron use — so this runtime-reachable\n // module never edges back to `agent.ts` (keeps the dependency graph acyclic).\n const { getAgentFacade } = await import(\"./internal/runtime/registry/agent-factory-registry.js\");\n const facade = getAgentFacade();\n const structured = await generateObjectImpl(\n {\n prompt: answer,\n schema: output,\n // `agentModel` arrives already normalized (`this.model` passed through\n // `normalizeModel` in the LocalAgent/CloudAgent constructor), so the widened\n // `string | ModelSelection` field only ever receives a `ModelSelection` here.\n model: agentModel ?? { id: DEFAULT_AGENTIC_MODEL_ID },\n // `local` is required to keep the transient structuring agent local-only;\n // default to the process cwd when the agent had no explicit local config.\n local: agentLocal ?? { cwd: process.cwd() },\n ...(agentApiKey !== undefined ? { apiKey: agentApiKey } : {}),\n ...(maxRetries !== undefined ? { maxRetries } : {}),\n ...(errorStrategy !== undefined ? { errorStrategy } : {}),\n },\n {\n create: (opts) => facade.create(opts),\n delete: (agentId) => facade.delete(agentId),\n },\n );\n\n return {\n object: structured.object,\n result,\n raw: structured.raw,\n usage: structured.usage,\n };\n}\n\n/** The GenerateObjectError constructor shape (typed structurally to avoid a static import). */\ntype GenerateObjectErrorCtor = new (\n code: \"no_tool_call\" | \"parse_failed\",\n message: string,\n cause?: unknown,\n) => Error;\n\n/**\n * Return the phase-1 run's final text answer, or throw a typed error when the run\n * did not FINISH with text to structure (error / cancelled / tool-only completion).\n */\nfunction structurableAnswerOrThrow(\n result: RunResult,\n GenerateObjectError: GenerateObjectErrorCtor,\n): string {\n if (result.status === \"error\") {\n throw new GenerateObjectError(\n \"no_tool_call\",\n `Agent run failed before an answer could be structured: ${result.error?.message ?? \"unknown error\"} [${result.error?.code ?? \"?\"}]`,\n result.error,\n );\n }\n if (result.status === \"cancelled\") {\n throw new GenerateObjectError(\n \"no_tool_call\",\n \"Agent run was cancelled before an answer could be structured.\",\n );\n }\n const answer = result.result;\n if (answer === undefined || answer.length === 0) {\n throw new GenerateObjectError(\n \"no_tool_call\",\n \"The tool loop finished with no text answer (tool-only completion) — there is nothing to structure.\",\n );\n }\n return answer;\n}\n","/**\n * Environment variable used to provide the default API key.\n *\n * @internal\n */\nexport const API_KEY_ENV_VAR = \"THEOKIT_API_KEY\";\n\n/**\n * Resolve the API key with the documented precedence:\n *\n * 1. Explicit `apiKey` argument.\n * 2. The `THEOKIT_API_KEY` environment variable.\n *\n * Returns `undefined` when neither is set.\n *\n * @internal\n */\nexport function resolveApiKey(explicit?: string): string | undefined {\n if (explicit !== undefined && explicit.length > 0) {\n return explicit;\n }\n const fromEnv = process.env[API_KEY_ENV_VAR];\n if (fromEnv !== undefined && fromEnv.length > 0) {\n return fromEnv;\n }\n return undefined;\n}\n","import { randomUUID } from \"node:crypto\";\n\n/**\n * Stable prefixes that drive runtime auto-detection in `Agent.resume()`,\n * `Agent.get()`, etc.\n *\n * @internal\n */\nconst PREFIX = {\n localAgent: \"agent-\",\n cloudAgent: \"bc-\",\n run: \"run-\",\n call: \"call-\",\n cron: \"cron-\",\n request: \"request-\",\n} as const;\n\n/**\n * Generate a local-runtime agent ID. Format: `agent-<uuid>`.\n *\n * @internal\n */\nexport function generateLocalAgentId(): string {\n return `${PREFIX.localAgent}${randomUUID()}`;\n}\n\n/**\n * Generate a cloud-runtime agent ID. Format: `bc-<uuid>`.\n *\n * @internal\n */\nexport function generateCloudAgentId(): string {\n return `${PREFIX.cloudAgent}${randomUUID()}`;\n}\n\n/**\n * Generate a run ID. Format: `run-<uuid>`.\n *\n * @internal\n */\nexport function generateRunId(): string {\n return `${PREFIX.run}${randomUUID()}`;\n}\n\n/**\n * Generate a tool-call ID. Format: `call-<uuid>`.\n *\n * @internal\n */\nexport function generateCallId(): string {\n return `${PREFIX.call}${randomUUID()}`;\n}\n\n/**\n * Generate a cron job ID. Format: `cron-<uuid>`.\n *\n * @internal\n */\nexport function generateCronId(): string {\n return `${PREFIX.cron}${randomUUID()}`;\n}\n\n/**\n * Generate a user-input/approval request ID. Format: `request-<uuid>`.\n *\n * @internal\n */\nexport function generateRequestId(): string {\n return `${PREFIX.request}${randomUUID()}`;\n}\n\n/**\n * Detect whether an agent ID belongs to the local runtime.\n *\n * @internal\n */\nexport function isLocalAgentId(id: string): boolean {\n return id.startsWith(PREFIX.localAgent);\n}\n","/**\n * SE8 — boundary normalizer for the model bare-string shorthand.\n *\n * `AgentOptions.model` and `SendOptions.model` accept `string | ModelSelection`\n * (matching every peer SDK's `\"provider/model\"` shorthand). This is the ONE seam\n * that maps a bare string to `{ id }`, so all downstream code keeps seeing a\n * `ModelSelection`. `\"inherit\"` is an `AgentOptions`-only sentinel handled inline\n * at the create seam — NOT here — so this helper stays `string | ModelSelection`.\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport type { ModelSelection } from \"../../types/agent-prims.js\";\n\n/** Normalize a model selection: a bare string id → `{ id }`; object/undefined pass through. */\nexport function normalizeModel(m: string | ModelSelection | undefined): ModelSelection | undefined {\n if (m === undefined || typeof m !== \"string\") return m;\n const id = m.trim();\n if (id.length === 0) {\n throw new ConfigurationError(\n 'model must be a non-empty \"provider/model\" id string or a ModelSelection object',\n { code: \"invalid_model_selection\" },\n );\n }\n return { id };\n}\n","import type { PluginsSettings } from \"../../types/providers.js\";\nimport type { Plugin } from \"./types.js\";\n\n/**\n * Type guard: is the `AgentOptions.plugins` value the array (code-`Plugin`)\n * form rather than the named-enable settings form?\n *\n * `Array.isArray` alone does not narrow a `readonly Plugin[]` out of the union\n * (its built-in predicate is `arg is any[]`, which excludes readonly arrays),\n * so we wrap it in a predicate that names the readonly array explicitly.\n */\nfunction isPluginArray(plugins: PluginsSettings | readonly Plugin[]): plugins is readonly Plugin[] {\n return Array.isArray(plugins);\n}\n\n/**\n * Narrow the `AgentOptions.plugins` union to the named-enable settings form,\n * collapsing the array (code-`Plugin`) form to `undefined`. Use this where the\n * distinction between `undefined` (\"no filter / load all\") and `[]` (\"explicit\n * empty\") matters — e.g. the file-discovery plugin filter and registry\n * serialization. Code `Plugin` objects are handled separately by\n * `extractCodePlugins` and cannot be persisted, so they map to `undefined`.\n *\n * @internal\n */\nexport function asPluginsSettings(\n plugins: PluginsSettings | readonly Plugin[] | undefined,\n): PluginsSettings | undefined {\n if (plugins === undefined) return undefined;\n return isPluginArray(plugins) ? undefined : plugins;\n}\n\n/**\n * Extract the named-enable list from the `AgentOptions.plugins` union.\n *\n * Both the array (code-`Plugin`) form and the settings-without-`enabled` form\n * yield `[]`. Use this at count/iteration sites; use {@link asPluginsSettings}\n * where `undefined` must stay distinct from `[]`.\n *\n * @internal\n */\nexport function enabledPluginNames(\n plugins: PluginsSettings | readonly Plugin[] | undefined,\n): string[] {\n return asPluginsSettings(plugins)?.enabled ?? [];\n}\n","import { join } from \"node:path\";\n\nimport type { AgentOptions } from \"../../../types/agent.js\";\nimport type { ModelSelection } from \"../../../types/agent-prims.js\";\nimport { withCwdMutex } from \"../../persistence/cwd-mutex.js\";\nimport { readVersionedJson, writeVersionedJson } from \"../../persistence/schema-version.js\";\nimport { asPluginsSettings } from \"../../plugins/enabled-names.js\";\nimport { normalizeModel } from \"../model-selection.js\";\nimport type { AgentRuntime, RegisteredAgent } from \"./agent-registry-contract.js\";\n\n/**\n * Persistent agent registry (ADR D17).\n *\n * Per-cwd JSON file at `.theokit/agents/registry.json`. Atomic writes via\n * `replaceFileAtomic`. Secrets in `options` are stripped before persisting\n * (D17 + reuses the cloud-config-serializer allow-list philosophy).\n *\n * Multi-process write race is the documented limitation: one SDK process per\n * cwd (EC-10).\n *\n * @internal\n */\n\n/** Current numeric schema version for the agent registry (ADR D62). */\nconst SCHEMA_VERSION = 1;\nconst LEGACY_SCHEMA_VERSION_STRING = \"1.0\";\nconst REGISTRY_RELATIVE_PATH = join(\".theokit\", \"agents\", \"registry.json\");\n\n/** Legacy on-disk shape (pre-D62 — `schemaVersion` string field + flat `agents`). */\ninterface LegacyRegistryFile {\n schemaVersion?: string;\n agents?: Record<string, SerializedAgent>;\n}\n\ninterface SerializedAgent {\n agentId: string;\n runtime: AgentRuntime;\n name?: string;\n summary?: string;\n model?: RegisteredAgent[\"model\"];\n createdAt: number;\n lastModified: number;\n archived: boolean;\n options: SerializedAgentOptions;\n cwd?: string;\n repos?: string[];\n status?: RegisteredAgent[\"status\"];\n}\n\n/**\n * Strips secrets from AgentOptions before persisting. Mirrors the allow-list\n * approach used by the cloud-config-serializer (ADR D15).\n *\n * @internal\n */\nexport function stripSecretsFromOptions(options: AgentOptions): SerializedAgentOptions {\n // EC-2: apiKey, mcpServers (may contain headers/env secrets), AgentOptions.tools\n // (custom-tool handlers are closures and cannot be serialized), hooks closures —\n // all explicitly NOT forwarded. The agent loop re-resolves these from env on\n // rehydration; custom tools must be re-passed via Agent.resume(id, { tools: [...] }).\n return assignDefined<SerializedAgentOptions>({\n name: options.name,\n model: (() => {\n const m = normalizeModel(options.model);\n return m !== undefined ? { id: m.id } : undefined;\n })(),\n systemPrompt: typeof options.systemPrompt === \"string\" ? options.systemPrompt : undefined,\n local: serializeLocal(options.local),\n cloud: serializeCloud(options.cloud),\n memory: serializeMemory(options.memory),\n // SE22 — a SkillsResolver function isn't serializable; persist only the static form.\n skills: serializeEnabledList(typeof options.skills === \"function\" ? undefined : options.skills),\n // Code-`Plugin` objects are closures and cannot be persisted (like custom\n // tools); only the named-enable settings form is serialized.\n plugins: serializeEnabledList(asPluginsSettings(options.plugins)),\n context: serializeContext(options.context),\n providers: serializeProviders(options.providers),\n agents: serializeAgents(options.agents),\n });\n}\n\n/** Drops `undefined` entries from a partial object, preserving the field shape. */\nfunction assignDefined<T extends object>(partial: { [K in keyof T]?: T[K] | undefined }): T {\n const result = {} as T;\n for (const key of Object.keys(partial) as (keyof T)[]) {\n const value = partial[key];\n if (value !== undefined) result[key] = value as T[typeof key];\n }\n return result;\n}\n\nfunction serializeEnabledList(\n list: { enabled?: ReadonlyArray<string> } | undefined,\n): { enabled?: ReadonlyArray<string> } | undefined {\n if (list === undefined) return undefined;\n return list.enabled !== undefined ? { enabled: [...list.enabled] } : {};\n}\n\nfunction serializeLocal(local: AgentOptions[\"local\"]): SerializedAgentOptions[\"local\"] | undefined {\n if (local === undefined) return undefined;\n const out: SerializedAgentOptions[\"local\"] = {};\n if (typeof local.cwd === \"string\") out.cwd = local.cwd;\n if (Array.isArray(local.settingSources)) out.settingSources = [...local.settingSources];\n // Sandbox config — not a secret; needs to survive resume so that\n // safe-by-default doesn't silently regress to unsandboxed on restart.\n if (local.sandboxOptions !== undefined) {\n out.sandboxOptions = { enabled: local.sandboxOptions.enabled === true };\n }\n return out;\n}\n\nfunction serializeCloud(cloud: AgentOptions[\"cloud\"]): SerializedAgentOptions[\"cloud\"] | undefined {\n if (cloud === undefined) return undefined;\n return {\n repos: (cloud.repos ?? []).map((r) => ({\n url: r.url,\n ...(typeof r.startingRef === \"string\" ? { startingRef: r.startingRef } : {}),\n })),\n ...(cloud.autoCreatePR === true ? { autoCreatePR: true } : {}),\n };\n}\n\nfunction serializeMemory(\n memory: AgentOptions[\"memory\"],\n): SerializedAgentOptions[\"memory\"] | undefined {\n if (memory === undefined) return undefined;\n const out: SerializedAgentOptions[\"memory\"] = { enabled: memory.enabled === true };\n if (memory.namespace !== undefined) out.namespace = memory.namespace;\n if (memory.userId !== undefined) out.userId = memory.userId;\n if (memory.scope !== undefined) out.scope = memory.scope;\n if (memory.activeRecall !== undefined) out.activeRecall = { ...memory.activeRecall };\n if (memory.index !== undefined) out.index = serializeMemoryIndex(memory.index);\n return out;\n}\n\nfunction serializeMemoryIndex(\n index: NonNullable<AgentOptions[\"memory\"]>[\"index\"],\n): NonNullable<SerializedAgentOptions[\"memory\"]>[\"index\"] {\n const out: NonNullable<SerializedAgentOptions[\"memory\"]>[\"index\"] = {};\n if (index === undefined) return out;\n if (index.tools !== undefined) out.tools = index.tools;\n if (index.backend !== undefined) out.backend = index.backend;\n if (index.embedding !== undefined) {\n out.embedding = {\n provider: index.embedding.provider,\n ...(index.embedding.model !== undefined ? { model: index.embedding.model } : {}),\n };\n }\n return out;\n}\n\nfunction serializeContext(\n context: AgentOptions[\"context\"],\n): SerializedAgentOptions[\"context\"] | undefined {\n if (context === undefined) return undefined;\n // Context manager config — no secrets, persists for Agent.resume rehydration.\n const out: NonNullable<SerializedAgentOptions[\"context\"]> = {};\n if (context.manager !== undefined) out.manager = context.manager;\n if (context.maxTokens !== undefined) out.maxTokens = context.maxTokens;\n return out;\n}\n\nfunction serializeProviders(\n providers: AgentOptions[\"providers\"],\n): SerializedAgentOptions[\"providers\"] | undefined {\n if (providers === undefined) return undefined;\n // Provider routing — capability/provider/model are public catalog entries.\n return {\n routes: providers.routes.map((r) => ({\n capability: r.capability,\n provider: r.provider,\n ...(r.model !== undefined ? { model: r.model } : {}),\n })),\n ...(providers.fallback !== undefined ? { fallback: [...providers.fallback] } : {}),\n };\n}\n\nfunction serializeAgents(\n agents: AgentOptions[\"agents\"],\n): SerializedAgentOptions[\"agents\"] | undefined {\n if (agents === undefined) return undefined;\n // Subagents (inline `AgentDefinition` map) — persist description + prompt + model (WITH its params, so\n // per-subagent reasoning effort survives resume) + the security-relevant `tools` whitelist and\n // `sandbox` toggle. Dropping `tools`/`sandbox` was a default-open on resume: a confined child came back\n // unconfined. Subagent `mcpServers` MAY carry headers/env secrets, so they stay stripped.\n const out: NonNullable<SerializedAgentOptions[\"agents\"]> = {};\n for (const [name, def] of Object.entries(agents)) {\n out[name] = {\n description: def.description,\n prompt: def.prompt,\n ...(def.model !== undefined ? { model: def.model } : {}),\n ...(def.tools !== undefined ? { tools: def.tools } : {}),\n ...(def.sandbox !== undefined ? { sandbox: def.sandbox } : {}),\n };\n }\n return out;\n}\n\nexport interface SerializedAgentOptions {\n name?: string;\n model?: { id: string };\n systemPrompt?: string;\n local?: {\n cwd?: string;\n settingSources?: ReadonlyArray<string>;\n sandboxOptions?: { enabled: boolean };\n };\n cloud?: {\n repos: ReadonlyArray<{ url: string; startingRef?: string }>;\n autoCreatePR?: boolean;\n };\n memory?: {\n enabled: boolean;\n namespace?: string;\n userId?: string;\n scope?: string;\n index?: {\n tools?: boolean;\n backend?: string;\n embedding?: { provider: string; model?: string };\n };\n activeRecall?: Record<string, unknown>;\n };\n skills?: { enabled?: ReadonlyArray<string> };\n plugins?: { enabled?: ReadonlyArray<string> };\n context?: { manager?: string; maxTokens?: number };\n providers?: {\n routes: ReadonlyArray<{ capability: string; provider: string; model?: string }>;\n fallback?: ReadonlyArray<string>;\n };\n agents?: Record<\n string,\n {\n description: string;\n prompt: string;\n model?: ModelSelection | \"inherit\";\n tools?: string[];\n sandbox?: boolean;\n }\n >;\n}\n\nfunction registryPath(cwd: string): string {\n return join(cwd, REGISTRY_RELATIVE_PATH);\n}\n\n/**\n * Read the persisted registry from disk. Returns `{}` on missing file OR\n * malformed JSON (EC-4 — never throws on corrupt registry). Emits a stderr\n * warning when corruption is detected.\n *\n * @internal\n */\nexport async function loadRegistry(cwd: string): Promise<Record<string, SerializedAgent>> {\n return readVersionedJson<Record<string, SerializedAgent>>({\n path: registryPath(cwd),\n currentVersion: SCHEMA_VERSION,\n defaultValue: () => ({}),\n // EC-2 fix: `parsed` is the full object so we can detect + migrate legacy\n // shape `{ schemaVersion: \"1.0\", agents: {...} }` (no `_schemaVersion`,\n // no `data` wrapper).\n migrate: (parsed, _fromVersion) => {\n if (typeof parsed !== \"object\" || parsed === null) return {};\n const legacy = parsed as LegacyRegistryFile;\n if (legacy.schemaVersion === LEGACY_SCHEMA_VERSION_STRING && legacy.agents) {\n return legacy.agents;\n }\n return {};\n },\n });\n}\n\n/**\n * Write the registry to disk via `replaceFileAtomic` under a per-cwd mutex.\n * Coalesces concurrent in-process writes; cross-process writes still race\n * (EC-10 documented limitation).\n *\n * @internal\n */\nexport async function saveRegistry(\n cwd: string,\n agents: Record<string, RegisteredAgent>,\n): Promise<void> {\n const serialized: Record<string, SerializedAgent> = {};\n for (const [id, agent] of Object.entries(agents)) {\n serialized[id] = toSerialized(agent);\n }\n const path = registryPath(cwd);\n await withCwdMutex(`registry:${cwd}`, async () => {\n // writeVersionedJson writes `{ _schemaVersion: N, data: serialized }`\n // atomically (parent dir auto-created via atomicWriteJson).\n await writeVersionedJson(path, serialized, SCHEMA_VERSION);\n });\n}\n\nfunction toSerialized(agent: RegisteredAgent): SerializedAgent {\n const out: SerializedAgent = {\n agentId: agent.agentId,\n runtime: agent.runtime,\n createdAt: agent.createdAt,\n lastModified: agent.lastModified,\n archived: agent.archived,\n options: stripSecretsFromOptions(agent.options),\n };\n if (agent.name !== undefined) out.name = agent.name;\n if (agent.summary !== undefined) out.summary = agent.summary;\n if (agent.model !== undefined) out.model = agent.model;\n if (agent.cwd !== undefined) out.cwd = agent.cwd;\n if (agent.repos !== undefined) out.repos = [...agent.repos];\n if (agent.status !== undefined) out.status = agent.status;\n return out;\n}\n\n/**\n * Rehydrate a SerializedAgent from disk into a RegisteredAgent shape.\n * Returns undefined when the persisted options can't be revived (e.g.,\n * `local.cwd` no longer exists — caller throws agent_rehydration_failed).\n *\n * @internal\n */\nexport function fromSerialized(entry: SerializedAgent): RegisteredAgent {\n return {\n agentId: entry.agentId,\n runtime: entry.runtime,\n name: entry.name,\n summary: entry.summary,\n model: entry.model,\n createdAt: entry.createdAt,\n lastModified: entry.lastModified,\n archived: entry.archived,\n options: entry.options as unknown as AgentOptions,\n cwd: entry.cwd,\n repos: entry.repos,\n status: entry.status,\n };\n}\n","import { diag } from \"../../diagnostics.js\";\nimport type { AgentRuntime, RegisteredAgent } from \"./agent-registry-contract.js\";\nimport { fromSerialized, loadRegistry, saveRegistry } from \"./agent-registry-store.js\";\n\n/**\n * Process-wide agent registry. Holds the metadata needed to satisfy\n * Agent.list/Agent.get/Agent.resume across local and cloud runtimes,\n * plus the user-provided config that drives `agent.send()`.\n *\n * Write-through to disk per ADR D17: every mutation schedules a coalesced\n * save to `<cwd>/.theokit/agents/registry.json`. Reads stay sync; the public\n * `Agent.resume` / `Agent.list` / `Agent.get` entry points hydrate from disk\n * lazily via `hydrateRegistryFromDisk`.\n *\n * **T3.1 of plan `arch-review-fixes-2026-06-06` (ADR D431):** the shared\n * `AgentRuntime` and `RegisteredAgent` types are now defined in\n * `agent-registry-contract.ts` (a leaf types file) and re-exported here for\n * back-compat with downstream code. The store layer (`agent-registry-store.ts`)\n * imports the types from the contract too, breaking the previous\n * runtime↔store cycle.\n *\n * @internal\n */\n\n// Re-exported for back-compat — consumers that historically imported these\n// from `./agent-registry.js` keep working. New code SHOULD import from\n// `./agent-registry-contract.js` directly.\nexport type { AgentRuntime, RegisteredAgent };\n\nconst agents = new Map<string, RegisteredAgent>();\n/**\n * In-flight AND completed hydrations, keyed by `cwd`.\n *\n * M107 — this used to be a `Set<string>` marking \"already hydrated\", and the mark was written\n * BEFORE the `await` on the disk read. A second concurrent `hydrateRegistryFromDisk(cwd)` therefore\n * saw the mark and returned immediately, while the first call had not populated anything yet — so\n * the second caller listed an EMPTY registry and got `[]`. Memoizing the promise instead of a flag\n * makes the second caller await the same read.\n *\n * The bug was latent while `Agent.list` always hydrated `process.cwd()`; making `cwd` a real\n * parameter turns \"two concurrent listings of a not-yet-hydrated project\" into an ordinary path —\n * and that listing feeds `activeKnown`, a NEVER-delete guard on a path that calls `unlink`. An empty\n * listing there is not a slow listing, it is a deleted transcript.\n */\nconst hydrations = new Map<string, Promise<void>>();\nconst pendingSaves = new Map<string, Promise<void>>();\nconst dirtyCwds = new Set<string>();\n\nfunction resolveRegistryCwd(agent: Pick<RegisteredAgent, \"cwd\">): string {\n return agent.cwd ?? process.cwd();\n}\n\nfunction snapshotForCwd(cwd: string): Record<string, RegisteredAgent> {\n const snapshot: Record<string, RegisteredAgent> = {};\n for (const agent of agents.values()) {\n if (resolveRegistryCwd(agent) === cwd) {\n snapshot[agent.agentId] = agent;\n }\n }\n return snapshot;\n}\n\n/**\n * Coalesce burst writes per-cwd: if a save is already pending, the new\n * mutation rides on it (the pending save picks up the latest in-memory state\n * via `snapshotForCwd`).\n *\n * @internal\n */\nfunction scheduleSaveForCwd(cwd: string): Promise<void> {\n // Always mark dirty so a save already in flight will re-loop and pick up\n // this mutation. Without this, two synchronous registerAgent calls would\n // coalesce into ONE save whose snapshot only captured the first agent —\n // the second mutation's data would silently drop off disk.\n dirtyCwds.add(cwd);\n const existing = pendingSaves.get(cwd);\n if (existing !== undefined) return existing;\n const promise = (async () => {\n try {\n while (dirtyCwds.has(cwd)) {\n dirtyCwds.delete(cwd);\n // Yield once so the in-flight microtask burst (registerAgent +\n // updateRegisteredAgent calls fired in the same tick) all commit\n // their `agents.set` before we snapshot.\n await Promise.resolve();\n await saveRegistry(cwd, snapshotForCwd(cwd));\n // Loop guard: if a mutation arrived during saveRegistry's await,\n // dirtyCwds.has(cwd) is true again — go around for another save.\n }\n } catch (cause) {\n const msg = cause instanceof Error ? cause.message : String(cause);\n diag(`[theokit-sdk] registry persist failed (${cwd}): ${msg}\\n`);\n } finally {\n pendingSaves.delete(cwd);\n }\n })();\n pendingSaves.set(cwd, promise);\n return promise;\n}\n\nexport function registerAgent(agent: RegisteredAgent): void {\n agents.set(agent.agentId, agent);\n void scheduleSaveForCwd(resolveRegistryCwd(agent));\n}\n\nexport function getRegisteredAgent(agentId: string): RegisteredAgent | undefined {\n return agents.get(agentId);\n}\n\n/**\n * The registered agents, optionally narrowed by runtime and by workspace `cwd`.\n *\n * ## M107 — why `cwd` is a parameter here and not a filter at the call site\n *\n * The in-memory Map is process-wide, so hydrating a foreign `cwd` pours its entries into the SAME\n * Map that a later un-narrowed listing reads. Without this filter, listing project A would make\n * project B \"own\" A's sessions — and the consumer feeds that list into `activeKnown`, one of the\n * NEVER-delete guards on a path that calls `unlink`.\n *\n * The narrowing uses {@link resolveRegistryCwd}, NOT `agent.cwd === cwd`, and that is the whole\n * point: `cwd` is optional on a registered agent, and its absence ALREADY means `process.cwd()` for\n * the purposes of routing the entry to a file on disk. A naive equality check would drop every\n * cwd-less entry from the listing of its own project — an entry missing from `activeKnown` is an\n * entry the collector stops protecting. Filter and persistence must answer \"which project owns\n * this?\" the same way, or they are two oracles over one fact.\n *\n * @internal\n */\nexport function listRegisteredAgents(runtime?: AgentRuntime, cwd?: string): RegisteredAgent[] {\n let out = Array.from(agents.values());\n if (runtime !== undefined) out = out.filter((agent) => agent.runtime === runtime);\n if (cwd !== undefined) out = out.filter((agent) => resolveRegistryCwd(agent) === cwd);\n return out;\n}\n\nexport function updateRegisteredAgent(\n agentId: string,\n update: Partial<RegisteredAgent>,\n): RegisteredAgent | undefined {\n const existing = agents.get(agentId);\n if (existing === undefined) return undefined;\n const updated: RegisteredAgent = {\n ...existing,\n ...update,\n lastModified: Date.now(),\n };\n agents.set(agentId, updated);\n void scheduleSaveForCwd(resolveRegistryCwd(updated));\n return updated;\n}\n\nexport function removeRegisteredAgent(agentId: string): boolean {\n const existing = agents.get(agentId);\n const removed = agents.delete(agentId);\n if (removed && existing !== undefined) {\n void scheduleSaveForCwd(resolveRegistryCwd(existing));\n }\n return removed;\n}\n\nexport function clearAgentRegistry(): void {\n agents.clear();\n hydrations.clear();\n}\n\n/**\n * Lazily load the persisted registry for `cwd` into the in-memory Map. Skips\n * if this cwd has already been hydrated in this process. Disk-only entries\n * win over the empty in-memory state; in-memory entries (already-registered\n * agents) are never overwritten by hydration.\n *\n * @internal\n */\nexport async function hydrateRegistryFromDisk(cwd: string): Promise<void> {\n const inFlight = hydrations.get(cwd);\n if (inFlight !== undefined) return inFlight;\n const hydration = (async () => {\n const persisted = await loadRegistry(cwd);\n for (const [id, entry] of Object.entries(persisted)) {\n if (!agents.has(id)) {\n agents.set(id, fromSerialized(entry));\n }\n }\n })().catch((cause: unknown) => {\n // A failed hydration must not stay memoized as \"done\": the next call would resolve\n // successfully over a registry that was never read — an empty list indistinguishable from\n // \"this project has no agents\". Dropping the entry lets the next call retry, and the error\n // still propagates to THIS caller (`error-handling.md § 2` — never swallow).\n hydrations.delete(cwd);\n throw cause;\n });\n hydrations.set(cwd, hydration);\n return hydration;\n}\n\n/**\n * Invalidate the hydration cache for `cwd` (or all cwds when omitted). Forces\n * the next `hydrateRegistryFromDisk(cwd)` to re-read from disk. Test-only.\n *\n * @internal\n */\nexport function invalidateRegistryHydration(cwd?: string): void {\n if (cwd !== undefined) hydrations.delete(cwd);\n else hydrations.clear();\n}\n\n/**\n * Wait for all pending registry saves to complete. Used by tests and by the\n * agent dispose path to guarantee on-disk state matches the in-memory state\n * before the caller continues.\n *\n * @internal\n */\nexport async function flushRegistrySaves(cwd?: string): Promise<void> {\n if (cwd !== undefined) {\n await (pendingSaves.get(cwd) ?? Promise.resolve());\n return;\n }\n while (pendingSaves.size > 0) {\n await Promise.all(Array.from(pendingSaves.values()));\n }\n}\n","import type {\n AgentOptions,\n SystemPromptContext,\n SystemPromptResolver,\n} from \"../../../types/agent.js\";\nimport type { SendOptions } from \"../../../types/run.js\";\n\n/**\n * Resolve the effective system prompt for one `agent.send()` call.\n *\n * Priority (per ADR D4):\n * 1. `override` (from `SendOptions.systemPrompt`) — wins even when empty\n * string (the user explicitly cleared the system context).\n * 2. `agent` as plain string — returned directly.\n * 3. `agent` as resolver function — awaited with `ctx`.\n * 4. Neither defined — returns `undefined`.\n *\n * Defensive coercion (per edge-case review EC-2): if the resolver returns\n * anything other than a string at runtime (null, a number, an object),\n * the function returns `undefined` instead of forwarding the bad value to\n * the LLM client.\n *\n * The SDK does NOT impose a timeout on the resolver. Errors thrown by the\n * resolver propagate to the caller of `agent.send()`.\n *\n * @internal\n */\nexport async function resolveSystemPrompt(\n agent: AgentOptions[\"systemPrompt\"],\n override: SendOptions[\"systemPrompt\"],\n ctx: SystemPromptContext,\n): Promise<string | undefined> {\n if (override !== undefined) return override;\n if (agent === undefined) return undefined;\n if (typeof agent === \"string\") return agent;\n const resolver = agent satisfies SystemPromptResolver;\n const resolved = await resolver(ctx);\n return typeof resolved === \"string\" ? resolved : undefined;\n}\n\n/**\n * Cheap predicate used by `LocalAgent` and `CloudAgent` to skip building\n * the {@link SystemPromptContext} when neither agent-level nor per-call\n * prompt is configured. Avoids the lazy skills lookup in the hot path.\n *\n * @internal\n */\nexport function shouldResolveSystemPrompt(\n agent: AgentOptions[\"systemPrompt\"],\n override: SendOptions[\"systemPrompt\"],\n): boolean {\n return agent !== undefined || override !== undefined;\n}\n\n/**\n * High-level helper used by both `LocalAgent.send` and `CloudAgent.send`.\n * Short-circuits when neither side configured a prompt, otherwise calls\n * `buildCtx` (which may be async — e.g. lazy skills lookup) and delegates\n * to {@link resolveSystemPrompt}.\n *\n * @internal\n */\nexport async function resolveSystemPromptForSend(\n agent: AgentOptions[\"systemPrompt\"],\n override: SendOptions[\"systemPrompt\"],\n buildCtx: () => Promise<SystemPromptContext>,\n): Promise<string | undefined> {\n if (!shouldResolveSystemPrompt(agent, override)) return undefined;\n const ctx = await buildCtx();\n return resolveSystemPrompt(agent, override, ctx);\n}\n","import type { AgentOptions } from \"../../types/agent.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { enabledPluginNames } from \"../plugins/enabled-names.js\";\nimport { normalizeModel } from \"../runtime/model-selection.js\";\nimport type {\n CloudAgentPayload,\n McpHttpRedacted,\n McpStdioRedacted,\n MemoryPayload,\n ProvidersRedacted,\n SubagentRef,\n} from \"./cloud-payload-types.js\";\n\n/**\n * Pure JSON serializer for the cloud-agent payload (ADR D15, T1.1).\n *\n * Per-feature allow-list (EC-2): every field forwarded to PaaS is explicitly\n * picked from `AgentOptions`. Fields containing secrets (`apiKey`,\n * `headers.Authorization`, mcp `env`, provider-route credentials) are NEVER\n * forwarded, even if present in input.\n *\n * Determinism (EC-1): `canonicalize()` recursively sorts object keys before\n * `JSON.stringify`. Identical conceptual inputs produce byte-identical JSON\n * regardless of insertion order.\n *\n * Size guardrail (EC-7): payloads larger than 1 MB emit a stderr warning\n * (no throw — pure observability).\n *\n * @internal\n */\n\nconst MAX_PAYLOAD_BYTES = 1_048_576; // 1 MB\n\nexport function serializeCloudAgentConfig(options: AgentOptions): CloudAgentPayload {\n if (options.cloud === undefined) {\n throw new Error(\"serializeCloudAgentConfig called without options.cloud\");\n }\n const payload: CloudAgentPayload = {\n schemaVersion: \"1.0\",\n cloud: serializeCloud(options.cloud),\n };\n if (typeof options.agentId === \"string\") payload.agentId = options.agentId;\n const cfgModel = normalizeModel(options.model);\n if (cfgModel !== undefined) payload.model = { id: cfgModel.id };\n if (typeof options.systemPrompt === \"string\") payload.systemPrompt = options.systemPrompt;\n const skills = serializeSkills(options.skills);\n if (skills !== undefined) payload.skills = skills;\n const plugins = serializePlugins(options.plugins);\n if (plugins !== undefined) payload.plugins = plugins;\n const mcp = serializeMcp(options.mcpServers);\n if (mcp !== undefined) payload.mcpServers = mcp;\n const agents = serializeAgents(options.agents);\n if (agents !== undefined) payload.agents = agents;\n const providers = serializeProviders(options.providers);\n if (providers !== undefined) payload.providers = providers;\n const memory = serializeMemory(options.memory);\n if (memory !== undefined) payload.memory = memory;\n return payload;\n}\n\n/**\n * Stringify a payload to canonical JSON. Object keys are sorted\n * recursively before stringify (EC-1). Emits a stderr warning when the\n * result exceeds {@link MAX_PAYLOAD_BYTES} (EC-7).\n *\n * @internal\n */\nexport function stringifyCloudPayload(payload: CloudAgentPayload): string {\n const sorted = canonicalize(payload);\n const json = JSON.stringify(sorted);\n const size = Buffer.byteLength(json, \"utf8\");\n if (size > MAX_PAYLOAD_BYTES) {\n diag(\n `[theokit-sdk] cloud agent payload is ${size} bytes (>1 MB) — PaaS may reject large payloads. Consider trimming subagents/context.\\n`,\n );\n }\n return json;\n}\n\n/**\n * Recursively sort object keys for deterministic stringify (EC-1).\n *\n * @internal\n */\nexport function canonicalize(value: unknown): unknown {\n if (Array.isArray(value)) return value.map(canonicalize);\n if (value !== null && typeof value === \"object\") {\n const sorted: Record<string, unknown> = {};\n for (const key of Object.keys(value as Record<string, unknown>).sort()) {\n sorted[key] = canonicalize((value as Record<string, unknown>)[key]);\n }\n return sorted;\n }\n return value;\n}\n\nfunction serializeCloud(cloud: NonNullable<AgentOptions[\"cloud\"]>): CloudAgentPayload[\"cloud\"] {\n const repos = (cloud.repos ?? []).map((r) => {\n const entry: { url: string; startingRef?: string } = { url: r.url };\n if (typeof r.startingRef === \"string\") entry.startingRef = r.startingRef;\n return entry;\n });\n const result: CloudAgentPayload[\"cloud\"] = { repos };\n if (cloud.autoCreatePR === true) result.autoCreatePR = true;\n return result;\n}\n\nfunction serializeSkills(skills: AgentOptions[\"skills\"]): CloudAgentPayload[\"skills\"] | undefined {\n // SE22 — a SkillsResolver function is rejected for cloud upstream\n // (validateCloudToolParity); guard here too so the type narrows cleanly.\n if (typeof skills === \"function\") return undefined;\n if (skills?.enabled === undefined || skills.enabled.length === 0) return undefined;\n return { enabled: [...skills.enabled] };\n}\n\nfunction serializePlugins(\n plugins: AgentOptions[\"plugins\"],\n): CloudAgentPayload[\"plugins\"] | undefined {\n const enabled = enabledPluginNames(plugins);\n if (enabled.length === 0) return undefined;\n return { enabled: [...enabled] };\n}\n\nfunction serializeMcp(\n mcpServers: AgentOptions[\"mcpServers\"],\n): CloudAgentPayload[\"mcpServers\"] | undefined {\n if (mcpServers === undefined) return undefined;\n const result: Record<string, McpHttpRedacted | McpStdioRedacted> = {};\n for (const [name, raw] of Object.entries(mcpServers)) {\n const entry = serializeMcpEntry(raw);\n if (entry !== undefined) result[name] = entry;\n }\n return Object.keys(result).length > 0 ? result : undefined;\n}\n\nfunction serializeMcpEntry(raw: unknown): McpHttpRedacted | McpStdioRedacted | undefined {\n const config = raw as { type?: string; url?: string; command?: string; args?: unknown };\n if (config.type === \"http\" && typeof config.url === \"string\") {\n // EC-2: only `url` + `type` cross to PaaS. Drop headers (Authorization),\n // any other caller-side fields.\n return { type: \"http\", url: config.url };\n }\n if (\n (config.type === \"stdio\" || config.type === undefined) &&\n typeof config.command === \"string\"\n ) {\n // EC-2: drop env entirely (TOKEN, SECRET, etc.). Drop cwd (caller FS).\n const entry: McpStdioRedacted = { type: \"stdio\", command: config.command };\n if (Array.isArray(config.args)) entry.args = config.args.map((a) => String(a));\n return entry;\n }\n return undefined;\n}\n\nfunction serializeAgents(agents: AgentOptions[\"agents\"]): CloudAgentPayload[\"agents\"] | undefined {\n if (agents === undefined) return undefined;\n const result: Record<string, SubagentRef> = {};\n for (const [name, def] of Object.entries(agents)) {\n if (def === undefined || def === null) continue;\n result[name] = buildSubagentRef(def);\n }\n return Object.keys(result).length > 0 ? result : undefined;\n}\n\nfunction buildSubagentRef(def: NonNullable<AgentOptions[\"agents\"]>[string]): SubagentRef {\n const ref: SubagentRef = {};\n if (typeof def.description === \"string\") ref.description = def.description;\n if (typeof def.prompt === \"string\") ref.systemPrompt = def.prompt;\n if (def.model !== undefined && def.model !== \"inherit\" && typeof def.model.id === \"string\") {\n ref.model = { id: def.model.id };\n }\n return ref;\n}\n\nfunction serializeProviders(providers: AgentOptions[\"providers\"]): ProvidersRedacted | undefined {\n if (providers === undefined) return undefined;\n const result: ProvidersRedacted = {};\n if (Array.isArray(providers.routes)) {\n // EC-2: route entries strip any credential field; only provider/model cross.\n result.routes = providers.routes.map((r) => {\n const route: { provider: string; model?: string } = { provider: r.provider };\n if (typeof r.model === \"string\") route.model = r.model;\n return route;\n });\n }\n if (Array.isArray(providers.fallback)) {\n result.fallback = [...providers.fallback];\n }\n return Object.keys(result).length > 0 ? result : undefined;\n}\n\nfunction serializeMemory(memory: AgentOptions[\"memory\"]): MemoryPayload | undefined {\n if (memory === undefined) return undefined;\n const result: MemoryPayload = { enabled: memory.enabled === true };\n if (memory.index?.backend !== undefined || memory.index?.embedding !== undefined) {\n const index: MemoryPayload[\"index\"] = { backend: memory.index?.backend ?? \"sqlite-vec\" };\n if (memory.index?.embedding !== undefined) {\n // EC-2: embedding config only forwards provider + model. Adapter\n // credentials live in the PaaS-side keystore, never in the payload.\n const emb: { provider: string; model?: string } = {\n provider: memory.index.embedding.provider,\n };\n if (typeof memory.index.embedding.model === \"string\") {\n emb.model = memory.index.embedding.model;\n }\n index.embedding = emb;\n }\n result.index = index;\n }\n return result;\n}\n","import type { ConversationTurn } from \"../../../types/conversation.js\";\nimport type {\n SDKAssistantMessage,\n SDKRequestMessage,\n SDKStatusMessage,\n SDKSystemMessage,\n SDKTaskMessage,\n SDKThinkingMessage,\n SDKToolUseMessage,\n SDKUserMessageEvent,\n} from \"../../../types/messages.js\";\nimport { generateRequestId } from \"../../ids.js\";\nimport { enabledPluginNames } from \"../../plugins/enabled-names.js\";\nimport type { FixtureRequest } from \"./fixture-types.js\";\n\n/**\n * Low-level event builders + tool-list helper used by the fixture script\n * builders. Kept in a dedicated module so individual builder files stay\n * focused on their specific script shape rather than event plumbing.\n *\n * @internal\n */\n\nexport function assistantOnlyConversation(text: string): ConversationTurn[] {\n return [\n {\n type: \"agentConversationTurn\",\n turn: {\n steps: [{ type: \"assistantMessage\", message: { text } }],\n },\n },\n ];\n}\n\nexport function systemEvent(request: FixtureRequest, tools: string[]): SDKSystemMessage {\n return {\n type: \"system\",\n subtype: \"init\",\n agent_id: request.agentId,\n run_id: request.runId,\n model: request.model,\n tools,\n };\n}\n\nexport function userEvent(request: FixtureRequest): SDKUserMessageEvent {\n return {\n type: \"user\",\n agent_id: request.agentId,\n run_id: request.runId,\n message: { role: \"user\", content: [{ type: \"text\", text: request.userMessage }] },\n };\n}\n\nexport function assistantText(request: FixtureRequest, text: string): SDKAssistantMessage {\n return {\n type: \"assistant\",\n agent_id: request.agentId,\n run_id: request.runId,\n message: { role: \"assistant\", content: [{ type: \"text\", text }] },\n };\n}\n\nexport function thinkingEvent(request: FixtureRequest, text: string): SDKThinkingMessage {\n return {\n type: \"thinking\",\n agent_id: request.agentId,\n run_id: request.runId,\n text,\n };\n}\n\nexport function toolCallRunning(\n request: FixtureRequest,\n callId: string,\n name: string,\n): SDKToolUseMessage {\n return {\n type: \"tool_call\",\n agent_id: request.agentId,\n run_id: request.runId,\n call_id: callId,\n name,\n status: \"running\",\n args: { command: \"fixture\" },\n };\n}\n\nexport function toolCallCompleted(\n request: FixtureRequest,\n callId: string,\n name: string,\n): SDKToolUseMessage {\n return {\n type: \"tool_call\",\n agent_id: request.agentId,\n run_id: request.runId,\n call_id: callId,\n name,\n status: \"completed\",\n args: { command: \"fixture\" },\n result: { stdout: \"ok\", exitCode: 0 },\n };\n}\n\nexport function cloudStatus(\n request: FixtureRequest,\n status: SDKStatusMessage[\"status\"],\n): SDKStatusMessage {\n return {\n type: \"status\",\n agent_id: request.agentId,\n run_id: request.runId,\n status,\n };\n}\n\nexport function taskEvent(request: FixtureRequest, status: string): SDKTaskMessage {\n return {\n type: \"task\",\n agent_id: request.agentId,\n run_id: request.runId,\n status,\n };\n}\n\nexport function requestEvent(request: FixtureRequest): SDKRequestMessage {\n return {\n type: \"request\",\n agent_id: request.agentId,\n run_id: request.runId,\n request_id: generateRequestId(),\n };\n}\n\nexport function defaultLocalTools(request: FixtureRequest): string[] {\n const tools: string[] = [\"shell\"];\n const inlineMcp = request.sendOptions.mcpServers ?? request.agentOptions.mcpServers;\n if (inlineMcp !== undefined) {\n for (const name of Object.keys(inlineMcp)) {\n tools.push(`mcp_${sanitizeMcpName(name)}_call`);\n }\n }\n if (request.settingSourcesIncludeProject) {\n for (const name of Object.keys(request.projectMcpServers)) {\n tools.push(`mcp_${sanitizeMcpName(name)}_call`);\n }\n }\n for (const _pluginName of enabledPluginNames(request.agentOptions.plugins)) {\n tools.push(\"mcp_search_provider_web_search\");\n }\n return tools;\n}\n\nfunction sanitizeMcpName(name: string): string {\n // Replace anything that's not alphanumeric or hyphen with an underscore.\n // Hyphens are preserved (some MCP server names like `fixture-shell` rely\n // on them being stable in the public tool list).\n return name.replace(/[^a-zA-Z0-9-]+/g, \"_\").replace(/^[_-]+|[_-]+$/g, \"\");\n}\n","import { access, readFile, unlink } from \"node:fs/promises\";\nimport { diag } from \"../diagnostics.js\";\nimport { appendFactToMarkdown, memoryMdPath } from \"./storage/markdown-store.js\";\nimport { legacyMemoryJsonPath, type MemoryConfig, type MemoryFact } from \"./types.js\";\n\n/**\n * One-shot legacy-JSON → markdown migration (ADR D8 of memory-system-peer-project-parity).\n *\n * Triggers when `.theokit/memory/<namespace>/<scope>-<userId>.json` exists AND\n * `.theokit/memory/MEMORY.md` does not. Reads the JSON facts, writes each\n * bullet to MEMORY.md, then deletes the JSON file. Idempotent.\n *\n * @internal\n */\n\nasync function fileExists(path: string): Promise<boolean> {\n try {\n await access(path);\n return true;\n } catch {\n return false;\n }\n}\n\nasync function readLegacyFacts(jsonPath: string): Promise<MemoryFact[] | undefined> {\n try {\n const raw = await readFile(jsonPath, \"utf8\");\n const parsed = JSON.parse(raw) as { facts?: MemoryFact[] };\n return Array.isArray(parsed.facts) ? parsed.facts : [];\n } catch {\n return undefined;\n }\n}\n\nasync function writeMigratedFacts(\n cwd: string,\n jsonPath: string,\n facts: MemoryFact[],\n): Promise<MigrationResult> {\n try {\n for (const fact of facts) await appendFactToMarkdown(cwd, fact);\n await unlink(jsonPath).catch(() => undefined);\n diag(`[theokit-sdk] migrated ${facts.length} fact(s) from ${jsonPath} to MEMORY.md\\n`);\n return { migrated: true, factCount: facts.length };\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : String(cause);\n diag(`[theokit-sdk] memory migration failed (readonly fs?): ${message}\\n`);\n return { migrated: false, factCount: 0, reason: \"readonly-fs\" };\n }\n}\n\nconst migrationRun = new Set<string>();\n\nexport interface MigrationResult {\n migrated: boolean;\n factCount: number;\n reason?: \"already-migrated\" | \"no-legacy-json\" | \"markdown-exists\" | \"readonly-fs\";\n}\n\nexport async function migrateLegacyJson(\n cwd: string,\n config: MemoryConfig,\n): Promise<MigrationResult> {\n const key = `${cwd}::${config.namespace ?? \"default\"}::${config.scope ?? \"agent\"}::${config.userId ?? \"default\"}`;\n if (migrationRun.has(key)) return { migrated: false, factCount: 0, reason: \"already-migrated\" };\n migrationRun.add(key);\n\n const jsonPath = legacyMemoryJsonPath(cwd, config);\n if (!(await fileExists(jsonPath))) {\n return { migrated: false, factCount: 0, reason: \"no-legacy-json\" };\n }\n if (await fileExists(memoryMdPath(cwd))) {\n diag(\n `[theokit-sdk] memory migration skipped: both MEMORY.md and legacy JSON exist at ${jsonPath}; leaving both intact\\n`,\n );\n return { migrated: false, factCount: 0, reason: \"markdown-exists\" };\n }\n\n const facts = await readLegacyFacts(jsonPath);\n if (facts === undefined) return { migrated: false, factCount: 0, reason: \"no-legacy-json\" };\n return writeMigratedFacts(cwd, jsonPath, facts);\n}\n\n/** Test-only — reset the in-process migration flag map. */\nexport function resetMigrationStateForTests(): void {\n migrationRun.clear();\n}\n","import { migrateLegacyJson } from \"../../memory/migration.js\";\nimport {\n appendFact as appendFactMd,\n readFacts as readFactsMd,\n} from \"../../memory/storage/markdown-store.js\";\nimport { type MemoryConfig, type MemoryFact, redactSecrets } from \"../../memory/types.js\";\n\n/**\n * Workspace-level memory store. Storage migrated from JSON-array to\n * markdown-first per memory-system-peer-project-parity-plan ADR D1: facts live in\n * `.theokit/memory/MEMORY.md` under a `## Facts` section. On first read the\n * legacy JSON file is migrated and deleted (ADR D8).\n *\n * Public surface (`readMemoryFacts` + `appendMemoryFact`) is unchanged.\n *\n * @internal\n */\n\nexport type { MemoryConfig, MemoryFact };\nexport { redactSecrets };\n\nconst REMEMBER_PATTERN = /^\\s*Remember(?:\\s+this\\s+durable\\s+preference)?\\s*:\\s*(.+)$/i;\n\n/**\n * Predicate: does the user message opt into memory persistence via the\n * `Remember:` prefix? Anchored at start-of-message; case-insensitive.\n *\n * Shared by the fixture runtime and the real LLM runtime so both paths\n * agree on which user messages persist a fact.\n *\n * @internal\n */\nexport function isMemoryWritePrompt(message: string): boolean {\n return REMEMBER_PATTERN.test(message) || message.includes(\"Remember this durable\");\n}\n\n/**\n * Extract the fact text from a user message that matched\n * {@link isMemoryWritePrompt}. Strips the leading \"Remember:\" prefix and\n * a trailing period. Returns an empty string when the capture group is\n * empty — callers must check for that and skip the persistence call.\n *\n * @internal\n */\nexport function extractMemoryFact(message: string): string {\n const match = REMEMBER_PATTERN.exec(message);\n if (match === null || match[1] === undefined) return \"\";\n return match[1].trim().replace(/\\.$/, \"\");\n}\n\nexport async function readMemoryFacts(cwd: string, config: MemoryConfig): Promise<MemoryFact[]> {\n if (!config.enabled) return [];\n await migrateLegacyJson(cwd, config);\n return readFactsMd(cwd, config);\n}\n\nexport async function appendMemoryFact(\n cwd: string,\n config: MemoryConfig,\n fact: MemoryFact,\n): Promise<void> {\n if (!config.enabled) return;\n await migrateLegacyJson(cwd, config);\n const sanitized: MemoryFact = { text: redactSecrets(fact.text) };\n await appendFactMd(cwd, config, sanitized);\n}\n","import { generateCallId } from \"../../ids.js\";\nimport {\n assistantOnlyConversation,\n assistantText,\n cloudStatus,\n defaultLocalTools,\n requestEvent,\n systemEvent,\n taskEvent,\n thinkingEvent,\n toolCallCompleted,\n toolCallRunning,\n userEvent,\n} from \"./fixture-events.js\";\nimport type { FixtureRequest, FixtureScript } from \"./fixture-types.js\";\n\n/**\n * Concrete fixture script builders. Each function returns a fully assembled\n * `FixtureScript` for one of the prompt patterns recognised by the dispatcher\n * in `fixture-responder.ts`.\n *\n * @internal\n */\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Memory: detect Remember/recall patterns\n// ─────────────────────────────────────────────────────────────────────────────\n\nimport { extractMemoryFact } from \"../memory/memory-store.js\";\n\nexport { extractMemoryFact, isMemoryWritePrompt } from \"../memory/memory-store.js\";\n\nexport function isMemoryRecallPrompt(message: string, request: FixtureRequest): boolean {\n if (request.memoryFacts.length === 0 && request.sessionMessages.length === 0) return false;\n if (/^\\s*Remember/i.test(message)) return false;\n return (\n message.toLowerCase().includes(\"preferred\") ||\n message.includes(\"What answer did I ask you to remember\") ||\n message.includes(\"editor and token\") ||\n message.includes(\"What is my\")\n );\n}\n\nexport function memoryWriteScript(request: FixtureRequest): FixtureScript {\n const fact = extractMemoryFactOrMessage(request.userMessage);\n return {\n events: [\n systemEvent(request, defaultLocalTools(request)),\n userEvent(request),\n assistantText(request, `Remembered: ${fact}`),\n ],\n finalStatus: \"finished\",\n result: `Remembered: ${fact}`,\n cancellable: false,\n conversation: assistantOnlyConversation(`Remembered: ${fact}`),\n beforeComplete: async () => {\n if (request.persistMemoryFact === undefined) return;\n await request.persistMemoryFact({ text: fact });\n },\n };\n}\n\nexport function memoryRecallScript(request: FixtureRequest): FixtureScript {\n const haystack = [\n ...request.memoryFacts.map((fact) => fact.text),\n ...request.sessionMessages.filter((msg) => msg.role === \"user\").map((msg) => msg.text),\n ];\n const recalled = recallFromHaystack(request.userMessage, haystack);\n const answer = recalled ?? \"I don't have a stored answer for that yet.\";\n return {\n events: [\n systemEvent(request, defaultLocalTools(request)),\n userEvent(request),\n assistantText(request, answer),\n ],\n finalStatus: \"finished\",\n result: answer,\n cancellable: false,\n conversation: assistantOnlyConversation(answer),\n };\n}\n\n/**\n * Fixture-script-only wrapper: the shared {@link extractMemoryFact} returns\n * `\"\"` on no match, but the fixture's pre-existing semantics returned the\n * full message. Preserve that behaviour for the fixture path so existing\n * fixture contract tests stay green.\n */\nfunction extractMemoryFactOrMessage(message: string): string {\n const fact = extractMemoryFact(message);\n return fact.length > 0 ? fact : message;\n}\n\nfunction recallFromHaystack(question: string, haystack: string[]): string | undefined {\n const lc = question.toLowerCase();\n if (lc.includes(\"test runner\")) {\n const fact = haystack.find((entry) => /vitest/i.test(entry));\n if (fact !== undefined) return \"Vitest\";\n }\n if (lc.includes(\"answer\")) {\n const fact = haystack.find((entry) => /\\b\\d{2,}\\b/.test(entry));\n if (fact !== undefined) {\n const num = /\\b(\\d{2,})\\b/.exec(fact);\n if (num !== null && num[1] !== undefined) return `The answer is ${num[1]}.`;\n }\n }\n return undefined;\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Local script builders\n// ─────────────────────────────────────────────────────────────────────────────\n\n/**\n * Build a \"finished\" fixture script where the assistant simply replies with\n * `text` and the conversation contains a single assistant turn. Most local\n * scripts follow this shape — keeping the helper deduplicates the repeated\n * `{events, finalStatus, result, cancellable, conversation}` literal.\n */\nfunction finishedAssistantScript(request: FixtureRequest, text: string): FixtureScript {\n return {\n events: [\n systemEvent(request, defaultLocalTools(request)),\n userEvent(request),\n assistantText(request, text),\n ],\n finalStatus: \"finished\",\n result: text,\n cancellable: false,\n conversation: assistantOnlyConversation(text),\n };\n}\n\nexport function returnAnswerScript(request: FixtureRequest, answer: string): FixtureScript {\n const callId = generateCallId();\n return {\n events: [\n systemEvent(request, defaultLocalTools(request)),\n userEvent(request),\n toolCallCompleted(request, callId, \"shell\"),\n assistantText(request, answer),\n ],\n finalStatus: \"finished\",\n result: answer,\n cancellable: false,\n conversation: assistantOnlyConversation(answer),\n };\n}\n\nexport function buildCloudScript(request: FixtureRequest): FixtureScript {\n const result = \"Cloud run completed.\";\n return {\n events: [\n systemEvent(request, []),\n userEvent(request),\n cloudStatus(request, \"CREATING\"),\n cloudStatus(request, \"RUNNING\"),\n assistantText(request, result),\n cloudStatus(request, \"FINISHED\"),\n ],\n finalStatus: \"finished\",\n result,\n cancellable: false,\n conversation: assistantOnlyConversation(result),\n };\n}\n\nexport function slowRunScript(request: FixtureRequest): FixtureScript {\n return {\n events: [\n systemEvent(request, defaultLocalTools(request)),\n userEvent(request),\n assistantText(request, \"Starting the slow command...\"),\n ],\n finalStatus: \"cancelled\",\n cancellable: true,\n conversation: assistantOnlyConversation(\"Starting the slow command...\"),\n };\n}\n\nexport function errorRunScript(request: FixtureRequest): FixtureScript {\n return {\n events: [\n systemEvent(request, defaultLocalTools(request)),\n userEvent(request),\n assistantText(request, \"Command failed\"),\n ],\n finalStatus: \"error\",\n result: \"Command failed\",\n cancellable: false,\n conversation: assistantOnlyConversation(\"Command failed\"),\n };\n}\n\nexport function returnOnlyScript(request: FixtureRequest): FixtureScript {\n const trimmed = request.userMessage.replace(/^.*Return only:\\s*/i, \"\").trim();\n const text = trimmed.length === 0 ? \"The answer is 42.\" : trimmed;\n return finishedAssistantScript(request, text);\n}\n\nexport function shellWithApprovalScript(request: FixtureRequest): FixtureScript {\n const callId = generateCallId();\n return {\n events: [\n systemEvent(request, defaultLocalTools(request)),\n userEvent(request),\n thinkingEvent(request, \"Plan: inspect index.js, then ask before editing.\"),\n toolCallCompleted(request, callId, \"shell\"),\n assistantText(request, \"The answer is 42.\"),\n taskEvent(request, \"inspection-complete\"),\n requestEvent(request),\n ],\n finalStatus: \"finished\",\n result: \"The answer is 42.\",\n cancellable: false,\n conversation: assistantOnlyConversation(\"The answer is 42.\"),\n };\n}\n\nexport function twoShellCommandsScript(request: FixtureRequest): FixtureScript {\n const call1 = generateCallId();\n const call2 = generateCallId();\n return {\n events: [\n systemEvent(request, defaultLocalTools(request)),\n userEvent(request),\n toolCallRunning(request, call1, \"shell\"),\n toolCallCompleted(request, call1, \"shell\"),\n toolCallRunning(request, call2, \"shell\"),\n toolCallCompleted(request, call2, \"shell\"),\n assistantText(request, \"Both commands completed.\"),\n ],\n finalStatus: \"finished\",\n result: \"Both commands completed.\",\n cancellable: false,\n conversation: assistantOnlyConversation(\"Both commands completed.\"),\n };\n}\n\nexport function shellExplainScript(request: FixtureRequest): FixtureScript {\n const callId = generateCallId();\n return {\n events: [\n systemEvent(request, defaultLocalTools(request)),\n userEvent(request),\n toolCallCompleted(request, callId, \"shell\"),\n assistantText(request, \"ls succeeded and src/index.js exports answer().\"),\n ],\n finalStatus: \"finished\",\n result: \"ls succeeded and src/index.js exports answer().\",\n cancellable: false,\n conversation: [\n {\n type: \"agentConversationTurn\",\n turn: {\n userMessage: { text: request.userMessage },\n steps: [\n { type: \"assistantMessage\", message: { text: \"Reviewing src/index.js.\" } },\n { type: \"toolCall\", message: { callId, name: \"shell\" } },\n ],\n },\n },\n {\n type: \"shellConversationTurn\",\n turn: {\n shellCommand: { command: \"ls\" },\n shellOutput: { stdout: \"src\\npackage.json\\n\", stderr: \"\", exitCode: 0 },\n },\n },\n ],\n };\n}\n\nexport function spawnSubagentsScript(request: FixtureRequest): FixtureScript {\n const subagents = Object.entries(request.subagents);\n const lines: string[] = [\"Spawning subagents:\"];\n for (const [name, def] of subagents) {\n lines.push(`- ${name} (${def.description}): ${def.prompt}`);\n }\n return finishedAssistantScript(request, lines.join(\"\\n\"));\n}\n\nexport function listMcpToolsScript(request: FixtureRequest): FixtureScript {\n const tools = defaultLocalTools(request);\n return {\n events: [\n systemEvent(request, tools),\n userEvent(request),\n assistantText(request, `Active tools: ${tools.join(\", \")}`),\n ],\n finalStatus: \"finished\",\n result: `Active tools: ${tools.join(\", \")}`,\n cancellable: false,\n conversation: assistantOnlyConversation(`Active tools: ${tools.join(\", \")}`),\n };\n}\n\nexport function webSearchScript(request: FixtureRequest): FixtureScript {\n const callId = generateCallId();\n return {\n events: [\n systemEvent(request, defaultLocalTools(request)),\n userEvent(request),\n toolCallCompleted(request, callId, \"mcp_search_provider_web_search\"),\n assistantText(request, \"Search complete.\"),\n ],\n finalStatus: \"finished\",\n result: \"Search complete.\",\n cancellable: false,\n conversation: assistantOnlyConversation(\"Search complete.\"),\n };\n}\n\nexport function providerFallbackScript(request: FixtureRequest): FixtureScript {\n const fallback = request.agentOptions.providers?.fallback?.[0] ?? \"openrouter\";\n const fallbackModel = `${fallback}:fallback-default`;\n return {\n events: [\n systemEvent(request, defaultLocalTools(request)),\n userEvent(request),\n assistantText(request, \"Falling back to alternate provider.\"),\n ],\n finalStatus: \"finished\",\n result: \"Falling back to alternate provider.\",\n cancellable: false,\n conversation: assistantOnlyConversation(\"Falling back to alternate provider.\"),\n extraRunFields: {\n model: { id: fallbackModel },\n provider: {\n requested: \"unavailable\",\n selected: fallback,\n fallbackReason: \"unavailable-provider\",\n },\n },\n };\n}\n\nexport function printEnvScript(request: FixtureRequest): FixtureScript {\n return finishedAssistantScript(\n request,\n \"Environment summary printed (secrets redacted with ***).\",\n );\n}\n\nexport function useSkillScript(request: FixtureRequest, skillName: string): FixtureScript {\n return finishedAssistantScript(\n request,\n `Using skill: ${skillName} (metadata only — body redacted).`,\n );\n}\n\nexport function contextAwareScript(request: FixtureRequest): FixtureScript {\n return finishedAssistantScript(\n request,\n \"The project uses deterministic contract tests for the Theo SDK.\",\n );\n}\n\nexport function defaultFinishedScript(request: FixtureRequest): FixtureScript {\n return finishedAssistantScript(request, \"Done.\");\n}\n","import type { SDKMessage } from \"../../../types/messages.js\";\nimport type { RunResult } from \"../../../types/run.js\";\nimport { redactSecrets } from \"../../security/index.js\";\nimport {\n buildCloudScript,\n contextAwareScript,\n defaultFinishedScript,\n errorRunScript,\n isMemoryRecallPrompt,\n isMemoryWritePrompt,\n listMcpToolsScript,\n memoryRecallScript,\n memoryWriteScript,\n printEnvScript,\n providerFallbackScript,\n returnAnswerScript,\n returnOnlyScript,\n shellExplainScript,\n shellWithApprovalScript,\n slowRunScript,\n spawnSubagentsScript,\n twoShellCommandsScript,\n useSkillScript,\n webSearchScript,\n} from \"./fixture-scripts.js\";\nimport type { FixtureRequest, FixtureScript } from \"./fixture-types.js\";\n\n/**\n * Fixture responder entry point. Pattern-matches the user message against a\n * dispatch table, builds the script via the appropriate builder, then\n * redacts any provider-token-shaped substrings before returning.\n *\n * @internal\n */\n\nexport type { FixtureRequest, FixtureScript } from \"./fixture-types.js\";\n\ntype ScriptHandler = (request: FixtureRequest) => FixtureScript;\n\nconst LOCAL_SCRIPT_RULES: ReadonlyArray<{\n match: (m: string, request: FixtureRequest) => boolean;\n build: ScriptHandler;\n}> = [\n { match: (m, r) => isMemoryRecallPrompt(m, r), build: memoryRecallScript },\n { match: (m) => isMemoryWritePrompt(m), build: memoryWriteScript },\n { match: (m) => m.includes(\"Run npm run slow\"), build: slowRunScript },\n {\n match: (m) => m.includes(\"Run npm run fail\") || m.includes(\"failing-tool\"),\n build: errorRunScript,\n },\n { match: (m) => m.includes(\"Return only:\"), build: returnOnlyScript },\n {\n match: (m) =>\n m.includes(\"ask for approval before editing\") ||\n m.includes(\"Use shell to inspect src/index.js, then answer\"),\n build: shellWithApprovalScript,\n },\n { match: (m) => m.includes(\"Run two shell commands\"), build: twoShellCommandsScript },\n { match: (m) => m.includes(\"Run ls and explain\"), build: shellExplainScript },\n {\n match: (m) => m.includes(\"exported answer\") || m.includes(\"report the exported answer\"),\n build: (r) => returnAnswerScript(r, \"The answer is 42.\"),\n },\n { match: (m) => m.includes(\"Spawn reviewer and worker subagents\"), build: spawnSubagentsScript },\n {\n match: (m) =>\n m.includes(\"List available MCP tools\") ||\n m.includes(\"Which MCP servers are active\") ||\n m.includes(\"List MCP tools after resume\"),\n build: listMcpToolsScript,\n },\n {\n match: (m) => m.includes(\"Search docs for SDK contract testing patterns\"),\n build: webSearchScript,\n },\n { match: (m) => m.includes(\"Use provider fallback\"), build: providerFallbackScript },\n { match: (m) => m.includes(\"Print env and then summarize\"), build: printEnvScript },\n {\n match: (m) => m.includes(\"Use the code-review skill\"),\n build: (r) => useSkillScript(r, \"code-review\"),\n },\n { match: (m) => m.includes(\"Answer using loaded project context\"), build: contextAwareScript },\n];\n\n/**\n * Dispatch the user message to a deterministic fixture response.\n *\n * @internal\n */\nexport function buildFixtureScript(request: FixtureRequest): FixtureScript {\n const script =\n request.runtime === \"cloud\" ? buildCloudScript(request) : buildLocalScript(request);\n return redactScriptSecrets(script);\n}\n\nfunction buildLocalScript(request: FixtureRequest): FixtureScript {\n const m = request.userMessage;\n for (const rule of LOCAL_SCRIPT_RULES) {\n if (rule.match(m, request)) return rule.build(request);\n }\n return defaultFinishedScript(request);\n}\n\n// ─────────────────────────────────────────────────────────────────────────────\n// Secret redaction — strips obvious provider tokens + fixture sentinel\n// from event payloads. Canonical patterns come from `internal/security`;\n// the `fixture-search-secret` sentinel is local because:\n// - EC-2 fix: registering it via `Security.addPattern` would be cleared\n// by `_resetForTests({ clearExtras: true })` between tests (the module\n// init only runs once per worker).\n// - The sentinel is specific to fixture mode and shouldn't pollute the\n// global redaction surface that other consumers see.\n// ─────────────────────────────────────────────────────────────────────────────\n\nconst FIXTURE_SENTINEL = /fixture-search-secret/g;\n\nfunction redactScriptSecrets(script: FixtureScript): FixtureScript {\n const events = script.events.map(redactEventSecrets);\n return { ...script, events };\n}\n\nfunction redactEventSecrets(event: SDKMessage): SDKMessage {\n const serialized = JSON.stringify(event);\n // Step 1: local fixture sentinel — scoped to this module only.\n const localStripped = serialized.replace(FIXTURE_SENTINEL, \"***\");\n // Step 2: canonical redaction (12 builtin patterns + PARAM + user extras).\n const redacted = redactSecrets(localStripped);\n if (redacted === serialized) return event;\n return JSON.parse(redacted) as SDKMessage;\n}\n\n/**\n * Extract a Run-level extras object (e.g. fallback provider info) when the\n * script declared one. Used by the Run impl to merge into RunResult.\n *\n * @internal\n */\nexport function applyExtraRunFields(base: RunResult, script: FixtureScript): RunResult {\n if (script.extraRunFields === undefined) return base;\n return { ...base, ...script.extraRunFields } as RunResult;\n}\n","import type { ModelSelection } from \"../../../types/agent.js\";\nimport type { ConversationTurn } from \"../../../types/conversation.js\";\nimport type { SDKMessage } from \"../../../types/messages.js\";\nimport type {\n Run,\n RunOperation,\n RunResult,\n RunStatus,\n RunTimelineEvent,\n SDKUserMessage,\n} from \"../../../types/run.js\";\nimport { generateRunId } from \"../../ids.js\";\nimport { applyExtraRunFields } from \"./fixture-responder.js\";\nimport type { FixtureScript } from \"./fixture-types.js\";\n\n/**\n * Shared bootstrap state extracted from `createLocalRun` / `createCloudRun`.\n * Keeps the body of each factory readable while avoiding a tiny duplicated\n * preamble.\n *\n * @internal\n */\nexport function prepareRunContext(message: string | SDKUserMessage): {\n userText: string;\n userImages: SDKUserMessage[\"images\"];\n id: string;\n startTime: number;\n} {\n // M35 (multimodal) — carry a structured message's images alongside its text so the agent loop can\n // attach them as image content blocks. A plain-string message has no images.\n const userText = typeof message === \"string\" ? message : message.text;\n const userImages = typeof message === \"string\" ? undefined : message.images;\n return { userText, userImages, id: generateRunId(), startTime: Date.now() };\n}\n\n/**\n * Shared state machine backing both `LocalRun` and `CloudRun`. Subclasses\n * override `bootstrap()` and `extendRunResult()` to inject runtime-specific\n * lifecycle behavior (async beforeComplete, git metadata) without\n * duplicating the surrounding plumbing.\n *\n * @internal\n */\nexport interface FixtureRunBaseOptions {\n id: string;\n agentId: string;\n model: ModelSelection | undefined;\n script: FixtureScript;\n supportedOps: Set<RunOperation>;\n startTime: number;\n}\n\nexport abstract class FixtureRunBase implements Run {\n readonly id: string;\n readonly agentId: string;\n status: RunStatus = \"running\";\n result?: string;\n model?: ModelSelection;\n durationMs?: number;\n createdAt?: number;\n\n protected readonly script: FixtureScript;\n protected readonly startTime: number;\n protected readonly supportedOps: Set<RunOperation>;\n protected readonly listeners = new Set<(status: RunStatus) => void>();\n protected readonly terminationPromise: Promise<RunResult>;\n protected resolveTermination!: (value: RunResult) => void;\n protected terminated = false;\n private eventNotifier: { promise: Promise<void>; resolve: () => void };\n\n /**\n * theokit#140 - the run's single ordered timeline: structural events and live token/tool deltas,\n * in the order they actually occurred.\n *\n * Kept alongside `script.events` rather than replacing it. `stream()` is the SDKMessage view and\n * stays byte-identical for every existing consumer; this is the complete view, and a consumer\n * picks one. Merging them would have changed `stream()`'s element type - a breaking change for\n * an additive feature.\n */\n protected readonly timeline: RunTimelineEvent[] = [];\n\n constructor(options: FixtureRunBaseOptions) {\n this.id = options.id;\n this.agentId = options.agentId;\n if (options.model !== undefined) this.model = options.model;\n this.script = options.script;\n this.supportedOps = options.supportedOps;\n this.startTime = options.startTime;\n this.createdAt = options.startTime;\n this.terminationPromise = new Promise<RunResult>((resolve) => {\n this.resolveTermination = resolve;\n });\n this.eventNotifier = makeNotifier();\n }\n\n abstract bootstrap(): void;\n\n /**\n * Subclasses driving real (non-fixture) runtimes should call this after\n * pushing a new event into `this.script.events` so that already-awaiting\n * consumers of `stream()` wake up and yield it.\n */\n protected notifyNewEvents(): void {\n const current = this.eventNotifier;\n this.eventNotifier = makeNotifier();\n current.resolve();\n }\n\n /**\n * theokit#140 - every event of this run, in true order, from ONE source.\n *\n * ## The defect this replaces\n *\n * A consumer that needed tool calls interleaved with tokens had to fuse two surfaces by hand:\n * `stream()`, which was batched and post-completion, and `SendOptions.onDelta`, which was live.\n * Neither was complete alone - `onDelta` has no `run_started`/`system`, and `stream()` had no\n * token granularity - so the entire reconciliation, including its dedup, lived in the consumer.\n * `@theokit/agents` carried ~200 lines of exactly that, and it is the documented root of its\n * ordering bug (theokit#47), its namespace-dedup bug (#138) and its missing terminal frame (#142).\n *\n * The ordering is not reconstructed here. Both kinds are appended by the loop AS THEY HAPPEN, so\n * arrival order IS model order - there is nothing to sort, and no timestamp heuristic to get\n * wrong.\n *\n * `callId` is whatever the SDK's own `tool_call` events carry, so a consumer no longer holds two\n * id namespaces and no longer has to correlate them.\n */\n async *events(): AsyncGenerator<RunTimelineEvent, void> {\n let index = 0;\n while (!this.terminated) {\n while (index < this.timeline.length) {\n yield this.timeline[index++] as RunTimelineEvent;\n }\n if (this.terminated) break;\n await Promise.race([this.eventNotifier.promise, this.terminationPromise]);\n }\n // Drain what landed between the last wake-up and termination. Without this, the final events of\n // a fast run are silently lost - the same shape of bug as the missing terminal frame (#142).\n while (index < this.timeline.length) {\n yield this.timeline[index++] as RunTimelineEvent;\n }\n for await (const message of this.terminalErrorEvent()) {\n yield { kind: \"message\", message };\n }\n }\n\n /** theokit#140 - append to the timeline and wake `events()`. */\n protected pushTimeline(event: RunTimelineEvent): void {\n this.timeline.push(event);\n this.notifyNewEvents();\n }\n\n async *stream(): AsyncGenerator<SDKMessage, void> {\n let index = 0;\n while (!this.terminated) {\n while (index < this.script.events.length) {\n yield this.script.events[index++] as SDKMessage;\n }\n if (this.terminated) break;\n await Promise.race([this.eventNotifier.promise, this.terminationPromise]);\n }\n while (index < this.script.events.length) {\n yield this.script.events[index++] as SDKMessage;\n }\n yield* this.terminalErrorEvent();\n }\n\n /**\n * theokit#101 — when the run ends in error, `stream()` has to SAY SO.\n *\n * The error always existed: the loop records it in `ctx.error` and `wait()` returns\n * `status: 'error'` with the message. Only `stream()` failed to mention it — it drains\n * `script.events` and stops. A provider failure (404 \"No endpoints found\", auth, timeout)\n * produced a turn that looked successful and empty, on EVERY surface consuming the\n * stream: HTTP web, MCP, stdio, TUI in-process.\n *\n * A silent error is the worst kind (Unbreakable Rule 8). And the asymmetry was what made it\n * hard to diagnose: anyone debugging via `wait()` saw the error and would not reproduce the\n * report of anyone debugging via the stream.\n *\n * It emits `SDKStatusMessage` with `status: \"ERROR\"` — the type ALREADY EXISTS in the `SDKMessage` union\n * and is already expected by consumers. A new type would be breaking for every consumer doing\n * an exhaustive switch; this one is additive, and a consumer ignoring `status` simply\n * behaves as before — never worse than today.\n */\n private *terminalErrorEvent(): Generator<SDKMessage> {\n if (this.status !== \"error\") return;\n const detail = this.script.errorDetail;\n yield {\n type: \"status\",\n agent_id: this.agentId,\n run_id: this.id,\n status: \"ERROR\",\n // Without a message, the consumer knows THAT it failed and not WHAT — which is half the defect.\n ...(detail?.message !== undefined ? { message: detail.message } : {}),\n } satisfies SDKMessage;\n }\n\n wait(): Promise<RunResult> {\n return this.terminationPromise;\n }\n\n cancel(): Promise<void> {\n if (this.terminated) return Promise.resolve();\n this.transitionTo(\"cancelled\");\n return Promise.resolve();\n }\n\n conversation(): Promise<ConversationTurn[]> {\n return Promise.resolve(this.script.conversation);\n }\n\n supports(op: RunOperation): boolean {\n return this.supportedOps.has(op);\n }\n\n unsupportedReason(op: RunOperation): string | undefined {\n return this.supportedOps.has(op) ? undefined : `Operation ${op} is not supported`;\n }\n\n onDidChangeStatus(listener: (status: RunStatus) => void): () => void {\n this.listeners.add(listener);\n this.notifyListener(listener);\n return () => {\n this.listeners.delete(listener);\n };\n }\n\n protected transitionTo(nextStatus: RunStatus): void {\n if (this.terminated) return;\n this.terminated = true;\n this.status = nextStatus;\n this.durationMs = Date.now() - this.startTime;\n if (nextStatus !== \"cancelled\" && this.script.result !== undefined) {\n this.result = this.script.result;\n }\n this.notifyAllListeners();\n this.eventNotifier.resolve();\n this.resolveTermination(this.buildResult(nextStatus));\n }\n\n protected buildResult(status: RunStatus): RunResult {\n const base: RunResult = {\n id: this.id,\n status: status === \"running\" ? \"finished\" : status,\n ...(this.model !== undefined ? { model: this.model } : {}),\n durationMs: this.durationMs ?? Date.now() - this.startTime,\n };\n if ((status === \"finished\" || status === \"error\") && this.script.result !== undefined) {\n base.result = this.script.result;\n }\n // Surface the script's errorDetail (set by emitErrorEvent) so wait()\n // callers see the cause without having to drain stream().\n if (status === \"error\" && this.script.errorDetail !== undefined) {\n base.error = this.script.errorDetail;\n }\n applyScriptMetrics(base, this.script);\n return this.extendRunResult(applyExtraRunFields(base, this.script));\n }\n\n /** Subclasses override to attach runtime-specific fields (e.g. cloud git info). */\n protected extendRunResult(result: RunResult): RunResult {\n return result;\n }\n\n /** Whether `onDidChangeStatus` should fire immediately with the current status. */\n protected notifyImmediately(): boolean {\n return false;\n }\n\n private notifyListener(listener: (status: RunStatus) => void): void {\n if (!this.notifyImmediately()) return;\n try {\n listener(this.status);\n } catch {\n // listeners are user code; never propagate\n }\n }\n\n private notifyAllListeners(): void {\n for (const listener of this.listeners) {\n try {\n listener(this.status);\n } catch {\n // listeners are user code; never propagate\n }\n }\n }\n}\n\nfunction makeNotifier(): { promise: Promise<void>; resolve: () => void } {\n let resolve: () => void = () => undefined;\n const promise = new Promise<void>((res) => {\n resolve = res;\n });\n return { promise, resolve };\n}\n\n/**\n * Copy the script's run-metric fields onto the result (D376/D377 usage + cost\n * regardless of status; M1-2 silent-truncation signal). Extracted from\n * `buildResult` to keep it under the cognitive-complexity cap.\n */\nfunction applyScriptMetrics(base: RunResult, script: FixtureScript): void {\n if (script.usage !== undefined) base.usage = script.usage;\n if (script.cost !== undefined) base.cost = script.cost;\n if (script.stoppedAtIterationLimit === true) base.stoppedAtIterationLimit = true;\n if (script.stoppedByDoomLoop === true) base.stoppedByDoomLoop = true;\n // SE3 — forward the turn's provenance onto the run result.\n if (script.origin !== undefined) base.origin = script.origin;\n}\n","import type { AgentOptions, ModelSelection } from \"../../types/agent.js\";\nimport type {\n Run,\n RunGitInfo,\n RunOperation,\n RunResult,\n SDKUserMessage,\n SendOptions,\n} from \"../../types/run.js\";\nimport { buildFixtureScript } from \"../runtime/fixtures/fixture-responder.js\";\nimport {\n FixtureRunBase,\n type FixtureRunBaseOptions,\n prepareRunContext,\n} from \"../runtime/fixtures/fixture-run-base.js\";\n\n/**\n * Options accepted by `createCloudRun()`.\n *\n * @internal\n */\nexport interface CreateCloudRunOptions {\n agentId: string;\n model: ModelSelection;\n message: string | SDKUserMessage;\n agentOptions: AgentOptions;\n sendOptions: SendOptions;\n /** Accepted for API parity; fixture cloud path does not use it. */\n systemPrompt?: string;\n}\n\n/**\n * Build a cloud Run handle. In fixture mode, mimics Theo PaaS behavior\n * (CREATING/RUNNING/FINISHED status events + git metadata on result).\n *\n * @internal\n */\nexport function createCloudRun(options: CreateCloudRunOptions): Run {\n const { userText, id, startTime } = prepareRunContext(options.message);\n const supported = new Set<RunOperation>([\n \"stream\",\n \"wait\",\n \"cancel\",\n \"conversation\",\n \"listArtifacts\",\n \"downloadArtifact\",\n ]);\n\n const script = buildFixtureScript({\n agentId: options.agentId,\n runId: id,\n model: options.model,\n userMessage: userText,\n runtime: \"cloud\",\n agentOptions: options.agentOptions,\n sendOptions: options.sendOptions,\n workspaceCwd: undefined,\n subagents: {},\n settingSourcesIncludeProject: false,\n memoryFacts: [],\n sessionMessages: [],\n projectMcpServers: {},\n });\n\n const handle = new CloudRun({\n id,\n agentId: options.agentId,\n model: options.model,\n script,\n supportedOps: supported,\n startTime,\n git: buildGitInfo(),\n });\n handle.bootstrap();\n return handle;\n}\n\ninterface CloudRunCtorOptions extends FixtureRunBaseOptions {\n git: RunGitInfo;\n}\n\nclass CloudRun extends FixtureRunBase {\n git?: RunGitInfo;\n private readonly gitInfo: RunGitInfo;\n\n constructor(options: CloudRunCtorOptions) {\n super(options);\n this.gitInfo = options.git;\n this.git = options.git;\n }\n\n bootstrap(): void {\n if (this.script.cancellable) return;\n setTimeout(() => this.transitionTo(this.script.finalStatus), 0);\n }\n\n protected override extendRunResult(result: RunResult): RunResult {\n return { ...result, git: this.gitInfo };\n }\n}\n\nfunction buildGitInfo(): RunGitInfo {\n return {\n branches: [\n {\n repoUrl: \"https://github.com/usetheo/example\",\n branch: \"feat/contract-fixture\",\n prUrl: \"https://github.com/usetheo/example/pull/1\",\n },\n ],\n };\n}\n","import { NetworkError } from \"../../errors.js\";\nimport type { AgentOptions, ModelSelection } from \"../../types/agent.js\";\nimport type { SDKAssistantMessage, SDKMessage, SDKStatusMessage } from \"../../types/messages.js\";\nimport type { Run, RunOperation, RunStatus, SDKUserMessage, SendOptions } from \"../../types/run.js\";\nimport { resolveApiKey } from \"../env.js\";\nimport { parseSseStream } from \"../llm/sse.js\";\nimport { getConfiguredBaseUrl } from \"../runtime/fixtures/fixture-mode.js\";\nimport { FixtureRunBase, prepareRunContext } from \"../runtime/fixtures/fixture-run-base.js\";\nimport type { FixtureScript } from \"../runtime/fixtures/fixture-types.js\";\nimport type { CloudAgentPayload } from \"./cloud-payload-types.js\";\n\n/**\n * Real cloud Run. When `THEOKIT_API_BASE_URL` is set + the API key is not\n * a fixture key, the Run hits the PaaS SSE endpoint at\n * `POST /v1/agents/{agentId}/runs` and translates server events into our\n * `SDKMessage` stream.\n *\n * The server contract is intentionally minimal in Phase 1:\n * - `event: status` `data: {\"status\":\"CREATING|RUNNING|FINISHED|ERROR\"}`\n * - `event: assistant` `data: {\"text\":\"...\"}`\n * - `event: result` `data: {\"result\":\"...\", \"status\":\"finished\"}`\n *\n * @internal\n */\n\nexport interface CreateRealCloudRunOptions {\n agentId: string;\n model: ModelSelection;\n message: string | SDKUserMessage;\n agentOptions: AgentOptions;\n sendOptions: SendOptions;\n fetch?: typeof fetch;\n /** Pre-resolved system prompt threaded by `CloudAgent.send`. */\n systemPrompt?: string;\n /** Canonical cloud-agent payload (ADR D15) — embedded in POST body as `agentConfig`. */\n agentConfig?: CloudAgentPayload;\n}\n\nexport function createRealCloudRun(options: CreateRealCloudRunOptions): Run {\n const { userText, id, startTime } = prepareRunContext(options.message);\n const supported = new Set<RunOperation>([\n \"stream\",\n \"wait\",\n \"cancel\",\n \"conversation\",\n \"listArtifacts\",\n \"downloadArtifact\",\n ]);\n\n // FixtureScript shape required by the base Run class but never consumed\n // by the real cloud run path (the cloud transport drives events instead).\n const unusedFixtureScript: FixtureScript = {\n events: [],\n finalStatus: \"running\",\n cancellable: false,\n conversation: [],\n };\n\n const apiKey = resolveApiKey(options.agentOptions.apiKey);\n const baseUrl = getConfiguredBaseUrl();\n const handle = new RealCloudRun(\n {\n id,\n agentId: options.agentId,\n model: options.model,\n script: unusedFixtureScript,\n supportedOps: supported,\n startTime,\n },\n {\n apiKey,\n baseUrl,\n userText,\n fetchImpl: options.fetch ?? fetch,\n sendOptions: options.sendOptions,\n systemPrompt: options.systemPrompt,\n agentConfig: options.agentConfig,\n },\n );\n handle.bootstrap();\n return handle;\n}\n\ninterface RealCloudRunInputs {\n apiKey: string | undefined;\n baseUrl: string | undefined;\n userText: string;\n fetchImpl: typeof fetch;\n sendOptions: SendOptions;\n systemPrompt: string | undefined;\n agentConfig: CloudAgentPayload | undefined;\n}\n\nclass RealCloudRun extends FixtureRunBase {\n private readonly inputs: RealCloudRunInputs;\n private readonly controller = new AbortController();\n\n constructor(\n options: ConstructorParameters<typeof FixtureRunBase>[0],\n inputs: RealCloudRunInputs,\n ) {\n super(options);\n this.inputs = inputs;\n }\n\n bootstrap(): void {\n setTimeout(() => {\n void this.drive();\n }, 0);\n }\n\n protected override notifyImmediately(): boolean {\n return true;\n }\n\n override cancel(): Promise<void> {\n this.controller.abort();\n return super.cancel();\n }\n\n private async drive(): Promise<void> {\n if (this.inputs.apiKey === undefined || this.inputs.baseUrl === undefined) {\n this.fail(\"Real cloud Run requires THEOKIT_API_KEY + THEOKIT_API_BASE_URL\");\n return;\n }\n try {\n const response = await this.postRun(this.inputs.apiKey, this.inputs.baseUrl);\n await this.consumeStream(response);\n } catch (cause) {\n if (this.terminated) return;\n this.fail(cause instanceof Error ? cause.message : String(cause));\n }\n }\n\n private async postRun(apiKey: string, baseUrl: string): Promise<Response> {\n const response = await this.inputs.fetchImpl(`${baseUrl}/v1/agents/${this.agentId}/runs`, {\n method: \"POST\",\n signal: this.controller.signal,\n headers: {\n \"content-type\": \"application/json\",\n accept: \"text/event-stream\",\n authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify({\n message: this.inputs.userText,\n mcpServers: this.inputs.sendOptions.mcpServers,\n ...(this.inputs.systemPrompt !== undefined\n ? { systemPrompt: this.inputs.systemPrompt }\n : {}),\n ...(this.inputs.agentConfig !== undefined ? { agentConfig: this.inputs.agentConfig } : {}),\n }),\n });\n if (!response.ok) {\n const text = await response.text().catch(() => \"\");\n throw new NetworkError(\n `Cloud Run endpoint returned ${response.status}: ${text.slice(0, 200)}`,\n { code: \"cloud_run_http_error\" },\n );\n }\n return response;\n }\n\n private async consumeStream(response: Response): Promise<void> {\n let finalStatus: RunStatus = \"finished\";\n let finalText = \"\";\n for await (const record of parseSseStream(response.body, this.controller.signal)) {\n const parsed = safeParse(record.data);\n if (parsed === undefined) continue;\n const update = this.applyRecord(record.event, parsed);\n if (update.finalText !== undefined) finalText = update.finalText;\n if (update.finalStatus !== undefined) finalStatus = update.finalStatus;\n }\n if (finalText.length > 0) this.script.result = finalText;\n this.transitionTo(finalStatus);\n }\n\n private applyRecord(\n eventName: string,\n parsed: Record<string, unknown>,\n ): { finalText?: string; finalStatus?: RunStatus } {\n if (eventName === \"status\") {\n this.script.events.push(this.buildStatusEvent(parsed.status as string));\n this.notifyNewEvents();\n return {};\n }\n if (eventName === \"assistant\") {\n const text = typeof parsed.text === \"string\" ? parsed.text : \"\";\n this.script.events.push(this.buildAssistantEvent(text));\n this.notifyNewEvents();\n return { finalText: text };\n }\n if (eventName === \"result\") {\n const update: { finalText?: string; finalStatus?: RunStatus } = {\n finalStatus: (parsed.status as RunStatus | undefined) ?? \"finished\",\n };\n if (typeof parsed.result === \"string\") update.finalText = parsed.result;\n return update;\n }\n return {};\n }\n\n private buildStatusEvent(status: string): SDKStatusMessage {\n return {\n type: \"status\",\n agent_id: this.agentId,\n run_id: this.id,\n status: status as SDKStatusMessage[\"status\"],\n };\n }\n\n private buildAssistantEvent(text: string): SDKAssistantMessage {\n return {\n type: \"assistant\",\n agent_id: this.agentId,\n run_id: this.id,\n message: { role: \"assistant\", content: [{ type: \"text\", text }] },\n };\n }\n\n private fail(message: string, code?: string): void {\n const event: SDKAssistantMessage = this.buildAssistantEvent(message);\n this.script.events.push(event satisfies SDKMessage);\n this.notifyNewEvents();\n this.script.result = message;\n if (this.script.errorDetail === undefined) {\n this.script.errorDetail = { message, ...(code !== undefined ? { code } : {}) };\n }\n this.transitionTo(\"error\" satisfies RunStatus);\n }\n}\n\nfunction safeParse(data: string): Record<string, unknown> | undefined {\n try {\n return JSON.parse(data) as Record<string, unknown>;\n } catch {\n return undefined;\n }\n}\n","import {\n agentGenerate,\n type GenerateOptions,\n type GenerateRunResult,\n} from \"../../agent-generate.js\";\nimport {\n ConfigurationError,\n UnknownAgentError,\n UnsupportedRunOperationError,\n} from \"../../errors.js\";\nimport type {\n AgentOptions,\n ModelSelection,\n SDKAgent,\n SDKArtifact,\n SystemPromptContext,\n} from \"../../types/agent.js\";\nimport type { Run, SDKUserMessage, SendOptions } from \"../../types/run.js\";\nimport { resolveApiKey } from \"../env.js\";\nimport { generateCloudAgentId } from \"../ids.js\";\nimport { withCwdMutex } from \"../persistence/cwd-mutex.js\";\nimport { DEFAULT_AGENTIC_MODEL_ID } from \"../runtime/config/default-model.js\";\nimport { getConfiguredBaseUrl, isFixtureApiKey } from \"../runtime/fixtures/fixture-mode.js\";\nimport { normalizeModel } from \"../runtime/model-selection.js\";\nimport {\n flushRegistrySaves,\n registerAgent,\n updateRegisteredAgent,\n} from \"../runtime/registry/agent-registry.js\";\nimport { resolveSystemPromptForSend } from \"../runtime/system-prompt/system-prompt.js\";\nimport { PathTraversalError, validateArtifactPath } from \"../security/path-guard.js\";\nimport { serializeCloudAgentConfig } from \"./cloud-config-serializer.js\";\nimport type { CloudAgentPayload } from \"./cloud-payload-types.js\";\nimport { createCloudRun } from \"./cloud-run.js\";\nimport { createRealCloudRun } from \"./real-cloud-run.js\";\n\n/**\n * Cloud SDKAgent implementation. Holds the cloud configuration and routes\n * runs to the fixture responder (which mimics PaaS behavior) or to real HTTP\n * when `THEOKIT_API_BASE_URL` is set.\n *\n * @internal\n */\nexport class CloudAgent implements SDKAgent {\n readonly agentId: string;\n model: ModelSelection | undefined;\n /**\n * Canonical JSON contract payload (ADR D15) that PaaS receives at runtime.\n * Re-serialized by `reload()` when filesystem state changes.\n * Public for contract testing — consumers can inspect what would be sent.\n */\n cloudPayload: CloudAgentPayload;\n private readonly options: AgentOptions;\n /** Idempotency guard for dispose() (EC-3). */\n private disposed = false;\n\n constructor(options: AgentOptions, providedAgentId?: string) {\n this.agentId = providedAgentId ?? options.agentId ?? generateCloudAgentId();\n this.model = normalizeModel(options.model);\n this.options = options;\n this.cloudPayload = serializeCloudAgentConfig({ ...options, agentId: this.agentId });\n\n const repoUrls = (options.cloud?.repos ?? []).map((repo) => repo.url);\n registerAgent({\n agentId: this.agentId,\n runtime: \"cloud\",\n name: options.name,\n summary: this.isFixtureMode() ? \"Cloud contract fixture\" : \"Cloud agent\",\n model: this.model,\n createdAt: Date.now(),\n lastModified: Date.now(),\n archived: false,\n options,\n // Persistence routing only (ADR D17). Cloud agents do not surface `cwd`\n // through `SDKAgentInfo` (toCloudAgentInfo strips it).\n cwd: process.cwd(),\n repos: repoUrls,\n status: \"running\",\n });\n }\n\n /**\n * Fixture-mode is on iff the API key matches the `theo_test_*` test pattern\n * AND no real `THEOKIT_API_BASE_URL` is configured. Outside fixture-mode,\n * cloud operations are pre-release and must surface explicit errors.\n */\n private isFixtureMode(): boolean {\n const apiKey = resolveApiKey(this.options.apiKey);\n return isFixtureApiKey(apiKey) && getConfiguredBaseUrl() === undefined;\n }\n\n // SE9 — integrated structured output; delegates to the shared helper.\n generate<T extends import(\"zod\").ZodType>(\n message: string | SDKUserMessage,\n options: GenerateOptions<T>,\n ): Promise<GenerateRunResult<import(\"zod\").z.infer<T>>> {\n return agentGenerate(\n this,\n this.model,\n this.options.apiKey,\n this.options.local,\n message,\n options,\n );\n }\n\n async send(message: string | SDKUserMessage, options: SendOptions = {}): Promise<Run> {\n // Custom inline tools are local-only — cloud agents reject per-call\n // tools the same way creation-time tools are rejected (handlers cannot\n // cross the wire). Mirror the ConfigurationError code so callers can\n // catch both surfaces uniformly.\n if (options.tools !== undefined && options.tools.length > 0) {\n throw new ConfigurationError(\n \"Custom inline tools are local-only in SDK v1.0 — cloud agents cannot serialize handler functions\",\n { code: \"cloud_custom_tools_rejected\" },\n );\n }\n // D370: Task wrapping is local-only in v1 (cloud runtime pre-release).\n if (options.task !== undefined) {\n const { UnsupportedTaskOperationError } = await import(\"../../errors.js\");\n throw new UnsupportedTaskOperationError(\"send\", { cause: undefined });\n }\n // ADR D19: same per-agent send mutex as LocalAgent. Holds until the run\n // completes so concurrent sends to the same agentId serialize end-to-end.\n return new Promise<Run>((resolve, reject) => {\n void withCwdMutex(`agent-send:${this.agentId}`, async () => {\n let run: Run;\n try {\n run = await this.sendLocked(message, options);\n } catch (err) {\n reject(err);\n return;\n }\n resolve(run);\n // T1.10 — bound the mutex hold on run.wait() so a hanging cloud\n // run (pre-release runtime is unreliable) doesn't block all\n // subsequent sends to this agentId forever. The run continues\n // in the background — only the MUTEX hold is bounded. Default\n // timeout: 5 minutes (generous for LLM round-trips; operators\n // override via THEOKIT_CLOUD_SEND_MUTEX_TIMEOUT_MS env var).\n const mutexTimeoutMs = Number(process.env.THEOKIT_CLOUD_SEND_MUTEX_TIMEOUT_MS) || 300_000;\n try {\n await Promise.race([run.wait(), new Promise<void>((r) => setTimeout(r, mutexTimeoutMs))]);\n } catch {\n // Caller observes via their own wait/stream.\n }\n });\n });\n }\n\n private async sendLocked(message: string | SDKUserMessage, options: SendOptions): Promise<Run> {\n // SE8 — normalize a bare-string send-model override to `{ id }`.\n const overrideModel = normalizeModel(options.model);\n if (overrideModel !== undefined) {\n this.model = overrideModel;\n updateRegisteredAgent(this.agentId, { model: overrideModel });\n }\n const userText = typeof message === \"string\" ? message : message.text;\n const systemPrompt = await this.resolveSystemPromptForSend(userText, options);\n const apiKey = resolveApiKey(this.options.apiKey);\n const useRealRuntime =\n apiKey !== undefined && !isFixtureApiKey(apiKey) && getConfiguredBaseUrl() !== undefined;\n return useRealRuntime\n ? createRealCloudRun({\n agentId: this.agentId,\n model: this.model ?? { id: DEFAULT_AGENTIC_MODEL_ID },\n message,\n agentOptions: this.options,\n sendOptions: options,\n agentConfig: this.cloudPayload,\n ...(systemPrompt !== undefined ? { systemPrompt } : {}),\n })\n : createCloudRun({\n agentId: this.agentId,\n model: this.model ?? { id: DEFAULT_AGENTIC_MODEL_ID },\n message,\n agentOptions: this.options,\n sendOptions: options,\n ...(systemPrompt !== undefined ? { systemPrompt } : {}),\n });\n }\n\n private resolveSystemPromptForSend(\n userText: string,\n options: SendOptions,\n ): Promise<string | undefined> {\n return resolveSystemPromptForSend(\n this.options.systemPrompt,\n options.systemPrompt,\n (): Promise<SystemPromptContext> =>\n Promise.resolve({\n agentId: this.agentId,\n cwd: undefined,\n model: this.model,\n skills: [],\n userMessage: userText,\n memory: [],\n }),\n );\n }\n\n close(): void {\n // Cloud agents stay registered until explicit dispose/delete.\n }\n\n reload(): Promise<void> {\n // EC-6: re-serialize the cloud payload so filesystem-derived state\n // (skills.enabled may shift as new SKILL.md files appear in repo) is\n // reflected in subsequent send() dispatches.\n this.cloudPayload = serializeCloudAgentConfig({ ...this.options, agentId: this.agentId });\n return Promise.resolve();\n }\n\n async dispose(): Promise<void> {\n // EC-3: idempotent. `await using` may dispatch dispose twice (the using\n // exit hook + explicit `await agent.dispose()`); second call is a no-op.\n if (this.disposed) return;\n this.disposed = true;\n await flushRegistrySaves(process.cwd());\n }\n\n [Symbol.asyncDispose](): Promise<void> {\n return this.dispose();\n }\n\n listArtifacts(): Promise<SDKArtifact[]> {\n if (!this.isFixtureMode()) {\n return Promise.reject(\n new ConfigurationError(\n \"Cloud runtime is pre-release. listArtifacts() will return real artifacts when Theo PaaS ships; today it is only available in fixture mode (theo_test_* keys).\",\n { code: \"cloud_runtime_pre_release\" },\n ),\n );\n }\n return Promise.resolve(buildFixtureArtifacts());\n }\n\n downloadArtifact(path: string): Promise<Buffer> {\n // T1.4 — delegate path-traversal rejection to the centralized\n // path-guard module (handles `..`, backslash, %2e%2e, NUL byte,\n // Windows drive prefix, home-tilde, absolute paths). The original\n // 2-vector inline check shipped a typed `artifact_path_traversal`\n // error; we preserve that error contract here regardless of which\n // vector trips the validator.\n try {\n validateArtifactPath(path);\n } catch (cause) {\n if (cause instanceof PathTraversalError) {\n return Promise.reject(\n new ConfigurationError(`Artifact path must stay inside the workspace: ${path}`, {\n code: \"artifact_path_traversal\",\n cause,\n }),\n );\n }\n return Promise.reject(cause as Error);\n }\n if (!this.isFixtureMode()) {\n return Promise.reject(\n new ConfigurationError(\n \"Cloud runtime is pre-release. downloadArtifact() will fetch real PaaS artifacts when the cloud runtime ships; today it is only available in fixture mode (theo_test_* keys).\",\n { code: \"cloud_runtime_pre_release\" },\n ),\n );\n }\n const match = buildFixtureArtifacts().find((artifact) => artifact.path === path);\n if (match === undefined) {\n return Promise.reject(\n new UnknownAgentError(`Artifact ${path} not found`, { code: \"unknown_artifact\" }),\n );\n }\n return Promise.resolve(Buffer.from(`fixture artifact content for ${path}\\n`));\n }\n\n /**\n * Cloud runtime manages goal loops server-side (ADR D122). The local\n * fork pattern is also not available in cloud — both throw synchronously\n * with `UnsupportedRunOperationError` so callers branch early (EC-G).\n *\n * @public\n */\n runUntil(): never {\n throw new UnsupportedRunOperationError(\n \"Agent.runUntil() is not supported on cloud agents. Cloud runtime manages goal loops server-side. Use a local agent for autonomous Ralph loops.\",\n \"runUntil\",\n );\n }\n\n /**\n * Forked sub-agents are local-only (ADRs D110-D114).\n *\n * @public\n */\n fork(): never {\n throw new UnsupportedRunOperationError(\n \"Agent.fork() is not supported on cloud agents. Fork inheritance requires local credential + system-prompt access. Use a local agent.\",\n \"fork\",\n );\n }\n\n /**\n * The continuation driver re-sends against a stateful local session; the\n * cloud runtime manages its own continuation policy server-side (M1 Phase 3).\n *\n * @public\n */\n runToCompletion(): never {\n throw new UnsupportedRunOperationError(\n \"Agent.runToCompletion() is not supported on cloud agents. Cloud runtime manages continuation server-side. Use a local agent.\",\n \"runToCompletion\",\n );\n }\n\n /**\n * Cloud agents do not expose the streaming continuation driver (V3-4);\n * the cloud runtime manages continuation server-side.\n *\n * @public\n */\n streamToCompletion(): never {\n throw new UnsupportedRunOperationError(\n \"Agent.streamToCompletion() is not supported on cloud agents. Cloud runtime manages continuation server-side. Use a local agent.\",\n \"streamToCompletion\",\n );\n }\n\n /**\n * Personality presets require consistent server-side enforcement that\n * the cloud runtime (pre-release) does not yet provide. Reject explicitly\n * to avoid silent divergence between local and cloud behaviour (ADR D169).\n *\n * @public\n */\n usePersonality(): Promise<never> {\n return Promise.reject(\n new UnsupportedRunOperationError(\n \"Agent.usePersonality() is not supported on cloud agents (pre-release). Use a local agent or wait for cloud GA.\",\n \"usePersonality\",\n ),\n );\n }\n}\n\n/**\n * Canonical fixture artifact list. Only used when the agent is in fixture\n * mode (theo_test_* keys, no THEOKIT_API_BASE_URL). Real PaaS artifacts will\n * be fetched over HTTP when the cloud runtime ships.\n */\nfunction buildFixtureArtifacts(): SDKArtifact[] {\n return [\n {\n path: \"dist/report.txt\",\n sizeBytes: 42,\n updatedAt: \"2024-01-01T00:00:00.000Z\",\n },\n ];\n}\n","import { ConfigurationError } from \"../../errors.js\";\nimport type { AgentOptions } from \"../../types/agent.js\";\nimport type { McpServerConfig } from \"../../types/mcp.js\";\n\n/**\n * Cloud tool parity validator (ADR D15 + D16).\n *\n * When `cloud:` is set on `AgentOptions`, this validator rejects\n * configurations that can't survive the trip to TheoCloud. The goal: no\n * silent-drop. Either the feature serializes to JSON for PaaS (passes here)\n * or it's local-only and the caller hears about it immediately at\n * `Agent.create()` time, not at runtime.\n *\n * Coordinates with the existing checks in `validateAgentOptions`:\n * - `programmatic_hooks_rejected` — universal (covers EC-4 hook closures).\n * - `cloud_plugin_path_rejected` — universal cloud + plugin path.\n * - `cloud_stdio_cwd_rejected` — cloud + stdio with cwd.\n * - `runtime_exclusive` — local + cloud both set.\n *\n * This module adds:\n * - `cloud_incompatible_mcp_stdio_local` — stdio command on a local FS path\n * (`/`, `~/`, `./`, `../`). Bare commands like `npx`/`uvx`/`node`\n * accepted (EC-3 fix: blacklist over whitelist).\n * - `cloud_incompatible_function_resolver` — `systemPrompt` as a\n * `SystemPromptResolver` function (must be a serializable string for\n * cloud).\n *\n * @internal\n */\n\nexport function validateCloudToolParity(options: AgentOptions): void {\n if (options.cloud === undefined) return;\n rejectFunctionSystemPrompt(options);\n rejectFunctionSkills(options);\n rejectProcessors(options);\n rejectStdioMcpLocalPaths(options);\n}\n\nfunction rejectProcessors(options: AgentOptions): void {\n const hasProcessors =\n (options.inputProcessors?.length ?? 0) > 0 || (options.outputProcessors?.length ?? 0) > 0;\n if (hasProcessors) {\n throw new ConfigurationError(\n \"Cloud agents can't run guardrail processors — a Processor carries function handlers that don't survive serialization to PaaS. Run processors on a local agent, or move the guardrail into a server-side gateway in front of TheoCloud.\",\n { code: \"cloud_incompatible_function_resolver\" },\n );\n }\n}\n\nfunction rejectFunctionSystemPrompt(options: AgentOptions): void {\n if (typeof options.systemPrompt === \"function\") {\n throw new ConfigurationError(\n \"Cloud agents require systemPrompt as a serializable string. SystemPromptResolver functions can't run on PaaS — resolve to a string before Agent.create() or move the dynamic logic into a hook rule.\",\n { code: \"cloud_incompatible_function_resolver\" },\n );\n }\n}\n\nfunction rejectFunctionSkills(options: AgentOptions): void {\n if (typeof options.skills === \"function\") {\n throw new ConfigurationError(\n \"Cloud agents require skills as a static settings object. SkillsResolver functions can't run on PaaS — resolve to a SkillsSettings object before Agent.create() or move the dynamic logic into a hook rule.\",\n { code: \"cloud_incompatible_function_resolver\" },\n );\n }\n}\n\nfunction rejectStdioMcpLocalPaths(options: AgentOptions): void {\n if (options.mcpServers === undefined) return;\n for (const [name, config] of Object.entries(options.mcpServers)) {\n if (!isStdioCommandConfig(config)) continue;\n const command = (config as { command?: string }).command ?? \"\";\n if (isLocalPath(command)) {\n throw new ConfigurationError(\n `MCP server \"${name}\" uses a local-FS command path (${command}). Cloud agents can't reach local binaries — use a bare command (npx, uvx, node, …) that the PaaS VM image provides, or switch to an HTTP MCP server.`,\n { code: \"cloud_incompatible_mcp_stdio_local\" },\n );\n }\n }\n}\n\nfunction isStdioCommandConfig(config: McpServerConfig): boolean {\n const obj = config as { type?: string; command?: unknown };\n if (obj.type !== undefined && obj.type !== \"stdio\") return false;\n return typeof obj.command === \"string\" && obj.command.length > 0;\n}\n\n/**\n * Local-FS path heuristic (EC-3). Conservative: reject only patterns that\n * are unambiguously paths on the caller's disk. Bare commands (no path\n * separator at the start) are assumed to be available in the VM's PATH.\n *\n * @internal\n */\nexport function isLocalPath(command: string): boolean {\n return (\n command.startsWith(\"/\") ||\n command.startsWith(\"~/\") ||\n command.startsWith(\"./\") ||\n command.startsWith(\"../\")\n );\n}\n","/**\n * PersonalityStore — session-default + persistent JSON state of the\n * currently-active personality slug per agentId (T2.1, ADR D163).\n *\n * Storage layout (`$THEOKIT_HOME/personality.json`):\n *\n * ```json\n * { \"version\": 1, \"agents\": { \"agent-xyz\": \"coder\" } }\n * ```\n *\n * **EC-B (MUST FIX):** `setActive(agentId, undefined, { save: true })`\n * **DELETES** the key from the `agents` map. Never writes `null`.\n * \"Key absent === no active personality\" is the single canonical\n * representation. Hydration only reads present keys.\n *\n * **EC-N (DOCUMENT):** Brief memory/disk divergence on persist failure is\n * tolerated — session state always wins; next successful call recovers.\n * Disk write failures log a one-shot warn (via redactSecrets) and do NOT\n * throw to the caller (mirrors credential-pool EC-A pattern).\n *\n * Cross-process safety: writes go through `withFileLock` (D61) and use\n * `atomicWriteJson` (atomic rename). Reads always re-load from disk\n * inside the lock so concurrent writers don't lose updates (EC-6).\n *\n * @internal\n */\n\nimport { mkdir, readFile } from \"node:fs/promises\";\nimport { dirname, join } from \"node:path\";\n\nimport { atomicWriteJson } from \"../persistence/atomic-write.js\";\nimport { withFileLock } from \"../persistence/file-lock.js\";\nimport { getTheokitHome } from \"../persistence/paths.js\";\nimport { warnOnce } from \"../runtime/hooks/hooks-source.js\";\nimport { redactSecrets } from \"../security/redact.js\";\n\ninterface PersonalityStateV1 {\n readonly version: 1;\n readonly agents: Record<string, string>;\n}\n\nconst SCHEMA_VERSION = 1;\nconst FILE_NAME = \"personality.json\";\n\nfunction emptyState(): PersonalityStateV1 {\n return { version: SCHEMA_VERSION, agents: {} };\n}\n\nfunction isStateV1(value: unknown): value is PersonalityStateV1 {\n if (value === null || typeof value !== \"object\") return false;\n const v = value as { version?: unknown; agents?: unknown };\n if (v.version !== SCHEMA_VERSION) return false;\n if (v.agents === null || typeof v.agents !== \"object\") return false;\n return true;\n}\n\nasync function readState(filePath: string): Promise<PersonalityStateV1> {\n let raw: string;\n try {\n raw = await readFile(filePath, \"utf8\");\n } catch (err) {\n const code = (err as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\") return emptyState();\n throw err;\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch {\n warnOnce(\n \"personality-store-json-parse\",\n \"[theokit-sdk] personality.json is malformed; treating as empty\",\n );\n return emptyState();\n }\n if (!isStateV1(parsed)) {\n warnOnce(\n \"personality-store-bad-version\",\n `[theokit-sdk] personality.json has unknown version; treating as empty (file kept untouched)`,\n );\n return emptyState();\n }\n return parsed;\n}\n\n/**\n * Tracks per-agent personality slug in session memory; optionally persists\n * via JSON file under `$THEOKIT_HOME/personality.json`.\n *\n * @internal\n */\nexport class PersonalityStore {\n readonly #cwd: string;\n readonly #session = new Map<string, string>();\n\n constructor(cwd: string) {\n this.#cwd = cwd;\n }\n\n /** Active personality slug for `agentId`. Undefined = no active preset. */\n active(agentId: string): string | undefined {\n return this.#session.get(agentId);\n }\n\n /**\n * Set active personality. Returns previous value (for cache-invalidation\n * decisions in the caller). When `opts.save: true`, also persists to\n * the on-disk JSON file. Persist failures log+continue (never throw).\n */\n async setActive(\n agentId: string,\n slug: string | undefined,\n opts?: { save?: boolean },\n ): Promise<string | undefined> {\n const previous = this.#session.get(agentId);\n if (slug === undefined) this.#session.delete(agentId);\n else this.#session.set(agentId, slug);\n\n if (opts?.save === true) {\n try {\n await this.#persist(agentId, slug);\n } catch (err) {\n warnOnce(\n `personality-store-persist-failure-${agentId}`,\n `[theokit-sdk] personality persist failed for ${redactSecrets(agentId)}: ${redactSecrets(\n (err as Error).message,\n )}`,\n );\n }\n }\n return previous;\n }\n\n /** Hydrate session state for `agentId` from the persistent file. */\n async hydrate(agentId: string): Promise<void> {\n const filePath = this.#filePath();\n let state: PersonalityStateV1;\n try {\n // Hydrate is read-only; no need for cross-process lock (writers\n // already use atomic rename via atomicWriteJson, so reads observe\n // either the old or new state — never torn writes).\n state = await readState(filePath);\n } catch (err) {\n warnOnce(\n `personality-store-hydrate-failure-${agentId}`,\n `[theokit-sdk] personality hydrate failed for ${redactSecrets(agentId)}: ${redactSecrets(\n (err as Error).message,\n )}`,\n );\n return;\n }\n const slug = state.agents[agentId];\n if (slug !== undefined) this.#session.set(agentId, slug);\n else this.#session.delete(agentId);\n }\n\n /** Test-only reset. @internal */\n _reset(): void {\n this.#session.clear();\n }\n\n async #persist(agentId: string, slug: string | undefined): Promise<void> {\n const filePath = this.#filePath();\n // withFileLock needs the parent dir to exist (lock companion is sibling\n // to filePath). atomicWriteJson does its own mkdir but runs INSIDE the\n // lock — so ensure the dir up front.\n await mkdir(dirname(filePath), { recursive: true });\n await withFileLock(filePath, async () => {\n const current = await readState(filePath);\n const nextAgents = { ...current.agents };\n if (slug === undefined) delete nextAgents[agentId];\n else nextAgents[agentId] = slug;\n const next: PersonalityStateV1 = { version: SCHEMA_VERSION, agents: nextAgents };\n await atomicWriteJson(filePath, next);\n });\n }\n\n #filePath(): string {\n return join(getTheokitHome(this.#cwd), FILE_NAME);\n }\n}\n","/**\n * PluginContext implementation + dev-mode seal (T1.2, ADR D99).\n *\n * `createPluginContext()` returns a fresh `{ ctx, registrations }` pair\n * for each plugin. In dev mode (`NODE_ENV !== \"production\"`) the context\n * is wrapped in a Proxy that throws on `set`/`delete` to catch plugin\n * abuse early. In production the raw impl is returned (zero overhead).\n *\n * @internal\n */\n\nimport type { CustomTool } from \"../../types/agent.js\";\nimport { diag } from \"../diagnostics.js\";\nimport type {\n CommandHandler,\n CommandOptions,\n HookHandler,\n HookName,\n PluginContext,\n} from \"./types.js\";\n\ninterface CommandEntry {\n name: string;\n handler: CommandHandler;\n description?: string;\n}\n\ninterface InjectedMessage {\n content: string;\n role: \"user\" | \"system\";\n}\n\nexport interface PluginRegistrations {\n tools: CustomTool[];\n commands: CommandEntry[];\n hooks: Map<HookName, HookHandler[]>;\n injected: InjectedMessage[];\n}\n\nexport function createPluginContext(): {\n ctx: PluginContext;\n registrations: PluginRegistrations;\n} {\n const registrations: PluginRegistrations = {\n tools: [],\n commands: [],\n hooks: new Map(),\n injected: [],\n };\n\n const impl: PluginContext = {\n registerTool(tool) {\n registrations.tools.push(tool);\n },\n registerCommand(name, handler, opts: CommandOptions = {}) {\n const entry: CommandEntry = { name, handler };\n if (opts.description !== undefined) entry.description = opts.description;\n registrations.commands.push(entry);\n },\n on(hook, handler) {\n // EC-2 fix: defense-in-depth. Plugin author can bypass TS via `as any`\n // and pass null/undefined; ignore + warn rather than crash the loop\n // downstream when `runPreToolCallHooks` tries to invoke the handler.\n if (typeof handler !== \"function\") {\n diag(`[theokit-sdk] ignoring non-function handler for hook \"${hook}\"\\n`);\n return;\n }\n const existing = registrations.hooks.get(hook) ?? [];\n existing.push(handler);\n registrations.hooks.set(hook, existing);\n },\n injectMessage(content, role = \"user\") {\n registrations.injected.push({ content, role });\n },\n };\n\n const ctx = shouldSeal() ? sealContext(impl) : impl;\n return { ctx, registrations };\n}\n\nfunction shouldSeal(): boolean {\n return process.env.NODE_ENV !== \"production\";\n}\n\nfunction sealContext(impl: PluginContext): PluginContext {\n return new Proxy(impl, {\n set(_target, prop) {\n throw new Error(\n `[theokit-sdk] PluginContext is sealed — cannot set ${String(prop)}. ` +\n `Plugins must use registerTool, registerCommand, on, or injectMessage.`,\n );\n },\n deleteProperty(_target, prop) {\n throw new Error(`[theokit-sdk] PluginContext is sealed — cannot delete ${String(prop)}.`);\n },\n });\n}\n","/**\n * PluginManager — constructs PluginContext per plugin, invokes register()\n * once, aggregates registrations + provider profiles + memory factories\n * (T1.3, ADRs D97-D101).\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\n// SE45/SE46 — `MemoryProviderFactory` (@internal) is imported from the contract\n// module directly; the `./types.js` shim deliberately does not re-export it (a\n// stripped-internal re-export trips rollup-plugin-dts). See ./types.ts.\nimport type { MemoryProviderFactory } from \"../../types/plugin.js\";\nimport { diag } from \"../diagnostics.js\";\nimport type { ProviderProfile } from \"../providers/types.js\";\nimport { createPluginContext, type PluginRegistrations } from \"./context.js\";\nimport type {\n HookHandler,\n HookName,\n LlmCallContext,\n Plugin,\n PostAssistantReplyContext,\n PostToolCallContext,\n PreToolCallContext,\n PreToolCallDecision,\n PreUserSendContext,\n PreUserSendResult,\n SessionLifecycleContext,\n ToolResultTransformContext,\n TransformContext,\n} from \"./types.js\";\n\nexport interface ProviderEntry {\n pluginName: string;\n profile: ProviderProfile;\n}\n\nexport interface MemoryEntry {\n pluginName: string;\n createProvider: MemoryProviderFactory;\n}\n\nexport interface AggregatedPlugins {\n tools: PluginRegistrations[\"tools\"];\n commands: PluginRegistrations[\"commands\"];\n hooks: PluginRegistrations[\"hooks\"];\n injected: PluginRegistrations[\"injected\"];\n providerProfiles: ProviderEntry[];\n memoryProviders: MemoryEntry[];\n}\n\nexport class PluginManager {\n #aggregated: AggregatedPlugins = {\n tools: [],\n commands: [],\n hooks: new Map(),\n injected: [],\n providerProfiles: [],\n memoryProviders: [],\n };\n #initialized = false;\n // #68 — registrations of plugins added post-init via `register()`, keyed by\n // plugin name so a re-register REPLACES (not appends) the prior hooks.\n readonly #byName = new Map<string, PluginRegistrations>();\n\n async initialize(plugins: ReadonlyArray<Plugin>): Promise<void> {\n if (this.#initialized) {\n throw new Error(\"PluginManager.initialize called twice — register only once per process\");\n }\n this.#initialized = true;\n // EC-4: surface duplicate plugin names so operators notice. Two plugins\n // with the same name are usually a mistake (npm install with override).\n const seen = new Set<string>();\n for (const plugin of plugins) {\n if (seen.has(plugin.name)) {\n diag(\n `[theokit-sdk] duplicate plugin name \"${plugin.name}\" — both will register independently\\n`,\n );\n }\n seen.add(plugin.name);\n await this.#dispatchPlugin(plugin);\n }\n }\n\n /**\n * #68 — register a single `general` plugin AFTER `initialize()` has run.\n *\n * The bulk `initialize()` is single-shot (one call per process); late\n * registration is a distinct, named operation used by adapters that install\n * a plugin per-session/per-request (e.g. the ACP permission veto, which is\n * installed once the permission mode + connection are known — after the\n * agent's own plugins were already initialized).\n *\n * Idempotent by plugin NAME: re-registering a plugin with the same name\n * REPLACES its prior hooks/tools instead of appending duplicates (the ACP\n * permission plugin is re-installed on every prompt).\n *\n * Only `general` plugins may be registered late — model-provider / memory\n * plugins are resolved during the bulk init and cannot be added afterwards.\n */\n async register(plugin: Plugin): Promise<void> {\n if (plugin.kind !== \"general\") {\n throw new ConfigurationError(\n `late register supports general plugins only (got \"${plugin.kind}\" for \"${plugin.name}\")`,\n { code: \"plugin_late_register_kind\" },\n );\n }\n const prior = this.#byName.get(plugin.name);\n if (prior !== undefined) this.#unmerge(prior);\n const { ctx, registrations } = createPluginContext();\n await plugin.register(ctx);\n this.#byName.set(plugin.name, registrations);\n this.#merge(registrations);\n }\n\n get aggregated(): Readonly<AggregatedPlugins> {\n return this.#aggregated;\n }\n\n /**\n * Run all `pre_tool_call` hooks; first decision with `block: true` wins.\n * D101: veto pattern — return `{ block: true, message }` makes the loop\n * surface a tool_result with `isError: false, content: message` so the\n * LLM can self-correct.\n */\n async runPreToolCallHooks(ctx: PreToolCallContext): Promise<PreToolCallDecision | undefined> {\n const handlers = this.#aggregated.hooks.get(\"pre_tool_call\") ?? [];\n for (const h of handlers) {\n const decision = (await (h as (c: PreToolCallContext) => unknown)(ctx)) as\n | PreToolCallDecision\n | undefined;\n if (decision !== undefined && (decision as { block?: boolean }).block === true) {\n return decision as PreToolCallDecision;\n }\n }\n return undefined;\n }\n\n /** Aggregated handlers for a given hook (read-only view). @internal */\n hooksFor(name: Parameters<AggregatedPlugins[\"hooks\"][\"get\"]>[0]): ReadonlyArray<HookHandler> {\n return this.#aggregated.hooks.get(name) ?? [];\n }\n\n /**\n * Run all `pre_user_send` hooks; concatenate non-empty `recalledContext`\n * outputs with `\\n\\n` and cap total length at `maxRecallContextBytes`\n * (EC-A). Per-handler failures are caught + logged to stderr (EC-8) so a\n * single broken adapter never blocks the LLM call (graceful degrade).\n *\n * Returns the assembled context (or undefined if empty after cap).\n *\n * @internal\n */\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: per-handler try/catch + EC-A cap + EC-8 isolation are 3 concerns that share state (parts buffer); splitting fragments the single-pass aggregation.\n async runPreUserSendHooks(\n ctx: PreUserSendContext,\n maxRecallContextBytes: number,\n ): Promise<string | undefined> {\n const handlers = this.#aggregated.hooks.get(\"pre_user_send\") ?? [];\n if (handlers.length === 0) return undefined;\n const parts: string[] = [];\n for (const h of handlers) {\n try {\n const result = (await (h as (c: PreUserSendContext) => unknown)(ctx)) as\n | PreUserSendResult\n | undefined;\n if (result?.recalledContext && result.recalledContext.length > 0) {\n parts.push(result.recalledContext);\n }\n } catch (err) {\n diag(\n `[theokit-sdk] pre_user_send hook failed: ${\n err instanceof Error ? err.message : String(err)\n }\\n`,\n );\n }\n }\n if (parts.length === 0) return undefined;\n let combined = parts.join(\"\\n\\n\");\n // EC-A: cap to prevent context-window blowout.\n if (combined.length > maxRecallContextBytes) {\n combined = `${combined.slice(0, maxRecallContextBytes)}\\n…[truncated]`;\n }\n return combined;\n }\n\n /**\n * Run all `post_assistant_reply` hooks. Fire-and-forget: errors are\n * surfaced to stderr (EC-O) so a slow/broken sync never blocks the\n * caller's `wait()`. Returns a Promise that callers may optionally\n * await for tests; production code typically `void`s it.\n *\n * @internal\n */\n async runPostAssistantReplyHooks(ctx: PostAssistantReplyContext): Promise<void> {\n const handlers = this.#aggregated.hooks.get(\"post_assistant_reply\") ?? [];\n for (const h of handlers) {\n try {\n await (h as (c: PostAssistantReplyContext) => unknown)(ctx);\n } catch (err) {\n diag(\n `[theokit-sdk] post_assistant_reply hook failed: ${\n err instanceof Error ? err.message : String(err)\n }\\n`,\n );\n }\n }\n }\n\n // #65 — the previously-dead hooks, now wired. Fire-and-forget hooks run\n // in order (per-handler errors logged, never thrown); transform hooks fold\n // over the payload (a handler returning a value replaces it).\n\n /** @internal */\n async #runFireAndForget<C>(name: HookName, ctx: C): Promise<void> {\n for (const h of this.#aggregated.hooks.get(name) ?? []) {\n try {\n await (h as (c: C) => unknown)(ctx);\n } catch (err) {\n diag(\n `[theokit-sdk] ${name} hook failed: ${err instanceof Error ? err.message : String(err)}\\n`,\n );\n }\n }\n }\n\n /** @internal — fold: each handler may return a replacement payload; a throw keeps the prior value. */\n async #runTransform<P>(name: HookName, payload: P, ctx: unknown): Promise<P> {\n let current = payload;\n for (const h of this.#aggregated.hooks.get(name) ?? []) {\n try {\n const out = (await (h as (p: P, c: unknown) => unknown)(current, ctx)) as P | undefined;\n if (out !== undefined) current = out;\n } catch (err) {\n diag(\n `[theokit-sdk] ${name} hook failed: ${err instanceof Error ? err.message : String(err)}\\n`,\n );\n }\n }\n return current;\n }\n\n /** #65 — fired after a tool call completes. @internal */\n runPostToolCallHooks(ctx: PostToolCallContext): Promise<void> {\n return this.#runFireAndForget(\"post_tool_call\", ctx);\n }\n\n /** #65 — fired before / after each LLM turn. @internal */\n runPreLlmCallHooks(ctx: LlmCallContext): Promise<void> {\n return this.#runFireAndForget(\"pre_llm_call\", ctx);\n }\n runPostLlmCallHooks(ctx: LlmCallContext): Promise<void> {\n return this.#runFireAndForget(\"post_llm_call\", ctx);\n }\n\n /** #65 — fired at run start / end. @internal */\n runOnSessionStartHooks(ctx: SessionLifecycleContext): Promise<void> {\n return this.#runFireAndForget(\"on_session_start\", ctx);\n }\n runOnSessionEndHooks(ctx: SessionLifecycleContext): Promise<void> {\n return this.#runFireAndForget(\"on_session_end\", ctx);\n }\n\n /** #65/#57 — transform tool results before they reach the LLM (the #57 seam). @internal */\n runTransformToolResultHooks<T>(results: T, ctx: ToolResultTransformContext): Promise<T> {\n return this.#runTransform(\"transform_tool_result\", results, ctx);\n }\n\n /** #65 — transform the LLM output text before it is consumed. @internal */\n runTransformLlmOutputHooks(output: string, ctx: TransformContext): Promise<string> {\n return this.#runTransform(\"transform_llm_output\", output, ctx);\n }\n\n async #dispatchPlugin(plugin: Plugin): Promise<void> {\n if (plugin.kind === \"general\") {\n const { ctx, registrations } = createPluginContext();\n await plugin.register(ctx);\n this.#merge(registrations);\n } else if (plugin.kind === \"model-provider\") {\n this.#aggregated.providerProfiles.push({\n pluginName: plugin.name,\n profile: plugin.profile,\n });\n } else if (plugin.kind === \"memory\") {\n this.#aggregated.memoryProviders.push({\n pluginName: plugin.name,\n createProvider: plugin.createProvider,\n });\n }\n }\n\n #merge(r: PluginRegistrations): void {\n this.#aggregated.tools.push(...r.tools);\n this.#aggregated.commands.push(...r.commands);\n for (const [hook, handlers] of r.hooks.entries()) {\n const existing = this.#aggregated.hooks.get(hook) ?? [];\n existing.push(...handlers);\n this.#aggregated.hooks.set(hook, existing);\n }\n this.#aggregated.injected.push(...r.injected);\n }\n\n /**\n * #68 — inverse of #merge: remove a prior registration's contributions from\n * the aggregated view by object identity. Used by `register()` to replace a\n * same-named plugin's hooks/tools instead of accumulating duplicates.\n */\n #unmerge(r: PluginRegistrations): void {\n removeAll(this.#aggregated.tools, r.tools);\n removeAll(this.#aggregated.commands, r.commands);\n removeAll(this.#aggregated.injected, r.injected);\n for (const [hook, handlers] of r.hooks.entries()) {\n const existing = this.#aggregated.hooks.get(hook);\n if (existing === undefined) continue;\n removeAll(existing, handlers);\n if (existing.length === 0) this.#aggregated.hooks.delete(hook);\n }\n }\n}\n\n/** Remove each element of `toRemove` from `arr` in place (by identity). */\nfunction removeAll<T>(arr: T[], toRemove: ReadonlyArray<T>): void {\n for (const item of toRemove) {\n const idx = arr.indexOf(item);\n if (idx !== -1) arr.splice(idx, 1);\n }\n}\n","import { type SpawnOptions, spawn } from \"node:child_process\";\nimport { type EnvPolicy, resolveChildEnv } from \"./env-policy.js\";\n\n/**\n * Shared `child_process.spawn` wrapper that collects stdout/stderr text and\n * enforces a timeout via SIGKILL. Used by both the hooks executor and the\n * shell tool so each spawn path doesn't reinvent the buffer + timer dance.\n *\n * @internal\n */\n\nexport interface SpawnCollectOptions {\n command: string;\n args?: string[];\n cwd: string;\n env?: Record<string, string>;\n /**\n * #54 — env inherit/scrub policy for the child. Defaults to\n * `inherit-scrubbed` (drop secret-like vars). `env` above is merged AFTER the\n * policy and always wins. Pass `\"all\"` to restore full inheritance.\n */\n envPolicy?: EnvPolicy;\n timeoutMs?: number;\n stdin?: string;\n}\n\nexport interface SpawnCollectResult {\n stdout: string;\n stderr: string;\n exitCode: number | null;\n timedOut: boolean;\n spawnError?: Error;\n}\n\nexport function spawnAndCollect(options: SpawnCollectOptions): Promise<SpawnCollectResult> {\n return new Promise<SpawnCollectResult>((resolve) => {\n const timeoutMs = options.timeoutMs ?? 30_000;\n const spawnOptions: SpawnOptions = {\n cwd: options.cwd,\n // #54 — scrub secret-like parent env by default; `options.env` still wins.\n env: resolveChildEnv({ policy: options.envPolicy, overrides: options.env }),\n };\n const child = spawn(options.command, options.args ?? [], spawnOptions);\n let stdout = \"\";\n let stderr = \"\";\n let timedOut = false;\n let settled = false;\n const settle = (result: SpawnCollectResult): void => {\n if (settled) return;\n settled = true;\n resolve(result);\n };\n const timer = setTimeout(() => {\n timedOut = true;\n try {\n child.kill(\"SIGKILL\");\n } catch {\n // child may already have exited\n }\n settle({ stdout, stderr, exitCode: null, timedOut: true });\n }, timeoutMs);\n child.stdout?.on(\"data\", (chunk: Buffer) => {\n stdout += chunk.toString(\"utf8\");\n });\n child.stderr?.on(\"data\", (chunk: Buffer) => {\n stderr += chunk.toString(\"utf8\");\n });\n child.on(\"error\", (cause) => {\n clearTimeout(timer);\n settle({ stdout, stderr, exitCode: -1, timedOut, spawnError: cause });\n });\n child.on(\"close\", (code) => {\n clearTimeout(timer);\n settle({ stdout, stderr, exitCode: code, timedOut });\n });\n if (options.stdin !== undefined && child.stdin !== null) {\n child.stdin.end(options.stdin);\n }\n });\n}\n","import { spawnAndCollect } from \"../lifecycle/spawn-collect.js\";\nimport { loadHookConfig } from \"./hooks-source.js\";\n\n/**\n * Real file-based hook executor. Reads `.theokit/hooks.json` from the\n * workspace, spawns the configured command for each event with a JSON\n * payload on stdin, and aggregates the decisions.\n *\n * Decisions are conservative by design:\n * - Non-zero exit code on a `preRun` / `preToolUse` hook fails the\n * attached operation with `HookDeniedError`-style data.\n * - JSON-shaped stdout (e.g. `{\"decision\":\"deny\",\"reason\":\"...\"}`) is\n * parsed and respected.\n *\n * @internal\n */\n\nexport type HookEvent = \"preRun\" | \"postRun\" | \"preToolUse\" | \"postToolUse\" | \"stop\";\n\nexport interface HookCommand {\n command: string;\n /** Optional matcher restricting the hook to specific tools (regex). */\n matcher?: string;\n /** Optional timeout in ms; defaults to 30s. */\n timeoutMs?: number;\n}\n\nexport interface HookDecision {\n decision: \"allow\" | \"deny\" | \"feedback\";\n reason?: string;\n feedback?: string;\n}\n\nexport interface HookPayload {\n event: HookEvent;\n tool?: string;\n input?: Record<string, unknown>;\n output?: Record<string, unknown>;\n agentId?: string;\n runId?: string;\n}\n\nexport interface HookExecutionResult {\n decisions: HookDecision[];\n blocked: boolean;\n reason?: string;\n}\n\ninterface HookConfig {\n hooks?: Partial<Record<HookEvent, HookCommand[]>>;\n}\n\nexport class HooksExecutor {\n private config: HookConfig = {};\n\n constructor(private readonly cwd: string) {}\n\n async initialize(settingSourcesIncludeProject: boolean): Promise<void> {\n if (!settingSourcesIncludeProject) {\n this.config = {};\n return;\n }\n // ADR D77: try .theokit/hooks/*.md first; fallback .theokit/hooks.json\n // with deprecation warn. Shared loader in hooks-source.ts.\n this.config = await loadHookConfig(this.cwd);\n }\n\n /** Fire every hook registered for `event` and aggregate the decisions. */\n async run(payload: HookPayload): Promise<HookExecutionResult> {\n const commands = this.commandsFor(payload.event, payload.tool);\n if (commands.length === 0) return { decisions: [], blocked: false };\n const decisions: HookDecision[] = [];\n for (const command of commands) {\n const decision = await this.executeOne(command, payload);\n decisions.push(decision);\n if (decision.decision === \"deny\") {\n const result: HookExecutionResult = {\n decisions,\n blocked: true,\n };\n if (decision.reason !== undefined) result.reason = decision.reason;\n return result;\n }\n }\n return { decisions, blocked: false };\n }\n\n private commandsFor(event: HookEvent, tool: string | undefined): HookCommand[] {\n const list = this.config.hooks?.[event] ?? [];\n if (tool === undefined) return list;\n return list.filter((entry) => {\n if (entry.matcher === undefined) return true;\n try {\n return new RegExp(entry.matcher).test(tool);\n } catch {\n return entry.matcher === tool;\n }\n });\n }\n\n private async executeOne(command: HookCommand, payload: HookPayload): Promise<HookDecision> {\n const timeoutMs = command.timeoutMs ?? 30_000;\n const result = await spawnAndCollect({\n command: \"sh\",\n args: [\"-c\", command.command],\n cwd: this.cwd,\n timeoutMs,\n stdin: JSON.stringify(payload),\n });\n if (result.timedOut) {\n return { decision: \"deny\", reason: `Hook timed out after ${timeoutMs}ms` };\n }\n if (result.spawnError !== undefined) {\n return { decision: \"deny\", reason: `Hook spawn failed: ${result.spawnError.message}` };\n }\n if (result.exitCode !== 0) {\n return {\n decision: \"deny\",\n reason:\n result.stderr.trim().length > 0\n ? result.stderr.trim()\n : `Hook exited with code ${result.exitCode}`,\n };\n }\n return parseDecisionFromStdout(result.stdout);\n }\n}\n\nfunction parseDecisionFromStdout(stdout: string): HookDecision {\n const trimmed = stdout.trim();\n if (trimmed.length === 0) return { decision: \"allow\" };\n try {\n const parsed = JSON.parse(trimmed) as Partial<HookDecision> & {\n decision?: string;\n };\n if (parsed.decision === \"deny\" || parsed.decision === \"feedback\") {\n const result: HookDecision = { decision: parsed.decision };\n if (parsed.reason !== undefined) result.reason = parsed.reason;\n if (parsed.feedback !== undefined) result.feedback = parsed.feedback;\n return result;\n }\n if (parsed.decision === \"allow\") return { decision: \"allow\" };\n } catch {\n // Treat unparseable stdout as feedback rather than failure.\n return { decision: \"feedback\", feedback: trimmed };\n }\n return { decision: \"allow\" };\n}\n","/**\n * Memory path selector (SDK 2.0 Phase 1 physical Stage 2b — iter 22).\n *\n * Pure helpers the future kernel flip will use to choose between\n * legacy direct-call path and new MemoryProvider port path. Shipped\n * in isolation so the helpers are tested + frozen BEFORE the actual\n * `LocalAgent.send()` refactor wires them.\n *\n * Gate semantics (option A from the progress doc):\n * - Default: legacy path (zero behavior change).\n * - `THEOKIT_PORT_MEMORY_PATH=1` (env var): port path active.\n *\n * Why env var (vs option flag):\n * - Easy to flip on/off at runtime without rebuild.\n * - No public API surface added (the env var is internal-only;\n * consumers don't see it in their TypeScript types).\n * - Future iter can remove the env var once port path is the\n * unconditional default — no deprecation cycle on the public API.\n *\n * @internal\n */\n\nimport type { CustomTool } from \"../../../types/agent.js\";\nimport type { MemoryToolSpec } from \"../../agent-loop/loop-types.js\";\nimport type { MemoryProvider } from \"./memory-provider.js\";\n\n/** Env var name — internal, not in public docs yet. */\nexport const PORT_MEMORY_PATH_ENV_VAR = \"THEOKIT_PORT_MEMORY_PATH\";\n\n/**\n * Returns true when the port-memory-path should be active for this send.\n *\n * Checks both `process.env` (Node) and `globalThis.process?.env`\n * (defensive — some test environments stub process differently).\n */\nexport function shouldUsePortMemoryPath(): boolean {\n const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process\n ?.env;\n if (env === undefined) return false;\n const val = env[PORT_MEMORY_PATH_ENV_VAR];\n return val === \"1\" || val === \"true\";\n}\n\n/**\n * Pick which `MemoryProvider` (if any) gets passed to the agent loop.\n *\n * Semantics:\n * - When consumer-supplied `options.memoryProvider` is set: ALWAYS\n * honor it (regardless of env flag). The flag only affects the\n * fall-back default.\n * - When consumer didn't supply AND port path enabled: return the\n * auto-installed `defaultMemoryProviderForLoop` (the adapter).\n * - When consumer didn't supply AND port path disabled: return\n * `undefined` (legacy path; agent-loop sees no provider).\n */\nexport function resolveMemoryProviderForLoop(\n consumerSupplied: MemoryProvider | undefined,\n defaultAdapter: MemoryProvider,\n portPathEnabled: boolean,\n): MemoryProvider | undefined {\n if (consumerSupplied !== undefined) return consumerSupplied;\n if (portPathEnabled) return defaultAdapter;\n return undefined;\n}\n\n/**\n * Pick which `memoryTools` (if any) get passed to the agent loop's\n * `inputs.memoryTools` field.\n *\n * Semantics:\n * - When port path active: return `undefined` (tools surface via\n * `provider.buildTools()` inside agent-loop instead — iter 18 T1.5.2).\n * - When port path inactive: return the legacy tools (from\n * `memoryGlue.ensureTools()`).\n */\nexport function resolveMemoryToolsForLoop(\n legacyTools: ReadonlyArray<MemoryToolSpec> | undefined,\n portPathEnabled: boolean,\n): ReadonlyArray<MemoryToolSpec> | undefined {\n if (portPathEnabled) return undefined;\n return legacyTools;\n}\n\n/**\n * Pick the `activeMemorySummary` value to fold into the system-prompt\n * assembly.\n *\n * Semantics:\n * - When port path active: return `undefined` (additions surface via\n * `provider.runActivePass()` inside agent-loop instead — iter 18 T1.5.3).\n * - When port path inactive: return the legacy summary (from\n * `memoryGlue.runActiveMemoryIfEnabled(...)`).\n */\nexport function resolveActiveMemorySummaryForSend(\n legacySummary: string | undefined,\n portPathEnabled: boolean,\n): string | undefined {\n if (portPathEnabled) return undefined;\n return legacySummary;\n}\n\n/**\n * Type-only re-export for downstream consumers of the helpers.\n * `CustomTool` is the port's tool shape; future iter may need it\n * when assembling memoryTools via the port path.\n */\nexport type { CustomTool };\n","/**\n * M77 — turn the context-budget decision into a structured event.\n *\n * Before this, the only signal that auto-compaction had no window to budget against was a\n * `process.stderr.write` guarded by a once-per-process `Set` on a global symbol. No surface can react\n * to that: the TUI does not read its own stderr, headless exec cannot correlate it with a turn, and a\n * SECOND unknown model in the same session says nothing at all because the `Set` already has a key.\n *\n * The event rides the channel that already exists — `RunEvent` / `emitRunEvent` — mirroring the shape\n * of `compact_boundary` (`types/run-events.ts:107`), which is emitted from the same file that makes\n * this decision.\n *\n * Deliberately silent on the happy path. An event that fires on every turn is an event surfaces learn\n * to ignore, and then it stops being a signal.\n */\nimport type { EffectiveContextWindow } from \"../../../compaction.js\";\nimport type { RunCompactionFallbackEvent } from \"../../../types/run-events.js\";\n\n/**\n * Build the fallback event, or `undefined` when no warning is warranted.\n *\n * Warranted only for `source === \"fallback\"` — neither the catalog nor the caller knew the window, so\n * the budget is running on a floor. `\"catalog\"` needs no event (it is the normal path) and\n * `\"override\"` needs none either: the caller who supplied the number already knows it is in use.\n */\nexport function buildContextBudgetEvent(\n model: string,\n resolved: EffectiveContextWindow,\n): RunCompactionFallbackEvent | undefined {\n if (resolved.source !== \"fallback\") return undefined;\n return { type: \"compaction_fallback\", model, window: resolved.window };\n}\n","import {\n CONTEXT_WINDOW_FLOOR,\n CONTEXT_WINDOW_MARGIN,\n type EffectiveContextWindow,\n resolveEffectiveContextWindow,\n} from \"../../../compaction.js\";\nimport type { Run } from \"../../../types/run.js\";\nimport type { RunEventSink } from \"../../../types/run-events.js\";\nimport { emitRunEvent } from \"../../../types/run-events.js\";\nimport type { SessionStore } from \"../../../types/session-store.js\";\nimport { diag } from \"../../diagnostics.js\";\nimport type { LocalAgentMemory } from \"../../local-agent/local-agent-memory.js\";\nimport { writeSessionSummary } from \"../../memory/storage/session-summary-writer.js\";\nimport { getCatalogModelInfo } from \"../../providers/catalog-loader.js\";\nimport { buildDefaultSummarizer } from \"../../session/compact-session.js\";\nimport {\n appendSessionMessage,\n flushSessionWrites,\n persistTurnToTranscript,\n} from \"../../session/index.js\";\nimport type { HooksExecutor } from \"../hooks/hooks-executor.js\";\nimport { shouldUsePortMemoryPath } from \"../memory/memory-path-selector.js\";\nimport type { MemoryProvider } from \"../memory/memory-provider.js\";\nimport { buildContextBudgetEvent } from \"./context-budget-event.js\";\n\n/**\n * Inputs for {@link runPostRunLifecycle}. Bundled into a single record so the\n * caller (LocalAgent.send) doesn't carry a long positional argument list.\n *\n * SE41 — the `sessionStore` persists the native records (FS default or an injected\n * external store); `model` is stamped into the assistant records.\n *\n * @internal\n */\nexport interface PostRunLifecycleInputs {\n run: Run;\n userText: string;\n agentId: string;\n workspaceCwd: string;\n /** SE41 — the session record store (FS default, or an injected external store). */\n sessionStore: SessionStore;\n /** SE40 — model id stamped into the assistant records. */\n model: string;\n /**\n * M94 — window declared on the agent definition, in tokens.\n *\n * Forwarded as `override` to the resolver. It exists because a model with no catalog entry\n * (OpenRouter) stayed pinned to the 128k floor despite having 400k — compacting ~3x more than\n * needs it. The catalog clamp still protects against an inflated value.\n */\n contextWindow?: number | undefined;\n /** M50 — provider key for the auto-compaction summarizer (absent ⇒ env-resolved by the router). */\n apiKey?: string;\n /** SE2 — surface a `compact_boundary` RunEvent when a persistence-side compaction fires. */\n onRunEvent?: RunEventSink;\n hooksExecutor: HooksExecutor;\n memoryGlue: LocalAgentMemory;\n /**\n * SDK 2.0 Phase 1 physical Stage 3 prep — iter 27 (refined iter 28):\n * optional port-based session-summary recorder. When supplied AND the\n * provider implements `recordSessionSummary`, the kernel delegates\n * the write through the port. When absent, falls back to the\n * legacy direct `writeSessionSummary` import (current behavior).\n *\n * STATELESS — no handle param needed (post-run-lifecycle runs AFTER\n * runAgentLoop disposes the per-run handle). `cwd` lives on the\n * args passed to the impl.\n */\n memoryProvider?: MemoryProvider;\n}\n\n/**\n * Post-run side effects executed inside the per-agent send mutex (ADR D19):\n *\n * 1. Persist the assistant turn to the per-agent JSONL (ADR D18).\n * 2. On status=finished, write a session-summary markdown for the\n * `corpus=\"sessions\"` memory_search index (ADR D20).\n * 3. Fire the `postRun` hook with the resolved status.\n * 4. Flush pending session writes so dispose() never races the writer.\n *\n * Errors are swallowed at the call site so `agent.send()` callers observe\n * failures through their own `run.wait()` / `stream()` surfaces. Mutex release\n * is guaranteed via the final `flushSessionWrites` even on the cancelled path.\n *\n * Extracted from LocalAgent to keep that class under the G8 LoC budget.\n *\n * @internal\n */\n/**\n * Resolves the window to budget for a run — the point where the declared window meets the catalog.\n *\n * It exists as its own function because the WIRING is what was broken: `resolveEffectiveContextWindow`\n * has accepted `override` since M77 and the only call site never passed it. A pure function makes that\n * forwarding testable without rebuilding half the runtime — a mutant that stops forwarding fails.\n *\n * A non-positive `contextWindow` is ignored: as an override it would produce a budget that triggers\n * compaction every turn, which is worse than the conservative floor.\n *\n * @internal\n */\nexport function resolveWindowForRun(\n model: string,\n contextWindow: number | undefined,\n): EffectiveContextWindow {\n const override = contextWindow !== undefined && contextWindow > 0 ? contextWindow : undefined;\n return resolveEffectiveContextWindow({\n ...(override !== undefined ? { override } : {}),\n catalog: getCatalogModelInfo(model)?.limit?.context,\n margin: CONTEXT_WINDOW_MARGIN,\n floor: CONTEXT_WINDOW_FLOOR,\n });\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: lifecycle orchestrator dispatches across multiple subsystems\nexport async function runPostRunLifecycle(inputs: PostRunLifecycleInputs): Promise<void> {\n const {\n run,\n userText,\n agentId,\n workspaceCwd,\n sessionStore,\n model,\n contextWindow,\n onRunEvent,\n hooksExecutor,\n memoryGlue,\n memoryProvider,\n } = inputs;\n let result: Awaited<ReturnType<Run[\"wait\"]>>;\n try {\n result = await run.wait();\n } catch {\n // M93 — persists what the turn HAS ALREADY PRODUCED before leaving.\n //\n // The `flushSessionWrites` below has always been here, and always drained an **empty** set:\n // `persistTurnToTranscript` is only called later in this function — the **only** caller in the\n // repository — after this `return`. A 429 after eight tool calls destroyed the whole turn\n // leaving nothing on disk, and combined with the absent retry on the single-key path (also\n // closed in M93) the loss was total.\n //\n // Persists the **partial**, without reconstructing: a turn that failed in `run.wait()` has real history\n // — user + completed tool calls. Discarding it is the loss; inventing the rest would be worse than the loss.\n // The inner `catch` exists because a write failure must not mask the turn's error, which is what\n // the caller is waiting on (`error-handling.md`: cleanup does not propagate over the original error).\n try {\n const partial = await safeConversation(run);\n if (partial !== undefined) {\n persistTurnToTranscript(sessionStore, { cwd: workspaceCwd, agentId, model }, agentId, {\n userText,\n conversation: partial,\n });\n }\n } catch (cause) {\n const msg = cause instanceof Error ? cause.message : String(cause);\n diag(`[theokit-sdk] partial transcript write failed (${agentId}): ${msg}\\n`);\n }\n // Caller observes failures via their own run.wait()/stream(); the\n // mutex still releases via the flushes below.\n await flushSessionWrites();\n return;\n }\n\n if (result.result !== undefined) {\n // In-memory cache: seed `priorMessages` for the NEXT send.\n appendSessionMessage(agentId, { role: \"assistant\", text: result.result });\n }\n\n // SE40 — persist the WHOLE turn (user + assistant + tool blocks) to the native\n // Claude-shaped transcript, once per send, from the rich `run.conversation()` view.\n // SE41 — through the session store (FS default or injected external store).\n const conversation = await safeConversation(run);\n // M50 — size-driven auto-compaction rides the SAME persistence chain: real usage from the run's\n // Completed (Codex `last_token_usage.total_tokens` analog) vs the model's context window. The\n // summarizer is the compression subsystem's aux-LLM via `buildDefaultSummarizer`.\n //\n // M77 — this used to read the catalog directly and, when the model was absent, leave the window\n // `undefined` so the trigger never fired. The comment here called that \"fail-safe\"; it was the\n // opposite. Not compacting when the window is unknown lets the conversation grow until the\n // PROVIDER rejects it — fail-OPEN, and silent. It now resolves to a floor and says so, so the\n // budget degrades instead of disappearing.\n const resolvedWindow = resolveWindowForRun(model, contextWindow);\n const effectiveWindow = resolvedWindow.window;\n const budgetEvent = buildContextBudgetEvent(model, resolvedWindow);\n if (budgetEvent !== undefined && onRunEvent !== undefined) {\n emitRunEvent(onRunEvent, budgetEvent);\n }\n // M50 review F3 — Codex uses the LAST response's usage as the active-context proxy; the aggregate\n // sums every round (each re-sends the whole context) and fires the trigger prematurely on\n // multi-round agentic turns. Prefer the last request's breakdown when available.\n const lastRequestUsage = result.usage?.requests?.at(-1)?.totalTokens;\n const usageForTrigger = lastRequestUsage ?? result.usage?.totalTokens;\n persistTurnToTranscript(\n sessionStore,\n { cwd: workspaceCwd, agentId, model },\n agentId,\n {\n userText,\n conversation,\n autoCompact: {\n usageTotal: usageForTrigger,\n // The EFFECTIVE window (after override, clamp and margin) — not the declared one. Swapping for\n // `contextWindow` here would budget against a number the clamp already rejected.\n contextWindow: effectiveWindow,\n summarize: buildDefaultSummarizer({\n agentModel: model,\n ...(inputs.apiKey !== undefined ? { apiKey: inputs.apiKey } : {}),\n }),\n },\n },\n onRunEvent !== undefined\n ? () => emitRunEvent(onRunEvent, { type: \"compact_boundary\", trigger: \"auto\" })\n : undefined,\n );\n\n // ADR D20 + EC-9: only finished runs feed the corpus=\"sessions\" index.\n if (result.status === \"finished\" && result.result !== undefined) {\n const summaryArgs = {\n cwd: workspaceCwd,\n runId: result.id,\n agentId,\n userText,\n assistantText: result.result,\n status: \"finished\" as const,\n at: Date.now(),\n };\n try {\n // SDK 2.0 Phase 1 physical Stage 3 prep — iter 27 (refined iter 28):\n // prefer the STATELESS port-based `provider.recordSessionSummary`\n // when defined. Falls back to the direct `writeSessionSummary`\n // import otherwise (legacy behavior). Both paths handle the\n // markdown write + disk persistence; the difference is WHERE the\n // impl lives. Stateless = no handle needed (post-run-lifecycle\n // runs AFTER runAgentLoop disposed the per-run handle).\n if (memoryProvider?.recordSessionSummary !== undefined) {\n await memoryProvider.recordSessionSummary(summaryArgs);\n } else {\n await writeSessionSummary(summaryArgs);\n }\n // EC-3: trigger sync so the next memory_search({corpus:\"sessions\"})\n // sees the just-written summary. Fire-and-forget; the read path\n // tolerates a missed sync because IndexManager re-scans on each call.\n //\n // SDK 2.0 Phase 1 physical Stage 2b — iter 26: under\n // `THEOKIT_PORT_MEMORY_PATH=1` the agent-loop already fired\n // `provider.sync()` post-finished-run. Calling syncIfReady() here\n // would be redundant (double sync). Skip when flag is on.\n if (!shouldUsePortMemoryPath()) {\n void memoryGlue.syncIfReady();\n }\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : String(cause);\n diag(`[theokit-sdk] session summary write failed (${result.id}): ${message}\\n`);\n }\n }\n\n await hooksExecutor.run({\n event: \"postRun\",\n output: {\n status: result.status,\n ...(result.result !== undefined ? { result: result.result } : {}),\n },\n agentId,\n runId: result.id,\n });\n await flushSessionWrites();\n}\n\n/**\n * Read the rich per-turn conversation view for transcript persistence. Best-effort:\n * a run without `conversation()` (or one that throws) yields `[]` so persistence\n * degrades to the user turn only rather than crashing the post-run lifecycle.\n */\nasync function safeConversation(run: Run): Promise<Awaited<ReturnType<Run[\"conversation\"]>>> {\n try {\n return await run.conversation();\n } catch {\n return [];\n }\n}\n","// `zod` referenced only as a TYPE — `import type` is erased by tsc/tsup, so\n// the compiled `dist/index.js` does NOT have a top-level `import \"zod\"`.\n// Consumers who don't call `defineTool` don't need `zod` installed (the peer\n// dependency stays truly optional per ADR D24). The runtime JSON-Schema\n// conversion uses Zod v4's native `z.toJSONSchema()` via the internal shim.\nimport type { z as ZodNamespace, ZodType } from \"zod\";\n\nimport { toJsonSchema } from \"./internal/zod/to-json-schema.js\";\nimport { sanitizeToolInput } from \"./sanitize/sanitize-tool-input.js\";\nimport type { SanitizeOptions } from \"./sanitize/types.js\";\nimport type { CustomTool } from \"./types/agent.js\";\nimport type { ToolResultContentBlock } from \"./types/content-blocks.js\";\n\n/**\n * Spec accepted by {@link defineTool}. `inputSchema` is a Zod schema; the\n * `handler` argument type is inferred via `z.infer<T>` — no `as` casts.\n *\n * @public\n */\n/**\n * SE16 — the handler's return type. With no `outputSchema` the tool returns a\n * plain `string` (pre-SE16 shape). With an `outputSchema` the handler returns the\n * STRUCTURED output inferred from it (validated + serialized to the tool result).\n * The `[O]` tuple wrap prevents distribution so `never` maps cleanly to `string`.\n */\ntype ToolHandlerReturn<O extends ZodType> = [O] extends [never] ? string : ZodNamespace.infer<O>;\n\nexport interface DefineToolSpec<T extends ZodType, O extends ZodType = never> {\n /** Tool name surfaced to the LLM. Same constraints as {@link CustomTool.name}. */\n name: string;\n /** Description surfaced to the LLM. */\n description: string;\n /** Zod schema describing the input. Must be `z.object(...)` at the root for the LLM tool contract. */\n inputSchema: T;\n /**\n * SE16 — optional Zod schema describing the OUTPUT. When set, the handler\n * returns the structured value inferred from it; the value is validated against\n * this schema and serialized to the tool result (a string stays as-is, an object\n * is JSON-stringified). A validation failure raises `ZodError`, converted to a\n * `tool_result(isError)`. Absent ⇒ the handler returns a plain string (unchanged).\n */\n outputSchema?: O;\n /**\n * Handler invoked with the parsed input. Type is inferred via `z.infer<T>`; the\n * return type is `z.infer<O>` when `outputSchema` is set, else `string`.\n * #65 — an optional 2nd `ToolContext` argument carries the run's `AbortSignal`,\n * so a cooperative handler can stop early when the run is cancelled. Existing\n * single-argument handlers are unaffected.\n */\n handler: (\n input: ZodNamespace.infer<T>,\n ctx?: { signal?: AbortSignal; context?: unknown; threadId?: string },\n ) => ToolHandlerReturn<O> | Promise<ToolHandlerReturn<O>>;\n /**\n * SE17 — map the handler's (validated) output to the compact / multimodal\n * representation the MODEL sees in the tool_result. The handler keeps returning\n * the FULL result (validated by `outputSchema`); `toModelOutput` shapes only what\n * reaches the model, so app-facing detail is not forced into model context.\n * Returns a string OR SE7 `ToolResultContentBlock[]` (text + image). Absent ⇒\n * the tool_result is the serialized handler output (SE16 / pre-SE17 behavior).\n * The split is REAL: the model's `tool_result` carries this compact value, while\n * observability (`onToolEnd.result`) receives the FULL raw handler output\n * (serialized) — so the app keeps the complete result. ONE handler execution\n * feeds both channels.\n */\n toModelOutput?: (output: ToolHandlerReturn<O>) => string | ToolResultContentBlock[];\n /**\n * Sanitize the raw model-emitted args BEFORE schema validation (`@theokit/sdk/sanitize`).\n * `true` trims whitespace; an object opts into coercion / JSON-repair. Coercion is schema-aware\n * against this tool's `inputSchema`. Absent ⇒ args reach validation untouched. Sanitize is\n * hygiene, not a validity bypass — a genuinely invalid arg still raises `ZodError`.\n */\n sanitize?: boolean | SanitizeOptions;\n}\n\n/**\n * Type-safe builder for {@link CustomTool}. Converts a Zod schema to JSON\n * Schema (for the LLM-facing `inputSchema` field), wraps the handler with a\n * runtime `schema.parse` step, and preserves type inference.\n *\n * Behaviour (ADR D24):\n * - JSON Schema conversion uses Zod 4's native `z.toJSONSchema` with\n * `unrepresentable: \"any\"` so transforms/refinements round-trip.\n * - Runtime parse failures throw `ZodError`; the SDK's tool-dispatch converts\n * them to `tool_result(isError)` with the Zod message.\n * - Handler signature is `(input: z.infer<T>)`, not `Record<string, unknown>`.\n * - `zod` loads lazily via `createRequire` — consumers who don't call\n * `defineTool` don't need `zod` installed.\n *\n * @public\n */\n/**\n * SE17 — symbol under which a `toModelOutput` tool carries its model/app SPLIT\n * resolver on the built `CustomTool.handler` function. The runtime tool dispatch\n * (`tool-executors.ts`) prefers this resolver so it can route the FULL raw output\n * to observability (`onToolEnd`) while the compact `toModelOutput` result goes to\n * the model's `tool_result`. Absent ⇒ the plain handler return is used for both\n * (pre-SE17 behavior). A hidden symbol (not a public `CustomTool` field) mirrors\n * the `INHERIT_CREDENTIALS` pattern — the split is an internal wire concern.\n * @internal\n */\nexport const TOOL_SPLIT_RESOLVER: unique symbol = Symbol(\"theokit.toolSplitResolver\");\n\n/** @internal — the two channels a `toModelOutput` tool produces from ONE handler run. */\nexport interface ToolOutputSplit {\n /** What the MODEL sees in the `tool_result` (compact / multimodal). */\n model: string | ToolResultContentBlock[];\n /** What the APP / observability keeps (the full raw handler output, serialized). */\n app: string | ToolResultContentBlock[];\n}\n\n/** @internal — a handler carrying an SE17 split resolver. */\nexport type SplitResolver = (\n input: Record<string, unknown>,\n ctx?: { signal?: AbortSignal; context?: unknown; threadId?: string },\n) => Promise<ToolOutputSplit>;\n\n/**\n * Run the input pipeline (sanitize → parse → handler → `outputSchema` validate)\n * and return the FULL VALIDATED structured output — the single source both output\n * channels derive from. Kept separate so the public handler and the SE17 split\n * resolver share ONE handler execution.\n */\nasync function runValidated<T extends ZodType, O extends ZodType>(\n spec: DefineToolSpec<T, O>,\n input: Record<string, unknown>,\n ctx?: { signal?: AbortSignal; context?: unknown; threadId?: string },\n): Promise<ToolHandlerReturn<O>> {\n const raw = spec.sanitize\n ? sanitizeToolInput(input, {\n ...(spec.sanitize === true ? {} : spec.sanitize),\n schema: spec.inputSchema,\n }).value\n : input;\n const parsed = spec.inputSchema.parse(raw) as ZodNamespace.infer<T>;\n // #65 — forward the ToolContext (run signal / user context) to the user's handler.\n const out = await spec.handler(parsed, ctx);\n // `parse(out)` returns `z.infer<O>` ≡ `ToolHandlerReturn<O>` when `O ≠ never`; the\n // cast closes the conditional-type gap the compiler can't narrow through here.\n return (\n spec.outputSchema === undefined ? out : spec.outputSchema.parse(out)\n ) as ToolHandlerReturn<O>;\n}\n\n/** Serialize a validated output to a tool_result string (string as-is, else JSON). */\nfunction serializeOutput(validated: unknown): string {\n return typeof validated === \"string\" ? validated : JSON.stringify(validated);\n}\n\n/**\n * SE16 + SE17 — from the validated output, produce the MODEL-facing tool_result:\n * `toModelOutput` maps it to the compact string/blocks, else it is serialized.\n */\nfunction shapeModelOutput<T extends ZodType, O extends ZodType>(\n spec: DefineToolSpec<T, O>,\n validated: ToolHandlerReturn<O>,\n): string | ToolResultContentBlock[] {\n if (spec.toModelOutput !== undefined) return spec.toModelOutput(validated);\n return serializeOutput(validated);\n}\n\n/**\n * SE36 — the uniform `X.create()` namespace API. `Tool.create(spec)` is the sole public\n * constructor for a {@link CustomTool}; it wraps the internal builder so behavior is identical\n * (ADR 0015). A `private constructor` makes `Tool` a namespace, not an instantiable value —\n * `new Tool()` is a compile error. Mirrors `Agent.create` / `Cron.create`.\n *\n * @public\n */\nexport class Tool {\n private constructor() {}\n static create<T extends ZodType, O extends ZodType = never>(\n spec: DefineToolSpec<T, O>,\n ): CustomTool {\n return defineTool(spec);\n }\n}\n\nfunction defineTool<T extends ZodType, O extends ZodType = never>(\n spec: DefineToolSpec<T, O>,\n): CustomTool {\n // Zod v4 native JSON Schema converter via internal shim.\n // `unrepresentable: \"any\"` lets transforms / refinements / branded types\n // round-trip to JSON Schema as `{}` (effectively `any`). The runtime parse\n // still enforces the full Zod contract; the LLM just sees a looser hint.\n const inputSchema = toJsonSchema(spec.inputSchema, {\n unrepresentable: \"any\",\n });\n const handler = async (\n input: Record<string, unknown>,\n ctx?: { signal?: AbortSignal; context?: unknown; threadId?: string },\n ): Promise<string | ToolResultContentBlock[]> => {\n // SE16 (validate) + SE17 (model-facing shaping). A direct caller gets the\n // MODEL-facing value — unchanged pre/post SE17-split.\n const validated = await runValidated(spec, input, ctx);\n return shapeModelOutput(spec, validated);\n };\n const tool: CustomTool = { name: spec.name, description: spec.description, inputSchema, handler };\n // SE17 gap closure — when `toModelOutput` is set, attach the split resolver so\n // the runtime routes the FULL raw output to `onToolEnd` while the model sees the\n // compact value. ONE handler execution feeds both channels (`runValidated`).\n if (spec.toModelOutput !== undefined) {\n const resolver: SplitResolver = async (input, ctx) => {\n const validated = await runValidated(spec, input, ctx);\n return { model: shapeModelOutput(spec, validated), app: serializeOutput(validated) };\n };\n (handler as unknown as Record<symbol, SplitResolver>)[TOOL_SPLIT_RESOLVER] = resolver;\n }\n return tool;\n}\n","/**\n * SE37 — `reasoning: true` support internals: the CoT preamble + the\n * double-reasoning guard.\n *\n * A native reasoning model (configured with `model.params: [{ id: \"thinking\" }]`)\n * already reasons internally, so layering the prompt-based `reasoning: true`\n * preamble + think tool on top wastes tokens and can degrade output. When a\n * native reasoning param is detected, `reasoning: true` is INERT (with a\n * one-time warn) — native reasoning wins.\n *\n * @internal\n */\n\nimport { z } from \"zod\";\n\nimport { Tool } from \"../../../define-tool.js\";\nimport type { CustomTool } from \"../../../types/agent.js\";\nimport type { ModelSelection } from \"../../../types/agent-prims.js\";\nimport { diag } from \"../../diagnostics.js\";\n\n/** Param ids that mean the model is doing its own (native) reasoning. */\nconst NATIVE_REASONING_PARAM_IDS = new Set([\"thinking\", \"reasoning\", \"reasoning_effort\"]);\n\n/**\n * The CoT preamble prepended to the system prompt when `reasoning: true` is\n * active. Steers a non-reasoning model into a reason -> act -> observe loop and\n * self-validation via the `think` tool. Kept terse (bundle budget).\n */\nexport const REASONING_PREAMBLE =\n \"Think step by step before answering: use the `think` tool to reason through each step, \" +\n \"validate your work, then answer. Reason about magnitude before comparing numbers.\";\n\n/**\n * The lean internal `think` scratchpad tool auto-attached by `reasoning: true`.\n * The richer public toolkit (`think` + `analyze`) ships from `@theokit/sdk-tools`\n * as `ReasoningTools.create()` — kept out of the core bundle. @internal\n */\nexport function createThinkTool(): CustomTool {\n return Tool.create({\n name: \"think\",\n description:\n \"Scratchpad: reason through ONE step before answering. No side effects — your private \" +\n \"reasoning space. Call it repeatedly before the final answer.\",\n inputSchema: z.object({ thought: z.string().min(1, \"think: `thought` must be non-empty.\") }),\n handler: ({ thought }) => thought,\n });\n}\n\n/**\n * True when the selected model is a native reasoning model — i.e. its `params`\n * carry a thinking/reasoning id. A bare-string model or one without such a param\n * is NOT native (returns false), so `reasoning: true` applies to it.\n */\nexport function isNativeReasoning(model: ModelSelection | string | undefined): boolean {\n if (model === undefined || typeof model === \"string\") return false;\n const params = model.params;\n if (params === undefined) return false;\n return params.some((p) => NATIVE_REASONING_PARAM_IDS.has(p.id));\n}\n\nconst warned = new Set<string>();\n\n/**\n * Emit the \"native reasoning detected, `reasoning: true` skipped\" warning once\n * per process. Idempotent; safe to call from both the prompt-assembly and the\n * tool-attach paths without double-logging.\n *\n * @internal\n */\nexport function warnDoubleReasoningOnce(): void {\n if (warned.has(\"double-reasoning\")) return;\n warned.add(\"double-reasoning\");\n diag(\n \"[theokit-sdk] `reasoning: true` skipped — a native reasoning model is configured \" +\n \"(model.params thinking/reasoning); native reasoning wins. Remove one to silence.\\n\",\n );\n}\n\n/** Reset for tests; not exported via barrel. @internal */\nexport function _resetReasoningWarnForTests(): void {\n warned.clear();\n}\n\n/**\n * The effective decision: should `reasoning: true` inject the preamble + tool?\n * True only when the flag is on AND the model is not already reasoning natively.\n * Emits the one-time warn when suppressed by a native model.\n *\n * @internal\n */\nexport function reasoningActive(\n reasoning: boolean | undefined,\n model: ModelSelection | string | undefined,\n): boolean {\n if (reasoning !== true) return false;\n if (isNativeReasoning(model)) {\n warnDoubleReasoningOnce();\n return false;\n }\n return true;\n}\n","import { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { diag } from \"../../diagnostics.js\";\nimport { discoverSkills, type Skill } from \"./discover-skills.js\";\nimport { stripSkillFrontmatter } from \"./skill-frontmatter.js\";\n\n/**\n * Skill metadata exposed via `agent.skills.list()`. Full skill prompt bodies\n * are NEVER returned — only frontmatter fields.\n *\n * @internal\n */\nexport type SkillMetadata = Skill;\n\n/**\n * A stored skill row. Filesystem skills are a bare {@link Skill}; inline\n * (`createSkill`) skills additionally carry their `instructions` body + optional\n * `references` on the object. Typing the store this way lets `get()` read those\n * fields directly, without a cast. @internal\n */\ntype StoredSkill = Skill & { instructions?: string; references?: Record<string, string> };\n\n/** SE20 — a skill resolved with its body (+ SE21 references). @internal */\nexport interface SkillDetail {\n name: string;\n description: string;\n instructions: string;\n references?: Record<string, string>;\n}\n\n/** SE20 — the internal `agent.skills` handle shape (list + get), shared by the runtime wiring. @internal */\nexport interface SkillsHandle {\n /**\n * Lean listing — name + description ONLY. Inline skills carry their body +\n * references on the underlying object; the public handle projects them away so\n * `agent.skills.list()` never leaks a body. Full bodies come only via `get`.\n */\n list: () => Promise<Array<{ name: string; description: string }>>;\n get: (name: string) => Promise<SkillDetail | undefined>;\n}\n\n/**\n * File-based skills loader. Discovers `.theokit/skills/<name>/SKILL.md`\n * frontmatter when `local.settingSources` includes `\"project\"`.\n *\n * Delegates the discovery loop to the shared `discoverSkills` primitive (M4-1,\n * single source of truth, also public via `@theokit/sdk/skills`). Per the\n * strict-frontmatter ADR + EC-5, a malformed skill is excluded from `list()`\n * and emits a stderr warning; the agent run continues without it.\n *\n * @internal\n */\nexport class SkillsManager {\n private skills: StoredSkill[] = [];\n\n constructor(\n private readonly cwd: string,\n _enabled: string[] | undefined,\n private readonly settingSourcesIncludeProject: boolean,\n // M22 — optional custom skills directory + inline (code-defined) skills.\n private readonly skillsDir?: string,\n private readonly inline?: StoredSkill[],\n ) {\n void _enabled;\n }\n\n async initialize(): Promise<void> {\n // M22 — inline skills work even without project setting sources (they need no filesystem).\n if (!this.settingSourcesIncludeProject) {\n this.skills = this.mergeInline([]);\n return;\n }\n await this.refresh();\n }\n\n async refresh(): Promise<void> {\n // M22 — a custom skillsDir overrides the default `<cwd>/.theokit/skills` root.\n const skillsRoot = this.skillsDir ?? join(this.cwd, \".theokit\", \"skills\");\n const discovered = await discoverSkills(skillsRoot, {\n onInvalidSkill: (info) => {\n diag(`[theokit-sdk] skill ${info.name} skipped (${info.code}): ${info.message}\\n`);\n },\n });\n this.skills = this.mergeInline(discovered);\n }\n\n /** M22 — merge inline skills over discovered ones; inline wins on a name conflict. */\n private mergeInline(discovered: StoredSkill[]): StoredSkill[] {\n if (this.inline === undefined || this.inline.length === 0) return discovered;\n const inlineNames = new Set(this.inline.map((s) => s.name));\n return [...discovered.filter((s) => !inlineNames.has(s.name)), ...this.inline];\n }\n\n list(): Promise<SkillMetadata[]> {\n // Return every discovered skill — `enabled` is a runtime hint for which\n // skills the parent agent may invoke, not a visibility filter.\n return Promise.resolve(this.skills);\n }\n\n /**\n * SE20 — resolve a skill by name INCLUDING its body. Inline (`createSkill`)\n * skills carry `instructions` on the object; filesystem skills read the body\n * from their `source` SKILL.md (frontmatter stripped). `undefined` when no\n * enabled skill matches (malformed skills were already excluded at discovery).\n */\n async get(name: string): Promise<SkillDetail | undefined> {\n const skill = this.skills.find((s) => s.name === name);\n if (skill === undefined) return undefined;\n // Inline skills carry the body; filesystem skills re-read it from `source`.\n const instructions =\n typeof skill.instructions === \"string\"\n ? skill.instructions\n : stripSkillFrontmatter(await readFile(skill.source, \"utf8\"));\n // SE21 — inline skills may bundle `references`; filesystem skills carry none here.\n const references = skill.references;\n return {\n name: skill.name,\n description: skill.description,\n instructions,\n ...(references !== undefined ? { references } : {}),\n };\n }\n}\n","import type { AgentOptions, ModelSelection, SystemPromptContext } from \"../../../types/agent.js\";\nimport type { FileContextManager } from \"../context/context-manager.js\";\nimport type { MemoryFact } from \"../memory/memory-store.js\";\nimport { reasoningActive } from \"../reasoning/native-reasoning.js\";\nimport { SkillsManager } from \"../skills/skills-manager.js\";\nimport type { SystemPromptPipeline } from \"./pipeline.js\";\nimport type { SystemPromptAssemblyContext } from \"./types.js\";\n\n/**\n * Bundles the per-agent state that the assembly helpers need without forcing\n * LocalAgent to expose private fields. Extracted from LocalAgent so the parent\n * class stays under the G8 LoC budget.\n *\n * @internal\n */\nexport interface LocalAssemblyInputs {\n agentId: string;\n workspaceCwd: string;\n model: ModelSelection | undefined;\n options: AgentOptions;\n context: FileContextManager | undefined;\n skillsManager: SkillsManager | undefined;\n /** SE22 — needed to build the per-send transient manager when `options.skills` is a resolver. */\n settingSourcesIncludeProject: boolean;\n systemPromptPipeline: SystemPromptPipeline;\n}\n\n/**\n * SE22 — resolve the effective skills for THIS send. A static\n * `SkillsSettings` object uses the create-time (base) manager unchanged; a\n * {@link import(\"../../../types/agent.js\").SkillsResolver} function is evaluated\n * with the per-send context and drives a fresh transient manager. A throwing\n * resolver propagates (fail-fast, no silent fallback — Rule 8).\n *\n * @internal\n */\nexport async function resolveSendSkills(\n inputs: LocalAssemblyInputs,\n userText: string,\n memoryFacts: ReadonlyArray<MemoryFact>,\n): Promise<{ manager: SkillsManager | undefined; autoInject: boolean }> {\n const skills = inputs.options.skills;\n if (typeof skills !== \"function\") {\n return { manager: inputs.skillsManager, autoInject: skills?.autoInject ?? true };\n }\n const settings = await skills({\n agentId: inputs.agentId,\n cwd: inputs.workspaceCwd,\n model: inputs.model,\n userMessage: userText,\n memory: memoryFacts.map((fact) => ({ text: fact.text })),\n });\n const manager = new SkillsManager(\n inputs.workspaceCwd,\n settings.enabled,\n inputs.settingSourcesIncludeProject,\n settings.skillsDir,\n settings.inline,\n );\n // `initialize()` skips the filesystem scan when project sources are off (fast\n // path — inline-only), so a per-send resolver is cheap for inline skills.\n await manager.initialize();\n return { manager, autoInject: settings.autoInject ?? true };\n}\n\n/**\n * Build the base {@link SystemPromptContext} surfaced to a resolver function.\n * Resolves skills lazily — never throws when the manager is absent. The\n * effective manager defaults to the base one; the assembly path passes the\n * per-send resolved manager (SE22).\n *\n * @internal\n */\nexport async function buildSystemPromptContext(\n inputs: LocalAssemblyInputs,\n userText: string,\n memoryFacts: ReadonlyArray<MemoryFact>,\n manager: SkillsManager | undefined = inputs.skillsManager,\n): Promise<SystemPromptContext> {\n const skills = manager !== undefined ? await manager.list() : [];\n return {\n agentId: inputs.agentId,\n cwd: inputs.workspaceCwd,\n model: inputs.model,\n skills: skills.map((skill) => ({ name: skill.name, description: skill.description })),\n userMessage: userText,\n memory: memoryFacts.map((fact) => ({ text: fact.text })),\n };\n}\n\n/**\n * Build the full {@link SystemPromptAssemblyContext} that the pipeline\n * consumes, including the optional active-memory summary and context snapshot.\n *\n * @internal\n */\nexport async function buildAssemblyContext(\n inputs: LocalAssemblyInputs,\n userText: string,\n baseSystemPrompt: string | undefined,\n memoryFacts: ReadonlyArray<MemoryFact>,\n activeMemorySummary: string | undefined,\n contextPaths?: readonly string[],\n): Promise<SystemPromptAssemblyContext> {\n // SE22 — resolve skills ONCE per send; the resolver (if any) runs here, before\n // assembly. `buildSystemPromptContext` receives the resolved manager so the\n // <skills> block reflects the per-send resolution.\n const resolved = await resolveSendSkills(inputs, userText, memoryFacts);\n const baseCtx = await buildSystemPromptContext(inputs, userText, memoryFacts, resolved.manager);\n const assemblyCtx: SystemPromptAssemblyContext = {\n ...baseCtx,\n skillsAutoInject: resolved.autoInject,\n memoryAutoInject: inputs.options.memory?.autoInject ?? true,\n };\n if (baseSystemPrompt !== undefined) assemblyCtx.baseSystemPrompt = baseSystemPrompt;\n if (activeMemorySummary !== undefined && activeMemorySummary.length > 0) {\n assemblyCtx.activeMemorySummary = activeMemorySummary;\n }\n // SE37 — inject the reasoning preamble when `reasoning: true` and the model is\n // not already reasoning natively (guard + one-time warn inside reasoningActive).\n if (reasoningActive(inputs.options.reasoning, inputs.model)) {\n assemblyCtx.reasoning = true;\n }\n if (inputs.context !== undefined) {\n // T3 — apply the per-send in-scope file set so path-scoped rules\n // (`.theokit/rules/*.md`, `.cursor/rules/*.mdc` globs) activate for THIS\n // send. No-op when the scope is unchanged / never set (non-users pay nothing).\n await inputs.context.applyScope(contextPaths);\n const internal = inputs.context.internalAssemblySnapshot();\n assemblyCtx.contextSnapshot = { sources: internal.sources };\n if (internal.maxTokens !== undefined) assemblyCtx.contextMaxTokens = internal.maxTokens;\n }\n return assemblyCtx;\n}\n\n/**\n * Convenience wrapper: build the assembly context and run it through the\n * pipeline in one call. Returns the final system-prompt string (or undefined\n * if the pipeline produces no output).\n *\n * @internal\n */\nexport async function assembleSystemPromptForSend(\n inputs: LocalAssemblyInputs,\n userText: string,\n baseSystemPrompt: string | undefined,\n memoryFacts: ReadonlyArray<MemoryFact>,\n activeMemorySummary: string | undefined,\n contextPaths?: readonly string[],\n): Promise<string | undefined> {\n const ctx = await buildAssemblyContext(\n inputs,\n userText,\n baseSystemPrompt,\n memoryFacts,\n activeMemorySummary,\n contextPaths,\n );\n return inputs.systemPromptPipeline.assemble(ctx);\n}\n","import { diag } from \"../../diagnostics.js\";\n/**\n * Try/catch wrapper that catches BOTH synchronous throws AND async rejections.\n * On error, writes a one-line diagnostic to stderr and returns `fallback`.\n *\n * Used by:\n * - `SystemPromptPipeline` — each provider's `contribute` is wrapped so a\n * broken provider cannot crash the run (ADR D8).\n * - The real agent loop — `SendOptions.onStep` / `onDelta` callbacks are\n * wrapped so a user callback throwing cannot abort the LLM run (ADR D1).\n * - `LocalAgent.send` memory read — corrupt memory file degrades gracefully\n * (edge-case review EC-4).\n *\n * @internal\n */\nexport async function safeCall<T>(\n fn: () => T | Promise<T>,\n fallback: T,\n label = \"safeCall\",\n): Promise<T> {\n try {\n return await fn();\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : String(cause);\n diag(`[theokit-sdk] ${label} failed: ${message}\\n`);\n return fallback;\n }\n}\n","import { escapeBlockBody } from \"../escape.js\";\nimport type { SystemPromptAssemblyContext, SystemPromptProvider } from \"../types.js\";\n\n/**\n * Contributes the `<active-memory>` block (ADR D6 of memory-system-peer-project-parity).\n *\n * Priority 5 — fires BEFORE Context/Skills/Memory providers so the recall\n * summary sits at the top of the system prompt. The summary itself is\n * produced by `runActiveMemory` and threaded via\n * `SystemPromptAssemblyContext.activeMemorySummary`.\n *\n * @internal\n */\nexport class ActiveMemoryPromptProvider implements SystemPromptProvider {\n readonly id = \"active-memory\";\n readonly priority = 5;\n\n contribute(ctx: SystemPromptAssemblyContext): Promise<string | undefined> {\n if (ctx.activeMemorySummary === undefined || ctx.activeMemorySummary.length === 0) {\n return Promise.resolve(undefined);\n }\n const body = escapeBlockBody(ctx.activeMemorySummary);\n return Promise.resolve(`<active-memory>\\n${body}\\n</active-memory>`);\n }\n}\n","import type { SystemPromptAssemblyContext, SystemPromptProvider } from \"../types.js\";\n\n/**\n * Wraps the user-resolved base system prompt as the final contribution in\n * the pipeline. Priority 100 = last (after Context/Skills/Memory).\n *\n * The base prompt is the agent author's own intent — it is NOT passed through\n * `escapeBlockBody`. Auto-injected blocks (context/skills/memory) escape\n * dynamic content because they may carry user-controlled data.\n *\n * @internal\n */\nexport class BasePromptProvider implements SystemPromptProvider {\n readonly id = \"base\";\n readonly priority = 100;\n\n contribute(ctx: SystemPromptAssemblyContext): Promise<string | undefined> {\n return Promise.resolve(ctx.baseSystemPrompt);\n }\n}\n","import { escapeBlockBody } from \"../escape.js\";\nimport type {\n ContextSourceForAssembly,\n SystemPromptAssemblyContext,\n SystemPromptProvider,\n} from \"../types.js\";\n\n/**\n * Contributes the `<context>` block (ADR D3 / D9).\n *\n * - Drops `excluded` sources.\n * - Truncates per source proportionally when the total exceeds the budget.\n * - Enforces a per-source floor (`MIN_SOURCE_TOKENS`) so a tiny budget shared\n * across many sources still yields meaningful slices.\n * - Escapes every source body through `escapeBlockBody` before embedding.\n *\n * @internal\n */\nexport class ContextPromptProvider implements SystemPromptProvider {\n readonly id = \"context\";\n readonly priority = 10;\n\n contribute(ctx: SystemPromptAssemblyContext): Promise<string | undefined> {\n if (ctx.contextSnapshot === undefined) return Promise.resolve(undefined);\n const included = ctx.contextSnapshot.sources.filter((src) => src.status === \"included\");\n if (included.length === 0) return Promise.resolve(undefined);\n const truncated = truncateToBudget(included, ctx.contextMaxTokens);\n if (truncated.length === 0) return Promise.resolve(undefined);\n const body = truncated.map((src) => formatSource(src.name, src.tokens)).join(\"\\n\");\n return Promise.resolve(`<context>\\n${body}\\n</context>`);\n }\n}\n\nconst MIN_SOURCE_TOKENS = 50;\n\nfunction truncateToBudget(\n sources: ReadonlyArray<ContextSourceForAssembly>,\n maxTokens: number | undefined,\n): Array<{ name: string; tokens: ReadonlyArray<string> }> {\n if (maxTokens === undefined || maxTokens <= 0) {\n return sources.map((src) => ({ name: src.name, tokens: src.tokens }));\n }\n const total = sources.reduce((sum, src) => sum + src.tokens.length, 0);\n if (total <= maxTokens) {\n return sources.map((src) => ({ name: src.name, tokens: src.tokens }));\n }\n const floor = Math.min(MIN_SOURCE_TOKENS, Math.floor(maxTokens / sources.length));\n const remaining = Math.max(0, maxTokens - floor * sources.length);\n return sources.map((src) => {\n const proportional = total === 0 ? 0 : Math.floor((src.tokens.length / total) * remaining);\n const allotted = Math.min(src.tokens.length, floor + proportional);\n return { name: src.name, tokens: src.tokens.slice(0, allotted) };\n });\n}\n\nfunction formatSource(name: string, tokens: ReadonlyArray<string>): string {\n if (tokens.length === 0) {\n return ` <source name=\"${escapeAttribute(name)}\" />`;\n }\n const body = escapeBlockBody(tokens.join(\" \"));\n return ` <source name=\"${escapeAttribute(name)}\">\\n ${body}\\n </source>`;\n}\n\nfunction escapeAttribute(name: string): string {\n return name.replace(/&/g, \"&amp;\").replace(/\"/g, \"&quot;\").replace(/</g, \"&lt;\");\n}\n","import { escapeBlockBody } from \"../escape.js\";\nimport type { SystemPromptAssemblyContext, SystemPromptProvider } from \"../types.js\";\n\n/**\n * Contributes the `<memory>` block (ADR D5 / D9).\n *\n * Each fact's `text` is passed through `escapeBlockBody` before embedding so\n * a persisted fact containing literal `</memory>` cannot escape the block.\n *\n * @internal\n */\nexport class MemoryPromptProvider implements SystemPromptProvider {\n readonly id = \"memory\";\n readonly priority = 30;\n\n contribute(ctx: SystemPromptAssemblyContext): Promise<string | undefined> {\n if (ctx.memoryAutoInject === false) return Promise.resolve(undefined);\n if (ctx.memory.length === 0) return Promise.resolve(undefined);\n const lines = ctx.memory.map((fact) => ` - ${escapeBlockBody(fact.text)}`);\n return Promise.resolve(`<memory>\\n${lines.join(\"\\n\")}\\n</memory>`);\n }\n}\n","import { REASONING_PREAMBLE } from \"../../reasoning/native-reasoning.js\";\nimport type { SystemPromptAssemblyContext, SystemPromptProvider } from \"../types.js\";\n\n/**\n * SE37 — contributes the reasoning CoT preamble when `reasoning: true` is active\n * for the send. Priority 1 places it at the very top of the assembled prompt\n * (before context/skills/memory/base), so the model reads the \"think step by\n * step\" instruction first. Inert (`undefined`) when reasoning is off — so the\n * assembled prompt is byte-identical to baseline when the flag is unused.\n *\n * @internal\n */\nexport class ReasoningPromptProvider implements SystemPromptProvider {\n readonly id = \"reasoning\";\n readonly priority = 1;\n\n contribute(ctx: SystemPromptAssemblyContext): Promise<string | undefined> {\n return Promise.resolve(ctx.reasoning === true ? REASONING_PREAMBLE : undefined);\n }\n}\n","import { buildSkillsBlock } from \"../../skills/skills-block.js\";\nimport type { SystemPromptAssemblyContext, SystemPromptProvider } from \"../types.js\";\n\n/**\n * Contributes the `<skills>` block (ADR D4 / D9).\n *\n * Delegates rendering to the shared `buildSkillsBlock` primitive (M4-1, single\n * source of truth, also public via `@theokit/sdk/skills`). The block builder\n * escapes name + description to neutralise prompt-injection vectors; the skill\n * body is not in the input type, so it cannot leak into the system prompt.\n *\n * @internal\n */\nexport class SkillsPromptProvider implements SystemPromptProvider {\n readonly id = \"skills\";\n readonly priority = 20;\n\n contribute(ctx: SystemPromptAssemblyContext): Promise<string | undefined> {\n if (ctx.skillsAutoInject === false) return Promise.resolve(undefined);\n return Promise.resolve(buildSkillsBlock(ctx.skills));\n }\n}\n","import { ConfigurationError } from \"../../../errors.js\";\nimport { safeCall } from \"./safe-call.js\";\nimport { ActiveMemoryPromptProvider } from \"./sources/active-memory-provider.js\";\nimport { BasePromptProvider } from \"./sources/base-provider.js\";\nimport { ContextPromptProvider } from \"./sources/context-provider.js\";\nimport { MemoryPromptProvider } from \"./sources/memory-provider.js\";\nimport { ReasoningPromptProvider } from \"./sources/reasoning-provider.js\";\nimport { SkillsPromptProvider } from \"./sources/skills-provider.js\";\nimport type { SystemPromptAssemblyContext, SystemPromptProvider } from \"./types.js\";\n\n/**\n * System-prompt assembly pipeline (ADR D8 — Strategy + Chain of\n * Responsibility additive).\n *\n * Sorts providers by `priority` ascending (lexicographic `id` tiebreak),\n * invokes each `contribute` sequentially through `safeCall`, filters\n * `undefined` / empty contributions, and joins the rest with a double\n * newline.\n *\n * Constructor rejects duplicate `(priority, id)` provider keys with\n * `ConfigurationError` code `pipeline_duplicate_provider` (EC-2).\n *\n * @internal\n */\nexport class SystemPromptPipeline {\n readonly providers: ReadonlyArray<SystemPromptProvider>;\n\n constructor(providers: ReadonlyArray<SystemPromptProvider>) {\n const seen = new Set<string>();\n for (const p of providers) {\n const key = `${p.priority}:${p.id}`;\n if (seen.has(key)) {\n throw new ConfigurationError(`Duplicate system-prompt provider ${key}`, {\n code: \"pipeline_duplicate_provider\",\n });\n }\n seen.add(key);\n }\n this.providers = [...providers].sort((a, b) => {\n if (a.priority !== b.priority) return a.priority - b.priority;\n return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;\n });\n }\n\n async assemble(ctx: SystemPromptAssemblyContext): Promise<string | undefined> {\n const parts: string[] = [];\n for (const provider of this.providers) {\n const contribution = await safeCall(\n () => provider.contribute(ctx),\n undefined,\n `system-prompt provider \"${provider.id}\"`,\n );\n if (contribution === undefined || contribution.length === 0) continue;\n parts.push(contribution);\n }\n return parts.length === 0 ? undefined : parts.join(\"\\n\\n\");\n }\n\n /**\n * Default factory — wires the four built-in providers. Phase 3 ships\n * `BasePromptProvider`; Phases 3.2 / 4 / 5 register Context / Skills /\n * Memory by editing THIS factory and adding nothing else.\n */\n static default(): SystemPromptPipeline {\n return new SystemPromptPipeline([\n new ReasoningPromptProvider(),\n new ActiveMemoryPromptProvider(),\n new ContextPromptProvider(),\n new SkillsPromptProvider(),\n new MemoryPromptProvider(),\n new BasePromptProvider(),\n ]);\n }\n}\n","import { ConfigurationError } from \"../../../errors.js\";\nimport type {\n AgentDefinition,\n AgentOptions,\n CloudOptions,\n CustomTool,\n} from \"../../../types/agent.js\";\nimport type { McpServerConfig } from \"../../../types/mcp.js\";\n\n/**\n * Pre-flight validation for `Agent.create()` options. Throws\n * `ConfigurationError` on any rule violation; otherwise returns silently.\n *\n * Rules enforced:\n * - exactly one of local/cloud\n * - local requires `model`\n * - cloud `envVars` keys must not start with `THEOKIT_`\n * - cloud stdio MCP must not pass `cwd`\n * - subagent inline definitions require `description` and `prompt`\n * - programmatic `hooks` are rejected (hooks are file-based only)\n * - memory `storePath`, when relative, must stay inside the workspace\n * - custom `tools`: unique names, reserved-name collisions rejected,\n * schema shape valid, cloud agents reject any non-empty tools array\n *\n * @internal\n */\nexport function validateAgentOptions(options: AgentOptions): void {\n rejectProgrammaticHooks(options);\n ensureRuntimeShape(options);\n if (options.local !== undefined) {\n if (options.model === undefined) {\n throw new ConfigurationError(\"Local agents require a model selection\", {\n code: \"missing_model\",\n });\n }\n }\n if (options.cloud !== undefined) {\n validateCloud(options.cloud);\n }\n validateMcpServers(options);\n validateSubagents(options.agents);\n validateMemory(options);\n validatePlugins(options);\n validateCustomTools(options);\n validateCredentialPoolShape(options);\n}\n\n/**\n * EC-J: `apiKey: \"k\"` AND `apiKeys: { provider: [...] }` together is\n * ambiguous — caller must pick exactly one shape. Throws\n * `ConfigurationError(code: \"credential_pool_ambiguous\")` with an\n * educational message.\n *\n * @internal\n */\nfunction validateCredentialPoolShape(options: AgentOptions): void {\n const apiKey = (options as { apiKey?: string }).apiKey;\n const apiKeys = options.providers?.apiKeys;\n if (apiKey === undefined || apiKey.length === 0) return;\n if (apiKeys === undefined) return;\n const populated = Object.entries(apiKeys).filter(\n ([, arr]) => Array.isArray(arr) && arr.some((k) => typeof k === \"string\" && k.length > 0),\n );\n if (populated.length === 0) return;\n throw new ConfigurationError(\n \"Ambiguous credential configuration: use either `apiKey: '...'` (single-key, simplest) \" +\n \"OR `apiKeys: { provider: [...] }` (multi-key pool), not both.\",\n { code: \"credential_pool_ambiguous\" },\n );\n}\n\nfunction validatePlugins(options: AgentOptions): void {\n const plugins = (options as { plugins?: { paths?: string[] } }).plugins;\n if (plugins?.paths === undefined) return;\n if (options.cloud !== undefined && plugins.paths.length > 0) {\n throw new ConfigurationError(\n \"Cloud agents require committed plugin manifests; local plugin paths are not supported\",\n { code: \"cloud_plugin_path_rejected\" },\n );\n }\n}\n\nfunction ensureRuntimeShape(options: AgentOptions): void {\n if (options.local !== undefined && options.cloud !== undefined) {\n throw new ConfigurationError(\n \"Pass either local or cloud — they are mutually exclusive runtimes\",\n { code: \"runtime_exclusive\" },\n );\n }\n}\n\nfunction rejectProgrammaticHooks(options: AgentOptions): void {\n if ((options as { hooks?: unknown }).hooks !== undefined) {\n throw new ConfigurationError(\n \"Programmatic hooks are not supported — hooks are file-based only (.theokit/hooks.json)\",\n { code: \"programmatic_hooks_rejected\" },\n );\n }\n}\n\nfunction validateCloud(cloud: CloudOptions): void {\n if (cloud.envVars !== undefined) {\n for (const key of Object.keys(cloud.envVars)) {\n if (key.startsWith(\"THEOKIT_\")) {\n throw new ConfigurationError(\n `Cloud envVars cannot use the reserved THEOKIT_ prefix (got \"${key}\")`,\n { code: \"reserved_env_prefix\" },\n );\n }\n }\n }\n}\n\nfunction validateMcpServers(options: AgentOptions): void {\n if (options.mcpServers === undefined) return;\n for (const [name, config] of Object.entries(options.mcpServers)) {\n if (options.cloud !== undefined && isStdioWithCwd(config)) {\n throw new ConfigurationError(\n `MCP server \"${name}\" uses stdio with cwd, which is rejected for cloud agents`,\n { code: \"cloud_stdio_cwd_rejected\" },\n );\n }\n }\n}\n\nfunction isStdioWithCwd(config: McpServerConfig): boolean {\n const stdio = config as { type?: string; cwd?: string };\n if (stdio.type !== \"stdio\" && stdio.type !== undefined) return false;\n if (\"command\" in config && typeof stdio.cwd === \"string\" && stdio.cwd.length > 0) {\n return true;\n }\n return false;\n}\n\nfunction validateSubagents(agents: Record<string, AgentDefinition> | undefined): void {\n if (agents === undefined) return;\n for (const [name, definition] of Object.entries(agents)) {\n if (typeof definition.description !== \"string\" || definition.description.length === 0) {\n throw new ConfigurationError(`Subagent \"${name}\" requires a non-empty description`, {\n code: \"subagent_missing_description\",\n });\n }\n if (typeof definition.prompt !== \"string\" || definition.prompt.length === 0) {\n throw new ConfigurationError(`Subagent \"${name}\" requires a non-empty prompt`, {\n code: \"subagent_missing_prompt\",\n });\n }\n }\n}\n\nconst TOOL_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;\nconst RESERVED_TOOL_NAMES: ReadonlySet<string> = new Set([\"shell\", \"memory_search\", \"memory_get\"]);\n\n/**\n * Shared per-tool catalog validator used by both creation-time AgentOptions\n * and per-call SendOptions paths. Runs the same name/schema/dedupe rules\n * against any tools array. Does NOT enforce the cloud-runtime rejection —\n * that lives in {@link validateCustomTools} (creation) and the\n * per-runtime send paths (cloud agents reject at dispatch).\n *\n * @internal\n */\nexport function validateToolCatalog(tools: ReadonlyArray<CustomTool>): void {\n const seen = new Set<string>();\n for (const tool of tools) {\n validateSingleTool(tool);\n if (seen.has(tool.name)) {\n throw new ConfigurationError(`Duplicate custom tool name \"${tool.name}\"`, {\n code: \"duplicate_tool_name\",\n });\n }\n seen.add(tool.name);\n }\n}\n\nfunction validateCustomTools(options: AgentOptions): void {\n const tools = options.tools;\n if (tools === undefined || tools.length === 0) return;\n if (options.cloud !== undefined) {\n throw new ConfigurationError(\n \"Custom inline tools are local-only in SDK v1.0 — cloud agents cannot serialize handler functions\",\n { code: \"cloud_custom_tools_rejected\" },\n );\n }\n validateToolCatalog(tools);\n}\n\nfunction validateSingleTool(tool: CustomTool): void {\n validateToolName(tool);\n validateToolDescription(tool);\n validateToolSchema(tool);\n if (typeof tool.handler !== \"function\") {\n throw new ConfigurationError(`Custom tool \"${tool.name}\" requires a handler function`, {\n code: \"tool_missing_handler\",\n });\n }\n}\n\nfunction validateToolName(tool: CustomTool): void {\n if (typeof tool.name !== \"string\" || tool.name.length === 0) {\n throw new ConfigurationError(\"Custom tool requires a non-empty name\", {\n code: \"tool_missing_name\",\n });\n }\n if (!TOOL_NAME_PATTERN.test(tool.name)) {\n throw new ConfigurationError(\n `Custom tool name \"${tool.name}\" must match /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/`,\n { code: \"tool_invalid_name\" },\n );\n }\n if (RESERVED_TOOL_NAMES.has(tool.name) || tool.name.startsWith(\"mcp_\")) {\n throw new ConfigurationError(\n `Custom tool name \"${tool.name}\" collides with a reserved SDK tool name`,\n { code: \"tool_reserved_name\" },\n );\n }\n}\n\nfunction validateToolDescription(tool: CustomTool): void {\n if (typeof tool.description !== \"string\" || tool.description.length === 0) {\n throw new ConfigurationError(`Custom tool \"${tool.name}\" requires a non-empty description`, {\n code: \"tool_missing_description\",\n });\n }\n}\n\nfunction validateToolSchema(tool: CustomTool): void {\n const schema = tool.inputSchema as { type?: unknown } | null | undefined;\n if (schema === null || schema === undefined || typeof schema !== \"object\") {\n throw new ConfigurationError(`Custom tool \"${tool.name}\" requires an inputSchema object`, {\n code: \"tool_missing_schema\",\n });\n }\n if (schema.type !== \"object\") {\n throw new ConfigurationError(\n `Custom tool \"${tool.name}\" inputSchema must declare \\`type: \"object\"\\``,\n { code: \"tool_invalid_schema_type\" },\n );\n }\n}\n\nfunction validateMemory(options: AgentOptions): void {\n const memory = (options as { memory?: { storePath?: string } }).memory;\n if (memory?.storePath === undefined) return;\n const storePath = memory.storePath;\n if (storePath.includes(\"..\") || storePath.startsWith(\"/\") || /^[A-Z]:/i.test(storePath)) {\n throw new ConfigurationError(\n `Memory storePath must stay inside the workspace; got \"${storePath}\"`,\n { code: \"memory_path_traversal\" },\n );\n }\n}\n","/**\n * Closed-enum of all canonical span names emitted by the SDK telemetry layer.\n *\n * Wiring discipline (T0.1 + downstream tasks):\n * - `agent.create` — emitted in `Agent.create` static factory (T0.1).\n * - `agent.send` — parent span wrapping `LocalAgent.send` (T0.1).\n * - `agent.send.<step>` — 8 child spans inside `sendLocked` (T1.7).\n * - `memory.recall` — entry to `runActiveMemory` (T0.1).\n * - `tool.call` — per tool invocation in `tool-dispatch` (T2.4).\n * - `llm.call` — per provider HTTP turn (T3.*).\n *\n * Using a closed `as const` map (NOT `string`) means downstream span emitters\n * cannot drift names; the `SpanName` literal union is exhaustive and the\n * `(string & {})` discipline from T1.1 applies. ADR D438 anticipates the\n * \"no string-literal escape hatch in public unions\" rule for SDK internals.\n *\n * @internal\n */\nexport const SPAN_NAMES = {\n AGENT_CREATE: \"agent.create\",\n AGENT_SEND: \"agent.send\",\n AGENT_SEND_HYDRATE: \"agent.send.hydrate\",\n AGENT_SEND_MODEL_OVERRIDE: \"agent.send.model_override\",\n AGENT_SEND_PRE_HOOK: \"agent.send.pre_hook\",\n AGENT_SEND_PRE_USER_SEND: \"agent.send.pre_user_send\",\n AGENT_SEND_MEMORY_RECALL: \"agent.send.memory_recall\",\n AGENT_SEND_SYSTEM_PROMPT: \"agent.send.system_prompt\",\n AGENT_SEND_DISPATCH: \"agent.send.dispatch\",\n AGENT_SEND_POST_REPLY: \"agent.send.post_reply\",\n MEMORY_RECALL: \"memory.recall\",\n TOOL_CALL: \"tool.call\",\n LLM_CALL: \"llm.call\",\n} as const;\n\nexport type SpanName = (typeof SPAN_NAMES)[keyof typeof SPAN_NAMES];\n\n/** Histogram names emitted by the SDK. M3 #64 closes the wiring-triad pillar-c\n * gap: tool/LLM durations + LLM token throughput were measured but never emitted. */\nexport const HISTOGRAM_NAMES = {\n MEMORY_RECALL_DURATION_MS: \"theokit_memory_recall_duration_ms\",\n TOOL_CALL_DURATION_MS: \"theokit_tool_call_duration_ms\",\n LLM_CALL_DURATION_MS: \"theokit_llm_call_duration_ms\",\n LLM_TOKENS: \"theokit_llm_tokens\",\n /** M3 #66 — count of finishes where the provider omitted usage (silent undercount). */\n LLM_USAGE_MISSING: \"theokit_llm_usage_missing\",\n} as const;\n","import { createRequire } from \"node:module\";\n\n/**\n * Adapter helper: safely require a module via `createRequire`, returning\n * `undefined` when not installed. Lives in its own module so adapters\n * (langfuse, sentry, posthog) can import without creating a cycle with\n * `adapter-registry.ts` (which lists them).\n *\n * @internal\n */\nexport function safeRequire<T = unknown>(moduleName: string): T | undefined {\n try {\n const r = createRequire(import.meta.url);\n return r(moduleName) as T;\n } catch {\n return undefined;\n }\n}\n\n/**\n * Shared adapter interface. Each adapter (langfuse, sentry, posthog) imports\n * this from `safe-require.ts` rather than `adapter-registry.ts`.\n *\n * @internal\n */\nexport interface TelemetryAdapter {\n moduleName: string;\n displayName: string;\n detect: () => boolean;\n register: () => void;\n}\n","import { safeRequire, type TelemetryAdapter } from \"../safe-require.js\";\n\n/**\n * Arize Phoenix OTel adapter (T10.2, ADR D449). Detects `arize-phoenix-otel`\n * and registers its span processor on the active OTel provider.\n *\n * @internal\n */\n\ninterface ArizeModule {\n PhoenixSpanProcessor: new (opts?: Record<string, unknown>) => unknown;\n}\n\ninterface OTelTraceApi {\n getTracerProvider(): {\n addSpanProcessor?: (processor: unknown) => void;\n };\n}\n\nlet registeredHere = false;\n\nexport const arizeAdapter: TelemetryAdapter = {\n moduleName: \"arize-phoenix-otel\",\n displayName: \"Arize Phoenix\",\n detect: () => safeRequire<ArizeModule>(\"arize-phoenix-otel\") !== undefined,\n register: () => {\n if (registeredHere) return;\n const arize = safeRequire<ArizeModule>(\"arize-phoenix-otel\");\n const otel = safeRequire<{ trace: OTelTraceApi }>(\"@opentelemetry/api\");\n if (arize === undefined || otel === undefined) return;\n const provider = otel.trace.getTracerProvider();\n if (provider.addSpanProcessor === undefined) return;\n const processor = new arize.PhoenixSpanProcessor();\n provider.addSpanProcessor(processor);\n registeredHere = true;\n },\n};\n","import { safeRequire, type TelemetryAdapter } from \"../safe-require.js\";\n\n/**\n * Braintrust adapter (T10.2, ADR D449). Detects `braintrust` and\n * configures its eval tracing.\n *\n * @internal\n */\n\ninterface BraintrustModule {\n init: (opts?: Record<string, unknown>) => void;\n wrapTraced: <T>(fn: () => T) => T;\n}\n\nlet registeredHere = false;\n\nexport const braintrustAdapter: TelemetryAdapter = {\n moduleName: \"braintrust\",\n displayName: \"Braintrust\",\n detect: () => safeRequire<BraintrustModule>(\"braintrust\") !== undefined,\n register: () => {\n if (registeredHere) return;\n const bt = safeRequire<BraintrustModule>(\"braintrust\");\n if (bt === undefined) return;\n // Braintrust auto-instruments via BRAINTRUST_API_KEY env var.\n // Registration ensures the module is loaded.\n registeredHere = true;\n },\n};\n","import { safeRequire, type TelemetryAdapter } from \"../safe-require.js\";\n\n/**\n * Datadog dd-trace adapter (T10.2, ADR D449). Detects `dd-trace` and\n * registers its OTel-compatible tracer on the active provider.\n *\n * @internal\n */\n\ninterface DdTraceModule {\n init: (opts?: Record<string, unknown>) => unknown;\n tracer: { use: (name: string, opts?: Record<string, unknown>) => void };\n}\n\nlet registeredHere = false;\n\nexport const datadogAdapter: TelemetryAdapter = {\n moduleName: \"dd-trace\",\n displayName: \"Datadog\",\n detect: () => safeRequire<DdTraceModule>(\"dd-trace\") !== undefined,\n register: () => {\n if (registeredHere) return;\n const dd = safeRequire<DdTraceModule>(\"dd-trace\");\n if (dd === undefined) return;\n dd.init({ logInjection: true });\n registeredHere = true;\n },\n};\n","import { diag } from \"../../diagnostics.js\";\nimport { safeRequire, type TelemetryAdapter } from \"../safe-require.js\";\n\n/**\n * Langfuse OTel adapter (ADR D42). Detects `@langfuse/node` and registers\n * `LangfuseSpanProcessor` on the active OTel provider.\n *\n * EC-12: if a Langfuse processor is already attached, skips silently.\n *\n * @internal\n */\n\ninterface LangfuseModule {\n Langfuse: new (opts?: Record<string, unknown>) => unknown;\n LangfuseSpanProcessor?: new (opts: { langfuse: unknown }) => unknown;\n}\n\ninterface OTelTraceApi {\n getTracerProvider(): {\n addSpanProcessor?: (processor: unknown) => void;\n getActiveSpanProcessor?: () => unknown;\n };\n}\n\nlet registeredHere = false;\n\nexport const langfuseAdapter: TelemetryAdapter = {\n moduleName: \"@langfuse/node\",\n displayName: \"Langfuse\",\n detect: () => safeRequire<LangfuseModule>(\"@langfuse/node\") !== undefined,\n register: () => {\n if (registeredHere) return;\n const lf = safeRequire<LangfuseModule>(\"@langfuse/node\");\n const otel = safeRequire<{ trace: OTelTraceApi }>(\"@opentelemetry/api\");\n if (lf === undefined || otel === undefined) return;\n const provider = otel.trace.getTracerProvider();\n if (provider.addSpanProcessor === undefined) {\n // Provider is a no-op proxy — user hasn't configured a real one.\n // Skip; their app likely doesn't use OTel pipelines yet.\n return;\n }\n // EC-12: detect existing Langfuse processor on the provider.\n const existing = provider.getActiveSpanProcessor?.();\n if (typeof existing === \"object\" && existing !== null) {\n const ctor = existing.constructor?.name ?? \"\";\n if (ctor.toLowerCase().includes(\"langfuse\")) {\n // Already wired — skip.\n registeredHere = true;\n return;\n }\n }\n if (lf.LangfuseSpanProcessor === undefined) {\n // Langfuse v2: no OTel span processor. Skip with a one-time hint.\n diag(\n \"[theokit-sdk] @langfuse/node detected but LangfuseSpanProcessor not found (v2?). Use Langfuse v3+ for auto-instrumentation.\\n\",\n );\n return;\n }\n const client = new lf.Langfuse();\n const processor = new lf.LangfuseSpanProcessor({ langfuse: client });\n provider.addSpanProcessor(processor);\n registeredHere = true;\n },\n};\n","import { safeRequire, type TelemetryAdapter } from \"../safe-require.js\";\n\n/**\n * LangSmith adapter (T10.2, ADR D449). Detects `langsmith` and\n * configures its tracing client for span export.\n *\n * @internal\n */\n\ninterface LangSmithModule {\n Client: new (\n opts?: Record<string, unknown>,\n ) => {\n createRun: (params: Record<string, unknown>) => Promise<void>;\n };\n}\n\nlet registeredHere = false;\n\nexport const langsmithAdapter: TelemetryAdapter = {\n moduleName: \"langsmith\",\n displayName: \"LangSmith\",\n detect: () => safeRequire<LangSmithModule>(\"langsmith\") !== undefined,\n register: () => {\n if (registeredHere) return;\n const ls = safeRequire<LangSmithModule>(\"langsmith\");\n if (ls === undefined) return;\n // LangSmith auto-instruments via LANGCHAIN_TRACING_V2 env var.\n // Registration ensures the module is loaded so its auto-hooks fire.\n registeredHere = true;\n },\n};\n","import { safeRequire, type TelemetryAdapter } from \"../safe-require.js\";\n\n/**\n * PostHog OTel adapter (ADR D42). Detects `posthog-node` and captures\n * key span events as PostHog events. Privacy-respecting per\n * `telemetry.includeContent`.\n *\n * @internal\n */\n\ninterface PostHogModule {\n PostHog: new (\n key: string,\n opts?: Record<string, unknown>,\n ) => {\n capture: (event: {\n distinctId: string;\n event: string;\n properties?: Record<string, unknown>;\n }) => void;\n shutdown?: () => Promise<void>;\n };\n}\n\ninterface OTelTraceApi {\n getTracerProvider(): {\n addSpanProcessor?: (processor: unknown) => void;\n };\n}\n\nlet registeredHere = false;\n\nexport const posthogAdapter: TelemetryAdapter = {\n moduleName: \"posthog-node\",\n displayName: \"PostHog\",\n detect: () => safeRequire<PostHogModule>(\"posthog-node\") !== undefined,\n register: () => {\n if (registeredHere) return;\n const ph = safeRequire<PostHogModule>(\"posthog-node\");\n const otel = safeRequire<{ trace: OTelTraceApi }>(\"@opentelemetry/api\");\n if (ph === undefined || otel === undefined) return;\n const key = process.env.POSTHOG_API_KEY ?? process.env.POSTHOG_PROJECT_API_KEY;\n if (typeof key !== \"string\" || key.length === 0) {\n // No PostHog key — skip silently (don't error).\n return;\n }\n const client = new ph.PostHog(key, {\n host: process.env.POSTHOG_HOST ?? \"https://us.i.posthog.com\",\n });\n\n const provider = otel.trace.getTracerProvider();\n if (provider.addSpanProcessor === undefined) return;\n\n // Minimal SpanProcessor adapter — capture each ended span as a\n // PostHog event when its name matches our agent.send/llm.call/tool.call\n // taxonomy. Privacy: only counts + IDs, no content (unless explicitly\n // enabled at the agent level — we don't have that info here, so default\n // is always counts-only).\n const processor = {\n onStart: () => {},\n onEnd: (span: {\n name: string;\n attributes: Record<string, unknown>;\n duration?: [number, number];\n }) => {\n if (\n !span.name.startsWith(\"agent.\") &&\n !span.name.startsWith(\"llm.\") &&\n !span.name.startsWith(\"tool.\")\n ) {\n return;\n }\n client.capture({\n distinctId: String(span.attributes[\"agent.id\"] ?? \"anonymous\"),\n event: `theokit.${span.name}`,\n properties: {\n // Pass through scalar attributes only.\n ...Object.fromEntries(\n Object.entries(span.attributes).filter(\n ([_, v]) =>\n typeof v === \"string\" || typeof v === \"number\" || typeof v === \"boolean\",\n ),\n ),\n },\n });\n },\n shutdown: async () => {\n if (client.shutdown !== undefined) await client.shutdown();\n },\n forceFlush: async () => {},\n };\n provider.addSpanProcessor(processor);\n registeredHere = true;\n },\n};\n","import { safeRequire, type TelemetryAdapter } from \"../safe-require.js\";\n\n/**\n * Sentry OTel adapter (ADR D42). Detects `@sentry/node` and attaches an\n * event-processor that enriches captured events with OTel trace context.\n *\n * Preferred path is `@sentry/opentelemetry` but that package is volatile\n * across Sentry v8; we use `@sentry/node` directly for stability. Documented\n * as a known limitation.\n *\n * @internal\n */\n\ninterface SentryModule {\n addEventProcessor?: (fn: (event: unknown) => unknown) => void;\n getActiveSpan?: () => unknown;\n isInitialized?: () => boolean;\n}\n\nlet registeredHere = false;\n\nexport const sentryAdapter: TelemetryAdapter = {\n moduleName: \"@sentry/node\",\n displayName: \"Sentry\",\n detect: () => safeRequire<SentryModule>(\"@sentry/node\") !== undefined,\n register: () => {\n if (registeredHere) return;\n const sentry = safeRequire<SentryModule>(\"@sentry/node\");\n if (sentry === undefined) return;\n // Some Sentry versions only expose addEventProcessor after Sentry.init().\n if (typeof sentry.addEventProcessor !== \"function\") {\n return;\n }\n // EC-12: only register once.\n sentry.addEventProcessor((event: unknown) => {\n // Best-effort enrichment: attach traceId/spanId from OTel active span.\n const otel = safeRequire<{\n trace: {\n getActiveSpan(): { spanContext(): { traceId: string; spanId: string } } | undefined;\n };\n }>(\"@opentelemetry/api\");\n if (otel === undefined) return event;\n const span = otel.trace.getActiveSpan();\n if (span === undefined) return event;\n const ctx = span.spanContext();\n if (typeof event === \"object\" && event !== null) {\n const contexts = (event as { contexts?: Record<string, unknown> }).contexts ?? {};\n contexts.trace = { trace_id: ctx.traceId, span_id: ctx.spanId };\n (event as { contexts?: Record<string, unknown> }).contexts = contexts;\n }\n return event;\n });\n registeredHere = true;\n },\n};\n","import type { TelemetrySettings } from \"../../types/agent.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { arizeAdapter } from \"./adapters/arize.js\";\nimport { braintrustAdapter } from \"./adapters/braintrust.js\";\nimport { datadogAdapter } from \"./adapters/datadog.js\";\nimport { langfuseAdapter } from \"./adapters/langfuse.js\";\nimport { langsmithAdapter } from \"./adapters/langsmith.js\";\nimport { posthogAdapter } from \"./adapters/posthog.js\";\nimport { sentryAdapter } from \"./adapters/sentry.js\";\nimport type { TelemetryAdapter } from \"./safe-require.js\";\n\n// Re-export the shared adapter contract for callers that consume registry\n// types directly. Implementation lives in `safe-require.ts` to keep the\n// adapter modules acyclic (depcruise enforces no-circular).\nexport type { TelemetryAdapter };\n\n/**\n * Auto-instrumentation adapter registry (ADR D42).\n *\n * Each adapter feature-detects a vendor lib (`@langfuse/node`, `@sentry/node`,\n * `posthog-node`) via `createRequire` and wires it into the active OTel\n * tracer provider. Errors in any adapter are caught — they never propagate\n * to `agent.send`.\n *\n * @internal\n */\n\nconst ALL_ADAPTERS: TelemetryAdapter[] = [\n langfuseAdapter,\n sentryAdapter,\n posthogAdapter,\n datadogAdapter,\n langsmithAdapter,\n arizeAdapter,\n braintrustAdapter,\n];\n\nconst registered = new Set<string>();\n\n/**\n * Try to register every detected adapter. Idempotent: subsequent calls\n * skip already-registered adapters.\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: per-adapter detect/register/skip/error-handle is inherent to the registry; splitting harms the once-per-vendor narrative.\nexport function tryAutoRegisterAdapters(settings: TelemetrySettings | undefined): void {\n if (settings?.enabled !== true) return;\n if (settings.autoDetect === false) return;\n const disabled = new Set(settings.disable ?? []);\n for (const adapter of ALL_ADAPTERS) {\n if (registered.has(adapter.moduleName)) continue;\n if (disabled.has(adapter.displayName.toLowerCase())) continue;\n if (!adapter.detect()) continue;\n try {\n adapter.register();\n registered.add(adapter.moduleName);\n diag(`[theokit-sdk] telemetry: ${adapter.displayName} auto-instrumented.\\n`);\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : String(cause);\n diag(\n `[theokit-sdk] telemetry: ${adapter.displayName} detected but failed to register: ${message}\\n`,\n );\n }\n }\n}\n\n/**\n * Test helper: reset registration state.\n *\n * @internal\n */\nexport function _resetAdapterRegistry(): void {\n registered.clear();\n}\n\n/**\n * Test helper: check if an adapter was registered.\n *\n * @internal\n */\nexport function _isRegistered(moduleName: string): boolean {\n return registered.has(moduleName);\n}\n\n/**\n * Test helper: list of adapters (for inspection in tests).\n *\n * @internal\n */\nexport function _getAllAdapters(): readonly TelemetryAdapter[] {\n return ALL_ADAPTERS;\n}\n","import { createRequire } from \"node:module\";\n\n/**\n * Lazy-loaded OpenTelemetry tracer for the SDK. Consumers opt in via\n * `AgentOptions.telemetry`. When `enabled: false` (default) or when\n * `@opentelemetry/api` is not installed, every API on this module is a\n * no-op. See ADR D34. Auto-instrumentation of Langfuse/Sentry/PostHog is\n * wired here (ADR D42).\n *\n * @internal\n */\n\nimport type { TelemetrySettings } from \"../../types/agent.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { redactSecrets } from \"../security/index.js\";\nimport { tryAutoRegisterAdapters } from \"./adapter-registry.js\";\n\n/** Minimal shape of `@opentelemetry/api` consumed by this wrapper. */\ninterface OTelApi {\n trace: {\n getTracer(name: string, version?: string): OTelTracer;\n // M3 #64 — set a parent SpanContext on a context so the next `startSpan`\n // (run within `context.with`) nests under it. traceFlags is present at\n // runtime on a real span context even though `OTelSpan.spanContext()` narrows it.\n setSpanContext(\n ctx: OTelContext,\n spanContext: { traceId: string; spanId: string; traceFlags?: number },\n ): OTelContext;\n };\n context: {\n active(): OTelContext;\n with<T>(ctx: OTelContext, fn: () => T): T;\n };\n trace_setSpan?: (ctx: OTelContext, span: OTelSpan) => OTelContext;\n SpanStatusCode: { OK: number; ERROR: number };\n}\n\nexport interface OTelSpan {\n setAttribute(key: string, value: string | number | boolean): void;\n setAttributes(attrs: Record<string, string | number | boolean | undefined>): void;\n addEvent(name: string, attrs?: Record<string, string | number | boolean>): void;\n setStatus(status: { code: number; message?: string }): void;\n recordException(err: unknown): void;\n end(endTime?: number): void;\n spanContext(): { traceId: string; spanId: string };\n isRecording(): boolean;\n}\n\ninterface OTelContext {\n // opaque\n readonly [marker: symbol]: unknown;\n}\n\ninterface OTelTracer {\n // M3 #64 — the real OTel Tracer accepts an explicit parent `context` as the 3rd\n // arg (independent of a registered ContextManager, which the test collector omits).\n startSpan(\n name: string,\n options?: { attributes?: Record<string, unknown> },\n context?: OTelContext,\n ): OTelSpan;\n startActiveSpan<T>(\n name: string,\n options: { attributes?: Record<string, unknown> } | undefined,\n fn: (span: OTelSpan) => T,\n ): T;\n}\n\n/**\n * Telemetry handle returned by {@link createTelemetry}. Callers use this to\n * start spans, add events, etc. When telemetry is disabled OR OTel is not\n * installed, every method is a safe no-op.\n *\n * @internal\n */\nexport interface TelemetryHandle {\n readonly enabled: boolean;\n readonly includeContent: boolean;\n /** Start a span. Returns a no-op span if telemetry is disabled. */\n startSpan(name: string, attrs?: Record<string, string | number | boolean>): OTelSpan;\n /** Start a child span nested under `parent` (M3 #64). `undefined` parent →\n * a root span (parentless callers, or telemetry with no run span). */\n startChildSpan(\n parent: OTelSpan | undefined,\n name: string,\n attrs?: Record<string, string | number | boolean>,\n ): OTelSpan;\n /**\n * Record a histogram observation. T0.1 ships\n * `theokit_memory_recall_duration_ms`; downstream tasks add more.\n * No-op when telemetry is disabled or when `@opentelemetry/api`'s metrics\n * namespace is unavailable. ADR D34 — exporter errors are swallowed by `safe()`.\n */\n recordHistogram(\n name: string,\n valueMs: number,\n attrs?: Record<string, string | number | boolean>,\n ): void;\n /** End all open spans on this handle (best-effort, used by Agent.dispose). */\n endAll(): void;\n}\n\nlet cachedOtel: OTelApi | undefined | null;\n\n/** Lazy-load `@opentelemetry/api` via createRequire. Caches null on failure. */\nfunction loadOtel(): OTelApi | null {\n if (cachedOtel === undefined) {\n try {\n const r = createRequire(import.meta.url);\n const mod = r(\"@opentelemetry/api\") as OTelApi;\n cachedOtel = mod;\n } catch {\n cachedOtel = null;\n }\n }\n return cachedOtel ?? null;\n}\n\nexport const NOOP_SPAN: OTelSpan = {\n setAttribute: () => {},\n setAttributes: () => {},\n addEvent: () => {},\n setStatus: () => {},\n recordException: () => {},\n end: () => {},\n spanContext: () => ({ traceId: \"0\".repeat(32), spanId: \"0\".repeat(16) }),\n isRecording: () => false,\n};\n\nconst NOOP_HANDLE: TelemetryHandle = {\n enabled: false,\n includeContent: false,\n startSpan: () => NOOP_SPAN,\n startChildSpan: () => NOOP_SPAN,\n recordHistogram: () => {},\n endAll: () => {},\n};\n\n/**\n * Wrap a callable with try/catch so OTel side-effects can never propagate\n * into the agent loop. Logs once to stderr on the first failure (EC-1).\n *\n * @internal\n */\nlet warnedOnce = false;\nfunction safe<T>(op: () => T, fallback: T): T {\n try {\n return op();\n } catch (cause) {\n if (!warnedOnce) {\n warnedOnce = true;\n const message = cause instanceof Error ? cause.message : String(cause);\n diag(\n `[theokit-sdk] telemetry exporter error (suppressed; agent.send continues): ${message}\\n`,\n );\n }\n return fallback;\n }\n}\n\n/**\n * Create a telemetry handle from the per-agent settings. Loads OTel lazily\n * and produces a no-op handle when telemetry is disabled or OTel is not\n * installed.\n *\n * @internal\n */\nexport function createTelemetry(settings: TelemetrySettings | undefined): TelemetryHandle {\n if (settings === undefined || settings.enabled !== true) return NOOP_HANDLE;\n const otel = loadOtel();\n if (otel === null) {\n // Telemetry enabled but OTel not installed — warn once and degrade to no-op.\n if (!warnedOnce) {\n warnedOnce = true;\n diag(\n \"[theokit-sdk] telemetry.enabled = true but `@opentelemetry/api` is not installed; telemetry is a no-op.\\n\",\n );\n }\n return NOOP_HANDLE;\n }\n const tracer = safe(\n () => otel.trace.getTracer(settings.serviceName ?? \"theokit-sdk\", \"1.2.0\"),\n undefined,\n );\n if (tracer === undefined) return NOOP_HANDLE;\n\n // ADR D42: try to auto-register Langfuse / Sentry / PostHog when present.\n // Idempotent — multiple agents share the registry; subsequent calls skip.\n safe(() => tryAutoRegisterAdapters(settings), undefined);\n\n const openSpans = new Set<OTelSpan>();\n // OTel context propagation is implicit when startSpan is called inside an\n // active context. For simplicity, we always startSpan; child relationship\n // is established by callers using OTel API directly when needed. The\n // wrapper records spans in `openSpans` so dispose() can endAll().\n const startNewSpan = (name: string, attrs?: Record<string, string | number | boolean>) => {\n // T1.2 (ADR D68): redact string attrs at the boundary — values go to\n // Langfuse / Sentry / PostHog via the OTel SpanProcessor.\n const redactedAttrs = attrs === undefined ? undefined : redactAttrs(attrs);\n const span = safe(\n () => tracer.startSpan(name, redactedAttrs ? { attributes: redactedAttrs } : undefined),\n NOOP_SPAN,\n );\n if (span !== NOOP_SPAN) openSpans.add(span);\n return wrapSpan(span, openSpans);\n };\n // T0.1: lazy-load metrics namespace separately — `@opentelemetry/api` ships\n // metrics in `api.metrics`, but older 1.x versions may omit it. Returns null\n // and we degrade `recordHistogram` to no-op (same EC-1 discipline as spans).\n const histograms = new Map<string, unknown>();\n const resolveHistogram = (name: string): unknown | undefined => {\n const existing = histograms.get(name);\n if (existing !== undefined) return existing;\n const otelAny = otel as unknown as {\n metrics?: { getMeter(n: string, v?: string): unknown };\n };\n const meterProvider = otelAny.metrics;\n if (meterProvider === undefined) return undefined;\n const meter = meterProvider.getMeter(settings.serviceName ?? \"theokit-sdk\", \"1.2.0\") as {\n createHistogram?: (n: string, opts?: { unit?: string }) => unknown;\n };\n if (typeof meter.createHistogram !== \"function\") return undefined;\n const created = meter.createHistogram(name, { unit: \"ms\" });\n histograms.set(name, created);\n return created;\n };\n const recordHistogram = (\n name: string,\n valueMs: number,\n attrs?: Record<string, string | number | boolean>,\n ): void => {\n if (!Number.isFinite(valueMs)) return;\n safe(() => {\n const histogram = resolveHistogram(name);\n if (histogram === undefined) return;\n const redacted = attrs === undefined ? undefined : redactAttrs(attrs);\n const h = histogram as { record(value: number, attrs?: Record<string, unknown>): void };\n h.record(valueMs, redacted);\n }, undefined);\n };\n const handle: TelemetryHandle = {\n enabled: true,\n includeContent: settings.includeContent === true,\n startSpan: startNewSpan,\n // M3 #64 — actually nest the child under its parent instead of discarding it.\n // The parent's SpanContext is set on a fresh OTel context so the child links\n // to it (traceId + parentSpanId), reconstructing the causal trace tree. Falls\n // back to a root span when the parent has no valid span id (telemetry off /\n // NOOP), preserving the pre-M3 behavior for parentless callers.\n startChildSpan: (parent, name, attrs) => {\n const redactedAttrs = attrs === undefined ? undefined : redactAttrs(attrs);\n const opts = redactedAttrs ? { attributes: redactedAttrs } : undefined;\n const pctx = safe(() => parent?.spanContext(), undefined);\n const span = safe(() => {\n if (pctx !== undefined && pctx.spanId !== \"0\".repeat(16)) {\n // Pass the parent context EXPLICITLY (3rd arg) so the child links to it\n // without needing a registered ContextManager.\n const childCtx = otel.trace.setSpanContext(otel.context.active(), pctx);\n return tracer.startSpan(name, opts, childCtx);\n }\n return tracer.startSpan(name, opts);\n }, NOOP_SPAN);\n if (span !== NOOP_SPAN) openSpans.add(span);\n return wrapSpan(span, openSpans);\n },\n recordHistogram,\n endAll: () => {\n for (const span of openSpans) safe(() => span.end(), undefined);\n openSpans.clear();\n },\n };\n return handle;\n}\n\n/**\n * Wrap a raw OTel span so every method goes through safe(). This is the\n * EC-1 enforcement: exporter errors thrown via setAttribute/end/etc never\n * propagate to the agent loop.\n */\nfunction wrapSpan(span: OTelSpan, openSpans: Set<OTelSpan>): OTelSpan {\n if (span === NOOP_SPAN) return span;\n return {\n setAttribute: (k, v) => safe(() => span.setAttribute(k, redactAttrValue(v)), undefined),\n setAttributes: (attrs) => safe(() => span.setAttributes(redactAttrs(attrs)), undefined),\n addEvent: (name, attrs) =>\n safe(() => span.addEvent(name, attrs ? redactAttrs(attrs) : undefined), undefined),\n setStatus: (status) => safe(() => span.setStatus(status), undefined),\n recordException: (err) => safe(() => span.recordException(err), undefined),\n end: (endTime) => {\n safe(() => span.end(endTime), undefined);\n openSpans.delete(span);\n },\n spanContext: () =>\n safe(() => span.spanContext(), { traceId: \"0\".repeat(32), spanId: \"0\".repeat(16) }),\n isRecording: () => safe(() => span.isRecording(), false),\n };\n}\n\n/**\n * Redact a single attribute value. Strings go through `redactSecrets`;\n * numbers/booleans/undefined pass through untouched. T1.2.\n *\n * @internal — exported only so unit tests can exercise the wire without\n * a real `@opentelemetry/api` install. Production callers reach it via\n * the `wrapSpan` closure.\n */\nexport function _redactAttrValueForTests<T extends string | number | boolean | undefined>(\n value: T,\n): T {\n return redactAttrValue(value);\n}\n\n/**\n * Redact every string value in an attributes record. T1.2.\n *\n * @internal — exported only so unit tests can exercise the wire.\n */\nexport function _redactAttrsForTests<\n T extends Record<string, string | number | boolean | undefined>,\n>(attrs: T): T {\n return redactAttrs(attrs);\n}\n\nfunction redactAttrValue<T extends string | number | boolean | undefined>(value: T): T {\n if (typeof value !== \"string\") return value;\n return redactSecrets(value) as T;\n}\n\nfunction redactAttrs<T extends Record<string, string | number | boolean | undefined>>(attrs: T): T {\n const out = {} as Record<string, string | number | boolean | undefined>;\n for (const [k, v] of Object.entries(attrs)) {\n out[k] = typeof v === \"string\" ? redactSecrets(v) : v;\n }\n return out as T;\n}\n\n/** Exported for tests — resets the OTel cache and the warning-once latch. */\nexport function _resetTelemetryCacheForTests(): void {\n cachedOtel = undefined;\n warnedOnce = false;\n}\n","import type { ModelSelection } from \"../../../types/agent.js\";\nimport type {\n PluginsSettings,\n ProviderRoutingSettings,\n ResolvedProviderRoute,\n SDKProvidersManager,\n} from \"../../../types/providers.js\";\nimport { enabledPluginNames } from \"../../plugins/enabled-names.js\";\nimport type { Plugin } from \"../../plugins/types.js\";\n\n/**\n * Provider routing inspector. Computes the resolved capability →\n * provider mapping from `AgentOptions.providers` + `AgentOptions.plugins` +\n * the model selection.\n *\n * @internal\n */\nexport class ProvidersManagerImpl implements SDKProvidersManager {\n constructor(\n private readonly model: ModelSelection | undefined,\n private readonly providers: ProviderRoutingSettings | undefined,\n private readonly plugins: PluginsSettings | readonly Plugin[] | undefined,\n ) {}\n\n routes(): Promise<ResolvedProviderRoute[]> {\n const resolved: ResolvedProviderRoute[] = [];\n const modelProvider = providerFromModel(this.model);\n const seen = new Set<string>();\n if (this.providers?.routes !== undefined) {\n for (const route of this.providers.routes) {\n const resolvedRoute = resolveRoute(route, modelProvider, this.plugins);\n if (!seen.has(route.capability)) {\n seen.add(route.capability);\n resolved.push(resolvedRoute);\n }\n }\n }\n return Promise.resolve(resolved);\n }\n}\n\nfunction providerFromModel(model: ModelSelection | undefined): string | undefined {\n if (model === undefined) return undefined;\n const id = model.id;\n if (id.includes(\":\")) return id.split(\":\")[0];\n return undefined;\n}\n\nfunction resolveRoute(\n route: { capability: string; provider: string; model?: string },\n modelProvider: string | undefined,\n plugins: PluginsSettings | readonly Plugin[] | undefined,\n): ResolvedProviderRoute {\n if (route.capability === \"chat\" && modelProvider === route.provider) {\n const modelName = extractModelName(modelProvider, route);\n const base: ResolvedProviderRoute = {\n capability: route.capability,\n provider: route.provider,\n reason: \"explicit-model-provider\",\n };\n if (modelName !== undefined) base.model = modelName;\n return base;\n }\n if (enabledPluginNames(plugins).length > 0) {\n return {\n capability: route.capability,\n provider: route.provider,\n reason: \"first-available-plugin-provider\",\n };\n }\n return {\n capability: route.capability,\n provider: route.provider,\n reason: \"explicit-route\",\n };\n}\n\nfunction extractModelName(\n prefix: string,\n route: { model?: string; provider: string },\n): string | undefined {\n if (route.model !== undefined) return route.model;\n // When the model id is \"anthropic:claude-3-7-sonnet\" and the route is chat→anthropic,\n // surface the model name from the prefix split.\n return prefix === route.provider ? defaultModelForProvider(prefix) : undefined;\n}\n\nfunction defaultModelForProvider(provider: string): string | undefined {\n if (provider === \"anthropic\") return \"claude-3-7-sonnet\";\n return undefined;\n}\n","/**\n * Shared loader for `.theokit/<dir>/<name>.md` (or `.theokit/<dir>/<name>/PLUGIN.md`)\n * config files. Mirrors the SKILL.md pattern: YAML frontmatter delimited by\n * `---` blocks + optional markdown body for prose / rationale.\n *\n * Consumed by hooks-loader (T1.2), context-manager (T2.2), and\n * plugins-manager (T3.2) — DRY across all 3 user-edited config surfaces.\n *\n * ADRs: D74 (markdown format), D75 (1 file = 1 entity), D76 (Zod schema).\n *\n * @internal\n */\n\nimport { readdir, readFile, stat } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\n// T5.10 — 1 MB cap on individual markdown config files. A crafted\n// multi-MB file would be read into memory in full — a local DoS\n// vector on resource-constrained environments (edge, CI workers).\nconst MAX_MD_FILE_BYTES = 1_048_576; // 1 MB\n\nimport type { z } from \"zod\";\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { parseSimpleYaml } from \"../runtime/context/yaml-frontmatter.js\";\n\nexport interface MarkdownEntity<T> {\n /** Slug from filename (without `.md`) for flat pattern, or subdir name for nested. */\n slug: string;\n /** Validated frontmatter. */\n frontmatter: T;\n /** Markdown body (everything after the closing `---`). May be empty. */\n body: string;\n /** Absolute source path for audit / error context. */\n source: string;\n}\n\nexport interface LoadOptions<T> {\n /** Absolute path to the directory containing `*.md` files (flat) or\n * subdirs with `PLUGIN.md` (nested). */\n dir: string;\n /** Zod schema validating the frontmatter shape. */\n schema: z.ZodType<T>;\n /** `\"flat\"` = top-level `<slug>.md` files; `\"nested\"` = subdirs each with\n * `PLUGIN.md`. Default: `\"flat\"`. */\n pattern?: \"flat\" | \"nested\";\n /** Error code prefix (e.g., `\"hook\"` → `\"hook_frontmatter_invalid\"`). */\n errorCodePrefix: string;\n}\n\n/**\n * Load all markdown config entities from a directory, validating each\n * file's frontmatter against the provided Zod schema.\n *\n * Edge cases handled:\n * - **ENOENT on dir** → returns `[]` graciously.\n * - **EACCES on dir** → throws `<prefix>_dir_read_error` (EC-11 distinct).\n * - **Missing frontmatter `---` block** → throws `<prefix>_missing_frontmatter`.\n * - **Frontmatter delimited by `+++`** (Hugo/TOML) → throws `<prefix>_missing_frontmatter`.\n * - **Truncated frontmatter (no closing `---`)** → throws `<prefix>_missing_frontmatter`.\n * - **Body containing `---` horizontal rule** → NOT confused with frontmatter\n * end; only the first `---...---` block at file head is the frontmatter.\n * - **Zod schema validation failure** → throws `<prefix>_frontmatter_invalid`\n * with Zod error path embedded in the message.\n *\n * Note on cross-platform: filenames are case-sensitive in Linux, case-insensitive\n * in macOS/Windows. Use lowercase slug convention to avoid collisions.\n * T5.10: individual files capped at 1 MB to prevent local DoS on edge/CI.\n *\n * @internal\n */\nexport async function loadMarkdownEntities<T>(opts: LoadOptions<T>): Promise<MarkdownEntity<T>[]> {\n const { dir, schema, pattern = \"flat\", errorCodePrefix } = opts;\n const entries = await readDirSafe(dir, errorCodePrefix);\n if (entries === null) return [];\n\n const out: MarkdownEntity<T>[] = [];\n for (const entry of entries) {\n const resolved = resolveEntryPath(entry, pattern, dir);\n if (resolved === null) continue;\n // T5.10 — reject files > 1 MB before reading into memory.\n await assertFileSizeUnderCap(resolved.source, errorCodePrefix);\n const raw = await readFile(resolved.source, \"utf8\").catch(() => null);\n if (raw === null) continue;\n const split = splitFrontmatter(raw, resolved.source, errorCodePrefix);\n const fields = parseSimpleYaml(split.frontmatter);\n const parsed = schema.safeParse(fields);\n if (!parsed.success) {\n throw new ConfigurationError(\n `Invalid frontmatter in ${resolved.source}: ${parsed.error.message}`,\n { code: `${errorCodePrefix}_frontmatter_invalid` },\n );\n }\n out.push({\n slug: resolved.slug,\n frontmatter: parsed.data,\n body: split.body.trim(),\n source: resolved.source,\n });\n }\n return out;\n}\n\n/** T5.10 — reject files > 1 MB before reading into memory. */\nasync function assertFileSizeUnderCap(source: string, errorCodePrefix: string): Promise<void> {\n try {\n const info = await stat(source);\n if (info.size > MAX_MD_FILE_BYTES) {\n throw new ConfigurationError(\n `Config file ${source} exceeds 1 MB size limit (${info.size} bytes). ` +\n \"Reduce the file or split into multiple entities.\",\n { code: `${errorCodePrefix}_file_too_large` },\n );\n }\n } catch (cause) {\n if (cause instanceof ConfigurationError) throw cause;\n // stat failed — file unreadable; let readFile handle the ENOENT/EACCES\n }\n}\n\nasync function readDirSafe(\n dir: string,\n errorCodePrefix: string,\n): Promise<import(\"node:fs\").Dirent[] | null> {\n try {\n return (await readdir(dir, { withFileTypes: true })) as import(\"node:fs\").Dirent[];\n } catch (cause) {\n const code = (cause as NodeJS.ErrnoException).code;\n if (code === \"ENOENT\") return null;\n throw new ConfigurationError(`Failed to read ${dir}`, {\n code: `${errorCodePrefix}_dir_read_error`,\n cause,\n });\n }\n}\n\nfunction resolveEntryPath(\n entry: { name: string; isFile(): boolean; isDirectory(): boolean },\n pattern: \"flat\" | \"nested\",\n dir: string,\n): { slug: string; source: string } | null {\n if (pattern === \"flat\") {\n if (!entry.isFile() || !entry.name.endsWith(\".md\")) return null;\n return { slug: entry.name.slice(0, -3), source: join(dir, entry.name) };\n }\n if (!entry.isDirectory()) return null;\n return { slug: entry.name, source: join(dir, entry.name, \"PLUGIN.md\") };\n}\n\n/**\n * Split a markdown file into frontmatter (between two `---` lines at the top)\n * and body. Rejects `+++` (Hugo/TOML), truncated frontmatter, and missing\n * frontmatter with typed `ConfigurationError`.\n *\n * @internal\n */\nfunction splitFrontmatter(\n raw: string,\n source: string,\n errorCodePrefix: string,\n): { frontmatter: string; body: string } {\n // Strict: file MUST start with `---\\n`, then frontmatter content, then `---\\n`.\n // The body is whatever follows the closing `---`. Other `---` lines in body\n // (horizontal rules) are NOT confused with the frontmatter delim because\n // the regex anchors `^---\\s*\\n` at the start of the file.\n const match = /^---\\s*\\n([\\s\\S]*?)\\n---\\s*(?:\\n|$)/.exec(raw);\n if (match === null) {\n throw new ConfigurationError(\n `Missing or malformed frontmatter in ${source} (expected \\`---\\` delimited block at file head)`,\n { code: `${errorCodePrefix}_missing_frontmatter` },\n );\n }\n return {\n frontmatter: match[1] ?? \"\",\n body: raw.slice(match[0].length),\n };\n}\n","/**\n * Context file loaders + truncation (T1.2, ADRs D154 / D155 / D159).\n *\n * Reads context source files from disk, applies the per-file size cap\n * with 70%/20% head/tail truncation, and emits the\n * `context_files_truncated` telemetry counter when the cap fires.\n * Pure (no I/O) for `truncateWithMarker` — testable in isolation.\n *\n * @internal\n */\n\nimport { readFile } from \"node:fs/promises\";\n\nconst HEAD_RATIO = 0.7;\nconst TAIL_RATIO = 0.2;\nconst MARKER = \"\\n\\n…[truncated by theokit]\\n\\n\";\n\n/** Default per-file cap (40k chars ≈ 10k tokens). D155. */\nexport const DEFAULT_MAX_BYTES_PER_FILE = 40_000;\n\nexport interface LoadedSource {\n /** Absolute path the content came from. */\n readonly source: string;\n readonly content: string;\n readonly originalBytes: number;\n readonly truncated: boolean;\n}\n\nexport interface TruncateResult {\n readonly truncated: boolean;\n readonly finalContent: string;\n}\n\n/**\n * Cap `content` at `max` characters with 70%/20% head/tail truncation\n * and an explicit marker. Pure — no I/O, no telemetry.\n *\n * EC-C: when `max <= MARKER.length`, skip the marker entirely and\n * return a head-only slice. Without this guard, `budget = max -\n * MARKER.length` would go negative and `content.slice(-tailBytes)`\n * would slice from the END of the string rather than truncating.\n *\n * EC-H: codepoint integrity — `String.slice()` operates on UTF-16\n * code units, which can split surrogate pairs. We accept that\n * trailing/leading replacement chars (U+FFFD) may appear at boundaries.\n * Modern LLMs tolerate them; byte-exact safety would require Buffer\n * slicing + TextDecoder with `fatal: true` retry, which adds complexity\n * without value.\n *\n * @public\n */\nexport function truncateWithMarker(content: string, max: number): TruncateResult {\n if (content.length <= max) {\n return { truncated: false, finalContent: content };\n }\n // EC-C: max too small to fit even the marker — return head-only slice.\n if (max <= MARKER.length) {\n return { truncated: true, finalContent: content.slice(0, max) };\n }\n const budget = max - MARKER.length;\n const headBytes = Math.floor(budget * (HEAD_RATIO / (HEAD_RATIO + TAIL_RATIO)));\n const tailBytes = budget - headBytes;\n return {\n truncated: true,\n finalContent: content.slice(0, headBytes) + MARKER + content.slice(-tailBytes),\n };\n}\n\n/**\n * Read a file from disk and apply the per-file cap. Emits telemetry\n * counter when truncation fires.\n *\n * EC-G: file deleted between discovery and read (FS race) → returns\n * `undefined`, never throws.\n *\n * @internal\n */\nexport async function loadPlainMarkdown(\n absPath: string,\n opts: { maxBytesPerFile?: number } = {},\n): Promise<LoadedSource | undefined> {\n const max = opts.maxBytesPerFile ?? DEFAULT_MAX_BYTES_PER_FILE;\n let content: string;\n try {\n content = await readFile(absPath, \"utf8\");\n } catch {\n // EC-G: ENOENT / EACCES / etc → caller treats as missing.\n return undefined;\n }\n const { truncated, finalContent } = truncateWithMarker(content, max);\n if (truncated) {\n emitTruncationCounter(absPath);\n }\n return {\n source: absPath,\n content: finalContent,\n originalBytes: content.length,\n truncated,\n };\n}\n\n/**\n * EC-L: telemetry no-op when OTel is not imported. We import the tracer\n * lazily and use `safeCall` so the lookup never throws and never pulls\n * OTel into the import graph for users without `@opentelemetry/api`\n * installed.\n *\n * @internal\n */\nfunction emitTruncationCounter(source: string): void {\n // Lazy resolution via globalThis avoids static import of telemetry/tracer.\n // Tests can spy via the same path; production users without OTel see no-op.\n const tracer = (\n globalThis as { __theokit_tracer?: { inc?: (k: string, attrs: unknown) => void } }\n ).__theokit_tracer;\n if (tracer?.inc === undefined) return;\n try {\n tracer.inc(\"context_files_truncated\", { file: source });\n } catch {\n // Telemetry must never break the loader.\n }\n}\n","/**\n * Aggregate context cap (T4.1, ADR D155).\n *\n * After per-file truncation, applies a second-level cap on the TOTAL\n * size across all sources. Lower-priority sources are dropped when the\n * sum would exceed `maxBytesTotal`. The last partially-fitting source\n * is truncated to fit exactly into the remaining budget.\n *\n * EC-J: same-priority sources tie-break by absolute source path\n * lex-ascending for deterministic ordering (prompt-cache stability).\n *\n * @internal\n */\n\nimport { truncateWithMarker } from \"./context-loaders.js\";\n\n/** Default aggregate cap (120k chars across all context files). D155. */\nexport const DEFAULT_MAX_BYTES_TOTAL = 120_000;\n\nexport interface AggregatorSource {\n readonly id: string;\n readonly source: string;\n readonly content: string;\n readonly priority: number;\n readonly truncated: boolean;\n}\n\nexport interface AggregateResult {\n readonly kept: AggregatorSource[];\n readonly dropped: AggregatorSource[];\n}\n\n/**\n * Sort by priority ascending, tie-break by source path lex (EC-J),\n * then drop / partial-truncate to fit `maxBytesTotal`.\n *\n * @internal\n */\nexport function applyAggregateCap(\n sources: ReadonlyArray<AggregatorSource>,\n maxTotal: number,\n): AggregateResult {\n // EC-J: deterministic ordering. Priority asc, then path lex asc.\n const sorted = [...sources].sort((a, b) => {\n if (a.priority !== b.priority) return a.priority - b.priority;\n return a.source.localeCompare(b.source);\n });\n\n let totalBytes = 0;\n const kept: AggregatorSource[] = [];\n const dropped: AggregatorSource[] = [];\n\n for (const s of sorted) {\n if (totalBytes + s.content.length <= maxTotal) {\n kept.push(s);\n totalBytes += s.content.length;\n continue;\n }\n const remaining = maxTotal - totalBytes;\n if (remaining > 0) {\n // Partial keep — truncate this one to fit.\n const { finalContent } = truncateWithMarker(s.content, remaining);\n kept.push({ ...s, content: finalContent, truncated: true });\n totalBytes = maxTotal;\n } else {\n dropped.push(s);\n }\n }\n\n if (dropped.length > 0) {\n emitTotalDropCounter(dropped.map((d) => d.source));\n }\n return { kept, dropped };\n}\n\nfunction emitTotalDropCounter(droppedSources: string[]): void {\n const tracer = (\n globalThis as { __theokit_tracer?: { inc?: (k: string, attrs: unknown) => void } }\n ).__theokit_tracer;\n if (tracer?.inc === undefined) return;\n try {\n tracer.inc(\"context_files_total_truncated\", { dropped: droppedSources });\n } catch {\n // Telemetry must never break.\n }\n}\n","/**\n * `@path/to/file` import resolver (T2.1, ADR D156).\n *\n * Anthropic/Gemini convention: lines that are EXACTLY `@path` get\n * replaced with the imported file's content, recursively (5-hop cap),\n * with cycle detection. Inline `see @x.md, also @y.md` references are\n * NOT resolved (EC-Q — own-line only, mirrors Anthropic's actual\n * behavior).\n *\n * EC-D fix: every imported file is itself capped at `maxBytesPerFile`\n * via `loadPlainMarkdown` BEFORE concatenation. Prevents a CLAUDE.md\n * with 5 imports of 30k each from ballooning to 150k of imported\n * content before the outer cap fires.\n *\n * @internal\n */\n\nimport { homedir } from \"node:os\";\nimport { dirname, isAbsolute, join, resolve as resolvePath } from \"node:path\";\n\nimport { loadPlainMarkdown } from \"./context-loaders.js\";\n\n/** EC-Q: line-anchored. `@path` must be alone on its line. */\nconst IMPORT_RE = /^@(\\S+)\\s*$/gm;\nconst MAX_HOPS = 5;\n\nexport interface ResolveImportsOptions {\n /** Absolute paths already resolved (cycle detection). */\n readonly visited: Set<string>;\n /** Current recursion depth — caps at MAX_HOPS. */\n readonly depth: number;\n /** Per-import file cap (EC-D). Forwarded to loadPlainMarkdown. */\n readonly maxBytesPerFile: number;\n}\n\n/**\n * Resolve `@path` directives in `content`. Each match is replaced with\n * the imported file content (already cap-truncated per EC-D), and\n * recursion continues on the resolved content until MAX_HOPS or cycle.\n *\n * Failure modes (placeholders, never throws):\n * - file not found → `[@import not found: <path>]`\n * - cycle detected → `[@import cycle detected: <path>]`\n * - depth exceeded → trailing `\\n\\n…[@import depth limit 5 reached]\\n\\n`\n *\n * @internal\n */\nexport async function resolveImports(\n content: string,\n basePath: string,\n opts: ResolveImportsOptions,\n): Promise<string> {\n if (opts.depth >= MAX_HOPS) {\n return `${content}\\n\\n…[@import depth limit ${MAX_HOPS} reached]\\n\\n`;\n }\n const baseDir = dirname(basePath);\n return replaceAsync(content, IMPORT_RE, async (raw) => {\n const absolute = resolveImportPath(raw, baseDir);\n if (opts.visited.has(absolute)) {\n return `[@import cycle detected: ${raw}]`;\n }\n opts.visited.add(absolute);\n const loaded = await loadPlainMarkdown(absolute, { maxBytesPerFile: opts.maxBytesPerFile });\n if (loaded === undefined) {\n return `[@import not found: ${raw}]`;\n }\n // Recurse with same visited set + incremented depth.\n return resolveImports(loaded.content, absolute, {\n visited: opts.visited,\n depth: opts.depth + 1,\n maxBytesPerFile: opts.maxBytesPerFile,\n });\n });\n}\n\nfunction resolveImportPath(raw: string, baseDir: string): string {\n if (raw.startsWith(\"~/\")) {\n return resolvePath(join(homedir(), raw.slice(2)));\n }\n if (isAbsolute(raw)) {\n return resolvePath(raw);\n }\n return resolvePath(join(baseDir, raw));\n}\n\n/**\n * Async equivalent of `String.prototype.replace` — sequential. Returns\n * `content` with every `re` match replaced by `await replacer(match)`.\n *\n * @internal\n */\nasync function replaceAsync(\n content: string,\n re: RegExp,\n replacer: (raw: string) => Promise<string>,\n): Promise<string> {\n const matches: Array<{ match: string; raw: string; index: number }> = [];\n // Reset lastIndex; clone the regex to avoid stateful traps.\n const localRe = new RegExp(re.source, re.flags);\n let m: RegExpExecArray | null;\n // biome-ignore lint/suspicious/noAssignInExpressions: idiomatic regex loop\n while ((m = localRe.exec(content)) !== null) {\n matches.push({ match: m[0], raw: m[1] ?? \"\", index: m.index });\n if (m.index === localRe.lastIndex) localRe.lastIndex += 1;\n }\n if (matches.length === 0) return content;\n let result = \"\";\n let cursor = 0;\n for (const entry of matches) {\n result += content.slice(cursor, entry.index);\n result += await replacer(entry.raw);\n cursor = entry.index + entry.match.length;\n }\n result += content.slice(cursor);\n return result;\n}\n","/**\n * Shared glob → RegExp compiler for context discovery (extracted from the\n * MDC parser so the `.cursor/rules/*.mdc` and `.theokit/rules/*.md` parsers\n * share ONE implementation — DRY, no new dependency).\n *\n * Supports `**` (any depth), `*` (single path segment, no `/`), `?` (single\n * non-separator char). Sufficient for the patterns Cursor and Claude Code\n * themselves recommend.\n *\n * @internal\n */\nexport function globToRegex(glob: string): RegExp {\n // Support **/ (zero-or-more path segments), ** (any depth), * (single\n // segment), ? (single non-separator char). `**/` collapses so `src/**/*.ts`\n // matches `src/foo.ts` AND `src/a/b/foo.ts` — the semantics Cursor and Claude\n // Code document (\"src/**/* → all files under src/\"). `*` and `?` never cross a\n // `/` (strict glob segment semantics). Escape other regex metas.\n const compiled = glob\n .replace(/[.+^${}()|[\\]\\\\]/g, \"\\\\$&\")\n .replace(/\\*\\*\\//g, \"::GLOBSTAR_SLASH::\")\n .replace(/\\*\\*/g, \"::GLOBSTAR::\")\n .replace(/\\*/g, \"[^/]*\")\n .replace(/\\?/g, \"[^/]\")\n .replace(/::GLOBSTAR_SLASH::/g, \"(?:.*/)?\")\n .replace(/::GLOBSTAR::/g, \".*\");\n return new RegExp(`^${compiled}$`);\n}\n\n/**\n * True when any of `patterns` glob-matches any of `paths`. Central helper so\n * both rule parsers agree on activation semantics.\n *\n * @internal\n */\nexport function anyGlobMatches(\n patterns: ReadonlyArray<string>,\n paths: ReadonlyArray<string>,\n): boolean {\n if (patterns.length === 0 || paths.length === 0) return false;\n const res = patterns.map(globToRegex);\n return paths.some((p) => res.some((re) => re.test(p)));\n}\n","/**\n * Minimal YAML-subset frontmatter parsing shared by the `.cursor/rules/*.mdc`\n * and `.theokit/rules/*.md` parsers (extracted for DRY — one parser, one set\n * of edge-case behaviours, no new dependency).\n *\n * Handles `key: value` lines (string scalars, booleans, integers) and `key:`\n * followed by indented `- item` arrays or inline `[a, b]` arrays. Sufficient\n * for the small, fixed frontmatter field sets these rule files use. Throws on\n * a truly malformed line (no colon).\n *\n * NOTE — distinct from the sibling `yaml-frontmatter.ts` `parseSimpleYaml` on\n * purpose: that one parses INLINE arrays only (`key: [a, b]`), whereas rule\n * files (`.cursor/rules/*.mdc`, `.theokit/rules/*.md`) use MULTI-LINE `- item`\n * lists (`paths:` / `globs:`), which this parser adds. Unifying onto the inline\n * parser would drop multi-line list support; unifying the other way would touch\n * the skills/subagents/persistence loaders that depend on the inline one. The\n * two intentionally coexist until a shared parser handles both shapes.\n *\n * @internal\n */\n\nconst FRONTMATTER_RE = /^---\\s*\\n([\\s\\S]*?)\\n---\\s*\\n([\\s\\S]*)$/;\n\nexport interface FrontmatterSplit {\n /** Raw YAML block between the `---` fences, or undefined when absent. */\n readonly yaml: string | undefined;\n /** The markdown body after the frontmatter (or the whole content). */\n readonly body: string;\n}\n\n/**\n * Split `---`-fenced frontmatter from the body. When no frontmatter fence is\n * present, `yaml` is undefined and `body` is the whole content.\n *\n * @internal\n */\nexport function splitFrontmatter(content: string): FrontmatterSplit {\n const m = FRONTMATTER_RE.exec(content);\n if (m === null) return { yaml: undefined, body: content };\n return { yaml: m[1] ?? \"\", body: m[2] ?? \"\" };\n}\n\n/**\n * Parse the minimal YAML subset. Throws on a line without a colon (malformed).\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: YAML-subset parser handles scalars + multi-line arrays + inline arrays in a single pass; extracting helpers fragments the line-state machine.\nexport function parseSimpleYaml(yaml: string): Record<string, unknown> {\n const out: Record<string, unknown> = {};\n const lines = yaml.split(/\\r?\\n/);\n let i = 0;\n while (i < lines.length) {\n const line = lines[i];\n i += 1;\n if (line === undefined) continue;\n const trimmed = line.trim();\n if (trimmed === \"\" || trimmed.startsWith(\"#\")) continue;\n const colon = trimmed.indexOf(\":\");\n if (colon === -1) throw new Error(`Invalid YAML line: ${trimmed}`);\n const key = trimmed.slice(0, colon).trim();\n const rest = trimmed.slice(colon + 1).trim();\n if (rest === \"\") {\n // Possible array; collect indented `- item` lines.\n const items: string[] = [];\n while (i < lines.length) {\n const next = lines[i];\n if (next === undefined) break;\n const nextTrim = next.trim();\n if (nextTrim.startsWith(\"- \")) {\n items.push(parseScalar(nextTrim.slice(2).trim()) as string);\n i += 1;\n } else if (nextTrim === \"\") {\n i += 1;\n } else {\n break;\n }\n }\n out[key] = items;\n } else if (rest.startsWith(\"[\") && rest.endsWith(\"]\")) {\n // Inline array `globs: [\"**/*.ts\", \"**/*.tsx\"]`\n const inner = rest.slice(1, -1).trim();\n out[key] =\n inner === \"\"\n ? []\n : inner.split(\",\").map((s) => parseScalar(s.trim().replace(/^[\"']|[\"']$/g, \"\")));\n } else {\n out[key] = parseScalar(rest);\n }\n }\n return out;\n}\n\nfunction parseScalar(s: string): string | boolean | number {\n if (s === \"true\") return true;\n if (s === \"false\") return false;\n if (/^-?\\d+$/.test(s)) return parseInt(s, 10);\n // Strip surrounding quotes if present.\n return s.replace(/^[\"']|[\"']$/g, \"\");\n}\n","/**\n * MDC (Markdown Cursor) parser for `.cursor/rules/*.mdc` (T3.1, ADR D154).\n *\n * Parses YAML frontmatter with `description` / `globs` / `alwaysApply`\n * fields. Honors activation per Cursor's docs:\n * - `alwaysApply: true` → activates unconditionally.\n * - `alwaysApply: false` + matching glob in `touchedFiles` → activates.\n * - `alwaysApply: false` + no glob match → skipped.\n *\n * **EC-I (v1 semantic):** at `agent.send()` time, `touchedFiles` is empty\n * UNLESS the caller passes `contextPaths` (the in-scope file set). When\n * `contextPaths` is provided, per-glob activation fires; otherwise only\n * `alwaysApply: true` rules activate. Description-based \"agent requested\"\n * classification is out of scope.\n *\n * Glob matching + the YAML subset are shared with the `.theokit/rules/*.md`\n * parser via `context-glob.ts` / `context-yaml-lite.ts` (DRY, no new dep).\n *\n * @internal\n */\n\nimport { z } from \"zod\";\n\nimport { anyGlobMatches } from \"./context-glob.js\";\nimport { parseSimpleYaml, splitFrontmatter } from \"./context-yaml-lite.js\";\n\n/** YAML frontmatter schema for MDC files. @internal */\nexport const McdFrontmatterSchema = z.object({\n description: z.string().optional(),\n globs: z.array(z.string()).optional(),\n alwaysApply: z.boolean().optional(),\n});\n\nexport type McdFrontmatter = z.infer<typeof McdFrontmatterSchema>;\n\nexport interface McdParseResult {\n readonly frontmatter: McdFrontmatter;\n readonly body: string;\n}\n\n/**\n * Parse `.mdc` content. Returns frontmatter + body. EC-18: when the\n * file has no `---` frontmatter, returns `frontmatter: {alwaysApply:\n * true}` so the body is treated as an unconditional rule.\n *\n * On YAML parse error, returns `undefined` and the caller emits a\n * telemetry counter (EC-21).\n *\n * @internal\n */\nexport function parseMdc(content: string): McdParseResult | undefined {\n const { yaml, body } = splitFrontmatter(content);\n if (yaml === undefined) {\n // EC-18: no frontmatter — treat as alwaysApply\n return { frontmatter: { alwaysApply: true }, body: content };\n }\n try {\n const parsed = parseSimpleYaml(yaml);\n const validated = McdFrontmatterSchema.safeParse(parsed);\n if (!validated.success) return undefined;\n return { frontmatter: validated.data, body };\n } catch {\n return undefined;\n }\n}\n\n/**\n * Decide whether an MDC rule activates given the currently-touched\n * files. EC-I: empty `touchedFiles` → only `alwaysApply: true`\n * activates.\n *\n * @internal\n */\nexport function shouldActivate(fm: McdFrontmatter, touchedFiles: ReadonlyArray<string>): boolean {\n if (fm.alwaysApply === true) return true;\n if (fm.globs === undefined || fm.globs.length === 0) return false;\n return anyGlobMatches(fm.globs, touchedFiles);\n}\n","/**\n * Parser for `.theokit/rules/*.md` — theokit-native path-scoped rules,\n * mirroring Claude Code's `.claude/rules/`.\n *\n * Frontmatter fields:\n * - `paths` — glob-pattern array (Claude Code parity: `.claude/rules` uses `paths:`).\n * - `globs` — glob-pattern array (Cursor-compatible alias; unioned with `paths`).\n * - `alwaysApply` — activate unconditionally (no scope needed).\n * - `enabled` — set `false` to disable the rule entirely (wins over everything).\n * - `description` — human note; not used for activation in v1.\n *\n * Activation (`shouldActivateRule`):\n * - `enabled: false` → never activates.\n * - `alwaysApply: true` → always activates.\n * - otherwise → activates iff a `paths`/`globs` pattern matches an in-scope\n * file (the caller's `agent.send(..., { contextPaths })`). With no in-scope\n * files, a scoped rule stays dormant (parity with Cursor `.mdc`).\n *\n * A file with no `---` frontmatter is treated as an unconditional rule\n * (`alwaysApply: true`). Malformed YAML → `undefined` (caller drops + counts).\n *\n * Glob + YAML subset are shared with the MDC parser (DRY, no new dependency).\n *\n * @internal\n */\n\nimport { z } from \"zod\";\n\nimport { anyGlobMatches } from \"./context-glob.js\";\nimport { parseSimpleYaml, splitFrontmatter } from \"./context-yaml-lite.js\";\n\n/** YAML frontmatter schema for `.theokit/rules/*.md` files. @internal */\nexport const RulesFrontmatterSchema = z.object({\n description: z.string().optional(),\n paths: z.array(z.string()).optional(),\n globs: z.array(z.string()).optional(),\n alwaysApply: z.boolean().optional(),\n enabled: z.boolean().optional(),\n});\n\nexport type RulesFrontmatter = z.infer<typeof RulesFrontmatterSchema>;\n\nexport interface RulesParseResult {\n readonly frontmatter: RulesFrontmatter;\n readonly body: string;\n}\n\n/**\n * Parse `.theokit/rules/*.md` content into frontmatter + body. No frontmatter\n * fence → unconditional rule. Malformed YAML → `undefined`.\n *\n * @internal\n */\nexport function parseRules(content: string): RulesParseResult | undefined {\n const { yaml, body } = splitFrontmatter(content);\n if (yaml === undefined) {\n return { frontmatter: { alwaysApply: true }, body: content };\n }\n try {\n const parsed = parseSimpleYaml(yaml);\n const validated = RulesFrontmatterSchema.safeParse(parsed);\n if (!validated.success) return undefined;\n return { frontmatter: validated.data, body };\n } catch {\n return undefined;\n }\n}\n\n/**\n * Decide whether a rule activates given the in-scope files. `paths` and\n * `globs` are unioned; both are glob patterns matched against the caller's\n * declared scope.\n *\n * @internal\n */\nexport function shouldActivateRule(\n fm: RulesFrontmatter,\n inScopePaths: ReadonlyArray<string>,\n): boolean {\n if (fm.enabled === false) return false;\n if (fm.alwaysApply === true) return true;\n const patterns = [...(fm.paths ?? []), ...(fm.globs ?? [])];\n if (patterns.length === 0) return false;\n return anyGlobMatches(patterns, inScopePaths);\n}\n","/**\n * Multi-format context discovery runner (T5.1, ADRs D150-D156).\n *\n * Walks `DEFAULT_DISCOVERY_SPECS` (or caller override), loads each\n * spec via the appropriate parser, applies `@import` resolution where\n * declared, and returns a flat list of `AggregatorSource[]` ready for\n * the aggregate cap.\n *\n * **EC-E privacy fix:** source disambiguation uses\n * `relative(gitRoot ?? cwd, ...)` — NEVER absolute paths in\n * `<source name=\"\">`.\n *\n * @internal\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport { dirname, relative } from \"node:path\";\n\nimport type { AggregatorSource } from \"./context-aggregator.js\";\nimport {\n DEFAULT_DISCOVERY_SPECS,\n type DiscoverySpec,\n findGitRoot,\n walkUpForFile,\n walkUpForGlob,\n} from \"./context-discovery.js\";\nimport { resolveImports } from \"./context-import-resolver.js\";\nimport { loadPlainMarkdown } from \"./context-loaders.js\";\nimport { parseMdc, shouldActivate } from \"./context-mdc-parser.js\";\nimport { parseRules, shouldActivateRule } from \"./context-rules-frontmatter.js\";\n\nexport interface DiscoveryRunnerOptions {\n /** Workspace root passed to all discovery scopes. */\n readonly cwd: string;\n /** Per-file truncation cap (D155). */\n readonly maxBytesPerFile: number;\n /** Optional override of the default registry. */\n readonly specs?: ReadonlyArray<DiscoverySpec>;\n /** Cursor MDC: file paths the LLM has touched this turn (EC-I: empty at send-time). */\n readonly touchedFiles?: ReadonlyArray<string>;\n /** When true, skip `theokit-context` spec — caller already handles the legacy path. */\n readonly skipLegacyTheokitContext?: boolean;\n}\n\n/**\n * Run discovery + loading across all specs. Returns sources ready for\n * the aggregator (priority + content fields populated).\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: per-spec dispatch ladder + cross-spec dedup is a flat orchestrator; splitting would obscure the priority-merge invariant.\nexport async function runDiscovery(opts: DiscoveryRunnerOptions): Promise<AggregatorSource[]> {\n const gitRoot = findGitRoot(opts.cwd);\n const specs = opts.specs ?? DEFAULT_DISCOVERY_SPECS;\n const out: AggregatorSource[] = [];\n const seenReal = new Set<string>();\n\n for (const spec of specs) {\n if (opts.skipLegacyTheokitContext && spec.id === \"theokit-context\") continue;\n const paths = await resolvePathsForSpec(spec, opts.cwd, gitRoot);\n for (const path of paths) {\n if (seenReal.has(path)) continue;\n seenReal.add(path);\n const source = await loadOneSource(spec, path, opts, gitRoot);\n if (source !== undefined) out.push(source);\n }\n }\n return out;\n}\n\nasync function resolvePathsForSpec(\n spec: DiscoverySpec,\n cwd: string,\n gitRoot: string | undefined,\n): Promise<string[]> {\n if (spec.scope === \"cwd-only\") {\n return walkUpForFile(cwd, spec.pattern, cwd);\n }\n if (spec.scope === \"git-root-walk\") {\n return walkUpForFile(cwd, spec.pattern, gitRoot ?? cwd);\n }\n // globbed\n return walkUpForGlob(cwd, spec.pattern);\n}\n\nasync function loadOneSource(\n spec: DiscoverySpec,\n path: string,\n opts: DiscoveryRunnerOptions,\n gitRoot: string | undefined,\n): Promise<AggregatorSource | undefined> {\n // EC-E privacy: name uses relative-to-git-root for disambiguation;\n // NEVER absolute paths in the public `<source name=\"\">` attribute.\n // For cwd-only specs (THEO.md), no disambiguation is needed because\n // the scope can only ever match a single file.\n const relPath = relative(gitRoot ?? opts.cwd, dirname(path));\n const needsSuffix = spec.scope !== \"cwd-only\" && relPath !== \"\" && relPath !== \".\";\n const id = needsSuffix ? `${spec.id}@${relPath}` : spec.id;\n\n if (spec.parser === \"mdc\") {\n return loadMdcSource(spec, path, id, opts);\n }\n if (spec.parser === \"rules-frontmatter\") {\n return loadRulesSource(spec, path, id, opts);\n }\n if (spec.parser === \"frontmatter-zod\") {\n // Legacy `.theokit/context/*.md` — handled by `loadContextConfig` in\n // `context-manager.ts` for backward compat. We skip here unless caller\n // explicitly wants us to load it (currently always skipped).\n return undefined;\n }\n // plain-markdown\n return loadPlainMarkdownSource(spec, path, id, opts);\n}\n\n/**\n * Shared read → parse → activation-gate → source pipeline for the frontmatter\n * discovery parsers (mdc, rules). Binds the parser + the activation predicate so\n * the mdc and rules loaders differ only in those two, not in the surrounding\n * read/guard/shape boilerplate (DRY).\n */\nasync function loadParsedSource<F>(\n spec: DiscoverySpec,\n path: string,\n id: string,\n parse: (raw: string) => { frontmatter: F; body: string } | undefined,\n isActive: (frontmatter: F) => boolean,\n): Promise<AggregatorSource | undefined> {\n let raw: string;\n try {\n raw = await readFile(path, \"utf8\");\n } catch {\n return undefined;\n }\n const parsed = parse(raw);\n if (parsed === undefined || !isActive(parsed.frontmatter)) return undefined;\n return { id, source: path, content: parsed.body, priority: spec.priority, truncated: false };\n}\n\nfunction loadMdcSource(\n spec: DiscoverySpec,\n path: string,\n id: string,\n opts: DiscoveryRunnerOptions,\n): Promise<AggregatorSource | undefined> {\n return loadParsedSource(spec, path, id, parseMdc, (fm) =>\n shouldActivate(fm, opts.touchedFiles ?? []),\n );\n}\n\nfunction loadRulesSource(\n spec: DiscoverySpec,\n path: string,\n id: string,\n opts: DiscoveryRunnerOptions,\n): Promise<AggregatorSource | undefined> {\n return loadParsedSource(spec, path, id, parseRules, (fm) =>\n shouldActivateRule(fm, opts.touchedFiles ?? []),\n );\n}\n\nasync function loadPlainMarkdownSource(\n spec: DiscoverySpec,\n path: string,\n id: string,\n opts: DiscoveryRunnerOptions,\n): Promise<AggregatorSource | undefined> {\n const loaded = await loadPlainMarkdown(path, { maxBytesPerFile: opts.maxBytesPerFile });\n if (loaded === undefined) return undefined;\n let content = loaded.content;\n if (spec.followImports) {\n content = await resolveImports(content, path, {\n visited: new Set([path]),\n depth: 0,\n maxBytesPerFile: opts.maxBytesPerFile,\n });\n }\n return {\n id,\n source: path,\n content,\n priority: spec.priority,\n truncated: loaded.truncated,\n };\n}\n","/**\n * Context source frontmatter schema (ADR D76 — mirrors D10 / hooks-frontmatter).\n *\n * Used by the markdown context loader (`context/<name>.md`). Each .md file\n * represents one context source with structured frontmatter + optional\n * prose body explaining why this source is part of the agent's context.\n *\n * @internal\n */\n\nimport { z } from \"zod\";\n\nimport { ConfigurationError } from \"../../../errors.js\";\n\nexport const ContextSourceFrontmatterSchema = z.object({\n /** Identifier; defaults to filename slug if omitted. */\n name: z.string().min(1).optional(),\n /** File path relative to cwd. */\n path: z.string().min(1),\n /** Disabled sources excluded from the context snapshot. */\n enabled: z.boolean().optional().default(true),\n /** Optional per-source token budget. */\n maxTokens: z.number().int().positive().optional(),\n});\n\nexport type ContextSourceFrontmatter = z.infer<typeof ContextSourceFrontmatterSchema>;\n\n/**\n * @throws ConfigurationError(code: \"context_frontmatter_invalid\")\n * @internal\n */\nexport function parseContextSourceFrontmatter(\n fields: Record<string, unknown>,\n slug: string,\n): ContextSourceFrontmatter {\n const parsed = ContextSourceFrontmatterSchema.safeParse(fields);\n if (!parsed.success) {\n throw new ConfigurationError(\n `Invalid context source frontmatter for \"${slug}\": ${parsed.error.message}`,\n { code: \"context_frontmatter_invalid\" },\n );\n }\n return parsed.data;\n}\n","import { existsSync } from \"node:fs\";\nimport { readFile, stat } from \"node:fs/promises\";\nimport { join, resolve as resolvePath } from \"node:path\";\n\nimport { ConfigurationError } from \"../../../errors.js\";\nimport type {\n ContextBudget,\n ContextSettings,\n ContextSnapshot,\n ContextSource,\n SDKContextManager,\n} from \"../../../types/context.js\";\nimport { loadMarkdownEntities } from \"../../persistence/markdown-config-loader.js\";\nimport { warnOnce } from \"../hooks/hooks-source.js\";\nimport {\n type AggregatorSource,\n applyAggregateCap,\n DEFAULT_MAX_BYTES_TOTAL,\n} from \"./context-aggregator.js\";\nimport { runDiscovery } from \"./context-discovery-runner.js\";\nimport { ContextSourceFrontmatterSchema } from \"./context-frontmatter.js\";\nimport { DEFAULT_MAX_BYTES_PER_FILE } from \"./context-loaders.js\";\n\n/**\n * File-based context manager. Reads `.theokit/context.json` from the\n * workspace cwd when `local.settingSources` includes `\"project\"`, loads each\n * referenced source, applies excludes, and exposes a redacted public\n * snapshot via `snapshot()`. Re-reads via `refresh()`.\n *\n * Public output is secret-free by design — raw absolute paths, .env content,\n * and excluded-file content never appear.\n *\n * @internal\n */\n\ninterface FileContextConfig {\n sources: Array<{ name: string; path: string }>;\n exclude?: string[];\n maxTokens?: number;\n}\n\ninterface InternalState {\n config: FileContextConfig;\n loadedSources: Array<{\n name: string;\n path: string;\n status: ContextSource[\"status\"];\n tokens: string[];\n }>;\n}\n\nexport class FileContextManager implements SDKContextManager {\n private state: InternalState | undefined;\n /**\n * The in-scope file set used by the most recent `refresh`. Tracked so\n * `applyScope` only touches state when the scope actually changes — a\n * caller that never scopes (the common case) keeps the create-time\n * snapshot untouched, at zero per-send cost.\n */\n private lastScope: ReadonlyArray<string> = [];\n\n constructor(\n private readonly cwd: string,\n private readonly settings: ContextSettings,\n private readonly settingSourcesIncludeProject: boolean,\n ) {}\n\n async initialize(): Promise<void> {\n // `context.manager: \"file\"` is itself an opt-in for project-level context\n // loading, even when `local.settingSources` does not include \"project\".\n if (!this.settingSourcesIncludeProject && this.settings.manager !== \"file\") {\n this.state = { config: { sources: [] }, loadedSources: [] };\n return;\n }\n await this.refresh();\n }\n\n /**\n * Re-run discovery for a specific per-send in-scope file set (T3). Path-scoped\n * rules (`.theokit/rules/*.md`, `.cursor/rules/*.mdc` globs) activate iff a\n * pattern matches one of `contextPaths`. Idempotent: unchanged scope is a\n * no-op, and `undefined` scope while never previously scoped never touches\n * state (preserves the create-time snapshot for non-users).\n */\n async applyScope(contextPaths: ReadonlyArray<string> | undefined): Promise<void> {\n const scope = contextPaths ?? [];\n if (scope.length === 0 && this.lastScope.length === 0) return;\n if (sameScope(scope, this.lastScope)) return;\n await this.refresh({ touchedFiles: scope });\n }\n\n async refresh(opts?: { touchedFiles?: ReadonlyArray<string> }): Promise<void> {\n const touchedFiles = opts?.touchedFiles ?? [];\n // Defensive copy — never alias the caller's array, so a caller reusing +\n // mutating the same `contextPaths` array between sends cannot corrupt the\n // `sameScope` short-circuit in `applyScope`.\n this.lastScope = [...touchedFiles];\n const config = await loadContextConfig(this.cwd);\n const legacy = await loadSources(config, this.cwd);\n\n // Phase 5 (ADRs D150-D156): multi-format discovery for AGENTS.md,\n // CLAUDE.md, GEMINI.md, .cursor/rules/*.mdc, .theokit/THEO.md.\n // Existing `.theokit/context/*.md` legacy sources keep working via\n // the path above; we feed them into the aggregator alongside the\n // newly-discovered sources.\n const maxBytesPerFile = this.settings.maxBytesPerFile ?? DEFAULT_MAX_BYTES_PER_FILE;\n const maxBytesTotal = this.settings.maxBytesTotal ?? DEFAULT_MAX_BYTES_TOTAL;\n const discovered = await runDiscovery({\n cwd: this.cwd,\n maxBytesPerFile,\n skipLegacyTheokitContext: true,\n touchedFiles,\n });\n\n const legacyAsAggregator: AggregatorSource[] = legacy.map((src) => ({\n id: src.name,\n source: src.path,\n content: src.tokens.join(\"\"),\n priority: 50, // matches DEFAULT_DISCOVERY_SPECS theokit-context\n truncated: false,\n }));\n\n const { kept } = applyAggregateCap([...discovered, ...legacyAsAggregator], maxBytesTotal);\n\n // Materialize kept sources as InternalState entries. Public type\n // `ContextSourceStatus` uses `\"summarized\"` for \"trimmed to fit budget\".\n const loadedSources: InternalState[\"loadedSources\"] = kept.map((s) => ({\n name: s.id,\n path: s.source,\n status: s.truncated ? \"summarized\" : \"included\",\n tokens: [s.content],\n }));\n\n this.state = { config, loadedSources };\n }\n\n snapshot(): Promise<ContextSnapshot> {\n const state = this.state ?? { config: { sources: [] }, loadedSources: [] };\n const sources: ContextSource[] = state.loadedSources.map((src) => ({\n name: src.name,\n path: src.path,\n status: src.status,\n }));\n const allTokens = state.loadedSources.flatMap((src) => src.tokens);\n const budget: ContextBudget = {};\n const maxTokens = this.settings.maxTokens ?? state.config.maxTokens;\n if (maxTokens !== undefined) budget.maxTokens = maxTokens;\n budget.usedTokens = allTokens;\n return Promise.resolve({ runtime: \"local\", sources, budget });\n }\n\n /**\n * Internal-only — returns per-source token slices so the system-prompt\n * `ContextPromptProvider` can format the `<source>` body. The public\n * `snapshot()` flattens tokens across sources for the budget summary,\n * which is the wrong shape for prompt assembly.\n *\n * @internal\n */\n internalAssemblySnapshot(): {\n sources: Array<{ name: string; status: ContextSource[\"status\"]; tokens: string[] }>;\n maxTokens: number | undefined;\n } {\n const state = this.state ?? { config: { sources: [] }, loadedSources: [] };\n const maxTokens = this.settings.maxTokens ?? state.config.maxTokens;\n return {\n sources: state.loadedSources.map((src) => ({\n name: src.name,\n status: src.status,\n tokens: [...src.tokens],\n })),\n maxTokens,\n };\n }\n}\n\n/**\n * Load context config with MD-first fallback (ADR D77, T2.2).\n *\n * 1. `.theokit/context/<name>.md` (preferred).\n * 2. `.theokit/context.json` (deprecated; emits warn).\n * 3. Neither → empty sources.\n *\n * @internal\n */\nasync function loadContextConfig(cwd: string): Promise<FileContextConfig> {\n const mdDir = join(cwd, \".theokit\", \"context\");\n const jsonPath = join(cwd, \".theokit\", \"context.json\");\n\n const mdEntities = await loadMarkdownEntities({\n dir: mdDir,\n schema: ContextSourceFrontmatterSchema,\n pattern: \"flat\",\n errorCodePrefix: \"context\",\n });\n\n if (mdEntities.length > 0) {\n if (existsSync(jsonPath)) {\n warnOnce(\n \"context-both-present\",\n \"[theokit-sdk] both .theokit/context/ and .theokit/context.json detected — using markdown; remove context.json\",\n );\n }\n return {\n sources: mdEntities\n .filter((e) => e.frontmatter.enabled !== false)\n .map((e) => ({ name: e.frontmatter.name ?? e.slug, path: e.frontmatter.path })),\n };\n }\n\n // Fallback: JSON\n if (!existsSync(jsonPath)) return { sources: [] };\n\n warnOnce(\n \"context-json-deprecated\",\n \"[theokit-sdk] .theokit/context.json is deprecated; migrate to .theokit/context/<name>.md via theokit-migrate-config\",\n );\n\n let raw: string;\n try {\n raw = await readFile(jsonPath, \"utf8\");\n } catch (cause) {\n throw new ConfigurationError(`Failed to read context config: ${jsonPath}`, {\n code: \"context_read_error\",\n cause,\n });\n }\n return parseConfig(raw, jsonPath);\n}\n\nfunction parseConfig(raw: string, configPath: string): FileContextConfig {\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (cause) {\n throw new ConfigurationError(`Invalid JSON in context config: ${configPath}`, {\n code: \"context_json_invalid\",\n cause,\n });\n }\n if (!parsed || typeof parsed !== \"object\") {\n throw new ConfigurationError(`Context config must be an object: ${configPath}`, {\n code: \"context_config_shape\",\n });\n }\n const record = parsed as Record<string, unknown>;\n const sources = readSources(record.sources, configPath);\n const exclude = Array.isArray(record.exclude)\n ? record.exclude.filter((entry): entry is string => typeof entry === \"string\")\n : undefined;\n const maxTokens = typeof record.maxTokens === \"number\" ? record.maxTokens : undefined;\n const result: FileContextConfig = { sources };\n if (exclude !== undefined) result.exclude = exclude;\n if (maxTokens !== undefined) result.maxTokens = maxTokens;\n return result;\n}\n\nfunction readSources(\n sourcesRaw: unknown,\n configPath: string,\n): Array<{ name: string; path: string }> {\n if (!Array.isArray(sourcesRaw)) {\n throw new ConfigurationError(`Context config sources must be an array: ${configPath}`, {\n code: \"context_sources_shape\",\n });\n }\n return sourcesRaw\n .filter(\n (entry): entry is Record<string, unknown> => Boolean(entry) && typeof entry === \"object\",\n )\n .map((entry) => {\n const name = typeof entry.name === \"string\" ? entry.name : \"\";\n const path = typeof entry.path === \"string\" ? entry.path : \"\";\n return { name, path };\n })\n .filter((entry) => entry.name.length > 0 && entry.path.length > 0);\n}\n\nasync function loadSources(\n config: FileContextConfig,\n cwd: string,\n): Promise<InternalState[\"loadedSources\"]> {\n const results: InternalState[\"loadedSources\"] = [];\n for (const source of config.sources) {\n if (isExcluded(source.path, config.exclude)) {\n results.push({ ...source, status: \"excluded\", tokens: [] });\n continue;\n }\n const absolute = resolvePath(cwd, source.path);\n if (!absolute.startsWith(resolvePath(cwd))) {\n results.push({ ...source, status: \"excluded\", tokens: [] });\n continue;\n }\n try {\n await stat(absolute);\n const content = await readFile(absolute, \"utf8\");\n const tokens = tokenizeContent(content);\n results.push({ ...source, status: \"included\", tokens });\n } catch {\n results.push({ ...source, status: \"excluded\", tokens: [] });\n }\n }\n return results;\n}\n\nfunction isExcluded(path: string, excludes: string[] | undefined): boolean {\n if (excludes === undefined) return false;\n return excludes.some((pattern) => matchesGlob(pattern, path));\n}\n\nfunction matchesGlob(pattern: string, path: string): boolean {\n // Simple glob: \"**/.env\" → path ends with \".env\"; \"**/secrets/**\" → contains \"/secrets/\"\n if (pattern === path) return true;\n if (pattern.startsWith(\"**/\") && pattern.endsWith(\"/**\")) {\n const middle = pattern.slice(3, -3);\n return path.includes(middle);\n }\n if (pattern.startsWith(\"**/\")) {\n return path.endsWith(pattern.slice(3));\n }\n if (pattern.endsWith(\"/**\")) {\n return path.startsWith(pattern.slice(0, -3));\n }\n return false;\n}\n\nfunction tokenizeContent(content: string): string[] {\n return content.split(/\\s+/).filter((token) => token.length > 0);\n}\n\nfunction sameScope(a: ReadonlyArray<string>, b: ReadonlyArray<string>): boolean {\n if (a.length !== b.length) return false;\n return a.every((v, i) => v === b[i]);\n}\n","/**\n * Plugin manifest frontmatter schema (ADR D76).\n *\n * Used by the markdown plugin loader (`plugins/<name>/PLUGIN.md`). Matches\n * the legacy `plugin.json` shape consumed by `plugins-manager.ts`:\n * `{ name, version, capabilities, entry }`. Frontmatter is flat — no\n * nested provider object (parseSimpleYaml doesn't support nesting).\n *\n * @internal\n */\n\nimport { z } from \"zod\";\n\nimport { ConfigurationError } from \"../../../errors.js\";\n\nexport const PluginFrontmatterSchema = z.object({\n /** Plugin identifier; defaults to folder name if omitted. */\n name: z.string().min(1).optional(),\n /** SemVer string; defaults to \"0.0.0\" if omitted. */\n version: z.string().optional(),\n /** What this plugin provides. */\n capabilities: z.array(z.string()).optional(),\n /** Relative path to the JS entry file within the plugin folder. */\n entry: z.string().min(1).optional(),\n});\n\nexport type PluginFrontmatter = z.infer<typeof PluginFrontmatterSchema>;\n\n/**\n * @throws ConfigurationError(code: \"plugin_frontmatter_invalid\")\n * @internal\n */\nexport function parsePluginFrontmatter(\n fields: Record<string, unknown>,\n slug: string,\n): PluginFrontmatter {\n const parsed = PluginFrontmatterSchema.safeParse(fields);\n if (!parsed.success) {\n throw new ConfigurationError(\n `Invalid plugin frontmatter for \"${slug}\": ${parsed.error.message}`,\n { code: \"plugin_frontmatter_invalid\" },\n );\n }\n return parsed.data;\n}\n","import { existsSync } from \"node:fs\";\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { ConfigurationError } from \"../../../errors.js\";\nimport { loadMarkdownEntities } from \"../../persistence/markdown-config-loader.js\";\nimport { safePathJoin } from \"../../security/path-guard.js\";\nimport { readWorkspaceDir } from \"../config/workspace-dir.js\";\nimport { warnOnce } from \"../hooks/hooks-source.js\";\nimport { type PluginFrontmatter, PluginFrontmatterSchema } from \"./plugin-frontmatter.js\";\n\n/**\n * Plugin manifest exposed via `agent.plugins.list()`. Includes provenance\n * (source path) so callers can audit where the plugin came from.\n *\n * @internal\n */\nexport interface PluginMetadata {\n name: string;\n version: string;\n capabilities: string[];\n source: string;\n /** Relative path to JS entry within the plugin folder. Validated against\n * path traversal at assertEntryFileExists time (EC-1 fix). */\n entry?: string;\n}\n\n/**\n * File-based plugin loader. Discovers `.theokit/plugins/*\\/plugin.json`\n * manifests when `local.settingSources` includes `\"plugins\"`.\n *\n * @internal\n */\nexport class PluginsManager {\n private plugins: PluginMetadata[] = [];\n\n constructor(\n private readonly cwd: string,\n private readonly enabled: string[] | undefined,\n private readonly settingSourcesIncludePlugins: boolean,\n private readonly cloud: boolean,\n private readonly localPaths: string[] | undefined,\n ) {}\n\n async initialize(): Promise<void> {\n this.assertCloudRules();\n if (!this.settingSourcesIncludePlugins) {\n this.plugins = [];\n return;\n }\n await this.refresh();\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: MD-first + JSON fallback + both-present detection per plugin folder — branch table is clearer inlined.\n async refresh(): Promise<void> {\n this.plugins = [];\n const pluginsRoot = join(this.cwd, \".theokit\", \"plugins\");\n const entries = await readWorkspaceDir(pluginsRoot, \"plugins_read_error\", \"plugins directory\");\n for (const entry of entries) {\n if (!entry.isDirectory()) continue;\n const folderName = entry.name;\n // ADR D77: prefer PLUGIN.md; fall back to plugin.json with deprecation warn.\n const mdPath = join(pluginsRoot, folderName, \"PLUGIN.md\");\n const jsonPath = join(pluginsRoot, folderName, \"plugin.json\");\n const metadata = existsSync(mdPath)\n ? await loadPluginManifestFromMarkdown(pluginsRoot, folderName)\n : await loadPluginManifestFromJson(jsonPath, folderName);\n if (existsSync(mdPath) && existsSync(jsonPath)) {\n warnOnce(\n `plugin-${folderName}-both`,\n `[theokit-sdk] both ${folderName}/PLUGIN.md and ${folderName}/plugin.json detected — using markdown; remove plugin.json`,\n );\n }\n if (!existsSync(mdPath) && existsSync(jsonPath)) {\n warnOnce(\n \"plugin-json-deprecated\",\n \"[theokit-sdk] plugin.json manifests are deprecated; migrate to PLUGIN.md via theokit-migrate-config\",\n );\n }\n if (this.enabled === undefined || this.enabled.includes(metadata.name)) {\n await this.assertEntryFileExists(metadata, folderName);\n this.plugins.push(metadata);\n }\n }\n }\n\n list(): Promise<PluginMetadata[]> {\n return Promise.resolve(this.plugins);\n }\n\n private async assertEntryFileExists(metadata: PluginMetadata, folderName: string): Promise<void> {\n const entry = metadata.entry;\n if (entry === undefined) return;\n // ADRs D79-D80 (path-guard): safePathJoin resolves THEN prefix-checks,\n // catching both literal \"..\" and normalized escape (e.g. \"subdir/../../etc\").\n // Replaces the inline T3.2 markdown-config-migration guard that only handled\n // the literal cases. PathTraversalError extends ConfigurationError (code:\n // \"path_traversal\") so consumers catching ConfigurationError still see it.\n const pluginRoot = join(this.cwd, \".theokit\", \"plugins\", folderName);\n const entryPath = safePathJoin(pluginRoot, entry);\n try {\n await readFile(entryPath, \"utf8\");\n } catch (cause) {\n throw new ConfigurationError(`Plugin ${metadata.name} entry file is missing: ${entry}`, {\n code: \"plugin_entry_missing\",\n cause,\n });\n }\n }\n\n private assertCloudRules(): void {\n if (!this.cloud) return;\n if (this.localPaths !== undefined && this.localPaths.length > 0) {\n throw new ConfigurationError(\n \"Cloud agents reject local plugin paths — plugins must come from committed repo files\",\n { code: \"cloud_plugin_path_rejected\" },\n );\n }\n }\n}\n\nasync function loadPluginManifestFromJson(\n manifestPath: string,\n folderName: string,\n): Promise<PluginMetadata> {\n let raw: string;\n try {\n raw = await readFile(manifestPath, \"utf8\");\n } catch (cause) {\n throw new ConfigurationError(`Plugin ${folderName} is missing plugin.json`, {\n code: \"plugin_missing_manifest\",\n cause,\n });\n }\n let parsed: unknown;\n try {\n parsed = JSON.parse(raw);\n } catch (cause) {\n throw new ConfigurationError(`Plugin ${folderName} manifest is invalid JSON`, {\n code: \"plugin_manifest_invalid\",\n cause,\n });\n }\n if (!parsed || typeof parsed !== \"object\") {\n throw new ConfigurationError(`Plugin ${folderName} manifest must be an object`, {\n code: \"plugin_manifest_shape\",\n });\n }\n const record = parsed as Record<string, unknown>;\n const name = typeof record.name === \"string\" ? record.name : folderName;\n const version = typeof record.version === \"string\" ? record.version : \"0.0.0\";\n const capabilities = Array.isArray(record.capabilities)\n ? record.capabilities.filter((cap): cap is string => typeof cap === \"string\")\n : [];\n const source = manifestPath.slice(manifestPath.indexOf(\".theokit/\"));\n const metadata: PluginMetadata = { name, version, capabilities, source };\n if (typeof record.entry === \"string\") metadata.entry = record.entry;\n return metadata;\n}\n\n/** Load PLUGIN.md from a plugin folder via shared markdown-config-loader. */\nasync function loadPluginManifestFromMarkdown(\n pluginsRoot: string,\n folderName: string,\n): Promise<PluginMetadata> {\n // Use nested loader at the granularity of ONE folder by passing a tmp dir\n // expectation; simpler: read the single PLUGIN.md directly.\n const mdPath = join(pluginsRoot, folderName, \"PLUGIN.md\");\n let raw: string;\n try {\n raw = await readFile(mdPath, \"utf8\");\n } catch (cause) {\n throw new ConfigurationError(`Plugin ${folderName} is missing PLUGIN.md`, {\n code: \"plugin_missing_manifest\",\n cause,\n });\n }\n // Reuse the loader's split via a single-entity wrapper.\n const fakeDir = join(pluginsRoot, folderName);\n const entities = await loadMarkdownEntities({\n dir: fakeDir,\n schema: PluginFrontmatterSchema,\n pattern: \"flat\", // read all .md in folder; PLUGIN.md is the canonical name\n errorCodePrefix: \"plugin\",\n });\n const entity = entities.find((e) => e.slug === \"PLUGIN\");\n if (entity === undefined) {\n throw new ConfigurationError(`Plugin ${folderName} PLUGIN.md not parseable`, {\n code: \"plugin_missing_manifest\",\n });\n }\n const fm: PluginFrontmatter = entity.frontmatter;\n const source = mdPath.slice(mdPath.indexOf(\".theokit/\"));\n const metadata: PluginMetadata = {\n name: fm.name ?? folderName,\n version: fm.version ?? \"0.0.0\",\n capabilities: fm.capabilities ?? [],\n source,\n };\n if (fm.entry !== undefined) metadata.entry = fm.entry;\n // raw used to surface parse errors for legacy compat with tests that\n // expect the file is actually read; intentionally side-effect-free.\n void raw;\n return metadata;\n}\n","/**\n * `LocalAgent` constructor bootstrap helpers (extracted for G8 ≤400 LoC).\n *\n * Each helper builds one optional submanager from `AgentOptions` and\n * the resolved workspace cwd. The constructor itself stays focused on\n * the agentId / model wiring; submanager bootstrap is delegated here.\n *\n * @internal\n */\n\nimport type { AgentOptions, ModelSelection } from \"../../types/agent.js\";\nimport { asPluginsSettings, enabledPluginNames } from \"../plugins/enabled-names.js\";\nimport { ProvidersManagerImpl } from \"../runtime/config/providers-manager.js\";\nimport { FileContextManager } from \"../runtime/context/context-manager.js\";\nimport { normalizeModel } from \"../runtime/model-selection.js\";\nimport { type PluginMetadata, PluginsManager } from \"../runtime/plugins/plugins-manager.js\";\nimport { registerAgent } from \"../runtime/registry/agent-registry.js\";\nimport { type SkillsHandle, SkillsManager } from \"../runtime/skills/skills-manager.js\";\n\nexport function registerLocalAgent(args: {\n agentId: string;\n model: ModelSelection | undefined;\n options: AgentOptions;\n workspaceCwd: string;\n}): void {\n registerAgent({\n agentId: args.agentId,\n runtime: \"local\",\n name: args.options.name,\n summary: \"Local contract fixture\",\n model: args.model,\n createdAt: Date.now(),\n lastModified: Date.now(),\n archived: false,\n options: args.options,\n cwd: args.workspaceCwd,\n status: \"finished\",\n });\n}\n\nexport interface BootstrappedSubmanagers {\n context?: FileContextManager;\n providers?: ProvidersManagerImpl;\n skillsManager?: SkillsManager;\n skills?: SkillsHandle;\n pluginsManager?: PluginsManager;\n plugins?: { list: () => Promise<PluginMetadata[]> };\n}\n\nexport function bootstrapSubmanagers(args: {\n options: AgentOptions;\n workspaceCwd: string;\n settingSourcesIncludeProject: boolean;\n settingSourcesIncludePlugins: boolean;\n}): BootstrappedSubmanagers {\n const out: BootstrappedSubmanagers = {};\n if (args.options.context !== undefined) {\n out.context = new FileContextManager(\n args.workspaceCwd,\n args.options.context,\n args.settingSourcesIncludeProject,\n );\n }\n const providerCount =\n (args.options.providers?.routes?.length ?? 0) + enabledPluginNames(args.options.plugins).length;\n if (providerCount > 0 || args.options.providers !== undefined) {\n out.providers = new ProvidersManagerImpl(\n normalizeModel(args.options.model),\n args.options.providers,\n args.options.plugins,\n );\n }\n if (args.options.skills !== undefined || args.settingSourcesIncludeProject) {\n // SE22 — a SkillsResolver resolves per-send; the create-time (base) manager\n // that backs `agent.skills` is built from the STATIC config only.\n const staticSkills =\n typeof args.options.skills === \"function\" ? undefined : args.options.skills;\n out.skillsManager = new SkillsManager(\n args.workspaceCwd,\n staticSkills?.enabled,\n args.settingSourcesIncludeProject,\n // M22 — custom skills directory + inline (code-defined) skills.\n staticSkills?.skillsDir,\n staticSkills?.inline,\n );\n const localSkills = out.skillsManager;\n out.skills = {\n // Project to the public shape (name + description only). Inline skills carry\n // their body + references on the object; `list()` must never leak them —\n // the body is reachable exclusively through `get()`.\n list: async () =>\n (await localSkills.list()).map((s) => ({ name: s.name, description: s.description })),\n get: (name) => localSkills.get(name),\n };\n }\n if (args.options.plugins !== undefined || args.settingSourcesIncludePlugins) {\n out.pluginsManager = new PluginsManager(\n args.workspaceCwd,\n // The array (code-`Plugin`) form has no named-enable list; `undefined`\n // here preserves \"no filter / load all file-discovered plugins\".\n asPluginsSettings(args.options.plugins)?.enabled,\n args.settingSourcesIncludePlugins,\n false,\n undefined,\n );\n const localPlugins = out.pluginsManager;\n out.plugins = { list: () => localPlugins.list() };\n }\n return out;\n}\n","import type { Run } from \"../../../types/run.js\";\n\n/**\n * Process-wide run registry indexed by run id. Lets `Agent.listRuns()` and\n * `Agent.getRun()` return the exact Run instances created by previous sends.\n *\n * @internal\n */\n\nconst runs = new Map<string, Run>();\nconst runsByAgent = new Map<string, string[]>();\n\nexport function registerRun(run: Run): void {\n runs.set(run.id, run);\n const existing = runsByAgent.get(run.agentId) ?? [];\n if (!existing.includes(run.id)) existing.push(run.id);\n runsByAgent.set(run.agentId, existing);\n}\n\nexport function getRun(runId: string): Run | undefined {\n return runs.get(runId);\n}\n\nexport function listRunsByAgent(agentId: string): Run[] {\n const ids = runsByAgent.get(agentId) ?? [];\n return ids.map((id) => runs.get(id)).filter((run): run is Run => run !== undefined);\n}\n","import type { AgentDefinition, AgentOptions, ModelSelection } from \"../../types/agent.js\";\nimport type { Run, RunOperation, RunStatus, SDKUserMessage, SendOptions } from \"../../types/run.js\";\nimport { DEFAULT_AGENTIC_MODEL_ID } from \"../runtime/config/default-model.js\";\nimport { buildFixtureScript } from \"../runtime/fixtures/fixture-responder.js\";\nimport { FixtureRunBase, prepareRunContext } from \"../runtime/fixtures/fixture-run-base.js\";\nimport type { MemoryFact } from \"../runtime/memory/memory-store.js\";\nimport { registerRun } from \"../runtime/registry/run-registry.js\";\nimport type { SessionMessage } from \"../session/index.js\";\n\n/**\n * Options accepted by `createLocalRun()`.\n *\n * @internal\n */\nexport interface CreateLocalRunOptions {\n agentId: string;\n model: ModelSelection | undefined;\n message: string | SDKUserMessage;\n agentOptions: AgentOptions;\n sendOptions: SendOptions;\n workspaceCwd: string;\n subagents: Record<string, AgentDefinition>;\n settingSourcesIncludeProject: boolean;\n memoryFacts: MemoryFact[];\n sessionMessages: SessionMessage[];\n projectMcpServers: Record<string, unknown>;\n persistMemoryFact?: (fact: MemoryFact) => Promise<void>;\n /**\n * Accepted for API parity with the real runtime; the fixture responder is\n * deterministic and does not feed the prompt into its scripts.\n */\n systemPrompt?: string;\n}\n\n/**\n * Build a local Run handle backed by the in-process fixture responder.\n *\n * @internal\n */\nexport function createLocalRun(options: CreateLocalRunOptions): Run {\n const { userText, id, startTime } = prepareRunContext(options.message);\n const supported = new Set<RunOperation>([\"stream\", \"wait\", \"cancel\", \"conversation\"]);\n\n const script = buildFixtureScript({\n agentId: options.agentId,\n runId: id,\n model: options.model ?? { id: DEFAULT_AGENTIC_MODEL_ID },\n userMessage: userText,\n runtime: \"local\",\n agentOptions: options.agentOptions,\n sendOptions: options.sendOptions,\n workspaceCwd: options.workspaceCwd,\n subagents: options.subagents,\n settingSourcesIncludeProject: options.settingSourcesIncludeProject,\n memoryFacts: options.memoryFacts,\n sessionMessages: options.sessionMessages,\n projectMcpServers: options.projectMcpServers,\n ...(options.persistMemoryFact !== undefined\n ? { persistMemoryFact: options.persistMemoryFact }\n : {}),\n });\n\n // SE3 — capture the turn's provenance so `buildResult` forwards it onto RunResult.origin.\n if (options.sendOptions.origin !== undefined) script.origin = options.sendOptions.origin;\n\n const handle = new LocalRun({\n id,\n agentId: options.agentId,\n model: options.model,\n script,\n supportedOps: supported,\n startTime,\n });\n handle.bootstrap();\n registerRun(handle);\n return handle;\n}\n\nclass LocalRun extends FixtureRunBase {\n bootstrap(): void {\n if (this.script.cancellable) return;\n setTimeout(() => {\n void this.completeNaturally();\n }, 0);\n }\n\n protected override notifyImmediately(): boolean {\n // Local agents emit the \"running\" state synchronously to subscribers;\n // tests rely on observing the transition even when added pre-completion.\n return true;\n }\n\n private async completeNaturally(): Promise<void> {\n if (this.terminated) return;\n const beforeOk = await this.runBeforeComplete();\n if (!beforeOk) return;\n this.transitionTo(this.script.finalStatus);\n }\n\n /** Runs the optional beforeComplete hook. Returns false iff it failed and the run transitioned to error. */\n private async runBeforeComplete(): Promise<boolean> {\n if (this.script.beforeComplete === undefined) return true;\n try {\n await this.script.beforeComplete();\n return true;\n } catch (cause) {\n // Capture the beforeComplete failure on the script so the wait()\n // caller sees `result.error.message` instead of an opaque status.\n if (this.script.errorDetail === undefined) {\n const message = cause instanceof Error ? cause.message : String(cause);\n this.script.errorDetail = { message, code: \"before_complete_failed\", cause };\n }\n this.transitionTo(\"error\" satisfies RunStatus);\n return false;\n }\n }\n}\n","/**\n * Iteration budget for the agent loop (T2.1, ADRs D90-D91).\n *\n * Tracks remaining iterations + compression attempts + grace-call usage.\n * Caps prevent the 4 compression death spirals Hermes shipped:\n * - v0.4 #1723: `compression_attempts` never reset\n * - v0.7 #4750: compression triggers → fails → triggers again\n * - v0.11 #10065: stale agent timeout, empty response after tools\n * - v0.11 #10472: empty-tools after tools, premature loop exit\n *\n * Default: max 8 iterations, max 3 compressions per session, 1 grace call.\n *\n * NOTE on caller-supplied huge maxIterations (EC-12): `Number.MAX_SAFE_INTEGER`\n * is honored — caller is responsible for picking a reasonable cap. Recommended\n * ≤32 for production workloads.\n *\n * NOTE on per-send reset (EC-14): each `Agent.send` should construct a fresh\n * `IterationBudget`. This is intentional — every send is its own iteration\n * round, not a long-running budget shared across sends.\n *\n * @internal\n */\n\nexport class IterationBudgetExhaustedError extends Error {\n override readonly name: string = \"IterationBudgetExhaustedError\";\n}\n\nexport class CompressionExhaustedError extends Error {\n override readonly name: string = \"CompressionExhaustedError\";\n}\n\nexport class CompressionIneffectiveError extends Error {\n override readonly name: string = \"CompressionIneffectiveError\";\n}\n\nexport interface IterationBudgetOptions {\n /** Total iterations before grace call. Default 8. */\n maxIterations?: number;\n /** Max compression attempts per session (D91). Default 3. */\n maxCompressions?: number;\n /** When true (default), one final iteration is allowed after budget exhausted. */\n allowGraceCall?: boolean;\n}\n\n/**\n * Stateful budget tracker. Encapsulates state per ADR D90 — class is the\n * canonical home so leak across sessions is impossible (vs POJO that Hermes\n * #1723 shipped as a bug).\n *\n * @internal\n */\nexport class IterationBudget {\n #remaining: number;\n readonly #total: number;\n #compressionAttempts = 0;\n #graceCallUsed = false;\n readonly #maxCompressions: number;\n readonly #allowGrace: boolean;\n\n constructor(opts: IterationBudgetOptions = {}) {\n this.#total = opts.maxIterations ?? 8;\n this.#remaining = this.#total;\n this.#maxCompressions = opts.maxCompressions ?? 3;\n this.#allowGrace = opts.allowGraceCall ?? true;\n }\n\n get remaining(): number {\n return this.#remaining;\n }\n\n get total(): number {\n return this.#total;\n }\n\n get compressionAttempts(): number {\n return this.#compressionAttempts;\n }\n\n get graceCallUsed(): boolean {\n return this.#graceCallUsed;\n }\n\n /**\n * Decrement remaining by `amount` (default 1). EC-4 fix: NaN / negative\n * / non-finite values are treated as 0 (no-op) to prevent state corruption.\n */\n consume(amount = 1): void {\n if (!Number.isFinite(amount) || amount <= 0) return;\n this.#remaining = Math.max(0, this.#remaining - amount);\n }\n\n /**\n * Record a compression attempt. Returns `{ allowed: false, reason }` if\n * cap reached — caller MUST honor and abort compression.\n */\n recordCompression(): { allowed: boolean; reason?: string } {\n if (this.#compressionAttempts >= this.#maxCompressions) {\n return {\n allowed: false,\n reason: `compression cap reached (${this.#maxCompressions} per session)`,\n };\n }\n this.#compressionAttempts += 1;\n return { allowed: true };\n }\n\n /**\n * True iff the loop should run another iteration:\n * - remaining > 0, OR\n * - grace not yet used AND grace allowed.\n */\n shouldContinue(): boolean {\n if (this.#remaining > 0) return true;\n if (this.#allowGrace && !this.#graceCallUsed) return true;\n return false;\n }\n\n /**\n * Mark grace call as used. Idempotent — calling more than once is no-op.\n * Caller invokes when `remaining === 0` and takes the last shot.\n */\n useGraceCall(): void {\n this.#graceCallUsed = true;\n }\n}\n","/**\n * Validate-response helpers (T2.2, ADR D93).\n *\n * Detects empty-content + zero-toolCalls as a model-bailout signal. Weak\n * models (Gemini Flash, Mistral 7B) sometimes return content: \"\" with no\n * tool calls after a tool result; without detection, the loop would keep\n * spinning, inflating context and breaking prompt cache.\n *\n * NOTE on content type guarantee (EC-13): caller is responsible for\n * passing a string `content` (providers that return `{ text: \"...\" }` are\n * normalized in `internal/llm/*.ts`).\n *\n * @internal\n */\n\nexport interface ResponseValidation {\n ok: boolean;\n reason?: string;\n}\n\nexport interface AssistantResponseShape {\n content: string;\n toolCalls: readonly unknown[];\n}\n\n/**\n * `{ ok: false }` when content is empty/whitespace AND toolCalls is empty.\n * Caller should consume an iteration budget unit and inject a nudge\n * user-message (\"continue or end with a final answer\").\n *\n * @internal\n */\nexport function validateResponse(response: AssistantResponseShape): ResponseValidation {\n const trimmed = response.content.trim();\n const toolCallsArr = Array.isArray(response.toolCalls) ? response.toolCalls : [];\n if (trimmed === \"\" && toolCallsArr.length === 0) {\n return {\n ok: false,\n reason: \"empty response with no tool calls (model bailout)\",\n };\n }\n return { ok: true };\n}\n","import type { BudgetCheck, BudgetTracker } from \"../budget/tracker/budget-tracker.js\";\n\n/**\n * Pre-flight budget gate evaluated before each agent-loop iteration.\n *\n * The {@link BudgetTracker} contract says `check()` RETURNS a decision and\n * does not throw. A budget gate is a cost/safety control, so if a tracker\n * violates that contract by throwing, the loop MUST fail CLOSED (deny the\n * next iteration) rather than fail OPEN (silently proceed past budget).\n * This was the architecture-review L1 finding: the previous inline\n * `catch { decision = { allowed: true } }` let a broken tracker run forever.\n *\n * @internal\n */\nexport function evaluateBudgetGate(tracker: BudgetTracker | undefined): BudgetCheck {\n if (tracker === undefined) return { allowed: true };\n try {\n return tracker.check();\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n // Fail-closed: a budget guard that cannot evaluate denies the iteration.\n return {\n allowed: false,\n reason: \"custom\",\n detail: `budget_tracker_check_threw: ${message}`,\n };\n }\n}\n","/**\n * Doom-loop guard — detects consecutive IDENTICAL tool calls (same name + same canonical input)\n * and escalates `ok` → `soft` (one-time nudge) → `hard` (stop). Inspection is TOTAL — `signatureOf`\n * and `inspect` never throw on any tool-call input. The constructor validates thresholds and throws\n * a typed `ConfigurationError` on invalid config (fail-fast at the boundary — a 0/negative/non-integer\n * threshold is a caller bug, not a loop input). Ported in shape from a peer `LoopDetectionTracker`.\n * Complements the empty-round `no_progress` terminal (a DIFFERENT failure mode: model stuck repeating\n * vs model gone silent).\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\n\n/** Verdict from {@link DoomLoopTracker.inspect}. `soft` carries a guidance message, `hard` a stop message. */\nexport interface DoomLoopVerdict {\n kind: \"ok\" | \"soft\" | \"hard\";\n message?: string;\n}\n\n/** Consecutive-identical thresholds. `soft` fires once (at exactly the count); `hard` stops. */\nexport interface DoomLoopConfig {\n softThreshold: number;\n hardThreshold: number;\n}\n\n/** Public config on a send: `false` disables the guard; an object tunes the thresholds; absent = on. */\nexport type DoomLoopOption = false | Partial<DoomLoopConfig>;\n\n/** Resolve the per-send config to a tracker instance (default ON) or `undefined` when disabled. @internal */\nexport function createDoomLoopTracker(option?: DoomLoopOption): DoomLoopTracker | undefined {\n if (option === false) return undefined;\n return new DoomLoopTracker(option);\n}\n\nconst DEFAULT_CONFIG: DoomLoopConfig = { softThreshold: 3, hardThreshold: 5 };\n\n/** Fail-fast on caller misconfig: both thresholds must be positive integers. A `0` / negative /\n * non-integer would silently misbehave (stop on turn 1, or never fire). `soft >= hard` is NOT\n * rejected — it is a valid \"stop hard with no earlier nudge\" config (hard is checked first, so it\n * just wins and the nudge is suppressed), which also keeps `{ hardThreshold: N }` ergonomic. @internal */\nfunction assertValidThresholds(soft: number, hard: number): void {\n for (const [label, value] of [\n [\"softThreshold\", soft],\n [\"hardThreshold\", hard],\n ] as const) {\n if (!Number.isInteger(value) || value < 1) {\n throw new ConfigurationError(\n `doomLoop.${label} must be a positive integer (received ${value}).`,\n { code: \"invalid_doom_loop_threshold\" },\n );\n }\n }\n}\n\n/** Recursively key-sort an object so `{a,b}` and `{b,a}` canonicalize identically. */\nfunction sortKeys(value: unknown): unknown {\n if (value === null || typeof value !== \"object\") return value;\n if (Array.isArray(value)) return value.map(sortKeys);\n const out: Record<string, unknown> = {};\n for (const key of Object.keys(value as Record<string, unknown>).sort()) {\n out[key] = sortKeys((value as Record<string, unknown>)[key]);\n }\n return out;\n}\n\n/** Canonical identity of a tool call: `name` + NUL delimiter + key-sorted JSON of `input`.\n * The `\\u0000` delimiter is collision-proof (it cannot occur in a tool name), so\n * `{name:\"a b\", input:\"c\"}` and `{name:\"a\", input:\"b c\"}` never alias. Order-insensitive and\n * total (circular / non-serializable input falls back to `String()`, never throws). @internal */\nexport function signatureOf(call: { name: string; input: unknown }): string {\n const { input } = call;\n let inputSig: string;\n if (input === null || input === undefined) inputSig = \"null\";\n else if (typeof input !== \"object\") inputSig = String(input);\n else {\n try {\n inputSig = JSON.stringify(sortKeys(input)) ?? \"null\";\n } catch {\n inputSig = String(input);\n }\n }\n return `${call.name}\\u0000${inputSig}`;\n}\n\n/** Per-run detector of consecutive identical tool calls. Owned by one agent-loop run, inspected\n * sequentially per turn (no shared state across concurrent runs). @internal */\nexport class DoomLoopTracker {\n readonly #config: DoomLoopConfig;\n #lastSignature = \"\";\n #count = 0;\n\n constructor(config?: Partial<DoomLoopConfig>) {\n const softThreshold = config?.softThreshold ?? DEFAULT_CONFIG.softThreshold;\n const hardThreshold = config?.hardThreshold ?? DEFAULT_CONFIG.hardThreshold;\n assertValidThresholds(softThreshold, hardThreshold);\n this.#config = { softThreshold, hardThreshold };\n }\n\n inspect(call: { name: string; input: unknown }): DoomLoopVerdict {\n const signature = signatureOf(call);\n this.#count = signature === this.#lastSignature ? this.#count + 1 : 1;\n this.#lastSignature = signature;\n const count = this.#count;\n if (count >= this.#config.hardThreshold) {\n return {\n kind: \"hard\",\n message: `Detected ${count} consecutive identical calls to \\`${call.name}\\`; stopping to avoid a loop.`,\n };\n }\n // `soft` fires ONLY at ==softThreshold (not `>=`) so the nudge cannot spam between soft/hard (EC-1).\n if (count === this.#config.softThreshold) {\n return {\n kind: \"soft\",\n message: `Detected ${count} consecutive identical calls to \\`${call.name}\\`; try a different approach.`,\n };\n }\n return { kind: \"ok\" };\n }\n\n reset(): void {\n this.#lastSignature = \"\";\n this.#count = 0;\n }\n}\n\n/**\n * Inspect a turn's tool calls in order, returning the FIRST non-`ok` verdict (a `hard` stop wins\n * over a `soft` nudge encountered earlier in the same turn). Every call advances the tracker, so a\n * turn emitting the same call twice counts as two. Pure over the tracker's state; never throws.\n * @internal\n */\nexport function firstDoomLoopVerdict(\n tracker: DoomLoopTracker,\n calls: readonly { name: string; input: unknown }[],\n): DoomLoopVerdict {\n let escalation: DoomLoopVerdict = { kind: \"ok\" };\n for (const call of calls) {\n const v = tracker.inspect(call);\n if (v.kind === \"hard\") return v;\n if (v.kind === \"soft\" && escalation.kind === \"ok\") escalation = v;\n }\n return escalation;\n}\n","/**\n * UsageAccumulator — aggregate multi-step `LlmFinish` token counts\n * into a canonical `TokenUsage` (ADR D376, mirror a peer SDK\n * `Usage.add`).\n *\n * Each `add(step)` merges in a per-step finish; `toTokenUsage()`\n * produces the aggregated public shape with `requests[]` populated\n * when there were ≥2 steps.\n *\n * @internal\n */\n\nimport type { TokenUsage } from \"../../types/usage.js\";\n\ninterface StepUsage {\n inputTokens?: number;\n outputTokens?: number;\n cacheReadTokens?: number;\n cacheWriteTokens?: number;\n reasoningTokens?: number;\n}\n\nexport class UsageAccumulator {\n private input = 0;\n private output = 0;\n private cacheRead = 0;\n private cacheWrite = 0;\n private reasoning = 0;\n private readonly requests: Array<Omit<TokenUsage, \"requests\">> = [];\n\n add(step: StepUsage): void {\n const inputTokens = step.inputTokens ?? 0;\n const outputTokens = step.outputTokens ?? 0;\n const cacheReadTokens = step.cacheReadTokens ?? 0;\n const cacheWriteTokens = step.cacheWriteTokens ?? 0;\n const reasoningTokens = step.reasoningTokens ?? 0;\n this.input += inputTokens;\n this.output += outputTokens;\n this.cacheRead += cacheReadTokens;\n this.cacheWrite += cacheWriteTokens;\n this.reasoning += reasoningTokens;\n this.requests.push({\n inputTokens,\n outputTokens,\n ...(cacheReadTokens > 0 ? { cacheReadTokens } : {}),\n ...(cacheWriteTokens > 0 ? { cacheWriteTokens } : {}),\n ...(reasoningTokens > 0 ? { reasoningTokens } : {}),\n totalTokens: inputTokens + outputTokens,\n });\n }\n\n /** Did we observe any usage at all? */\n hasAny(): boolean {\n return this.requests.length > 0;\n }\n\n toTokenUsage(): TokenUsage {\n return {\n inputTokens: this.input,\n outputTokens: this.output,\n ...(this.cacheRead > 0 ? { cacheReadTokens: this.cacheRead } : {}),\n ...(this.cacheWrite > 0 ? { cacheWriteTokens: this.cacheWrite } : {}),\n ...(this.reasoning > 0 ? { reasoningTokens: this.reasoning } : {}),\n totalTokens: this.input + this.output,\n ...(this.requests.length > 1 ? { requests: this.requests.slice() } : {}),\n };\n }\n}\n","import type { SDKMessage } from \"../../types/messages.js\";\n\n/**\n * theokit#140 — the loop's event log, reporting each event AS IT HAPPENS.\n *\n * ## The defect this closes\n *\n * `runAgentLoop` collected events into a plain array and returned it, so nothing reached the run\n * until the loop had finished. `RealLocalRun.applyAgentLoopOutput` then copied the whole batch in\n * one pass. Meanwhile `SendOptions.onDelta` fired live from inside that same loop.\n *\n * Two clocks, one of which does not start until the other has stopped. A consumer that wanted tool\n * calls interleaved with tokens in true order had to fuse both surfaces itself — which is exactly\n * what `@theokit/agents` was doing, and the documented root of its ordering bug (theokit#47), its\n * namespace-dedup bug (theokit#138) and its missing terminal frame (theokit#142).\n *\n * ## Why a subclass, and not a callback threaded through nine call sites\n *\n * The events are appended from nine places across `loop.ts`, `loop-llm-stream.ts` and\n * `tool-dispatch.ts`. Threading an `onEvent` parameter to each would touch every one of them and,\n * worse, would leave the NEXT `events.push(...)` silently un-notified — a defect that reintroduces\n * itself by omission, which is the failure mode this whole issue is about.\n *\n * Extending `Array` moves the decision to the single place the log is CREATED. Every existing push\n * becomes live with no call-site change, and any push added later is live for free.\n *\n * It stays a real `Array`: `AgentLoopOutput.events` is still `SDKMessage[]`, `instanceof Array`\n * still holds, and every downstream consumer — including the batch copy in `applyAgentLoopOutput` —\n * is unchanged. This is additive; nothing that worked before observes a difference.\n *\n * `push` is the only override, deliberately. The loop only ever appends; overriding the rest of the\n * mutation surface would be guarding against callers that do not exist (YAGNI), and a subscriber\n * that must reason about splices is a worse contract than one that receives appends.\n */\nexport class LiveEventLog extends Array<SDKMessage> {\n /**\n * Not readonly, and not a constructor parameter — `Array` subclasses are re-instantiated by\n * `map`/`filter`/`slice` with a length argument, so a constructor with a different signature\n * breaks those. The sink is attached after construction instead.\n */\n #sink: ((event: SDKMessage) => void) | undefined;\n\n /** Attach the live subscriber. One sink: the run that owns this loop. */\n subscribe(sink: (event: SDKMessage) => void): void {\n this.#sink = sink;\n }\n\n override push(...events: SDKMessage[]): number {\n const length = super.push(...events);\n for (const event of events) {\n // A throwing subscriber must not take down the agent loop: the sink is an observer, and its\n // failure is its own. Swallowing anything else would be wrong, but here the alternative is\n // that a broken UI kills the run it is watching.\n try {\n this.#sink?.(event);\n } catch {\n // Deliberately ignored — see above. The event is still in the array, so the batch path\n // (`AgentLoopOutput.events`) delivers it regardless.\n }\n }\n return length;\n }\n}\n\n/**\n * Build the loop's event log, seeded with the events that exist before the loop starts.\n *\n * `LiveEventLog.from` rather than `new LiveEventLog(...seed)`: the `Array` constructor treats a\n * single numeric argument as a length, and a seed is a list of events, never a count.\n */\nexport function createEventLog(seed: readonly SDKMessage[]): LiveEventLog {\n const log = new LiveEventLog();\n log.push(...seed);\n return log;\n}\n","import type {\n SDKAssistantMessage,\n SDKSystemMessage,\n SDKThinkingMessage,\n SDKUserMessageEvent,\n} from \"../../types/messages.js\";\nimport type { LlmContentPart, LlmMessage, LlmThinkingPart, LlmToolCallPart } from \"../llm/types.js\";\nimport type { AgentLoopInputs } from \"./loop-types.js\";\n\n/**\n * Message-builder helpers extracted from `loop.ts` (G8 file-size budget).\n * Each function shapes one canonical SDK message variant or the assistant's\n * outgoing LLM turn. Pure functions — no side effects.\n *\n * @internal\n */\n\nexport function buildSystemEvent(inputs: AgentLoopInputs, toolNames: string[]): SDKSystemMessage {\n return {\n type: \"system\",\n subtype: \"init\",\n agent_id: inputs.agentId,\n run_id: inputs.runId,\n model: inputs.model,\n tools: toolNames,\n };\n}\n\nexport function buildUserEvent(inputs: AgentLoopInputs): SDKUserMessageEvent {\n return {\n type: \"user\",\n agent_id: inputs.agentId,\n run_id: inputs.runId,\n message: { role: \"user\", content: [{ type: \"text\", text: inputs.userMessage }] },\n };\n}\n\nexport function buildAssistantEvent(inputs: AgentLoopInputs, text: string): SDKAssistantMessage {\n return {\n type: \"assistant\",\n agent_id: inputs.agentId,\n run_id: inputs.runId,\n message: { role: \"assistant\", content: [{ type: \"text\", text }] },\n };\n}\n\n/**\n * issue #47: the reasoning the model produced this turn, as a `thinking` SDKMessage.\n * issue #48: when the reasoning duration was measured, carry it as `thinking_duration_ms`\n * so a `Run.stream()` replay can render how long the model reasoned.\n */\nexport function buildThinkingEvent(\n inputs: AgentLoopInputs,\n text: string,\n thinkingDurationMs?: number,\n signature?: string,\n): SDKThinkingMessage {\n const event: SDKThinkingMessage = {\n type: \"thinking\",\n agent_id: inputs.agentId,\n run_id: inputs.runId,\n text,\n };\n if (thinkingDurationMs !== undefined && thinkingDurationMs >= 0) {\n event.thinking_duration_ms = thinkingDurationMs;\n }\n // theokit#122 — carried so the turn can be persisted and replayed; absent for providers that\n // stream reasoning text without signing it.\n if (signature !== undefined) event.signature = signature;\n return event;\n}\n\n/**\n * theokit#122 — `thinking` is FIRST, and that ordering is a provider requirement, not a preference.\n *\n * Anthropic verifies the signed block on the next request and requires it to lead the assistant\n * message it belongs to. Omitting it (which this builder did until theokit#122's follow-up) makes\n * round 2 of any thinking + tools run fail with `400 \"thinking blocks cannot be modified\"` — the\n * exact failure the issue exists to remove. An unsigned block is passed through here and dropped at\n * the wire by `thinkingToWireBlock`, which is where that policy belongs.\n */\nexport function buildAssistantTurn(\n text: string,\n toolCalls: LlmToolCallPart[],\n thinking?: LlmThinkingPart,\n): LlmMessage {\n const content: LlmContentPart[] = [];\n if (thinking !== undefined) content.push(thinking);\n if (text.length > 0) content.push({ type: \"text\", text });\n for (const call of toolCalls) content.push(call);\n return { role: \"assistant\", content };\n}\n","import type { CustomTool, SDKAgent } from \"../../types/agent.js\";\nimport type { SDKUserMessage } from \"../../types/run.js\";\nimport { UsageAccumulator } from \"../budget/usage-accumulator.js\";\nimport type { LlmContentPart, LlmMessage } from \"../llm/types.js\";\n\n/**\n * M35 (multimodal) — build the first user turn's content: the text block plus one image part per attached\n * image. Both `SDKImage` shapes are carried (no silent drop): inline `{ data, mimeType }` → a base64\n * image part; `{ url }` → a url image part (provider adapters that support URLs forward it; those that\n * don't fail fast). Text-only ⇒ just the text block (unchanged shape).\n */\nfunction buildUserContent(text: string, images: SDKUserMessage[\"images\"]): LlmContentPart[] {\n const content: LlmContentPart[] = [{ type: \"text\", text }];\n for (const img of images ?? []) {\n content.push(\n \"data\" in img\n ? { type: \"image\", source: { type: \"base64\", media_type: img.mimeType, data: img.data } }\n : { type: \"image\", source: { type: \"url\", url: img.url } },\n );\n }\n return content;\n}\n\nimport { emitRunEvent, type RunEventSink } from \"../../types/run-events.js\";\nimport { diag } from \"../diagnostics.js\";\nimport type { McpClient, McpTool } from \"../mcp/client.js\";\nimport type { MemoryProviderHandle } from \"../runtime/memory/memory-provider.js\";\nimport { createDoomLoopTracker, type DoomLoopTracker } from \"./doom-loop-tracker.js\";\nimport { createEventLog, type LiveEventLog } from \"./live-events.js\";\nimport type { AgentLoopInputs } from \"./loop-types.js\";\nimport { buildSystemEvent, buildUserEvent } from \"./message-builders.js\";\nimport type { ResolvedTool } from \"./tool-dispatch.js\";\n\n/**\n * Mutable state for the agent loop. Extracted to share the shape between\n * `initLoopContext` and the main loop in `loop.ts`.\n *\n * @internal\n */\nexport interface LoopContext {\n /**\n * theokit#140 — a {@link LiveEventLog}, so the run that owns this loop can subscribe and see\n * events AS THEY HAPPEN instead of only when the loop returns. Still an `SDKMessage[]` to every\n * consumer that just reads it.\n */\n events: LiveEventLog;\n conversation: import(\"../../types/conversation.js\").ConversationTurn[];\n messages: LlmMessage[];\n tools: ResolvedTool[];\n finalText: string;\n finalStatus: import(\"../../types/run.js\").RunStatus;\n /**\n * M1-2 (T2.2): set true when the loop stopped because it exhausted the\n * iteration budget while the model still wanted to call tools (silent\n * truncation), as opposed to a clean `done` finish. Threaded onto\n * `AgentLoopOutput` → `RunResult.stoppedAtIterationLimit`.\n */\n stoppedAtIterationLimit?: boolean;\n /**\n * Doom-loop guard: set true when the loop stopped because the model repeated IDENTICAL tool calls\n * to the hard threshold (no progress). Threaded onto `AgentLoopOutput` → `RunResult.stoppedByDoomLoop`.\n */\n stoppedByDoomLoop?: boolean;\n /** Per-run doom-loop detector; `undefined` when disabled via `SendOptions.doomLoop: false`. */\n doomLoop?: DoomLoopTracker;\n usage: UsageAccumulator;\n error?: import(\"./loop-types.js\").AgentLoopErrorDetail;\n nudgeAttempts: number;\n /** M1-4: count of honored `stop`-hook feedback re-prompts, bounded by MAX_STOP_FEEDBACK_ATTEMPTS. */\n stopFeedbackAttempts: number;\n _consecutiveToolErrors?: number;\n memoryProviderHandle?: MemoryProviderHandle;\n memorySystemPromptAdditions?: string;\n /** M3 #64 — the run's `agent.send` span, threaded so child spans (llm.call,\n * tool.call) nest under it via `startChildSpan` instead of being flat siblings. */\n sendSpan?: import(\"../telemetry/tracer.js\").OTelSpan;\n}\n\n/**\n * Build the minimal `SDKAgent` view for MemoryProvider hooks.\n * @internal\n */\nexport function buildAgentRef(inputs: AgentLoopInputs): SDKAgent {\n return {\n agentId: inputs.agentId,\n model: inputs.model,\n } as SDKAgent;\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: pre-existing complexity from sdk-2-0 Phase 1 memory wiring (T1.5.1-T1.5.3). Refactor deferred to Phase 5 cleanup.\nexport async function initLoopContext(inputs: AgentLoopInputs): Promise<LoopContext> {\n let memoryProviderHandle: MemoryProviderHandle | undefined;\n if (inputs.memoryProvider !== undefined) {\n try {\n memoryProviderHandle = await inputs.memoryProvider.init({\n cwd: process.cwd(),\n });\n } catch {\n memoryProviderHandle = undefined;\n }\n }\n const tools = await collectTools(inputs.mcp, inputs.runEventSink);\n for (const memTool of inputs.memoryTools ?? []) {\n tools.push({\n name: memTool.name,\n description: memTool.description,\n inputSchema: memTool.inputSchema,\n origin: \"memory\",\n memoryHandler: memTool.execute,\n });\n }\n for (const customTool of inputs.customTools ?? []) {\n tools.push({\n name: customTool.name,\n description: customTool.description,\n inputSchema: customTool.inputSchema,\n origin: \"custom\",\n customHandler: customTool.handler,\n });\n }\n if (inputs.memoryProvider !== undefined && memoryProviderHandle !== undefined) {\n let providerTools: ReadonlyArray<CustomTool> = [];\n try {\n providerTools = inputs.memoryProvider.buildTools(memoryProviderHandle, buildAgentRef(inputs));\n } catch {\n providerTools = [];\n }\n for (const providerTool of providerTools) {\n tools.push({\n name: providerTool.name,\n description: providerTool.description,\n inputSchema: providerTool.inputSchema,\n origin: \"custom\",\n customHandler: providerTool.handler,\n });\n }\n }\n // theokit#140 — a live log, not a plain array. Every `events.push(...)` in the loop now reports\n // as it happens; `AgentLoopOutput.events` is still an `SDKMessage[]` and every batch consumer is\n // unchanged. The subscriber is attached by the run that owns the loop.\n const events = createEventLog([\n buildSystemEvent(\n inputs,\n tools.map((t) => t.name),\n ),\n buildUserEvent(inputs),\n ]);\n // theokit#140 - attach the run's subscriber, if it supplied one. Attached AFTER the seed so the\n // two events that exist before the loop starts arrive through the batch path like they always\n // did; re-delivering them live would be a behaviour change for no gain.\n if (inputs.onLoopEvent !== undefined) events.subscribe(inputs.onLoopEvent);\n const priorMessages: LlmMessage[] = (inputs.priorMessages ?? []).map((msg) => ({\n role: msg.role,\n content: [{ type: \"text\", text: msg.text }],\n }));\n let memorySystemPromptAdditions: string | undefined;\n if (inputs.memoryProvider !== undefined && memoryProviderHandle !== undefined) {\n try {\n const passResult = await inputs.memoryProvider.runActivePass(memoryProviderHandle, {\n userMessage: inputs.userMessage,\n history: (inputs.priorMessages ?? []).map((msg) => ({\n role: msg.role,\n content: msg.text,\n })),\n agentId: inputs.agentId,\n });\n if (\n passResult.systemPromptAdditions !== undefined &&\n passResult.systemPromptAdditions.length > 0\n ) {\n memorySystemPromptAdditions = passResult.systemPromptAdditions;\n }\n } catch {\n memorySystemPromptAdditions = undefined;\n }\n }\n return {\n events,\n conversation: [],\n messages: [\n ...priorMessages,\n { role: \"user\", content: buildUserContent(inputs.userMessage, inputs.userImages) },\n ],\n tools,\n finalText: \"\",\n finalStatus: \"finished\",\n doomLoop: createDoomLoopTracker(inputs.doomLoop),\n usage: new UsageAccumulator(),\n nudgeAttempts: 0,\n stopFeedbackAttempts: 0,\n ...(memoryProviderHandle !== undefined ? { memoryProviderHandle } : {}),\n ...(memorySystemPromptAdditions !== undefined ? { memorySystemPromptAdditions } : {}),\n };\n}\n\n/**\n * Lists tools from an MCP client with structured-stderr diagnostic on failure.\n * Exported for unit-test access to the catch path; internal-only.\n * @internal\n */\nexport async function safeListTools(\n client: McpClient,\n serverName?: string,\n sink?: RunEventSink,\n): Promise<McpTool[]> {\n try {\n return await client.listTools();\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : String(cause);\n const server = serverName ?? \"unknown\";\n diag(`[theokit-sdk] mcp listTools failed (server=${server}): ${message}\\n`);\n // theokit#188 — the diagnostic above goes to the SDK's stderr, which an embedding UI does not\n // read. The same fact now reaches the consumer through the typed sink, so a panel listing\n // configured servers can say this one produced no tools instead of showing it as healthy.\n emitRunEvent(sink, { type: \"mcp_server_failed\", serverName: server, message });\n return [];\n }\n}\n\nasync function collectTools(\n mcp: Map<string, McpClient>,\n sink?: RunEventSink,\n): Promise<ResolvedTool[]> {\n const tools: ResolvedTool[] = [\n {\n name: \"shell\",\n description: \"Run a shell command in the workspace and return stdout/stderr.\",\n inputSchema: {\n type: \"object\",\n required: [\"command\"],\n properties: { command: { type: \"string\", description: \"The shell command to run.\" } },\n },\n origin: \"shell\",\n },\n ];\n for (const [serverName, client] of mcp.entries()) {\n const mcpTools = await safeListTools(client, serverName, sink);\n for (const tool of mcpTools) {\n tools.push({\n name: `mcp_${sanitize(serverName)}_${sanitize(tool.name)}`,\n description: tool.description,\n inputSchema: tool.inputSchema,\n origin: \"mcp\",\n mcpServerName: serverName,\n mcpToolName: tool.name,\n });\n }\n }\n return tools;\n}\n\nfunction sanitize(name: string): string {\n return name.replace(/[^a-zA-Z0-9-]+/g, \"_\").replace(/^[_-]+|[_-]+$/g, \"\");\n}\n","/**\n * Strip `<think>...</think>` chain-of-thought blocks (T1.2, ADR D96).\n *\n * DeepSeek-R1, Qwen-QwQ, and similar reasoning models emit visible\n * `<think>` blocks in the `content` field. Without stripping, they enter\n * the message history; each turn accumulates 5k+ thinking tokens, and\n * prompt caching invalidates every turn (Hermes v0.2 #174, ~10x cost\n * regression).\n *\n * NOTE on `<think>` in legitimate prose (EC-10): a user/assistant message\n * that deliberately contains the `<think>` token will lose it. This is\n * provider-convention scope — `<think>` is reserved for CoT, never plain\n * content.\n *\n * @internal\n */\n\nconst THINK_PATTERN = /<think>[\\s\\S]*?<\\/think>\\s*/g;\n\nexport interface ThinkStripResult {\n /** Content with `<think>` blocks removed. */\n visible: string;\n /** Combined thinking text (without `<think>` tags), or null if none. */\n thinking: string | null;\n}\n\n/**\n * Extract `<think>...</think>` blocks from content. Returns visible text\n * (for history persistence) and concatenated thinking (for opt-in display).\n *\n * Unclosed `<think>` blocks (no matching `</think>`) are PRESERVED in\n * visible — fail-open semantics so corrupted provider streams don't\n * accidentally strip everything.\n *\n * @internal\n */\nexport function stripThinkBlocks(content: string): ThinkStripResult {\n const matches = [...content.matchAll(THINK_PATTERN)];\n const thinking =\n matches.length > 0\n ? matches\n .map((m) => m[0])\n .join(\"\\n\")\n .replace(/<\\/?think>/g, \"\")\n .trim()\n : null;\n const visible = content.replace(THINK_PATTERN, \"\").trim();\n return { visible, thinking };\n}\n","import { diag } from \"../diagnostics.js\";\nimport type { LlmClient, LlmThinkingPart, LlmTool, LlmToolCallPart } from \"../llm/types.js\";\nimport { safeCall } from \"../runtime/system-prompt/safe-call.js\";\nimport { HISTOGRAM_NAMES } from \"../telemetry/span-names.js\";\nimport { stripThinkBlocks } from \"../tool-dispatch/strip-think.js\";\nimport type { LoopContext } from \"./loop-context-init.js\";\nimport type { AgentLoopInputs } from \"./loop-types.js\";\nimport { buildAssistantEvent, buildThinkingEvent } from \"./message-builders.js\";\nimport type { ResolvedTool } from \"./tool-dispatch.js\";\n\n/** @internal */\nexport interface LlmTurnOutput {\n text: string;\n toolCalls: LlmToolCallPart[];\n stopReason: string;\n errored: boolean;\n inputTokens?: number;\n outputTokens?: number;\n cacheReadTokens?: number;\n cacheWriteTokens?: number;\n reasoningTokens?: number;\n /**\n * theokit#122 — the round's extended-thinking block.\n *\n * A per-ROUND value, deliberately. The first cut of this fix parked it on `LoopContext` as\n * `pendingThinking` and consumed it only where the assistant TEXT step was emitted — which is\n * skipped when a round produces thinking + a tool call and no preamble text (the common Anthropic\n * shape). The block then survived into the next round and was persisted against the WRONG text,\n * invalidating the signature it exists to preserve. Carrying it on the round's own output makes\n * that class of leak unrepresentable.\n */\n thinking?: LlmThinkingPart;\n}\n\n/**\n * Concat MemoryProvider's `systemPromptAdditions` to the inbound\n * `inputs.systemPrompt`.\n * @internal\n */\nexport function resolveSystemPromptWithMemoryAdditions(\n systemPrompt: string | undefined,\n additions: string | undefined,\n): string | undefined {\n if (additions === undefined || additions.length === 0) return systemPrompt;\n if (systemPrompt === undefined || systemPrompt.length === 0) return additions;\n return `${systemPrompt}\\n\\n${additions}`;\n}\n\nfunction toLlmTool(tool: ResolvedTool): LlmTool {\n return { name: tool.name, description: tool.description, inputSchema: tool.inputSchema };\n}\n\n/**\n * issue #47: extract the reasoning effort from `ModelSelection.params` — the canonical `thinking`\n * param (`{ id: \"thinking\", value: \"high\" }`) the agents bridge sets from `reasoningEffort`. Returns\n * undefined when absent so the provider request stays bare (no reasoning requested).\n * @internal\n */\nexport function reasoningEffortFromParams(\n params: AgentLoopInputs[\"model\"][\"params\"],\n): string | undefined {\n const thinking = params?.find((p) => p.id === \"thinking\");\n return thinking !== undefined && thinking.value.length > 0 ? thinking.value : undefined;\n}\n\n/**\n * M3 #64/#66 — emit the LLM-call duration + token throughput as metrics (were\n * span-attributes only); a provider that omits usage WARNs + counts\n * `llm_usage_missing` so budget undercount is observable instead of a silent 0.\n * @internal\n */\nfunction emitLlmMetrics(\n inputs: AgentLoopInputs,\n result: { inputTokens?: number; outputTokens?: number },\n startAt: number,\n): void {\n inputs.telemetry?.recordHistogram(HISTOGRAM_NAMES.LLM_CALL_DURATION_MS, Date.now() - startAt, {\n provider: inputs.llm.name,\n });\n if (result.inputTokens === undefined && result.outputTokens === undefined) {\n inputs.telemetry?.recordHistogram(HISTOGRAM_NAMES.LLM_USAGE_MISSING, 1, {\n provider: inputs.llm.name,\n });\n diag(\n `[theokit-sdk] llm usage missing from ${inputs.llm.name} finish — budget may undercount\\n`,\n );\n return;\n }\n inputs.telemetry?.recordHistogram(\n HISTOGRAM_NAMES.LLM_TOKENS,\n (result.inputTokens ?? 0) + (result.outputTokens ?? 0),\n { provider: inputs.llm.name },\n );\n}\n\n/** @internal */\nexport async function streamLlmTurn(\n inputs: AgentLoopInputs,\n ctx: LoopContext,\n): Promise<LlmTurnOutput> {\n // M3 #64 — nest llm.call under the run's agent.send span (not a flat sibling).\n const llmSpan = inputs.telemetry?.startChildSpan(ctx.sendSpan, \"llm.call\", {\n \"model.id\": inputs.model.id ?? \"auto\",\n provider: inputs.llm.name,\n });\n const startAt = Date.now();\n const signal = inputs.signal ?? new AbortController().signal;\n const generator = inputs.llm.stream(\n {\n model: inputs.model.id ?? \"auto\",\n ...((): { system?: string } => {\n const effective = resolveSystemPromptWithMemoryAdditions(\n inputs.systemPrompt,\n ctx.memorySystemPromptAdditions,\n );\n return effective !== undefined ? { system: effective } : {};\n })(),\n // issue #47: forward the reasoning effort from ModelSelection.params (the `thinking` param)\n // so the provider produces reasoning. Absent param ⇒ no `reasoning` field (bare request).\n ...((): { reasoning?: { effort: string } } => {\n const effort = reasoningEffortFromParams(inputs.model.params);\n return effort !== undefined ? { reasoning: { effort } } : {};\n })(),\n // Step-cap force-close: forward the per-run tool gate (`\"none\"` on a ceiling round forces a\n // text close even though tools are advertised). Absent ⇒ provider default (auto).\n ...(inputs.toolChoice !== undefined ? { toolChoice: inputs.toolChoice } : {}),\n messages: ctx.messages,\n tools: ctx.tools.map(toLlmTool),\n },\n signal,\n );\n const collected = await collectLlmEvents(generator, inputs, ctx);\n if (collected.errored || collected.finishValue === undefined) {\n llmSpan?.setAttribute(\"stopReason\", \"error\");\n llmSpan?.end();\n return {\n text: collected.accumulatedText,\n toolCalls: [],\n stopReason: \"error\",\n errored: true,\n };\n }\n const result = collected.finishValue.value as Awaited<\n ReturnType<LlmClient[\"stream\"]>\n > extends AsyncGenerator<unknown, infer R, unknown>\n ? R\n : never;\n llmSpan?.setAttributes({\n stopReason: result.stopReason,\n inputTokens: result.inputTokens ?? 0,\n outputTokens: result.outputTokens ?? 0,\n });\n emitLlmMetrics(inputs, result, startAt);\n llmSpan?.end();\n const stripped = stripThinkBlocks(collected.accumulatedText);\n // theokit#122 — the provider's own block wins. Anthropic reports it on the finish value WITH the\n // signature; `collected.thinking` is the reconstruction from `reasoning_delta`s, which is all an\n // OpenAI-compatible provider can offer (it never signs). Preferring the finish value is also what\n // stops `LlmFinish.thinking` from being the declared-but-unread channel theokit#144 deleted.\n const thinking = result.thinking ?? collected.thinking;\n return {\n text: stripped.visible,\n toolCalls: result.toolCalls,\n stopReason: result.stopReason,\n errored: false,\n inputTokens: result.inputTokens,\n outputTokens: result.outputTokens,\n cacheReadTokens: result.cacheReadTokens,\n cacheWriteTokens: result.cacheWriteTokens,\n reasoningTokens: result.reasoningTokens,\n ...(thinking !== undefined ? { thinking } : {}),\n };\n}\n\ninterface CollectedEvents {\n accumulatedText: string;\n errored: boolean;\n /** theokit#122 — the block rebuilt from `reasoning_delta`s, for providers that do not report one. */\n thinking?: LlmThinkingPart;\n finishValue: Awaited<ReturnType<ReturnType<LlmClient[\"stream\"]>[\"next\"]>> | undefined;\n}\n\nasync function collectLlmEvents(\n generator: ReturnType<LlmClient[\"stream\"]>,\n inputs: AgentLoopInputs,\n ctx: LoopContext,\n): Promise<CollectedEvents> {\n let accumulatedText = \"\";\n let errored = false;\n let finishValue: CollectedEvents[\"finishValue\"];\n let thinking: LlmThinkingPart | undefined;\n try {\n const result = await runCollectorLoop(generator, inputs, ctx);\n accumulatedText = result.accumulatedText;\n errored = result.errored;\n finishValue = result.finishValue;\n thinking = result.thinking;\n } catch (cause) {\n if (inputs.signal?.aborted === true) {\n ctx.finalText = \"[aborted]\";\n ctx.events.push(buildAssistantEvent(inputs, \"[aborted]\"));\n } else {\n registerLoopError(ctx, cause);\n ctx.finalText = \"\";\n }\n errored = true;\n }\n return {\n accumulatedText,\n errored,\n finishValue,\n ...(thinking !== undefined ? { thinking } : {}),\n };\n}\n\n/**\n * Set-once invariant (ADR D3, EC-3-A): first error wins.\n * @internal\n */\nexport function registerLoopError(ctx: LoopContext, cause: unknown): void {\n if (ctx.error !== undefined) return;\n const rawMessage = (cause as { message?: unknown } | null | undefined)?.message;\n const message =\n typeof rawMessage === \"string\"\n ? rawMessage\n : cause instanceof Error\n ? cause.message\n : String(cause);\n // Prefer the CANONICAL `metadata.code` (e.g. \"context_too_long\") over the\n // provider-PREFIXED top-level `.code` (e.g. \"anthropic_context_too_long\") that\n // the error mappers set for telemetry — so the run boundary (`RunResult.error.code`)\n // reports the canonical `ErrorCode` and consumer checks like\n // `result.error.code === \"context_too_long\"` work for every provider.\n const metaCode = (cause as { metadata?: { code?: unknown } } | null | undefined)?.metadata?.code;\n const rawCode = (cause as { code?: unknown } | null | undefined)?.code;\n const code =\n typeof metaCode === \"string\" ? metaCode : typeof rawCode === \"string\" ? rawCode : undefined;\n ctx.error = code !== undefined ? { message, code, cause } : { message, cause };\n}\n\n/**\n * Take one non-terminal stream event; returns the text it contributed (empty for reasoning).\n *\n * Extracted so `runCollectorLoop` stays under the cognitive-complexity cap once theokit#122 added\n * the reasoning branch's signature handling.\n */\nasync function consumeStreamEvent(\n inputs: AgentLoopInputs,\n reasoning: ReasoningAccumulator,\n event: { type: string; text?: string; signature?: string },\n): Promise<string> {\n if (event.type === \"text_delta\") {\n const text = event.text ?? \"\";\n await emitTextDeltaCallback(inputs, text);\n return text;\n }\n if (event.type === \"reasoning_delta\") {\n await consumeReasoningDelta(inputs, reasoning, {\n text: event.text ?? \"\",\n ...(event.signature !== undefined ? { signature: event.signature } : {}),\n });\n }\n return \"\";\n}\n\nasync function runCollectorLoop(\n generator: ReturnType<LlmClient[\"stream\"]>,\n inputs: AgentLoopInputs,\n ctx: LoopContext,\n): Promise<{\n accumulatedText: string;\n errored: boolean;\n finishValue: CollectedEvents[\"finishValue\"];\n thinking?: LlmThinkingPart;\n}> {\n let accumulatedText = \"\";\n // issue #47/#48: reasoning streams on its own channel — `text` is accumulated for the\n // `thinking` SDKMessage replay; `startedAt` (set on the first delta) measures the duration.\n const reasoning: ReasoningAccumulator = { text: \"\", startedAt: undefined, signature: undefined };\n let errored = false;\n let finishValue: CollectedEvents[\"finishValue\"];\n let thinking: LlmThinkingPart | undefined;\n // issue #48 (review Finding 1): finalize in a `finally` so a mid-stream THROW from the LLM\n // generator (e.g. a dropped connection after some reasoning deltas) still emits the one\n // `thinking-completed` — otherwise a consumer that opened a reasoning block on the first\n // `thinking-delta` would wait for a close signal that never comes. The in-band `error` event\n // path (break below) already reaches finalize; this covers the hard-throw path too.\n try {\n while (true) {\n const next = await generator.next();\n if (next.done === true) {\n finishValue = next;\n break;\n }\n if (next.value.type === \"error\") {\n registerLoopError(ctx, next.value);\n ctx.finalText = \"\";\n errored = true;\n break;\n }\n accumulatedText += await consumeStreamEvent(inputs, reasoning, next.value);\n }\n } finally {\n thinking = await finalizeReasoning(inputs, ctx, reasoning);\n }\n return { accumulatedText, errored, finishValue, ...(thinking !== undefined ? { thinking } : {}) };\n}\n\n/**\n * theokit#122 — take one reasoning delta, text and signature alike.\n *\n * The signature rides its OWN text-less delta (Anthropic emits `signature_delta` after the thinking\n * text), so it is captured before the text is accumulated — otherwise a signature-only delta would\n * be indistinguishable from an empty reasoning chunk and thrown away.\n */\nasync function consumeReasoningDelta(\n inputs: AgentLoopInputs,\n reasoning: ReasoningAccumulator,\n delta: { text: string; signature?: string },\n): Promise<void> {\n if (delta.signature !== undefined) reasoning.signature = delta.signature;\n await accumulateReasoning(inputs, reasoning, delta.text);\n}\n\n/** issue #47/#48: reasoning accumulated across a single LLM turn. */\ninterface ReasoningAccumulator {\n text: string;\n startedAt: number | undefined;\n /**\n * theokit#122 — the provider's cryptographic signature for this thinking block. Anthropic sends\n * it once, on its own delta, after the text. Kept as last-seen-wins: one block, one signature.\n */\n signature: string | undefined;\n}\n\n/**\n * issue #47/#48: accumulate one reasoning delta — stamp the block start on the first delta\n * (for the duration measurement) and surface it live as a `thinking-delta`.\n */\nasync function accumulateReasoning(\n inputs: AgentLoopInputs,\n reasoning: ReasoningAccumulator,\n text: string,\n): Promise<void> {\n if (reasoning.startedAt === undefined) reasoning.startedAt = Date.now();\n reasoning.text += text;\n await emitReasoningDeltaCallback(inputs, text);\n}\n\n/**\n * issue #47/#48: finalize the reasoning block for this turn. Emit the accumulated reasoning as a\n * `thinking` SDKMessage (run.stream replay) BEFORE the assistant turn — preserving reason-then-answer\n * order — carrying the measured duration, then close the live channel with a single\n * `thinking-completed` so a UI can end its reasoning block. No-op when the model produced no reasoning.\n */\nasync function finalizeReasoning(\n inputs: AgentLoopInputs,\n ctx: LoopContext,\n reasoning: ReasoningAccumulator,\n): Promise<LlmThinkingPart | undefined> {\n if (reasoning.text.length === 0) return undefined;\n const thinkingDurationMs =\n reasoning.startedAt === undefined ? 0 : Date.now() - reasoning.startedAt;\n ctx.events.push(\n buildThinkingEvent(inputs, reasoning.text, thinkingDurationMs, reasoning.signature),\n );\n await emitThinkingCompletedCallback(inputs, thinkingDurationMs);\n // theokit#122 — RETURNED, not stashed on the context. See `LlmTurnOutput.thinking` for why the\n // context-state version leaked a signature onto the following round's text.\n return {\n type: \"thinking\",\n text: reasoning.text,\n ...(reasoning.signature !== undefined ? { signature: reasoning.signature } : {}),\n };\n}\n\nasync function emitTextDeltaCallback(inputs: AgentLoopInputs, text: string): Promise<void> {\n if (inputs.onDelta === undefined) return;\n const cb = inputs.onDelta;\n await safeCall(\n () => cb({ update: { type: \"text-delta\", text } }),\n undefined,\n \"SendOptions.onDelta\",\n );\n}\n\n/** issue #47: deliver a reasoning delta live as a `thinking-delta` InteractionUpdate. */\nasync function emitReasoningDeltaCallback(inputs: AgentLoopInputs, text: string): Promise<void> {\n if (inputs.onDelta === undefined) return;\n const cb = inputs.onDelta;\n await safeCall(\n () => cb({ update: { type: \"thinking-delta\", text } }),\n undefined,\n \"SendOptions.onDelta\",\n );\n}\n\n/**\n * issue #48: close the reasoning channel with a single `thinking-completed` InteractionUpdate,\n * carrying the measured duration so a consumer can end its reasoning UI block.\n */\nasync function emitThinkingCompletedCallback(\n inputs: AgentLoopInputs,\n thinkingDurationMs: number,\n): Promise<void> {\n if (inputs.onDelta === undefined) return;\n const cb = inputs.onDelta;\n await safeCall(\n () => cb({ update: { type: \"thinking-completed\", thinkingDurationMs } }),\n undefined,\n \"SendOptions.onDelta\",\n );\n}\n","/**\n * theokit#122 — where a round's thinking block becomes a conversation step.\n *\n * Extracted from `loop.ts` when it crossed the G8 400-LoC cap. These two belong together: both\n * answer \"the round produced a thinking block — where does it land in the persisted conversation\",\n * and the answer differs by which path closes the round.\n *\n * @internal\n */\n\nimport type { ConversationStep } from \"../../types/conversation.js\";\nimport type { LlmThinkingPart } from \"../llm/types.js\";\nimport type { LoopContext } from \"./loop-context-init.js\";\n\n/**\n * theokit#122 — the round's thinking block as a conversation step.\n *\n * Shared by the two paths that can close a round: the assistant-text path and the tool_use path.\n * The tool_use path is the one that matters — a round of thinking + a tool call with NO preamble\n * text is the common Anthropic shape, and it is exactly the case the first version of this fix\n * dropped (the block stayed on the context and was persisted against the NEXT round's text).\n */\nexport function thinkingStep(thinking: LlmThinkingPart): ConversationStep {\n return {\n type: \"thinkingMessage\",\n message: {\n text: thinking.text,\n ...(thinking.signature !== undefined ? { signature: thinking.signature } : {}),\n },\n };\n}\n\n/**\n * theokit#122 — persist the block for a round that called a tool and said nothing.\n *\n * Such a round emits no assistant-text step, so without this the block is never recorded for it —\n * which is exactly how the first version of this fix let round N's signature reach round N+1.\n * No-op when the round had text (the text path already recorded it) or produced no thinking.\n */\nexport function recordThinkingOnSilentToolRound(\n ctx: LoopContext,\n text: string,\n thinking: LlmThinkingPart | undefined,\n): void {\n if (text.length > 0 || thinking === undefined) return;\n ctx.conversation.push({\n type: \"agentConversationTurn\",\n turn: { steps: [thinkingStep(thinking)] },\n });\n}\n","/**\n * Tool-call repair middleware (T1.1, ADR D87).\n *\n * Applies 3 idempotent repairs sequentially before tool dispatch:\n * 1. Case-insensitive name match (ADR D88 — no fuzzy match)\n * 2. JSON-string args → object parse\n * 3. Type coercion against JSON Schema (string → number/integer/boolean/object)\n *\n * Fixes 10+ provider-specific failure modes catalogued in\n * `.claude/knowledge-base/sdk-references/tool-call-failure-recovery.md`:\n * Hermes v0.2 #444 (DeepSeek JSON), v0.3 #1300 (parallel calls),\n * v0.8 #5265 (type coerce), and similar.\n *\n * NOTE on coerce limits (EC-9): regex `^-?\\d+(\\.\\d+)?$` accepts decimal\n * notation only — scientific (`1e5`), hex (`0xFF`), and `Infinity` are\n * preserved as strings and rejected by downstream schema validation. KISS:\n * 99% of provider-emitted tool args use plain decimal.\n *\n * @internal\n */\n\nexport interface ToolCall {\n name: string;\n args: unknown;\n id: string;\n}\n\nexport interface RepairableTool {\n name: string;\n /** JSON Schema for the tool's input. `properties` map drives coercion. */\n inputSchema: Record<string, unknown>;\n}\n\nexport interface RepairResult {\n call: ToolCall;\n /** Human-readable log of repairs applied (empty when no-op). */\n repairs: string[];\n}\n\nconst DECIMAL_RE = /^-?\\d+(\\.\\d+)?$/;\n\n/**\n * Apply idempotent repairs to a raw tool call from an LLM. Pure function:\n * does NOT mutate `raw` or `registry`. Runs in O(registry.size) for the\n * name lookup; O(properties.length) for coercion.\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: 3 sequential repair stages (name match / args parse / type coerce) live in one function by design — splitting them hides the repair order (ADR D87) that callers reason about via the `repairs` log.\nexport function repairToolCall(\n raw: ToolCall,\n registry: ReadonlyMap<string, RepairableTool>,\n): RepairResult {\n const repairs: string[] = [];\n let call: ToolCall = { ...raw };\n\n // Repair 1: case-insensitive name match. NEVER fuzzy (Hermes posture,\n // ADR D88) — typos get rejected downstream with available-tools list.\n if (!registry.has(call.name)) {\n const lower = call.name.toLowerCase();\n let match: string | undefined;\n for (const key of registry.keys()) {\n if (key.toLowerCase() === lower) {\n match = key;\n break;\n }\n }\n if (match !== undefined) {\n repairs.push(`name: \"${call.name}\" → \"${match}\"`);\n call = { ...call, name: match };\n }\n }\n\n // Repair 2: JSON-string args → object. Some providers stringify args\n // (DeepSeek v0.2 #444, Anthropic intermittently).\n if (typeof call.args === \"string\") {\n try {\n const parsed = JSON.parse(call.args);\n call = { ...call, args: parsed };\n repairs.push(\"args: parsed from string\");\n } catch {\n // Leave as string for downstream validator to reject.\n }\n }\n\n // Repair 3: type coercion against schema (Hermes v0.8 #5265).\n const tool = registry.get(call.name);\n if (\n tool !== undefined &&\n typeof call.args === \"object\" &&\n call.args !== null &&\n !Array.isArray(call.args)\n ) {\n const coerced = coerceArgsToSchema(call.args as Record<string, unknown>, tool.inputSchema);\n if (coerced.changed.length > 0) {\n call = { ...call, args: coerced.value };\n repairs.push(...coerced.changed);\n }\n }\n\n return { call, repairs };\n}\n\nexport interface CoerceResult {\n value: Record<string, unknown>;\n changed: string[];\n}\n\n/**\n * Coerce string-typed args to the schema's declared type. Supports\n * `number`, `integer`, `boolean`, `array`, `object`. Scientific notation,\n * hex, and `Infinity` are out of scope (EC-9 documented limitation).\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: 5-type coercion ladder (number / integer / boolean / array / object) is exhaustive by design — JSON Schema type taxonomy maps 1:1 to branch arms.\nexport function coerceArgsToSchema(\n args: Record<string, unknown>,\n schema: Record<string, unknown>,\n): CoerceResult {\n const changed: string[] = [];\n const out: Record<string, unknown> = { ...args };\n const properties = schema.properties as Record<string, unknown> | undefined;\n if (properties === undefined) return { value: out, changed };\n\n for (const [key, propDef] of Object.entries(properties)) {\n const val = out[key];\n if (typeof val !== \"string\") continue;\n const propType = (propDef as { type?: unknown }).type;\n if (typeof propType !== \"string\") continue;\n\n if (propType === \"number\" && DECIMAL_RE.test(val.trim())) {\n out[key] = Number(val);\n changed.push(`${key}: string→number`);\n } else if (propType === \"integer\" && /^-?\\d+$/.test(val.trim())) {\n out[key] = Number(val);\n changed.push(`${key}: string→integer`);\n } else if (propType === \"boolean\" && (val === \"true\" || val === \"false\")) {\n out[key] = val === \"true\";\n changed.push(`${key}: string→boolean`);\n } else if (propType === \"array\" || propType === \"object\") {\n try {\n const parsed = JSON.parse(val);\n if (propType === \"array\" && Array.isArray(parsed)) {\n out[key] = parsed;\n changed.push(`${key}: string→array`);\n } else if (\n propType === \"object\" &&\n typeof parsed === \"object\" &&\n parsed !== null &&\n !Array.isArray(parsed)\n ) {\n out[key] = parsed;\n changed.push(`${key}: string→object`);\n }\n } catch {\n // Not JSON — leave as string for validator.\n }\n }\n }\n\n return { value: out, changed };\n}\n","/**\n * SE7 — `ToolError`: thrown FROM a tool `handler` to report a failure back to\n * the model with structured content (text and/or an image), not just a string.\n * Kept in its own module (not `errors.ts`) so the error taxonomy file stays\n * under the G8 LoC budget and this tool-shaped error lives next to the tool\n * surface it serves.\n *\n * @public\n */\n\nimport { type ErrorMetadata, TheokitAgentError } from \"./errors.js\";\nimport type { ToolResultContentBlock } from \"./types/content-blocks.js\";\n\n/**\n * Thrown from a tool `handler` to surface a failure to the model. The SDK turns\n * it into a `tool_result` with `isError: true` carrying the content. A plain\n * `Error` thrown from a handler still works (its message becomes text);\n * `ToolError` is the opt-in for a clean message or a multimodal error (e.g. an\n * error screenshot).\n *\n * @public\n */\nexport class ToolError extends TheokitAgentError {\n override readonly name: string = \"ToolError\";\n /** The error content surfaced to the model: a string, or text/image blocks. */\n readonly content: string | ToolResultContentBlock[];\n\n constructor(\n content: string | ToolResultContentBlock[],\n options: { code?: string; cause?: unknown; metadata?: ErrorMetadata } = {},\n ) {\n super(renderToolErrorMessage(content), { ...options, isRetryable: false });\n this.content = content;\n }\n}\n\n/** Render a `ToolError`'s content into a plain-text `Error.message`. */\nfunction renderToolErrorMessage(content: string | ToolResultContentBlock[]): string {\n if (typeof content === \"string\") return content;\n return content\n .map((block) => (block.type === \"text\" ? block.text : `[${block.source.media_type} image]`))\n .join(\"\\n\");\n}\n","import { spawnAndCollect } from \"../lifecycle/spawn-collect.js\";\n\n/**\n * Real shell tool executor. Spawns a single command through `/bin/sh -c`,\n * captures stdout/stderr/exitCode, and honours per-call timeouts.\n *\n * Sandboxing is opt-in via `local.sandboxOptions.enabled`. The current\n * sandbox implementation simply scopes `cwd` to the configured workspace\n * and rejects shell escapes like `cd /` or absolute paths starting with\n * `/etc/`. A future iteration will hook into Node's permission model or a\n * platform-specific sandbox (Bubblewrap / sandbox-exec).\n *\n * @internal\n */\n\nexport interface ShellExecuteOptions {\n command: string;\n cwd: string;\n timeoutMs?: number;\n sandbox?: boolean;\n env?: Record<string, string>;\n}\n\nexport interface ShellExecuteResult {\n stdout: string;\n stderr: string;\n exitCode: number | null;\n timedOut: boolean;\n}\n\nexport async function runShell(options: ShellExecuteOptions): Promise<ShellExecuteResult> {\n if (options.sandbox === true && isObviouslyUnsafe(options.command)) {\n return {\n stdout: \"\",\n stderr: `Sandbox refused command: ${options.command}`,\n exitCode: 126,\n timedOut: false,\n };\n }\n const result = await spawnAndCollect({\n command: \"sh\",\n args: [\"-c\", options.command],\n cwd: options.cwd,\n ...(options.env !== undefined ? { env: options.env } : {}),\n ...(options.timeoutMs !== undefined ? { timeoutMs: options.timeoutMs } : {}),\n });\n const stderr =\n result.spawnError !== undefined ? result.stderr + result.spawnError.message : result.stderr;\n return {\n stdout: result.stdout,\n stderr,\n exitCode: result.exitCode,\n timedOut: result.timedOut,\n };\n}\n\nfunction isObviouslyUnsafe(command: string): boolean {\n // Cheap allow-list for the sandbox tier — refuse commands that reach\n // outside the workspace or touch sensitive paths. Real isolation will\n // come from process-level sandboxing.\n if (/(^|\\s)(rm|mv|cp)\\s+[^|;]*\\s+\\/(etc|var|root)\\b/.test(command)) return true;\n if (/sudo\\s/.test(command)) return true;\n return false;\n}\n","import { type SplitResolver, TOOL_SPLIT_RESOLVER } from \"../../define-tool.js\";\nimport { ToolError } from \"../../tool-error.js\";\nimport type { ToolContextMessage } from \"../../types/agent-prims.js\";\nimport type { ToolResultContentBlock } from \"../../types/content-blocks.js\";\nimport type { LlmToolCallPart } from \"../llm/types.js\";\nimport { runShell, type ShellExecuteOptions } from \"../runtime/tools/shell-tool.js\";\nimport type { AgentLoopInputs, ResolvedTool } from \"./loop-types.js\";\n\n/** @internal */\nexport interface ToolResult {\n stdout: string;\n stderr: string;\n exitCode?: number | null;\n /**\n * SE7 — authoritative tool_result content when set: a string OR structured\n * blocks (text + image). Populated by a handler that returns blocks, or a\n * `ToolError` (string or blocks); `stdout`/`stderr` remain for hooks/telemetry.\n * `undefined` → the legacy string path (`renderToolResult` over stdout/stderr).\n */\n content?: string | ToolResultContentBlock[];\n /**\n * SE17 — the FULL raw handler output (serialized), surfaced to observability\n * (`onToolEnd.result`) when a `toModelOutput` split is active. Distinct from\n * `content`/`stdout` (which carry the compact MODEL-facing value). `undefined`\n * for tools without a `toModelOutput` split — observability then falls back to\n * `content`/`stdout` (same value the model saw).\n */\n appResult?: string | ToolResultContentBlock[];\n}\n\n/** @internal */\nexport async function executeTool(\n inputs: AgentLoopInputs,\n resolved: ResolvedTool | undefined,\n call: LlmToolCallPart,\n): Promise<ToolResult> {\n if (resolved === undefined) {\n return { stdout: \"\", stderr: `Unknown tool ${call.name}`, exitCode: 127 };\n }\n if (resolved.origin === \"shell\") return runShellTool(inputs, call);\n // #119 — `inputs.agentId` is the run's session identity (the `Agent.getOrCreate(sessionId)`\n // key). Threaded to the handler as `ctx.threadId` so a stateful tool can scope state per session.\n if (resolved.origin === \"memory\")\n return runMemoryTool(resolved, call, inputs.context, inputs.agentId);\n if (resolved.origin === \"custom\")\n return runCustomTool(\n resolved,\n call,\n inputs.signal,\n inputs.context,\n inputs.messages,\n inputs.agentId,\n );\n return runMcpTool(inputs, resolved, call);\n}\n\nasync function runMemoryTool(\n resolved: ResolvedTool,\n call: LlmToolCallPart,\n context?: unknown,\n threadId?: string,\n): Promise<ToolResult> {\n return runHandlerTool(\n \"memory\",\n resolved.memoryHandler,\n call,\n undefined,\n context,\n undefined,\n threadId,\n );\n}\n\nasync function runCustomTool(\n resolved: ResolvedTool,\n call: LlmToolCallPart,\n signal?: AbortSignal,\n context?: unknown,\n messages?: readonly ToolContextMessage[],\n threadId?: string,\n): Promise<ToolResult> {\n return runHandlerTool(\n \"custom\",\n resolved.customHandler,\n call,\n signal,\n context,\n messages,\n threadId,\n );\n}\n\nasync function runHandlerTool(\n kind: \"memory\" | \"custom\",\n handler:\n | ((\n input: Record<string, unknown>,\n ctx?: {\n signal?: AbortSignal;\n context?: unknown;\n messages?: readonly ToolContextMessage[];\n threadId?: string;\n },\n ) => string | ToolResultContentBlock[] | Promise<string | ToolResultContentBlock[]>)\n | undefined,\n call: LlmToolCallPart,\n signal?: AbortSignal,\n context?: unknown,\n messages?: readonly ToolContextMessage[],\n threadId?: string,\n): Promise<ToolResult> {\n if (handler === undefined) {\n return { stdout: \"\", stderr: `${kind} tool ${call.name} has no handler`, exitCode: 127 };\n }\n try {\n // #65 — the run's abort signal on the ToolContext. M7 — also the run's user\n // `context` (from SendOptions.context). SE12 — `messages` is the read-only\n // transcript projection (custom tools only; memory tools pass undefined).\n // Single-arg handlers ignore all of them.\n // SE17 — a `toModelOutput` tool carries a split resolver on its handler: run it\n // ONCE and route the compact `model` channel to the tool_result while the full\n // `app` channel reaches `onToolEnd`. Absent ⇒ the plain single-channel path.\n const split = (handler as unknown as Record<symbol, SplitResolver | undefined>)[\n TOOL_SPLIT_RESOLVER\n ];\n if (split !== undefined) {\n const { model, app } = await split(call.input, { signal, context, threadId });\n const base: ToolResult =\n typeof model === \"string\"\n ? { stdout: model, stderr: \"\", exitCode: 0 }\n : { stdout: \"\", stderr: \"\", exitCode: 0, content: model };\n return { ...base, appResult: app };\n }\n const out = await handler(call.input, { signal, context, messages, threadId });\n // SE7 — a handler may return structured content blocks (text + image).\n if (typeof out !== \"string\") return { stdout: \"\", stderr: \"\", exitCode: 0, content: out };\n return { stdout: out, stderr: \"\", exitCode: 0 };\n } catch (cause) {\n // SE7 — a `ToolError` carries the error content (string or blocks) as the\n // authoritative tool_result content; `stderr` keeps the text message for the\n // `onToolError` hook. A string ToolError stays a string on the wire (symmetric\n // with a string handler return), a block ToolError carries its blocks.\n if (cause instanceof ToolError) {\n return { stdout: \"\", stderr: cause.message, exitCode: 1, content: cause.content };\n }\n const message = cause instanceof Error ? cause.message : String(cause);\n return { stdout: \"\", stderr: message, exitCode: 1 };\n }\n}\n\nasync function runShellTool(inputs: AgentLoopInputs, call: LlmToolCallPart): Promise<ToolResult> {\n const command =\n typeof call.input.command === \"string\" ? call.input.command : JSON.stringify(call.input);\n const shellOptions: ShellExecuteOptions = {\n command,\n cwd: inputs.shellCwd,\n sandbox: inputs.shellSandbox,\n };\n const result = await runShell(shellOptions);\n const final: ToolResult = { stdout: result.stdout, stderr: result.stderr };\n if (result.exitCode !== null && result.exitCode !== undefined) final.exitCode = result.exitCode;\n return final;\n}\n\nasync function runMcpTool(\n inputs: AgentLoopInputs,\n resolved: ResolvedTool,\n call: LlmToolCallPart,\n): Promise<ToolResult> {\n const client = inputs.mcp.get(resolved.mcpServerName ?? \"\");\n if (client === undefined || resolved.mcpToolName === undefined) {\n return {\n stdout: \"\",\n stderr: `MCP server ${resolved.mcpServerName ?? \"?\"} not connected`,\n exitCode: 127,\n };\n }\n try {\n const response = await client.callTool(resolved.mcpToolName, call.input);\n const text = response.content\n .filter((part) => part.type === \"text\")\n .map((part) => part.text)\n .join(\"\\n\");\n return { stdout: text, stderr: \"\", exitCode: response.isError === true ? 1 : 0 };\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : String(cause);\n return { stdout: \"\", stderr: message, exitCode: 1 };\n }\n}\n\n/** @internal */\nexport function renderToolResult(result: ToolResult): string {\n if (result.stderr.length > 0 && (result.exitCode ?? 0) !== 0) {\n return `${result.stdout}\\n[stderr]\\n${result.stderr}`.trim();\n }\n return result.stdout.trim();\n}\n","/**\n * #58 — bound a single tool execution by the run's cancellation signal and an\n * optional per-tool timeout, so a hung tool cannot wedge the agent loop and a\n * cancelled run interrupts an in-flight tool.\n *\n * Stdlib only (`AbortSignal.any` / `AbortSignal.timeout`, Node ≥22.12).\n *\n * @internal\n */\n\nimport type { ToolResult } from \"./tool-executors.js\";\n\nexport interface ToolRaceOptions {\n /** The run's cancellation signal (`AgentLoopInputs.signal`). */\n signal?: AbortSignal;\n /** Per-tool timeout in ms. Omit for no timeout. */\n timeoutMs?: number;\n}\n\n/** Exit code used for a tool that was aborted/timed out (matches the sandbox 124). */\nconst TOOL_ABORTED_EXIT = 124;\n\nfunction abortedResult(signal: AbortSignal): ToolResult {\n const reason = signal.reason as { name?: string } | undefined;\n const timedOut = reason?.name === \"TimeoutError\";\n return {\n stdout: \"\",\n stderr: timedOut ? \"tool execution timed out\" : \"tool execution aborted\",\n exitCode: TOOL_ABORTED_EXIT,\n };\n}\n\n/**\n * Race a tool execution against cancellation + an optional timeout. Returns the\n * tool's result if it finishes first, or a typed aborted/timed-out `ToolResult`\n * (exit 124) if the run is cancelled or the per-tool deadline elapses. When\n * neither a signal nor a timeout is supplied, the execution is returned as-is\n * (zero overhead, backward-compatible).\n */\nexport function raceToolExecution(\n exec: Promise<ToolResult>,\n opts: ToolRaceOptions,\n): Promise<ToolResult> {\n const { signal, timeoutMs } = opts;\n if (signal === undefined && timeoutMs === undefined) return exec;\n\n const signals: AbortSignal[] = [];\n if (signal !== undefined) signals.push(signal);\n if (timeoutMs !== undefined) signals.push(AbortSignal.timeout(timeoutMs));\n const merged = signals.length === 1 ? signals[0]! : AbortSignal.any(signals);\n\n if (merged.aborted) return Promise.resolve(abortedResult(merged));\n\n // ARCH-03 — attach the listener to a per-call controller, not the caller's\n // long-lived run signal, and remove it once the race settles, so tool-heavy\n // runs do not accumulate listeners on the shared signal.\n return new Promise<ToolResult>((resolve, reject) => {\n let settled = false;\n const onAbort = (): void => {\n if (settled) return;\n settled = true;\n resolve(abortedResult(merged));\n };\n merged.addEventListener(\"abort\", onAbort, { once: true });\n exec.then(\n (r) => {\n if (settled) return;\n settled = true;\n merged.removeEventListener(\"abort\", onAbort);\n resolve(r);\n },\n (e) => {\n if (settled) return;\n settled = true;\n merged.removeEventListener(\"abort\", onAbort);\n // Preserve the original rejection (existing dispatch error handling catches it).\n reject(e);\n },\n );\n });\n}\n","import type { SDKMessage, SDKToolUseMessage } from \"../../types/messages.js\";\nimport { emitRunEvent } from \"../../types/run-events.js\";\nimport type { InteractionUpdate } from \"../../types/updates.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { generateCallId } from \"../ids.js\";\nimport type { LlmContentPart, LlmToolCallPart } from \"../llm/types.js\";\nimport { checkToolWhitelist } from \"../runtime/concurrency/async-local-storage.js\";\nimport { mapWithConcurrency } from \"../runtime/concurrency/map-with-concurrency.js\";\nimport { HISTOGRAM_NAMES } from \"../telemetry/span-names.js\";\nimport { type RepairableTool, repairToolCall } from \"../tool-dispatch/repair-middleware.js\";\nimport type { AgentLoopInputs, ResolvedTool } from \"./loop-types.js\";\nimport { executeTool, renderToolResult, type ToolResult } from \"./tool-executors.js\";\nimport { raceToolExecution } from \"./tool-timeout.js\";\n\nexport type { ResolvedTool } from \"./loop-types.js\";\n\n/**\n * T2.4 — Parallel tool dispatch with bounded concurrency (DR2 finding #4).\n *\n * Pre-T2.4 this was a serial `for...of` loop — each tool call awaited\n * before the next. With N independent tools each taking Tms, total\n * wall-clock was N×Tms. T2.4 switches to `Promise.all` with bounded\n * concurrency via an inline semaphore (ADR D135 — in-house, no\n * `p-limit` dep). Default cap is 4 concurrent tools; consumer\n * overrides via `AgentLoopInputs.maxConcurrentTools`.\n *\n * Order preservation: `Promise.all` preserves input order in the\n * resolved array regardless of which promise settles first — the\n * LLM expects tool results in call order and this contract holds.\n *\n * Event array safety: `events` is append-only. In single-threaded\n * JS (Node event loop), concurrent `.push()` calls from different\n * microtask continuations do NOT interleave — each push is atomic.\n * The order of events across tools becomes non-deterministic, but\n * each individual tool's events are internally ordered.\n */\nexport async function dispatchTools(\n inputs: AgentLoopInputs,\n tools: ResolvedTool[],\n toolCalls: LlmToolCallPart[],\n events: SDKMessage[],\n // M3 #64 — the run's agent.send span, so each tool.call span nests under it.\n parentSpan?: ToolSpan,\n): Promise<LlmContentPart[]> {\n const maxConcurrent = (inputs as { maxConcurrentTools?: number }).maxConcurrentTools ?? 4;\n // M0-2: consolidated onto the shared ordered bounded pool (was a private\n // `boundedParallel` clone — see plan m0-foundation-expose-primitives).\n return mapWithConcurrency(toolCalls, maxConcurrent, (call) =>\n dispatchSingleCall(inputs, tools, call, events, parentSpan),\n );\n}\n\n/** M3 #64 — the OTel span type threaded for tool-span nesting. */\ntype ToolSpan = ReturnType<NonNullable<AgentLoopInputs[\"telemetry\"]>[\"startSpan\"]> | undefined;\n\n/**\n * T10.4 / PV#2 — `dispatchSingleCall` orchestrator split into named sub-steps.\n * Each step is a private function with a single concern; the orchestrator\n * sequences them. The previous complexity-suppression directive (over a\n * 158 LOC body with 5 origin branches inline) is no longer required after\n * the split.\n *\n * Step taxonomy:\n * 1. `applyRepairAndExtractCall` — ADRs D86-D88 repair middleware.\n * 2. `enforceForkWhitelist` — ADR D111 fork tool-whitelist veto.\n * 3. `startToolCallSpan` — OTel span init + repairs annotation.\n * 4. `runPluginPreToolVeto` — ADR D101 plugin veto.\n * 5. `runFileHookPreToolVeto` — operator-policy hook veto.\n * 6. `runToolWithLifecycle` — exec + onToolStart/End/Error hooks.\n * 7. `finalizeSpanAndPostHook` — span end + postToolUse + return shape.\n */\nasync function dispatchSingleCall(\n inputs: AgentLoopInputs,\n tools: ResolvedTool[],\n call: LlmToolCallPart,\n events: SDKMessage[],\n parentSpan?: ToolSpan,\n): Promise<LlmContentPart> {\n const { call: workingCall, repairs } = applyRepairAndExtractCall(tools, call);\n const callId = generateCallId();\n\n const forkVeto = vetoFromForkWhitelist(inputs, workingCall, callId, events);\n if (forkVeto !== undefined) return forkVeto;\n\n const resolved = tools.find((tool) => tool.name === workingCall.name);\n const toolSpan = startToolCallSpan(inputs, workingCall, resolved, callId, repairs, parentSpan);\n events.push(buildToolUseRunning(inputs, callId, workingCall));\n\n const pluginVeto = await vetoFromPluginPreHook(inputs, workingCall, callId, events);\n if (pluginVeto !== undefined) {\n // T2.5 — end the span on veto so we don't leak open OTel spans.\n // Pre-T2.5 the span started at step 3 but veto returns at step 4/5\n // skipped step 7's `toolSpan.end()` — leaked an open span.\n toolSpan?.setAttribute(\"tool.vetoed\", true);\n toolSpan?.setAttribute(\"tool.veto_source\", \"plugin\");\n toolSpan?.end();\n return pluginVeto;\n }\n\n const fileVeto = await vetoFromFileHookPreDecision(inputs, workingCall, callId, events);\n if (fileVeto !== undefined) {\n toolSpan?.setAttribute(\"tool.vetoed\", true);\n toolSpan?.setAttribute(\"tool.veto_source\", \"file_hook\");\n toolSpan?.end();\n return fileVeto;\n }\n\n // SE2 — all vetoes passed; the tool is about to dispatch. Emit tool_progress.\n emitRunEvent(inputs.runEventSink, {\n type: \"tool_progress\",\n toolName: workingCall.name,\n toolCallId: callId,\n });\n const result = await runToolWithLifecycle(inputs, resolved, workingCall, callId);\n // #65 — post_tool_call hook (previously dead) fires after each tool completes.\n await inputs.pluginManager?.runPostToolCallHooks({\n name: workingCall.name,\n args: workingCall.input,\n result: { stdout: result.stdout, stderr: result.stderr, exitCode: result.exitCode },\n agentId: inputs.agentId,\n runId: inputs.runId,\n });\n return finalizeSpanAndPostHook(inputs, workingCall, callId, result, events, toolSpan);\n}\n\ninterface RepairedCallShape {\n call: LlmToolCallPart;\n repairs: ReadonlyArray<string>;\n}\n\n/**\n * Step 1 — D86-D88 repair middleware. Returns the (possibly rewritten) call\n * and the list of repairs applied (used later for span annotation).\n */\nfunction applyRepairAndExtractCall(\n tools: ResolvedTool[],\n call: LlmToolCallPart,\n): RepairedCallShape {\n const registryMap = buildRepairRegistry(tools);\n const repaired = repairToolCall({ name: call.name, args: call.input, id: call.id }, registryMap);\n if (repaired.repairs.length === 0) return { call, repairs: repaired.repairs };\n return {\n call: {\n ...call,\n name: repaired.call.name,\n input: (repaired.call.args ?? {}) as Record<string, unknown>,\n },\n repairs: repaired.repairs,\n };\n}\n\n/**\n * Step 2 — D111 fork whitelist gate. Fires BEFORE plugin/file hooks because\n * a fork's allowedTools set is the strictest contract. Returns the\n * early-return content part when blocked; `undefined` to continue.\n */\nfunction vetoFromForkWhitelist(\n inputs: AgentLoopInputs,\n call: LlmToolCallPart,\n callId: string,\n events: SDKMessage[],\n): LlmContentPart | undefined {\n const whitelistDecision = checkToolWhitelist(call.name);\n if (whitelistDecision.allowed) return undefined;\n // SE2 — fork-whitelist denial is also an observable permission_denied.\n emitRunEvent(inputs.runEventSink, {\n type: \"permission_denied\",\n toolName: call.name,\n toolCallId: callId,\n source: \"fork_whitelist\",\n message: whitelistDecision.reason ?? \"tool not available in fork\",\n });\n events.push(buildToolUseRunning(inputs, callId, call));\n events.push(\n buildToolUseCompleted(inputs, callId, call, {\n stdout: \"\",\n stderr: whitelistDecision.reason ?? \"tool not available in fork\",\n exitCode: 126,\n }),\n );\n return {\n type: \"tool_result\",\n toolUseId: call.id,\n content: `Tool blocked by fork whitelist: ${whitelistDecision.reason}`,\n };\n}\n\n/**\n * Step 3 — OTel span init + repairs/args annotation. Returns the span\n * handle (or `undefined` when telemetry is disabled) for later finalization.\n */\nfunction startToolCallSpan(\n inputs: AgentLoopInputs,\n call: LlmToolCallPart,\n resolved: ResolvedTool | undefined,\n callId: string,\n repairs: ReadonlyArray<string>,\n parentSpan?: ToolSpan,\n): ToolSpan {\n // M3 #64 — nest tool.call under the run's agent.send span (not a flat sibling).\n const toolSpan = inputs.telemetry?.startChildSpan(parentSpan, \"tool.call\", {\n \"tool.name\": call.name,\n \"tool.origin\": resolved?.origin ?? \"unknown\",\n callId,\n });\n if (repairs.length > 0 && toolSpan !== undefined) {\n toolSpan.setAttribute(\"tool.repairs\", repairs.join(\"; \"));\n }\n if (toolSpan !== undefined && inputs.telemetry?.includeContent === true) {\n toolSpan.addEvent(\"args\", { input: JSON.stringify(call.input) });\n }\n return toolSpan;\n}\n\n/**\n * Step 4 — D101 plugin `pre_tool_call` veto. Plugins are author-supplied\n * (code-level safety) and fire BEFORE file hooks (operator policy).\n */\nasync function vetoFromPluginPreHook(\n inputs: AgentLoopInputs,\n call: LlmToolCallPart,\n callId: string,\n events: SDKMessage[],\n): Promise<LlmContentPart | undefined> {\n const pluginVeto = await inputs.pluginManager?.runPreToolCallHooks({\n name: call.name,\n args: call.input,\n agentId: inputs.agentId,\n runId: inputs.runId,\n // SE1 — thread the run's permission mode so a PermissionPlugin gates per-run.\n ...(inputs.permissionMode !== undefined ? { permissionMode: inputs.permissionMode } : {}),\n });\n if (pluginVeto === undefined) return undefined;\n // SE2 — a plugin veto (e.g. the permission gate) is a runtime-observability\n // signal: emit a typed `permission_denied` event out-of-band.\n emitRunEvent(inputs.runEventSink, {\n type: \"permission_denied\",\n toolName: call.name,\n toolCallId: callId,\n source: \"plugin\",\n message: pluginVeto.message,\n });\n events.push(\n buildToolUseCompleted(inputs, callId, call, {\n stdout: \"\",\n stderr: pluginVeto.message,\n exitCode: 126,\n }),\n );\n return {\n type: \"tool_result\",\n toolUseId: call.id,\n content: `Plugin blocked this tool call: ${pluginVeto.message}`,\n };\n}\n\n/**\n * Step 5 — file-based hooks `preToolUse` decision. Denial is surfaced as a\n * regular `tool_result` (not `isError`) so the model can react in narrative;\n * marking it `isError` would short-circuit the agent loop, which is too\n * harsh for a policy denial.\n */\nasync function vetoFromFileHookPreDecision(\n inputs: AgentLoopInputs,\n call: LlmToolCallPart,\n callId: string,\n events: SDKMessage[],\n): Promise<LlmContentPart | undefined> {\n const preDecision = await inputs.hooks.run({\n event: \"preToolUse\",\n tool: call.name,\n input: call.input,\n agentId: inputs.agentId,\n runId: inputs.runId,\n });\n if (!preDecision.blocked) return undefined;\n // SE2 — operator file-hook `preToolUse` denial is also an observable event.\n emitRunEvent(inputs.runEventSink, {\n type: \"permission_denied\",\n toolName: call.name,\n toolCallId: callId,\n source: \"file_hook\",\n message: preDecision.reason ?? \"blocked by hook\",\n });\n events.push(\n buildToolUseCompleted(inputs, callId, call, {\n stdout: \"\",\n stderr: preDecision.reason ?? \"blocked by hook\",\n exitCode: 126,\n }),\n );\n return {\n type: \"tool_result\",\n toolUseId: call.id,\n content: `Hook denied this tool call: ${preDecision.reason ?? \"no reason given\"}`,\n };\n}\n\n/**\n * Step 6 — exec + D315-D317 onToolStart/End/Error lifecycle. Fires\n * `onToolError` when stderr/exit signals failure; otherwise `onToolEnd`.\n * The `error` field passed to `onToolError` is ALWAYS an `Error` instance.\n */\nasync function runToolWithLifecycle(\n inputs: AgentLoopInputs,\n resolved: ResolvedTool | undefined,\n call: LlmToolCallPart,\n callId: string,\n): Promise<ToolResult> {\n const startAt = Date.now();\n await safeEmitToolHook(inputs.onToolStart, {\n toolName: call.name,\n args: call.input,\n conversationId: inputs.agentId,\n callId,\n });\n // #47-followup — surface the tool call LIVE via onDelta, at its true chronological position\n // (BETWEEN LLM rounds, before the post-tool answer streams). Tool dispatch already runs here, so\n // emitting the lifecycle from onDelta lets a consumer render tool→result ahead of the round-2 text\n // without the bridge having to HOLD the answer. The run.stream() replay of the same call/result is\n // deduped by callId downstream, so this never double-renders.\n await emitToolLifecycleDelta(inputs, {\n type: \"tool-call-started\",\n callId,\n toolCall: { callId, name: call.name, args: call.input },\n modelCallId: callId,\n });\n // #58 — bound the tool by the run's cancellation signal + optional per-tool\n // timeout so a hung tool cannot wedge the loop and cancel interrupts it.\n const result = await raceToolExecution(executeTool(inputs, resolved, call), {\n signal: inputs.signal,\n timeoutMs: inputs.perToolTimeoutMs,\n });\n const durationMs = Date.now() - startAt;\n // #47-followup — the matching live `tool-call-completed`, carrying the rendered result so the\n // consumer shows the output at the correct position (before the answer). Same value the returned\n // `tool_result` content part uses, so the onDelta render matches the run.stream() render it dedups.\n await emitToolLifecycleDelta(inputs, {\n type: \"tool-call-completed\",\n callId,\n toolCall: {\n callId,\n name: call.name,\n args: call.input,\n result: result.content !== undefined ? result.content : renderToolResult(result),\n },\n modelCallId: callId,\n });\n // M3 #64 — emit the tool-call duration as a metric (was hook-only).\n inputs.telemetry?.recordHistogram(HISTOGRAM_NAMES.TOOL_CALL_DURATION_MS, durationMs, {\n \"tool.name\": call.name,\n });\n if (result.exitCode !== undefined && result.exitCode !== 0 && result.exitCode !== null) {\n await safeEmitToolHook(inputs.onToolError, {\n toolName: call.name,\n args: call.input,\n error: new Error(result.stderr || `tool exited with code ${result.exitCode}`),\n conversationId: inputs.agentId,\n callId,\n durationMs,\n attempt: 1,\n });\n } else {\n await safeEmitToolHook(inputs.onToolEnd, {\n toolName: call.name,\n args: call.input,\n // SE17 — when a `toModelOutput` split is active, observability gets the FULL\n // raw output (`appResult`), NOT the compact model-facing value. SE7 — a\n // block-returning handler has empty `stdout`; surface its structured content\n // to the hook instead of an empty string.\n result:\n result.appResult !== undefined\n ? result.appResult\n : result.content !== undefined\n ? result.content\n : result.stdout,\n conversationId: inputs.agentId,\n callId,\n durationMs,\n });\n }\n return result;\n}\n\n/**\n * Step 7 — finalize the OTel span, emit the `tool_use_completed` event,\n * fire the `postToolUse` hook fire-and-forget, and build the\n * `tool_result` content part returned to the agent loop.\n */\nfunction finalizeSpanAndPostHook(\n inputs: AgentLoopInputs,\n call: LlmToolCallPart,\n callId: string,\n result: ToolResult,\n events: SDKMessage[],\n toolSpan: ReturnType<NonNullable<AgentLoopInputs[\"telemetry\"]>[\"startSpan\"]> | undefined,\n): LlmContentPart {\n toolSpan?.setAttribute(\"exitCode\", result.exitCode ?? 0);\n if (toolSpan !== undefined && inputs.telemetry?.includeContent === true) {\n toolSpan.addEvent(\"result\", { stdout: result.stdout.slice(0, 1000) });\n }\n toolSpan?.end();\n events.push(buildToolUseCompleted(inputs, callId, call, result));\n // T2.8 — postToolUse is fire-and-forget (runs AFTER the tool result\n // is captured, so a veto is meaningless). But errors must NOT be\n // silently swallowed — at minimum log WARN so operators know a hook\n // is misbehaving. Pre-T2.8 the bare `void` prefix lost errors entirely.\n inputs.hooks\n .run({\n event: \"postToolUse\",\n tool: call.name,\n input: call.input,\n output: {\n stdout: result.stdout,\n stderr: result.stderr,\n exitCode: result.exitCode ?? 0,\n // SE7 — structured content (text + image blocks) when the handler\n // returned/threw blocks; absent for the string path.\n ...(result.content !== undefined ? { content: result.content } : {}),\n },\n agentId: inputs.agentId,\n runId: inputs.runId,\n })\n .catch((err: unknown) => {\n diag(\n `[theokit-sdk] postToolUse hook error (swallowed): ${err instanceof Error ? err.message : String(err)}\\n`,\n );\n });\n return {\n type: \"tool_result\",\n toolUseId: call.id,\n // SE7 — structured content blocks (handler-returned or ToolError-carried)\n // are authoritative; otherwise the legacy string rendering.\n content: result.content !== undefined ? result.content : renderToolResult(result),\n ...(result.exitCode !== 0 && result.exitCode !== undefined ? { isError: true } : {}),\n };\n}\n\n/**\n * #47-followup — emit a tool-lifecycle `InteractionUpdate` (`tool-call-started` / `tool-call-completed`)\n * through `onDelta`, so the tool renders at its true stream position (between LLM rounds, before the\n * post-tool answer). Awaited + error-swallowed (mirrors the loop's `safeCall` around onDelta): a\n * throwing listener must never crash the agent loop. No-op when `onDelta` is unset.\n *\n * @internal\n */\nasync function emitToolLifecycleDelta(\n inputs: AgentLoopInputs,\n update: InteractionUpdate,\n): Promise<void> {\n if (inputs.onDelta === undefined) return;\n try {\n await inputs.onDelta({ update });\n } catch (err) {\n diag(\n `[theokit-sdk] onDelta tool-lifecycle emit error (swallowed): ${err instanceof Error ? err.message : String(err)}\\n`,\n );\n }\n}\n\n/**\n * D317 — fire-and-forget tool-lifecycle hook with error swallowed via\n * stderr warn. Single chokepoint so all three callbacks (start/end/error)\n * share the same hardening: a misbehaving listener cannot crash the agent\n * loop.\n *\n * @internal\n */\nasync function safeEmitToolHook<E>(\n callback: ((event: E) => void | Promise<void>) | undefined,\n event: E,\n): Promise<void> {\n if (callback === undefined) return;\n try {\n await callback(event);\n } catch (cause) {\n const msg = cause instanceof Error ? cause.message : String(cause);\n diag(`[theokit-sdk] tool lifecycle hook threw: ${msg}\\n`);\n }\n}\n\nfunction buildToolUseRunning(\n inputs: AgentLoopInputs,\n callId: string,\n call: LlmToolCallPart,\n): SDKToolUseMessage {\n return {\n type: \"tool_call\",\n agent_id: inputs.agentId,\n run_id: inputs.runId,\n call_id: callId,\n name: call.name,\n status: \"running\",\n args: call.input,\n };\n}\n\n/**\n * T4.1 helper: project the agent-loop's ResolvedTool[] into a registry\n * shape consumable by `repairToolCall`. Caller owns the Map lifetime\n * (rebuilt each dispatchSingleCall — O(tools.length) overhead is negligible\n * compared to the LLM round-trip).\n */\nfunction buildRepairRegistry(tools: ResolvedTool[]): ReadonlyMap<string, RepairableTool> {\n const out = new Map<string, RepairableTool>();\n for (const t of tools) {\n out.set(t.name, { name: t.name, inputSchema: t.inputSchema });\n }\n return out;\n}\n\nfunction buildToolUseCompleted(\n inputs: AgentLoopInputs,\n callId: string,\n call: LlmToolCallPart,\n result: ToolResult,\n): SDKToolUseMessage {\n return {\n type: \"tool_call\",\n agent_id: inputs.agentId,\n run_id: inputs.runId,\n call_id: callId,\n name: call.name,\n status: \"completed\",\n args: call.input,\n result: {\n stdout: result.stdout,\n stderr: result.stderr,\n exitCode: result.exitCode ?? 0,\n },\n };\n}\n","/**\n * #57 — content-level defense for tool results before they reach the LLM.\n *\n * Two opt-in behaviors, applied at the `transform_tool_result` seam (#65):\n * - `delimit`: wrap untrusted tool output in explicit data boundaries\n * (\"spotlighting\") so the model treats it as DATA, not instructions — the\n * primary mitigation against tool-result prompt injection. Non-destructive:\n * the content is preserved, only framed. A boundary marker appearing inside\n * the content is neutralized so it cannot break out of the frame.\n * - `redactPii`: replace common PII patterns (email, phone) with `[REDACTED]`.\n *\n * @internal\n */\n\nimport type { ToolResultGuardOptions } from \"../../types/run.js\";\nimport { renderToolResultContentText } from \"../llm/tool-result-content.js\";\nimport type { LlmContentPart } from \"../llm/types.js\";\n\n// SE45 / D435 — the ToolResultGuardOptions CONTRACT type now lives in `types/run.ts`\n// (domain layer); this impl module re-exports it so existing internal + public\n// importers (loop-types, index.ts) resolve the same type. Breaks madge cycle 1\n// (types/run.ts no longer imports internal/).\nexport type { ToolResultGuardOptions } from \"../../types/run.js\";\n\nconst OPEN = \"<untrusted-tool-output>\";\nconst CLOSE = \"</untrusted-tool-output>\";\n\nconst PII_PATTERNS: readonly RegExp[] = [\n /\\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,}\\b/g, // email\n /\\b(?:\\+?\\d{1,3}[-.\\s]?)?\\(?\\d{3}\\)?[-.\\s]?\\d{3}[-.\\s]?\\d{4}\\b/g, // phone\n];\n\nfunction guardText(content: string, opts: ToolResultGuardOptions): string {\n let out = content;\n if (opts.redactPii === true) {\n for (const re of PII_PATTERNS) out = out.replace(re, \"[REDACTED]\");\n }\n if (opts.delimit === true) {\n // Neutralize any attempt to forge the closing boundary from inside the data.\n const safe = out.split(CLOSE).join(\"</ untrusted-tool-output>\");\n out = `${OPEN}\\n${safe}\\n${CLOSE}`;\n }\n return out;\n}\n\n/**\n * Apply the tool-result guard to the tool_result parts of a content array. When\n * neither behavior is enabled the array is returned unchanged (zero overhead).\n */\nexport function applyToolResultGuard(\n parts: readonly LlmContentPart[],\n opts: ToolResultGuardOptions,\n): LlmContentPart[] {\n if (opts.delimit !== true && opts.redactPii !== true) return parts as LlmContentPart[];\n return parts.map((p) =>\n // SE7 — guard the TEXT of a tool result (string or the text blocks of a\n // structured content); image blocks pass through untouched.\n p.type === \"tool_result\"\n ? { ...p, content: renderToolResultContentText(p.content, (t) => guardText(t, opts)) }\n : p,\n );\n}\n","{\n \"_meta\": {\n \"pricingVersion\": \"litellm-2026-05-snapshot\",\n \"source\": \"https://github.com/BerriAI/litellm/blob/main/model_prices_and_context_window.json\",\n \"fetchedAt\": \"2026-05-27\",\n \"note\": \"Hand-curated snapshot of top models 2026; refresh via scripts/refresh-pricing.mjs. Per-million-tokens USD.\"\n },\n \"models\": {\n \"anthropic/claude-opus-4-7\": {\n \"input\": 5.0,\n \"output\": 25.0,\n \"cacheRead\": 0.5,\n \"cacheWrite\": 6.25\n },\n \"anthropic/claude-opus-4-6\": {\n \"input\": 5.0,\n \"output\": 25.0,\n \"cacheRead\": 0.5,\n \"cacheWrite\": 6.25\n },\n \"anthropic/claude-opus-4-5\": {\n \"input\": 5.0,\n \"output\": 25.0,\n \"cacheRead\": 0.5,\n \"cacheWrite\": 6.25\n },\n \"anthropic/claude-sonnet-4-6\": {\n \"input\": 3.0,\n \"output\": 15.0,\n \"cacheRead\": 0.3,\n \"cacheWrite\": 3.75\n },\n \"anthropic/claude-sonnet-4-5\": {\n \"input\": 3.0,\n \"output\": 15.0,\n \"cacheRead\": 0.3,\n \"cacheWrite\": 3.75\n },\n \"anthropic/claude-haiku-4-5\": {\n \"input\": 1.0,\n \"output\": 5.0,\n \"cacheRead\": 0.1,\n \"cacheWrite\": 1.25\n },\n \"anthropic/claude-3-5-sonnet\": {\n \"input\": 3.0,\n \"output\": 15.0,\n \"cacheRead\": 0.3,\n \"cacheWrite\": 3.75\n },\n \"anthropic/claude-3-5-haiku\": {\n \"input\": 0.8,\n \"output\": 4.0,\n \"cacheRead\": 0.08,\n \"cacheWrite\": 1.0\n },\n \"anthropic/claude-3-opus\": {\n \"input\": 15.0,\n \"output\": 75.0,\n \"cacheRead\": 1.5,\n \"cacheWrite\": 18.75\n },\n \"anthropic/claude-3-haiku\": {\n \"input\": 0.25,\n \"output\": 1.25,\n \"cacheRead\": 0.03,\n \"cacheWrite\": 0.3\n },\n \"openai/gpt-4o\": {\n \"input\": 2.5,\n \"output\": 10.0,\n \"cacheRead\": 1.25\n },\n \"openai/gpt-4o-mini\": {\n \"input\": 0.15,\n \"output\": 0.6,\n \"cacheRead\": 0.075\n },\n \"openai/gpt-4.1\": {\n \"input\": 2.0,\n \"output\": 8.0,\n \"cacheRead\": 0.5\n },\n \"openai/gpt-4.1-mini\": {\n \"input\": 0.4,\n \"output\": 1.6,\n \"cacheRead\": 0.1\n },\n \"openai/gpt-4.1-nano\": {\n \"input\": 0.1,\n \"output\": 0.4,\n \"cacheRead\": 0.025\n },\n \"openai/o3\": {\n \"input\": 2.0,\n \"output\": 8.0,\n \"cacheRead\": 0.5\n },\n \"openai/o3-mini\": {\n \"input\": 1.1,\n \"output\": 4.4,\n \"cacheRead\": 0.55\n },\n \"openai/o4-mini\": {\n \"input\": 1.1,\n \"output\": 4.4,\n \"cacheRead\": 0.275\n },\n \"deepseek/deepseek-chat\": {\n \"input\": 0.14,\n \"output\": 0.28\n },\n \"deepseek/deepseek-reasoner\": {\n \"input\": 0.55,\n \"output\": 2.19\n },\n \"google/gemini-2.5-pro\": {\n \"input\": 1.25,\n \"output\": 10.0\n },\n \"google/gemini-2.5-flash\": {\n \"input\": 0.15,\n \"output\": 0.6\n },\n \"google/gemini-2.0-flash\": {\n \"input\": 0.1,\n \"output\": 0.4\n }\n }\n}\n","/**\n * Pricing registry — bundled snapshot of LiteLLM JSON (ADR D379) with\n * lazy load + alias normalization (EC-2).\n *\n * Snapshot lives in `pricing-data.json` (hand-curated 2026-05; refresh\n * via `scripts/refresh-pricing.mjs`). All rates in USD per 1_000_000\n * tokens (D378).\n *\n * Lookup precedence (EC-2):\n * 1. Direct `provider/model` key\n * 2. Strip date suffix (-YYYYMMDD or -YYYY-MM-DD)\n * 3. Anthropic dot-to-dash normalization (claude-opus-4.7 → claude-opus-4-7)\n * 4. Strip `openrouter/` prefix\n *\n * @internal\n */\n\nimport { getCatalogModelInfo, isPatchedModelKey } from \"../providers/catalog-loader.js\";\nimport pricingData from \"./pricing-data.json\" with { type: \"json\" };\n\nexport interface PricingEntry {\n readonly provider: string;\n readonly model: string;\n readonly inputCostPerMillion: number;\n readonly outputCostPerMillion: number;\n readonly cacheReadCostPerMillion?: number;\n readonly cacheWriteCostPerMillion?: number;\n readonly reasoningCostPerMillion?: number;\n readonly pricingVersion: string;\n}\n\ninterface RawModelEntry {\n input: number;\n output: number;\n cacheRead?: number;\n cacheWrite?: number;\n reasoning?: number;\n}\n\ninterface RawPricingData {\n _meta: { pricingVersion: string; [k: string]: unknown };\n models: Record<string, RawModelEntry>;\n}\n\nconst data = pricingData as RawPricingData;\n\nfunction buildEntry(key: string, raw: RawModelEntry): PricingEntry {\n const [provider, ...modelParts] = key.split(\"/\");\n return {\n provider: provider ?? \"unknown\",\n model: modelParts.join(\"/\"),\n inputCostPerMillion: raw.input,\n outputCostPerMillion: raw.output,\n ...(raw.cacheRead !== undefined ? { cacheReadCostPerMillion: raw.cacheRead } : {}),\n ...(raw.cacheWrite !== undefined ? { cacheWriteCostPerMillion: raw.cacheWrite } : {}),\n ...(raw.reasoning !== undefined ? { reasoningCostPerMillion: raw.reasoning } : {}),\n pricingVersion: data._meta.pricingVersion,\n };\n}\n\nfunction stripDateSuffix(model: string): string {\n // EC-2: -20250507 or -2025-05-07 at end of name.\n return model.replace(/-\\d{4}-?\\d{2}-?\\d{2}$/, \"\");\n}\n\nfunction normalizeAnthropicDots(model: string): string {\n // EC-2: claude-opus-4.7 → claude-opus-4-7\n return model.replace(/(\\d+)\\.(\\d+)/g, \"$1-$2\");\n}\n\nfunction stripOpenRouterPrefix(modelId: string): string {\n return modelId.startsWith(\"openrouter/\") ? modelId.slice(\"openrouter/\".length) : modelId;\n}\n\nfunction lookupRaw(key: string): RawModelEntry | undefined {\n return data.models[key];\n}\n\n/**\n * Returns the pricing entry for a given `{provider, model}` route.\n * Tries direct lookup, then 3 alias normalizations (EC-2).\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: 4-step alias resolution chain (direct → date-strip → dot-norm → openrouter-strip) is intrinsic to the lookup; refactor adds noise without separation.\nexport function getPricingEntry(opts: {\n provider: string;\n model: string;\n baseUrl?: string;\n}): PricingEntry | undefined {\n // OpenRouter normalization: strip prefix if model includes it\n const cleaned = stripOpenRouterPrefix(opts.model);\n const directKey = `${opts.provider}/${cleaned}`;\n\n // 1. Direct\n const direct = lookupRaw(directKey);\n if (direct !== undefined) return buildEntry(directKey, direct);\n\n // 2. Strip date suffix\n const noSuffix = stripDateSuffix(cleaned);\n if (noSuffix !== cleaned) {\n const noSuffixKey = `${opts.provider}/${noSuffix}`;\n const found = lookupRaw(noSuffixKey);\n if (found !== undefined) return buildEntry(noSuffixKey, found);\n }\n\n // 3. Anthropic dot-to-dash\n if (opts.provider === \"anthropic\") {\n const normalized = normalizeAnthropicDots(stripDateSuffix(cleaned));\n const normKey = `${opts.provider}/${normalized}`;\n const found = lookupRaw(normKey);\n if (found !== undefined) return buildEntry(normKey, found);\n }\n\n // 4. Model id contains provider/model (e.g., openrouter passthrough)\n if (cleaned.includes(\"/\")) {\n const found = lookupRaw(cleaned);\n if (found !== undefined) return buildEntry(cleaned, found);\n // Try strip date on the full path too\n const stripped = stripDateSuffix(cleaned);\n if (stripped !== cleaned) {\n const found2 = lookupRaw(stripped);\n if (found2 !== undefined) return buildEntry(stripped, found2);\n }\n }\n\n // 5. M44 — catalog fallback (ADR D3: pricing-data.json FEEDS from the catalog, never replaced by it).\n // On a TOTAL LiteLLM miss, consult the model-info index's `cost` (models.dev USD-per-1M convention —\n // same unit as D378). Provenance marked \"catalog-vendored\" so CostBreakdown stays honest about the source.\n const catalogEntry = catalogCostFallback(opts.provider, cleaned);\n if (catalogEntry !== undefined) return catalogEntry;\n\n return undefined;\n}\n\n/** Step-5 catalog cost lookup: direct `provider/model`, then the model id as-is when it carries a path. */\n// PRE-EXISTING debt, exposed when M75 fixed the Biome config that used to abort before\n// sweeping these files (a nested root under refactor/). It is not new code and was not touched\n// by M75; refactoring SDK internals without review would trade a visible problem for a diff\n// risky. Tracked in usetheodev/theokit-sdk#151.\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: see the reason just above\nfunction catalogCostFallback(provider: string, cleanedModel: string): PricingEntry | undefined {\n // M44 L10 fix — also try the date-stripped id (parity with the LiteLLM chain's step 2).\n const stripped = stripDateSuffix(cleanedModel);\n const candidates = [`${provider}/${cleanedModel}`, cleanedModel];\n if (stripped !== cleanedModel) candidates.push(`${provider}/${stripped}`, stripped);\n for (const key of candidates) {\n const info = getCatalogModelInfo(key);\n const cost = info?.cost;\n if (cost === undefined) continue;\n const [prov, ...modelParts] = key.split(\"/\");\n return {\n provider: prov ?? provider,\n model: modelParts.join(\"/\") || cleanedModel,\n inputCostPerMillion: cost.input,\n outputCostPerMillion: cost.output,\n ...(cost.cache_read !== undefined ? { cacheReadCostPerMillion: cost.cache_read } : {}),\n ...(cost.cache_write !== undefined ? { cacheWriteCostPerMillion: cost.cache_write } : {}),\n // M44 M5 fix — honest provenance: a key patched by the LIVE models-dev source is not \"vendored\".\n pricingVersion: isPatchedModelKey(key) ? \"catalog-models-dev\" : \"catalog-vendored\",\n };\n }\n return undefined;\n}\n\nexport function pricingVersion(): string {\n return data._meta.pricingVersion;\n}\n","/**\n * computeCost — apply pricing entries to a TokenUsage and produce a\n * CostBreakdown (ADRs D377, D378).\n *\n * Edge cases absorbed:\n * - EC-13: negative pricing → status=\"unknown\" + note.\n * - EC-14: reasoning tokens fall back to outputCostPerMillion when\n * dedicated reasoning rate is undefined.\n * - EC-12: money precision via microcent normalization (× 1e6).\n * - \"subscription_included\" routes (Codex CLI, future Claude Pro) →\n * return $0 with status=\"included\".\n * - Provider unknown / pricing missing → status=\"unknown\" with\n * undefined amountUsd (does NOT return a false 0).\n *\n * @internal\n */\n\nimport type { CostBreakdown, TokenUsage } from \"../../types/usage.js\";\nimport { getPricingEntry, type PricingEntry } from \"./pricing-registry.js\";\n\nconst MICROCENT = 1e6;\n\nfunction isSubscriptionIncluded(provider: string): boolean {\n return provider === \"openai-codex\" || provider === \"codex\";\n}\n\nfunction pricingHasValidRates(entry: PricingEntry): boolean {\n // EC-13: negative pricing is corrupt data.\n return (\n entry.inputCostPerMillion >= 0 &&\n entry.outputCostPerMillion >= 0 &&\n (entry.cacheReadCostPerMillion === undefined || entry.cacheReadCostPerMillion >= 0) &&\n (entry.cacheWriteCostPerMillion === undefined || entry.cacheWriteCostPerMillion >= 0) &&\n (entry.reasoningCostPerMillion === undefined || entry.reasoningCostPerMillion >= 0)\n );\n}\n\nfunction costForTokens(tokens: number, perMillion: number): number {\n // EC-12: microcent precision; (tokens × $/Mtok × 1e6) / 1e6 / 1e6\n // Round to microcents to avoid float drift across additions.\n if (tokens === 0 || perMillion === 0) return 0;\n return Math.round((tokens * perMillion * MICROCENT) / 1_000_000) / MICROCENT;\n}\n\ninterface ComputeArgs {\n readonly usage: TokenUsage;\n readonly provider: string;\n readonly model: string;\n readonly baseUrl?: string;\n}\n\n/**\n * Returns CostBreakdown with `status=\"estimated\"`, `\"unknown\"`, or\n * `\"included\"`. Never throws; never returns 0 when pricing is missing.\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: 5-bucket pricing math + 4 fail-paths is inherently branchy; splitting adds indirection without reducing complexity.\nexport function computeCost(args: ComputeArgs): CostBreakdown {\n // subscription_included route\n if (isSubscriptionIncluded(args.provider)) {\n return {\n amountUsd: 0,\n status: \"included\",\n currency: \"USD\",\n source: \"subscription_included\",\n pricingVersion: undefined,\n };\n }\n\n const entry = getPricingEntry({\n provider: args.provider,\n model: args.model,\n ...(args.baseUrl !== undefined ? { baseUrl: args.baseUrl } : {}),\n });\n if (entry === undefined) {\n return {\n amountUsd: undefined,\n status: \"unknown\",\n currency: \"USD\",\n source: \"unknown\",\n pricingVersion: undefined,\n };\n }\n\n // EC-13: negative pricing entry\n if (!pricingHasValidRates(entry)) {\n return {\n amountUsd: undefined,\n status: \"unknown\",\n currency: \"USD\",\n source: \"unknown\",\n pricingVersion: entry.pricingVersion,\n notes: [\"pricing entry has negative rates; treated as invalid\"],\n };\n }\n\n const notes: string[] = [];\n const detail: {\n input?: number;\n output?: number;\n cacheRead?: number;\n cacheWrite?: number;\n reasoning?: number;\n } = {};\n\n const u = args.usage;\n const inputCost = costForTokens(u.inputTokens, entry.inputCostPerMillion);\n const outputCost = costForTokens(u.outputTokens, entry.outputCostPerMillion);\n detail.input = inputCost;\n detail.output = outputCost;\n let total = inputCost + outputCost;\n\n // Cache buckets — only if pricing available, otherwise mark unknown\n if (u.cacheReadTokens !== undefined && u.cacheReadTokens > 0) {\n if (entry.cacheReadCostPerMillion === undefined) {\n return {\n amountUsd: undefined,\n status: \"unknown\",\n currency: \"USD\",\n source: \"litellm_snapshot\",\n pricingVersion: entry.pricingVersion,\n notes: [\"cache-read tokens present but cacheReadCostPerMillion is undefined\"],\n };\n }\n const c = costForTokens(u.cacheReadTokens, entry.cacheReadCostPerMillion);\n detail.cacheRead = c;\n total += c;\n }\n if (u.cacheWriteTokens !== undefined && u.cacheWriteTokens > 0) {\n if (entry.cacheWriteCostPerMillion === undefined) {\n return {\n amountUsd: undefined,\n status: \"unknown\",\n currency: \"USD\",\n source: \"litellm_snapshot\",\n pricingVersion: entry.pricingVersion,\n notes: [\"cache-write tokens present but cacheWriteCostPerMillion is undefined\"],\n };\n }\n const c = costForTokens(u.cacheWriteTokens, entry.cacheWriteCostPerMillion);\n detail.cacheWrite = c;\n total += c;\n }\n\n // EC-14: reasoning tokens fall back to output rate\n if (u.reasoningTokens !== undefined && u.reasoningTokens > 0) {\n const rate = entry.reasoningCostPerMillion ?? entry.outputCostPerMillion;\n const c = costForTokens(u.reasoningTokens, rate);\n detail.reasoning = c;\n total += c;\n if (entry.reasoningCostPerMillion === undefined) {\n notes.push(\"reasoning tokens billed at output rate (no dedicated reasoning rate available)\");\n }\n }\n\n // Round total to microcents\n const amountUsd = Math.round(total * MICROCENT) / MICROCENT;\n\n return {\n amountUsd,\n status: \"estimated\",\n currency: \"USD\",\n source: \"litellm_snapshot\",\n pricingVersion: entry.pricingVersion,\n ...(notes.length > 0 ? { notes } : {}),\n detail,\n };\n}\n","/**\n * Usage + cost helpers extracted from `loop.ts` (ADRs D376/D377).\n *\n * - `accumulateUsage(usage, llmOutput)` — merge a single LLM turn's 5-bucket\n * token counts into the per-loop {@link UsageAccumulator}. Early-returns\n * when no bucket was populated (avoids spurious zero-step entries on\n * pure-error turns).\n * - `computeUsageCost(inputs, usage)` — resolve provider+model from the\n * `model.id` prefix (with LlmClient.name fallback) and run the pricing\n * registry lookup to produce the matching `CostBreakdown`. Returns\n * `undefined` for the `auto` sentinel model.\n *\n * @internal\n */\n\nimport type { CostBreakdown, TokenUsage } from \"../../types/usage.js\";\nimport { computeCost } from \"../budget/compute-cost.js\";\nimport type { UsageAccumulator } from \"../budget/usage-accumulator.js\";\nimport { parseModelId } from \"../llm/model-identifier.js\";\nimport type { AgentLoopInputs } from \"./loop-types.js\";\n\nexport interface LlmTurnUsage {\n inputTokens?: number;\n outputTokens?: number;\n cacheReadTokens?: number;\n cacheWriteTokens?: number;\n reasoningTokens?: number;\n}\n\nexport function accumulateUsage(usage: UsageAccumulator, turn: LlmTurnUsage): void {\n // D376: even errored turns may have surfaced partial usage; record them\n // when present so partial-failure runs still expose what was spent.\n const hasAnyToken =\n turn.inputTokens !== undefined ||\n turn.outputTokens !== undefined ||\n turn.cacheReadTokens !== undefined ||\n turn.cacheWriteTokens !== undefined ||\n turn.reasoningTokens !== undefined;\n if (!hasAnyToken) return;\n usage.add({\n inputTokens: turn.inputTokens,\n outputTokens: turn.outputTokens,\n cacheReadTokens: turn.cacheReadTokens,\n cacheWriteTokens: turn.cacheWriteTokens,\n reasoningTokens: turn.reasoningTokens,\n });\n}\n\nexport function computeUsageCost(\n inputs: AgentLoopInputs,\n usage: TokenUsage,\n): CostBreakdown | undefined {\n const modelId = inputs.model.id;\n if (modelId === undefined || modelId === \"auto\") return undefined;\n // Prefer the `provider/model` prefix on the model id (e.g.,\n // `anthropic/claude-opus-4-7`, `openai/gpt-4o-mini`). Fall back to the\n // LlmClient name (e.g., \"openai\" for OpenRouter passthrough). The pricing\n // registry's lookup chain (D376/EC-2) handles the openrouter-prefix and\n // date-suffix variants downstream.\n const parsed = parseModelId(modelId);\n const provider = parsed.provider ?? inputs.llm.name;\n const model = parsed.provider !== undefined ? parsed.name : modelId;\n return computeCost({ provider, model, usage });\n}\n","import type { ToolContextMessage } from \"../../types/agent-prims.js\";\nimport { IterationBudget } from \"../budget/tracker/budget.js\";\nimport type { LlmContentPart, LlmMessage, LlmThinkingPart, LlmToolCallPart } from \"../llm/types.js\";\nimport { safeCall } from \"../runtime/system-prompt/safe-call.js\";\nimport { validateResponse } from \"../runtime/validation/validate-response.js\";\nimport { evaluateBudgetGate } from \"./budget-gate.js\";\nimport { firstDoomLoopVerdict } from \"./doom-loop-tracker.js\";\nimport { initLoopContext, type LoopContext } from \"./loop-context-init.js\";\nimport { type LlmTurnOutput, streamLlmTurn } from \"./loop-llm-stream.js\";\nimport { recordThinkingOnSilentToolRound, thinkingStep } from \"./loop-thinking-steps.js\";\nimport type { AgentLoopInputs, AgentLoopOutput } from \"./loop-types.js\";\nimport { buildAssistantEvent, buildAssistantTurn } from \"./message-builders.js\";\nimport { dispatchTools } from \"./tool-dispatch.js\";\nimport { applyToolResultGuard } from \"./tool-result-guard.js\";\nimport { accumulateUsage, computeUsageCost } from \"./usage-and-cost.js\";\n\n/**\n * SE12 — flatten the running transcript to the read-only text projection tool\n * handlers receive on `ctx.messages`. Non-text parts (tool calls / results) are\n * dropped so a tool never sees raw wire parts or nested tool args.\n */\nfunction projectToolContextMessages(messages: readonly LlmMessage[]): ToolContextMessage[] {\n const projected: ToolContextMessage[] = [];\n for (const m of messages) {\n const content = m.content.flatMap((p) => (p.type === \"text\" ? [p.text] : [])).join(\"\");\n // Skip turns that project to empty text (a tool-only assistant turn or a\n // tool-result-only user turn) — the text projection has nothing to forward,\n // so a messageFilter never sees zero-content noise.\n if (content !== \"\") projected.push({ role: m.role, content });\n }\n return projected;\n}\n\n/**\n * The real agent loop. Given an LLM client, MCP clients, hooks, and a shell\n * runner, it drives the LLM-tool-LLM cycle until the model stops. All\n * intermediate states surface as `SDKMessage` events so the caller can\n * stream them through `Run.stream()`.\n *\n * @internal\n */\n\nexport type { AgentLoopInputs, AgentLoopOutput } from \"./loop-types.js\";\n\n/** T2.1 (ADR D93) — maximum number of bailout-nudge user messages to inject. */\nconst MAX_NUDGE_ATTEMPTS = 2;\n\n/** M1-4 — maximum number of `stop`-hook feedback re-prompts (reflection ceiling), mirroring MAX_NUDGE_ATTEMPTS. */\nexport const MAX_STOP_FEEDBACK_ATTEMPTS = 2;\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: agent loop is the orchestrator — context build, LLM round trip, tool dispatch, stop condition, span lifecycle are deliberately co-located so the streaming contract stays linear.\nexport async function runAgentLoop(inputs: AgentLoopInputs): Promise<AgentLoopOutput> {\n const sendSpan = inputs.telemetry?.startSpan(\"agent.send\", {\n agentId: inputs.agentId,\n runId: inputs.runId,\n \"model.id\": inputs.model.id ?? \"auto\",\n });\n if (sendSpan !== undefined && inputs.telemetry?.includeContent === true) {\n sendSpan.addEvent(\"prompt\", { content: inputs.userMessage });\n }\n let ctxRef: LoopContext | undefined;\n try {\n const ctx = await initLoopContext(inputs);\n ctxRef = ctx;\n // M3 #64 — expose the run span so child spans nest under it.\n ctx.sendSpan = sendSpan;\n // #65 — on_session_start hook (previously dead) fires once per run.\n await inputs.pluginManager?.runOnSessionStartHooks({\n agentId: inputs.agentId,\n runId: inputs.runId,\n });\n const budget =\n inputs.budget ?? new IterationBudget({ maxIterations: inputs.maxIterations ?? 8 });\n // M1-2 (T2.2): track the last turn's decision so we can tell a clean\n // `done` finish from a silent truncation at the iteration ceiling.\n let lastTurnDecision: \"continue\" | \"done\" | \"error\" | undefined;\n while (budget.shouldContinue()) {\n if (inputs.budgetTracker !== undefined) {\n // Fail-CLOSED gate: a tracker that throws denies the iteration\n // instead of silently proceeding past budget (arch-review L1).\n const decision = evaluateBudgetGate(inputs.budgetTracker);\n if (decision.allowed === false) {\n ctx.finalStatus = \"error\";\n if (decision.detail !== undefined) {\n ctx.error = { message: decision.detail, code: decision.reason ?? \"budget\" };\n }\n // M1-2 (T2.2): a pluggable tracker denying on its iteration ceiling is\n // the same \"hit the iteration limit\" event as the legacy IterationBudget\n // exhausting below — surface the same signal so a caller using\n // createCounterBudgetTracker({maxIterations}) detects it consistently.\n if (decision.reason === \"iteration_limit\") {\n ctx.stoppedAtIterationLimit = true;\n }\n break;\n }\n }\n const usingGrace = budget.remaining <= 0 && !budget.graceCallUsed;\n if (usingGrace) budget.useGraceCall();\n const decision = await runIteration(inputs, ctx);\n lastTurnDecision = decision;\n if (decision === \"done\") break;\n if (decision === \"error\") {\n ctx.finalStatus = \"error\";\n break;\n }\n budget.consume();\n // M1-1: advance the pluggable tracker's iteration counter once per turn\n // so trackers gating on maxIterations actually halt (the counter was dead\n // because nothing called this). Optional + non-throwing per the contract.\n inputs.budgetTracker?.nextIteration?.();\n // #58 — after a completed turn, stop before starting a new one if the run\n // was cancelled mid-round. The first turn always runs (its own abort UX,\n // \"[aborted]\", is produced inside runIteration); this only prevents a NEW\n // LLM turn after a cancel lands. The terminal status is `\"cancelled\"` so a\n // caller can distinguish a cancel from a clean finish (RunStatus contract).\n if (inputs.signal?.aborted === true) {\n ctx.finalStatus = \"cancelled\";\n break;\n }\n }\n // M1-2 (T2.2): the loop exited because the iteration budget is exhausted\n // (not via a `done`/`error` break) while the last turn still wanted tools —\n // a silent truncation the caller (or a continuation driver) must detect.\n if (lastTurnDecision === \"continue\" && budget.shouldContinue() === false) {\n ctx.stoppedAtIterationLimit = true;\n }\n if (\n budget.shouldContinue() === false &&\n ctx.finalStatus === \"finished\" &&\n ctx.finalText === \"\"\n ) {\n ctx.finalStatus = \"error\";\n }\n sendSpan?.setAttribute(\"status\", ctx.finalStatus);\n // Observability: a doom-loop stop reports finalStatus \"finished\" (a controlled stop), so\n // without this attribute it is indistinguishable from a clean finish in traces. Ops watching\n // OTel spans need to see the guard fire.\n if (ctx.stoppedByDoomLoop === true) sendSpan?.setAttribute(\"stoppedByDoomLoop\", true);\n if (inputs.telemetry?.includeContent === true && ctx.finalText.length > 0) {\n sendSpan?.addEvent(\"response\", { content: ctx.finalText });\n }\n const usage = ctx.usage.hasAny() ? ctx.usage.toTokenUsage() : undefined;\n const cost = usage !== undefined ? computeUsageCost(inputs, usage) : undefined;\n if (usage !== undefined) {\n sendSpan?.setAttributes({\n totalInputTokens: usage.inputTokens,\n totalOutputTokens: usage.outputTokens,\n ...(cost?.amountUsd !== undefined ? { totalCostUsd: cost.amountUsd } : {}),\n });\n }\n if (\n ctx.finalStatus === \"finished\" &&\n ctx.memoryProviderHandle !== undefined &&\n inputs.memoryProvider?.sync !== undefined\n ) {\n try {\n await inputs.memoryProvider.sync(ctx.memoryProviderHandle);\n } catch {\n // Swallow — sync() MUST be non-throwing on the hot path.\n }\n }\n return {\n events: ctx.events,\n finalStatus: ctx.finalStatus,\n result: ctx.finalText,\n conversation: ctx.conversation,\n ...(usage !== undefined ? { usage } : {}),\n ...(cost !== undefined ? { cost } : {}),\n ...(ctx.error !== undefined ? { error: ctx.error } : {}),\n ...(ctx.stoppedAtIterationLimit === true ? { stoppedAtIterationLimit: true } : {}),\n ...(ctx.stoppedByDoomLoop === true ? { stoppedByDoomLoop: true } : {}),\n };\n } finally {\n // #65 — on_session_end hook (previously dead) fires once per run, even on error.\n await inputs.pluginManager?.runOnSessionEndHooks({\n agentId: inputs.agentId,\n runId: inputs.runId,\n });\n if (\n ctxRef !== undefined &&\n ctxRef.memoryProviderHandle !== undefined &&\n inputs.memoryProvider !== undefined\n ) {\n try {\n await inputs.memoryProvider.dispose(ctxRef.memoryProviderHandle);\n } catch {\n // Per contract: dispose MUST be non-throwing on the hot path.\n }\n }\n sendSpan?.end();\n }\n}\n\nasync function emitAssistantTextStep(\n inputs: AgentLoopInputs,\n ctx: LoopContext,\n text: string,\n thinking: LlmThinkingPart | undefined,\n): Promise<void> {\n ctx.events.push(buildAssistantEvent(inputs, text));\n // theokit#122 — thinking and text belong to ONE assistant message. Anthropic requires the\n // thinking block to come first in the message it belongs to, and `mapAgentTurn` folds one\n // conversation turn into one assistant record — so they must share a turn, in this order.\n const steps: import(\"../../types/conversation.js\").ConversationStep[] = [\n ...(thinking !== undefined ? [thinkingStep(thinking)] : []),\n { type: \"assistantMessage\" as const, message: { text } },\n ];\n ctx.conversation.push({ type: \"agentConversationTurn\", turn: { steps } });\n ctx.finalText = text;\n if (inputs.onStep === undefined) return;\n const cb = inputs.onStep;\n await safeCall(\n () => cb({ step: { type: \"assistantMessage\", message: { text } } }),\n undefined,\n \"SendOptions.onStep\",\n );\n}\n\n/**\n * Build the ordered `toolCall` (+ paired `toolResult`) steps for a tool-using turn. Shared by the\n * live `onStep` emission and the `Run.conversation()` accumulation so the two surfaces never drift\n * (#SE39 — onStep previously emitted `toolCall` but dropped `toolResult`; both now use this).\n */\nfunction buildToolSteps(\n calls: LlmToolCallPart[],\n results: LlmContentPart[],\n): import(\"../../types/conversation.js\").ConversationStep[] {\n const steps: import(\"../../types/conversation.js\").ConversationStep[] = [];\n for (let i = 0; i < calls.length; i++) {\n const call = calls[i];\n if (call === undefined) continue;\n steps.push({\n type: \"toolCall\",\n message: { callId: call.id, name: call.name, args: call.input },\n });\n const result = results[i];\n if (result?.type === \"tool_result\") {\n steps.push({\n type: \"toolResult\",\n message: {\n callId: result.toolUseId ?? call.id,\n name: call.name,\n result:\n typeof result.content === \"string\" ? result.content : JSON.stringify(result.content),\n isError: result.isError === true,\n },\n });\n }\n }\n return steps;\n}\n\nfunction pushToolConversationSteps(\n ctx: LoopContext,\n calls: LlmToolCallPart[],\n results: LlmContentPart[],\n): void {\n const steps = buildToolSteps(calls, results);\n if (steps.length > 0) {\n ctx.conversation.push({ type: \"agentConversationTurn\", turn: { steps } });\n }\n}\n\nfunction handleToolErrorContinuation(\n inputs: AgentLoopInputs,\n ctx: LoopContext,\n toolResults: LlmContentPart[],\n): \"continue\" | \"error\" {\n const hasError = toolResults.some((part) => part.type === \"tool_result\" && part.isError === true);\n if (hasError) {\n ctx._consecutiveToolErrors = (ctx._consecutiveToolErrors ?? 0) + 1;\n const cap = (inputs as { maxConsecutiveToolErrors?: number }).maxConsecutiveToolErrors ?? 3;\n if (ctx._consecutiveToolErrors >= cap) return \"error\";\n return \"continue\";\n }\n ctx._consecutiveToolErrors = 0;\n return \"continue\";\n}\n\nfunction shouldNudgeAndContinue(ctx: LoopContext, llmOutput: LlmTurnOutput): boolean {\n if (ctx.nudgeAttempts >= MAX_NUDGE_ATTEMPTS) return false;\n const validation = validateResponse({\n content: llmOutput.text,\n toolCalls: llmOutput.toolCalls,\n });\n if (validation.ok) return false;\n ctx.nudgeAttempts += 1;\n ctx.messages.push({\n role: \"user\",\n content: [\n {\n type: \"text\",\n text: \"Please continue your previous answer or provide a final answer.\",\n },\n ],\n });\n return true;\n}\n\n/**\n * M1-4 — fire the file-based `stop` hook at the clean-finish terminal and, when a\n * hook returns `decision:\"feedback\"`, push that feedback as a `user` re-prompt and\n * continue the loop (a bounded reflection ladder). Returns `true` to re-prompt,\n * `false` to finish.\n *\n * The hook is ALWAYS fired on a clean finish (so an observer `stop` hook sees\n * every terminal, even once the re-prompt ceiling is reached). `decision:\"deny\"`\n * is authoritative regardless of hook ordering (`result.blocked`) → finish.\n * Re-prompting is bounded by `MAX_STOP_FEEDBACK_ATTEMPTS` (ADR D3); `allow`/\n * `deny`/no-hook all finish (ADR D2). Reuses the existing `HooksExecutor` (ADR D4).\n *\n * @internal\n */\nexport async function reflectAfterStop(\n inputs: AgentLoopInputs,\n ctx: LoopContext,\n): Promise<boolean> {\n // Always fire `stop` on a clean finish — an observer hook must see the terminal\n // even at the re-prompt ceiling (the ceiling gates re-prompting, not firing).\n const result = await inputs.hooks.run({\n event: \"stop\",\n agentId: inputs.agentId,\n runId: inputs.runId,\n });\n // A `deny` short-circuits the executor (`blocked`) and is authoritative\n // regardless of hook ordering — a later feedback never overrides an earlier deny.\n if (result.blocked) return false;\n if (ctx.stopFeedbackAttempts >= MAX_STOP_FEEDBACK_ATTEMPTS) return false;\n const feedback = result.decisions.find(\n (d) => d.decision === \"feedback\" && (d.feedback ?? \"\").length > 0,\n )?.feedback;\n if (feedback === undefined) return false;\n ctx.stopFeedbackAttempts += 1;\n ctx.messages.push({ role: \"user\", content: [{ type: \"text\", text: feedback }] });\n return true;\n}\n\n/**\n * M1-4 — the clean-finish decision: nudge (incomplete answer) OR `stop`-hook\n * feedback re-prompt (both bounded) keep the loop going; otherwise finish.\n *\n * @internal\n */\nasync function finishOrReflect(\n inputs: AgentLoopInputs,\n ctx: LoopContext,\n llmOutput: LlmTurnOutput,\n): Promise<\"continue\" | \"done\"> {\n if (shouldNudgeAndContinue(ctx, llmOutput)) return \"continue\";\n if (await reflectAfterStop(inputs, ctx)) return \"continue\";\n ctx.finalStatus = \"finished\";\n return \"done\";\n}\n\nasync function runIteration(\n inputs: AgentLoopInputs,\n ctx: LoopContext,\n): Promise<\"continue\" | \"done\" | \"error\"> {\n // #65 — pre/post_llm_call hooks (previously dead) fire around each LLM turn.\n const hookCtx = { agentId: inputs.agentId, runId: inputs.runId };\n await inputs.pluginManager?.runPreLlmCallHooks(hookCtx);\n const llmOutput = await streamLlmTurn(inputs, ctx);\n await inputs.pluginManager?.runPostLlmCallHooks(hookCtx);\n accumulateUsage(ctx.usage, llmOutput);\n if (inputs.budgetTracker !== undefined) {\n const modelId = inputs.model.id ?? \"auto\";\n const inputT = llmOutput.inputTokens ?? 0;\n const outputT = llmOutput.outputTokens ?? 0;\n try {\n if (inputT > 0) {\n inputs.budgetTracker.track({\n tokens: inputT,\n model: modelId,\n type: \"input\",\n });\n }\n if (outputT > 0) {\n inputs.budgetTracker.track({\n tokens: outputT,\n model: modelId,\n type: \"output\",\n });\n }\n } catch {\n // Tracker.track() is contracted as non-throwing — swallow.\n }\n }\n return continueOrTerminate(inputs, ctx, llmOutput);\n}\n\n/** #65 — apply the transform_llm_output hook fold (no-op when no plugin manager). */\nasync function transformLlmOutputText(\n inputs: AgentLoopInputs,\n text: string,\n ctx: { agentId: string; runId: string },\n): Promise<string> {\n return inputs.pluginManager !== undefined\n ? inputs.pluginManager.runTransformLlmOutputHooks(text, ctx)\n : text;\n}\n\n/**\n * #57/#65 — built-in tool-result guard then the transform_tool_result hook fold.\n *\n * M82 — `toolCalls` is threaded into the hook context. The data was already in the caller's scope\n * (`llmOutput.toolCalls`) and was simply dropped, which left this seam — the ONLY tool-stage channel\n * whose return value the SDK applies — unable to say which tool produced which result. A scoped\n * policy therefore had to sit on `post_tool_call`, whose return is discarded, and silently degraded\n * to observation. Plural because the seam is batch-shaped; correlate by `toolUseId === id`.\n */\nasync function guardAndTransformToolResults(\n inputs: AgentLoopInputs,\n raw: LlmContentPart[],\n ctx: { agentId: string; runId: string },\n toolCalls: readonly LlmToolCallPart[],\n): Promise<LlmContentPart[]> {\n const guarded =\n inputs.toolResultGuard !== undefined ? applyToolResultGuard(raw, inputs.toolResultGuard) : raw;\n return inputs.pluginManager !== undefined\n ? inputs.pluginManager.runTransformToolResultHooks(guarded, {\n ...ctx,\n toolCalls: toolCalls.map((c) => ({ id: c.id, name: c.name, args: c.input })),\n })\n : guarded;\n}\n\nexport async function continueOrTerminate(\n inputs: AgentLoopInputs,\n ctx: LoopContext,\n llmOutput: LlmTurnOutput,\n): Promise<\"continue\" | \"done\" | \"error\"> {\n if (llmOutput.errored) return \"error\";\n const tCtx = { agentId: inputs.agentId, runId: inputs.runId };\n // #65 — apply `transform_llm_output` ONCE, up front, so the transformed text\n // reaches the user-visible step + finalText + the message history, on final\n // text turns as well as tool-call turns (previously it ran only in the\n // tool_use branch and only into message history, never touching what the\n // caller actually receives).\n const text =\n llmOutput.text.length > 0\n ? await transformLlmOutputText(inputs, llmOutput.text, tCtx)\n : llmOutput.text;\n // theokit#122 — the round's block, consumed exactly once, on whichever path closes this round.\n const thinking = llmOutput.thinking;\n if (text.length > 0) {\n await emitAssistantTextStep(inputs, ctx, text, thinking);\n }\n if (llmOutput.stopReason !== \"tool_use\" || llmOutput.toolCalls.length === 0) {\n return finishOrReflect(inputs, ctx, llmOutput);\n }\n recordThinkingOnSilentToolRound(ctx, text, thinking);\n // theokit#122 — and the REPLAY must carry it too: Anthropic verifies the signed block on the next\n // request, so an assistant turn that reaches the provider without it is rejected outright.\n ctx.messages.push(buildAssistantTurn(text, llmOutput.toolCalls, thinking));\n const rawResults = await dispatchTools(\n // SE12 — forward a read-only text projection of the transcript-so-far to tool\n // handlers via `ctx.messages` (consumed by defineSubAgent's messageFilter).\n { ...inputs, messages: projectToolContextMessages(ctx.messages) },\n ctx.tools,\n llmOutput.toolCalls,\n ctx.events,\n ctx.sendSpan, // M3 #64 — nest tool.call spans under agent.send\n );\n const toolResults = await guardAndTransformToolResults(\n inputs,\n rawResults,\n tCtx,\n llmOutput.toolCalls,\n );\n ctx.messages.push({ role: \"user\", content: toolResults });\n if (inputs.onStep !== undefined) {\n const cb = inputs.onStep;\n // SE39 — emit toolCall AND the paired toolResult (was toolCall-only: an asymmetry vs the\n // ConversationStep union + Run.conversation()). Shared builder keeps the two surfaces in lock-step.\n for (const step of buildToolSteps(llmOutput.toolCalls, toolResults)) {\n await safeCall(() => cb({ step }), undefined, \"SendOptions.onStep\");\n }\n }\n pushToolConversationSteps(ctx, llmOutput.toolCalls, toolResults);\n if ((await inspectDoomLoop(inputs, ctx, llmOutput.toolCalls)) === \"stop\") return \"done\";\n return handleToolErrorContinuation(inputs, ctx, toolResults);\n}\n\n/**\n * Doom-loop guard, inspected after each turn's tools dispatch (kept in lockstep with the pure\n * `firstDoomLoopVerdict` — see agent-loop-doom-loop-wiring.test.ts). A `hard` verdict emits the stop\n * message as the final assistant text, flags `ctx.stoppedByDoomLoop`, and stops the run (a controlled\n * `done`). A `soft` verdict injects a one-time guidance nudge (once per streak, by the `==softThreshold`\n * semantics) and continues. No tracker (`doomLoop: false`) ⇒ never fires. @internal\n */\nasync function inspectDoomLoop(\n inputs: AgentLoopInputs,\n ctx: LoopContext,\n toolCalls: LlmToolCallPart[],\n): Promise<\"stop\" | \"continue\"> {\n if (ctx.doomLoop === undefined) return \"continue\";\n const verdict = firstDoomLoopVerdict(ctx.doomLoop, toolCalls);\n if (verdict.kind === \"hard\") {\n ctx.stoppedByDoomLoop = true;\n await emitAssistantTextStep(\n inputs,\n ctx,\n verdict.message ?? \"Stopped: repeated identical tool calls made no progress.\",\n // The doom-loop stop message is the SDK's own text, not a model turn — it has no thinking.\n undefined,\n );\n return \"stop\";\n }\n if (verdict.kind === \"soft\") {\n ctx.messages.push({ role: \"user\", content: [{ type: \"text\", text: verdict.message ?? \"\" }] });\n }\n return \"continue\";\n}\n\n/** Re-export safeListTools for backward compatibility. @internal */\nexport { safeListTools } from \"./loop-context-init.js\";\n","import { NetworkError } from \"../../errors.js\";\nimport { relayStream, tryFirstEvent } from \"./stream-relay.js\";\nimport type { LlmClient, LlmEvent, LlmFinish, LlmRequest } from \"./types.js\";\n\n/**\n * Chain-aware `LlmClient` wrapper (ADR D2 — provider fallback failover).\n *\n * On every `stream()`, tries each underlying client in order. When the first\n * `.next()` of a client's generator throws `NetworkError`, the wrapper logs\n * a diagnostic and tries the next client. Once the first event has yielded\n * from a client, the failover is OFF for that generator — partial output\n * would corrupt the stream.\n *\n * Per edge-case review EC-3, the wrapper checks `signal.aborted` BEFORE\n * iterating to the next client so a caller-side cancellation does not burn\n * a fallback HTTP round-trip.\n *\n * When every client fails, the LAST `NetworkError` is re-thrown so the\n * caller still receives a typed error.\n *\n * @internal\n */\nexport class FallbackLlmClient implements LlmClient {\n readonly name = \"fallback\";\n\n constructor(private readonly clients: ReadonlyArray<LlmClient>) {}\n\n async *stream(\n request: LlmRequest,\n signal: AbortSignal,\n ): AsyncGenerator<LlmEvent, LlmFinish, void> {\n let lastError: NetworkError | undefined;\n for (const client of this.clients) {\n if (signal.aborted) throw abortError(signal);\n const attempt = await tryFirstEvent(client, request, signal, true);\n if (attempt.kind === \"handshake_error\") {\n lastError = attempt.error as NetworkError;\n continue;\n }\n return yield* relayStream(attempt.generator, attempt.firstResult);\n }\n if (lastError !== undefined) throw lastError;\n throw new NetworkError(\"FallbackLlmClient has no providers configured\", {\n code: \"fallback_empty_chain\",\n });\n }\n}\n\nfunction abortError(signal: AbortSignal): Error {\n if (signal.reason instanceof Error) return signal.reason;\n return new Error(signal.reason !== undefined ? String(signal.reason) : \"aborted\");\n}\n","import { type ChildProcessWithoutNullStreams, spawn } from \"node:child_process\";\nimport { isAbsolute } from \"node:path\";\n\nimport { ConfigurationError, NetworkError } from \"../../errors.js\";\nimport type {\n McpHttpServerConfig,\n McpServerConfig,\n McpStdioServerConfig,\n} from \"../../types/mcp.js\";\nimport { resolveChildEnv } from \"../runtime/lifecycle/env-policy.js\";\nimport { safePathJoin } from \"../security/path-guard.js\";\n\n/**\n * Real MCP client implementing the subset of the 2024-11-05 spec used by the\n * SDK agent loop: `initialize`, `tools/list`, `tools/call`. Both stdio and\n * http transports are wired; sse uses the same wire format as http with a\n * streaming response handled identically by the JSON-RPC reader.\n *\n * @internal\n */\n\nexport interface McpTool {\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n}\n\nexport interface McpToolCallResult {\n content: Array<{ type: \"text\"; text: string }>;\n isError?: boolean;\n}\n\nexport interface McpClient {\n readonly name: string;\n initialize(): Promise<void>;\n listTools(): Promise<McpTool[]>;\n callTool(name: string, args: Record<string, unknown>): Promise<McpToolCallResult>;\n close(): Promise<void>;\n}\n\nexport function createMcpClient(\n name: string,\n config: McpServerConfig,\n fetchImpl: typeof fetch = fetch,\n): McpClient {\n if (isStdio(config)) return new StdioMcpClient(name, config);\n return new HttpMcpClient(name, config as McpHttpServerConfig, fetchImpl);\n}\n\n/** Default per-request MCP timeout (#59). */\nconst DEFAULT_MCP_TIMEOUT_MS = 30_000;\n\n/** Max buffered stdout bytes before a flooding stdio server is torn down (SEC-M0-04). */\nconst MAX_STDIO_BUFFER_BYTES = 8 * 1024 * 1024;\n\n/** M2 #59 — reconnect-after-drop bounds. Base for the full-jitter backoff between\n * reconnect attempts, and the max attempts before surfacing a typed error. */\nconst RECONNECT_BASE_MS = 250;\nconst MAX_RECONNECT_ATTEMPTS = 2;\n\n/** M2 #59 — full-jitter backoff (AWS Brooker 2015) for the Nth reconnect attempt,\n * then a plain delay. MCP requests carry no AbortSignal so the delay is unabortable. */\nfunction reconnectDelay(attempt: number): Promise<void> {\n const ceiling = RECONNECT_BASE_MS * 2 ** attempt;\n const ms = Math.floor(Math.random() * ceiling);\n return ms <= 0 ? Promise.resolve() : new Promise((resolve) => setTimeout(resolve, ms));\n}\n\n/** Typed timeout error shared by both transports (#59). */\nfunction mcpTimeoutError(name: string, timeoutMs: number): NetworkError {\n return new NetworkError(`MCP ${name} request timed out after ${timeoutMs}ms`, {\n code: \"mcp_timeout\",\n });\n}\n\n/**\n * True when a rejected fetch was aborted by our `AbortSignal.timeout` (#59).\n * `AbortSignal.timeout` rejects with a `DOMException` (name `TimeoutError`),\n * which is not always `instanceof Error`, so we inspect `.name` directly.\n */\nfunction isAbortLike(cause: unknown): boolean {\n if (typeof cause !== \"object\" || cause === null || !(\"name\" in cause)) return false;\n const name = (cause as { name: unknown }).name;\n return name === \"TimeoutError\" || name === \"AbortError\";\n}\n\ntype RpcRequester = (method: string, params: Record<string, unknown>) => Promise<unknown>;\n\nasync function rpcInitialize(request: RpcRequester): Promise<void> {\n await request(\"initialize\", {\n protocolVersion: \"2024-11-05\",\n capabilities: { tools: {} },\n clientInfo: { name: \"theokit-sdk\", version: \"0.0.0\" },\n });\n}\n\nasync function rpcListTools(request: RpcRequester): Promise<McpTool[]> {\n const response = await request(\"tools/list\", {});\n return (response as { result?: { tools?: McpTool[] } }).result?.tools ?? [];\n}\n\nasync function rpcCallTool(\n request: RpcRequester,\n name: string,\n args: Record<string, unknown>,\n): Promise<McpToolCallResult> {\n const response = await request(\"tools/call\", { name, arguments: args });\n const result = (response as { result?: McpToolCallResult }).result;\n if (result === undefined) {\n return { content: [{ type: \"text\", text: \"MCP returned empty result\" }], isError: true };\n }\n return result;\n}\n\n/** Shared base wiring `initialize` / `listTools` / `callTool` onto an\n * abstract RPC `request` implementation. Subclasses define the transport.\n */\nabstract class BaseMcpClient implements McpClient {\n abstract readonly name: string;\n\n abstract close(): Promise<void>;\n\n protected abstract request(method: string, params: Record<string, unknown>): Promise<unknown>;\n\n initialize(): Promise<void> {\n return rpcInitialize((method, params) => this.request(method, params));\n }\n\n listTools(): Promise<McpTool[]> {\n return rpcListTools((method, params) => this.request(method, params));\n }\n\n callTool(name: string, args: Record<string, unknown>): Promise<McpToolCallResult> {\n return rpcCallTool((method, params) => this.request(method, params), name, args);\n }\n}\n\nfunction isStdio(config: McpServerConfig): config is McpStdioServerConfig {\n if ((config as { type?: string }).type === \"stdio\") return true;\n return \"command\" in config && typeof (config as { command?: unknown }).command === \"string\";\n}\n\ninterface RpcRequest {\n jsonrpc: \"2.0\";\n id: number;\n method: string;\n params?: Record<string, unknown>;\n}\n\nclass StdioMcpClient extends BaseMcpClient {\n readonly name: string;\n private child: ChildProcessWithoutNullStreams | undefined;\n private nextId = 1;\n // #59 — pending requests carry a reject + timer so a silent server times out\n // (typed error), a late reply after timeout is a no-op, and close() settles them.\n private readonly pending = new Map<\n number,\n {\n resolve: (response: unknown) => void;\n reject: (error: unknown) => void;\n timer: NodeJS.Timeout;\n }\n >();\n private buffer = \"\";\n // M2 #59 — reconnect-after-drop state. `dropped` is set when the child exits\n // unexpectedly OR times out (not via close()); the next request re-spawns with\n // backoff. `reconnectPromise` is a SINGLE in-flight reconnect shared by every\n // concurrent request so parallel tool dispatch after a drop awaits one handshake\n // instead of racing (or spuriously failing with mcp_not_init).\n private dropped = false;\n private reconnectPromise: Promise<void> | undefined;\n\n constructor(\n name: string,\n private readonly config: McpStdioServerConfig,\n ) {\n super();\n this.name = name;\n }\n\n private get timeoutMs(): number {\n return this.config.requestTimeoutMs ?? DEFAULT_MCP_TIMEOUT_MS;\n }\n\n /** Spawn the server child and wire stdout/stderr/error/exit handlers.\n * Shared by `initialize()` and the M2 #59 reconnect path. */\n private spawnChild(): void {\n // ADR D79-D80: relative MCP `cwd` paths must safe-join under process.cwd()\n // so a malicious `.theokit/mcp.json` cannot point a server process at\n // `../../../etc`. Absolute paths are trusted (user explicitly chose).\n const resolvedCwd = resolveMcpCwd(this.config.cwd);\n const child = spawn(this.config.command, this.config.args ?? [], {\n cwd: resolvedCwd,\n // #54 (F-H1) — a third-party MCP server binary must not inherit host\n // secrets. Scrub secret-like vars by default; `config.env` still wins.\n env: resolveChildEnv({ policy: this.config.envPolicy, overrides: this.config.env }),\n });\n this.child = child;\n child.stdout.on(\"data\", (chunk: Buffer) => this.consume(chunk));\n child.stderr.on(\"data\", () => undefined);\n // M2 #59 — a write to a dead child's stdin (e.g. a request racing the child's\n // exit) emits an EPIPE on the stdin stream; without a listener Node escalates\n // it to an uncaught error. Swallow it — the exit handler + request timeout\n // already drive the drop/reconnect bookkeeping.\n child.stdin.on(\"error\", () => undefined);\n child.on(\"error\", () => {\n this.rejectAllPending(\n new NetworkError(`MCP ${this.name} process crashed`, { code: \"mcp_crashed\" }),\n );\n });\n // M2 #59 — a clean-exit / close mid-session used to leave pending requests\n // hung forever (a second permanent-hang vector distinct from timeout). Now\n // an unexpected exit of the ACTIVE child rejects all pending with a typed\n // error and marks the client dropped so the next request reconnects. The\n // `this.child === child` guard skips deliberate close()/replace teardowns.\n child.on(\"exit\", () => {\n if (this.child !== child) return;\n this.child = undefined;\n this.dropped = true;\n this.rejectAllPending(\n new NetworkError(`MCP ${this.name} disconnected`, { code: \"mcp_disconnected\" }),\n );\n });\n }\n\n /**\n * theokit#155 — idempotent while the child is LIVE.\n *\n * Under `mcpLifecycle: 'session'` the pool hands the same client back on the next turn, and\n * `initializeMcp` runs every turn. An unconditional `spawnChild()` would overwrite `this.child`,\n * orphaning a healthy process (its `exit` handler is skipped by the `this.child === child` guard)\n * and paying the ~146 ms spawn + handshake the option exists to avoid.\n *\n * This does NOT touch the #59 reconnect path: `reconnect()` calls `spawnChild()` and\n * `super.initialize()` directly, so it re-spawns exactly as before. After `close()` — or after a\n * drop, which clears `child` — this method spawns again, as it must.\n */\n override async initialize(): Promise<void> {\n if (this.child !== undefined) return;\n this.spawnChild();\n await super.initialize();\n }\n\n /** M2 #59 — ensure a live child before a request. Reconnect (bounded, with\n * full-jitter backoff) when the client was dropped; fail fast when never\n * initialized. Concurrent callers share ONE reconnect handshake. */\n private ensureConnected(): Promise<void> {\n if (this.child !== undefined) return Promise.resolve();\n if (!this.dropped) {\n return Promise.reject(\n new ConfigurationError(`MCP ${this.name} is not initialized`, { code: \"mcp_not_init\" }),\n );\n }\n // Share a single in-flight reconnect across concurrent requests.\n this.reconnectPromise ??= this.reconnect().finally(() => {\n this.reconnectPromise = undefined;\n });\n return this.reconnectPromise;\n }\n\n private async reconnect(): Promise<void> {\n // #59 — a single reconnect CYCLE tries up to MAX_RECONNECT_ATTEMPTS times\n // with backoff, then surfaces a typed disconnect. The attempt budget is\n // LOCAL to the cycle (not a sticky instance counter), so a later request\n // after a transient outage longer than the bound re-arms a fresh cycle\n // instead of permanently wedging the client.\n let lastErr: unknown;\n for (let attempt = 0; attempt < MAX_RECONNECT_ATTEMPTS; attempt += 1) {\n await reconnectDelay(attempt);\n this.spawnChild();\n try {\n // The handshake uses send() directly (child is now live) so it does not\n // re-enter ensureConnected.\n await super.initialize();\n this.dropped = false;\n return;\n } catch (err) {\n lastErr = err; // child dropped again — retry with backoff (bounded)\n }\n }\n throw new NetworkError(`MCP ${this.name} reconnect exhausted`, {\n code: \"mcp_disconnected\",\n ...(lastErr instanceof Error ? { cause: lastErr } : {}),\n });\n }\n\n async close(): Promise<void> {\n // #59 — settle in-flight requests instead of leaking their timers/promises.\n this.rejectAllPending(new NetworkError(`MCP ${this.name} closed`, { code: \"mcp_closed\" }));\n // Clear the ref BEFORE kill so the exit handler's `this.child === child`\n // guard treats this as a deliberate close (no drop / no reconnect).\n const child = this.child;\n this.child = undefined;\n this.dropped = false;\n child?.kill(\"SIGTERM\");\n }\n\n /** Reject + clear every pending request (crash / close). @internal */\n private rejectAllPending(error: NetworkError): void {\n for (const entry of this.pending.values()) {\n clearTimeout(entry.timer);\n entry.reject(error);\n }\n this.pending.clear();\n }\n\n private consume(chunk: Buffer): void {\n this.buffer += chunk.toString(\"utf8\");\n // SEC-M0-04 — a hostile/broken server flooding stdout with no newline must\n // not pin memory. Cap the buffer; on overflow tear the client down.\n if (this.buffer.length > MAX_STDIO_BUFFER_BYTES) {\n this.buffer = \"\";\n this.rejectAllPending(\n new NetworkError(`MCP ${this.name} exceeded stdout buffer limit`, {\n code: \"mcp_buffer_overflow\",\n }),\n );\n this.child?.kill(\"SIGKILL\");\n this.child = undefined;\n return;\n }\n let newlineIndex = this.buffer.indexOf(\"\\n\");\n while (newlineIndex !== -1) {\n const line = this.buffer.slice(0, newlineIndex).trim();\n this.buffer = this.buffer.slice(newlineIndex + 1);\n if (line.length > 0) this.handleLine(line);\n newlineIndex = this.buffer.indexOf(\"\\n\");\n }\n }\n\n private handleLine(line: string): void {\n let message: { id?: number };\n try {\n message = JSON.parse(line) as { id?: number };\n } catch {\n return;\n }\n if (typeof message.id !== \"number\") return;\n const entry = this.pending.get(message.id);\n // #59 — a late reply after timeout finds no entry → no-op (never double-settles).\n if (entry === undefined) return;\n this.pending.delete(message.id);\n clearTimeout(entry.timer);\n entry.resolve(message);\n }\n\n protected request(method: string, params: Record<string, unknown>): Promise<unknown> {\n const child = this.child;\n // Happy path stays fully synchronous (no extra `await` tick that could race\n // with a concurrent close()): a live child sends immediately.\n if (child !== undefined) return this.send(child, method, params);\n // M2 #59 — dropped (child exited or timed out): reconnect on this request.\n // Concurrent requests all await the single shared reconnect via ensureConnected.\n if (this.dropped) return this.reconnectAndRequest(method, params);\n // Never initialized.\n return Promise.reject(\n new ConfigurationError(`MCP ${this.name} is not initialized`, { code: \"mcp_not_init\" }),\n );\n }\n\n /** M2 #59 — reconnect a dropped client, then send. Separate async path so the\n * happy path above never pays an extra microtask tick. */\n private async reconnectAndRequest(\n method: string,\n params: Record<string, unknown>,\n ): Promise<unknown> {\n await this.ensureConnected();\n const child = this.child;\n if (child === undefined) {\n throw new ConfigurationError(`MCP ${this.name} is not initialized`, { code: \"mcp_not_init\" });\n }\n return this.send(child, method, params);\n }\n\n private send(\n child: ChildProcessWithoutNullStreams,\n method: string,\n params: Record<string, unknown>,\n ): Promise<unknown> {\n const id = this.nextId++;\n const payload: RpcRequest = { jsonrpc: \"2.0\", id, method, params };\n child.stdin.write(`${JSON.stringify(payload)}\\n`);\n return new Promise<unknown>((resolve, reject) => {\n // #59 — a silent server rejects with a typed timeout and drops the pending\n // entry (no leak) instead of hanging forever. SEC-M0-04 — an unresponsive\n // server is torn down (SIGKILL) so it cannot linger as a zombie / keep\n // flooding stdout past the deadline.\n const timer = setTimeout(() => {\n this.pending.delete(id);\n reject(mcpTimeoutError(this.name, this.timeoutMs));\n this.child?.kill(\"SIGKILL\");\n this.child = undefined;\n // M2 #59 — a timed-out server is a DROP: mark reconnectable (was missing,\n // leaving a timed-out client permanently un-reconnectable) and settle any\n // OTHER in-flight requests with the typed disconnect instead of letting\n // them each wait out their own timeout.\n this.dropped = true;\n this.rejectAllPending(\n new NetworkError(`MCP ${this.name} disconnected`, { code: \"mcp_disconnected\" }),\n );\n }, this.timeoutMs);\n this.pending.set(id, { resolve, reject, timer });\n });\n }\n}\n\nclass HttpMcpClient extends BaseMcpClient {\n readonly name: string;\n private nextId = 1;\n /**\n * The `mcp-session-id` a STATEFUL server issues on `initialize`.\n *\n * The comment on `request` used to say \"the http transport is stateless\". That is true of the\n * *connection* — each POST opens a fresh one — and false of the *session*: a server that follows\n * Streamable HTTP answers 400 to every call that omits this header, so a stateful server served\n * exactly zero tools to this client. Captured once, replayed after.\n */\n private sessionId: string | undefined;\n private readonly fetchImpl: typeof fetch;\n\n constructor(\n name: string,\n private readonly config: McpHttpServerConfig,\n fetchImpl: typeof fetch = fetch,\n ) {\n super();\n this.name = name;\n this.fetchImpl = fetchImpl;\n }\n\n close(): Promise<void> {\n return Promise.resolve();\n }\n\n /**\n * The wire headers for one request.\n *\n * Extracted from `request` rather than inlined: the session/accept handling pushed that method\n * past the cognitive-complexity ceiling, and a header policy is a different concern from the\n * fetch/timeout/error handling around it (SRP). The user-supplied spread stays LAST — that\n * override contract predates this change and is the only escape a user has while a server\n * misbehaves.\n */\n private buildHeaders(): Record<string, string> {\n return {\n \"content-type\": \"application/json\",\n // Streamable HTTP asks for BOTH media types. Declaring only `application/json` makes a\n // spec-enforcing server answer 406 before any RPC is even reachable.\n accept: \"application/json, text/event-stream\",\n // Present only for a STATEFUL server. For a stateless one nothing is sent — inventing a\n // header would trade one broken transport for another.\n ...(this.sessionId !== undefined ? { \"mcp-session-id\": this.sessionId } : {}),\n ...(this.config.headers ?? {}),\n };\n }\n\n /**\n * Capture the session on the FIRST response that carries it (the `initialize`).\n *\n * Never overwritten by a later one: a server that re-issues mid-session would otherwise split\n * the session in two, and the second half would not see the first half's state.\n */\n /**\n * Read one JSON-RPC response, in either encoding the server may choose.\n *\n * Streamable HTTP lets the server answer a POST with `application/json` OR `text/event-stream`,\n * and the client advertises both. Reading the body with `response.json()` unconditionally is what\n * turned a working server into `Unexpected token 'e', \"event: mes\"... is not valid JSON` the\n * moment the Accept header started asking for SSE — measured against a real server, not imagined.\n *\n * Only the `data:` payload is JSON; `event:` / `id:` / `retry:` lines and comments are framing.\n * A single JSON-RPC reply arrives as one event, so the FIRST parseable `data:` is the answer.\n */\n private async readBody(response: Response): Promise<unknown> {\n const contentType = response.headers.get(\"content-type\") ?? \"\";\n if (!contentType.includes(\"text/event-stream\")) return (await response.json()) as unknown;\n const text = await response.text();\n for (const line of text.split(/\\r?\\n/)) {\n if (!line.startsWith(\"data:\")) continue;\n const payload = line.slice(5).trim();\n if (payload === \"\") continue;\n return JSON.parse(payload) as unknown;\n }\n throw new NetworkError(`MCP ${this.name} returned an event stream with no data payload`, {\n code: \"mcp_http_error\",\n });\n }\n\n private captureSession(response: Response): void {\n if (this.sessionId !== undefined) return;\n const issued = response.headers.get(\"mcp-session-id\");\n if (issued !== null && issued !== \"\") this.sessionId = issued;\n }\n\n protected async request(method: string, params: Record<string, unknown>): Promise<unknown> {\n const id = this.nextId++;\n const payload: RpcRequest = { jsonrpc: \"2.0\", id, method, params };\n const headers = this.buildHeaders();\n const timeoutMs = this.config.requestTimeoutMs ?? DEFAULT_MCP_TIMEOUT_MS;\n let response: Response;\n try {\n response = await this.fetchImpl(this.config.url, {\n method: \"POST\",\n headers,\n body: JSON.stringify(payload),\n // #59 — bound the request; a non-responding endpoint aborts here.\n signal: AbortSignal.timeout(timeoutMs),\n });\n } catch (cause) {\n // #59 — map an abort/timeout to the typed timeout error; surface any other\n // fetch failure unchanged. The http transport is stateless, so a failed\n // request does not \"drop\" a connection — the next request reconnects\n // inherently (each POST opens a fresh connection). No in-call retry: that\n // would change the M0 error-surfacing contract and add latency to hard\n // failures. Stdio (a persistent child) is where explicit reconnect lives.\n if (isAbortLike(cause)) throw mcpTimeoutError(this.name, timeoutMs);\n throw cause;\n }\n if (!response.ok) {\n throw new NetworkError(`MCP ${this.name} returned ${response.status}`, {\n code: \"mcp_http_error\",\n });\n }\n this.captureSession(response);\n try {\n return await this.readBody(response);\n } catch (cause) {\n // #59 — the body read is bounded by the SAME `AbortSignal.timeout`. A\n // server that returns headers then stalls the body aborts here; map that\n // to the typed `mcp_timeout` too so the timeout contract holds across both\n // the header and body phases (error-handling.md — typed, not raw DOMException).\n if (isAbortLike(cause)) throw mcpTimeoutError(this.name, timeoutMs);\n throw cause;\n }\n }\n}\n\n/**\n * Resolve an MCP server `cwd` field safely. Absolute paths are returned\n * as-is (user explicitly chose absolute); relative paths are joined under\n * `process.cwd()` and prefix-checked via `safePathJoin`.\n *\n * @internal\n */\nfunction resolveMcpCwd(configCwd: string | undefined): string {\n if (configCwd === undefined) return process.cwd();\n if (isAbsolute(configCwd)) return configCwd;\n return safePathJoin(process.cwd(), configCwd);\n}\n","/**\n * Bridge plugin-aggregated provider profiles into the provider registry so a\n * `kind: \"model-provider\"` plugin actually routes (T1 — closes the half-wired\n * path: `PluginManager` aggregated `providerProfiles` were never registered,\n * so `getProviderProfile`/`resolveProviderChain` never saw them).\n *\n * `registerProvider` is idempotent + WARN-on-override (ADR D107), so calling\n * this once per local run is safe.\n *\n * @internal\n */\n\nimport { registerProvider } from \"./registry.js\";\nimport type { ProviderProfile } from \"./types.js\";\n\n/** One aggregated provider entry, as collected by `PluginManager`. */\nexport interface PluginProviderEntry {\n readonly pluginName: string;\n readonly profile: ProviderProfile;\n}\n\n/**\n * Register every plugin-contributed provider profile. Returns the number of\n * profiles registered (used as the runtime signal for the wiring triad).\n */\nexport function registerPluginProviderProfiles(\n entries: ReadonlyArray<PluginProviderEntry>,\n): number {\n let registered = 0;\n for (const entry of entries) {\n registerProvider(entry.profile);\n registered += 1;\n }\n return registered;\n}\n","/**\n * M77 — session-scoped MCP client pool.\n *\n * `buildMcpMap` (`real-local-run.ts`) builds a fresh `McpClient` on every run, so each `send` pays\n * spawn + handshake again: 193 / 138 / 134 ms per turn, measured. The reference anchors this at the\n * session — Codex keeps its `mcp_runtime: Arc<McpRuntime>` in `SessionServices`\n * (`codex-rs/core/src/state/service.rs:51-58`), next to a field commented *\"Session-scoped model\n * client shared across turns\"*, and REPLACES the runtime rather than rebuilding it.\n *\n * theokit#155: pooling the client OBJECT was never enough — the turn also has to stop closing what\n * it does not own. See `runOwnsMcpClients` (`real-local-run.ts`) and the idempotent\n * `StdioMcpClient.initialize()`.\n *\n * Generic over the client type on purpose: this file knows about keys, reuse and idleness, and\n * nothing about MCP. That keeps it unit-testable without spawning a server, and keeps `McpClient`'s\n * reconnect machinery (`internal/mcp/client.ts:165-171` — `dropped` + a single shared\n * `reconnectPromise` with full-jitter backoff) exactly where it already lives. The pool must not\n * reimplement surviving a dead server; it must not throw that capability away either.\n *\n * @internal\n */\n\n/** Options for {@link McpClientPool}. */\nexport interface McpClientPoolOptions {\n /**\n * Milliseconds a client may sit unused before {@link McpClientPool.reapIdle} closes it. The clock\n * is idle-based, not lifetime-based: a server used every turn is never reaped.\n *\n * Default 10 minutes. Honest about provenance — no precedent for this number was found in the\n * reference; it is a conservative default chosen so a forgotten server does not outlive the\n * conversation by much, and it is written down rather than left implicit.\n */\n readonly idleTtlMs?: number;\n /** Injected clock — `rules/testing.md § 6` forbids real time in unit tests. */\n readonly now?: () => number;\n}\n\ninterface Entry<C> {\n readonly client: C;\n readonly sessionId: string;\n lastUsedAt: number;\n}\n\nconst DEFAULT_IDLE_TTL_MS = 600_000;\n\n/**\n * Stable identity for a server config.\n *\n * Sorting the keys matters: `sendOptions.mcpServers` REPLACES `agentOptions.mcpServers`, so the same\n * server can be re-declared per run with its properties in a different order. A raw\n * `JSON.stringify` would hash `{a,b}` and `{b,a}` differently, quietly defeating reuse for\n * configurations that are in fact identical — the pool would look installed and do nothing.\n */\nfunction configKey(config: unknown): string {\n return JSON.stringify(config, (_k, v: unknown) =>\n v !== null && typeof v === \"object\" && !Array.isArray(v)\n ? Object.fromEntries(\n Object.entries(v as Record<string, unknown>).sort(([a], [b]) => (a < b ? -1 : 1)),\n )\n : v,\n );\n}\n\nexport class McpClientPool<C> {\n private readonly entries = new Map<string, Entry<C>>();\n private readonly idleTtlMs: number;\n private readonly now: () => number;\n\n constructor(options: McpClientPoolOptions = {}) {\n this.idleTtlMs = options.idleTtlMs ?? DEFAULT_IDLE_TTL_MS;\n this.now = options.now ?? Date.now;\n }\n\n /**\n * Return the pooled client for `(sessionId, serverName, config)`, creating it via `factory` on\n * first use. Every call refreshes idleness — the TTL measures time SINCE LAST USE, not age.\n *\n * Synchronous by design: `createMcpClient` is itself synchronous (the handshake happens later, on\n * `initialize`), so there is no `await` between the lookup and the insert and two concurrent runs\n * in the same session cannot both miss the cache.\n */\n acquire(sessionId: string, serverName: string, config: unknown, factory: () => C): C {\n const key = `${sessionId}\\u0000${serverName}\\u0000${configKey(config)}`;\n const existing = this.entries.get(key);\n if (existing !== undefined) {\n existing.lastUsedAt = this.now();\n return existing.client;\n }\n const client = factory();\n this.entries.set(key, { client, sessionId, lastUsedAt: this.now() });\n return client;\n }\n\n /**\n * Close and forget every client of ONE session. Scoped deliberately: clearing the whole map would\n * tear down the servers of every concurrent conversation.\n */\n disposeSession(sessionId: string, close: (client: C) => void): void {\n for (const [key, entry] of this.entries) {\n if (entry.sessionId !== sessionId) continue;\n close(entry.client);\n this.entries.delete(key);\n }\n }\n\n /** Close and forget every client idle for longer than the TTL. */\n reapIdle(close: (client: C) => void): void {\n const cutoff = this.now() - this.idleTtlMs;\n for (const [key, entry] of this.entries) {\n if (entry.lastUsedAt > cutoff) continue;\n close(entry.client);\n this.entries.delete(key);\n }\n }\n\n /** Live pooled-client count — for observability and tests. */\n size(): number {\n return this.entries.size;\n }\n}\n","/**\n * applyPersonalityFilter — additive narrowing of exposed tools by an\n * active personality preset's `tools` whitelist (T4.1, ADRs D102+D167).\n *\n * Contract:\n *\n * - `whitelist === undefined` → return `exposedTools` unchanged (no\n * active personality OR personality has no tool restriction).\n * - `whitelist === []` → return empty array (explicit \"no tools for\n * this persona\").\n * - Otherwise → return the subset of `exposedTools` whose `name` is\n * present in `whitelist`. Missing entries emit a one-shot stderr\n * warning per `(agentId, personalityName, missingTool)` combo\n * (advisory only — D167 says missing tools must NOT crash).\n *\n * **EC-I:** MCP-style names like `mcp__server__tool` are matched as\n * exact strings (no regex semantics) — the registry already produces\n * the verbatim name.\n *\n * **EC-15:** Duplicate entries in `whitelist` are deduped silently.\n *\n * **EC-17:** Missing names within Levenshtein distance ≤2 of an exposed\n * tool emit a \"did you mean: X\" hint inside the warning.\n *\n * The function is **pure**: it never mutates the input array.\n *\n * @internal\n */\n\nimport { warnOnce } from \"../runtime/hooks/hooks-source.js\";\n\nexport interface ToolNamed {\n readonly name: string;\n}\n\nexport interface ApplyPersonalityFilterOptions {\n /** Used in the dedup key + warning prefix so logs are traceable. */\n agentId?: string;\n /** Active personality slug — used in the dedup key + warning. */\n personalityName?: string;\n}\n\n/**\n * Filter `exposedTools` to the personality `whitelist`. Pure.\n *\n * @internal\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: undefined → unchanged, empty → empty, then filter + per-missing warning with Levenshtein hint — each branch is one short line of intent.\nexport function applyPersonalityFilter<T extends ToolNamed>(\n exposedTools: ReadonlyArray<T>,\n whitelist: ReadonlyArray<string> | undefined,\n opts?: ApplyPersonalityFilterOptions,\n): ReadonlyArray<T> {\n if (whitelist === undefined) return exposedTools;\n if (whitelist.length === 0) return [];\n\n const wanted = new Set(whitelist); // EC-15: dedup\n const exposedSet = new Set(exposedTools.map((t) => t.name));\n const kept = exposedTools.filter((t) => wanted.has(t.name));\n\n // EC-17: warn once per missing tool (with did-you-mean hint when close).\n for (const name of wanted) {\n if (exposedSet.has(name)) continue;\n const hint = suggestClosest(name, exposedSet);\n const message =\n hint !== undefined\n ? `[theokit-sdk] personality \"${opts?.personalityName ?? \"?\"}\" references unknown tool \"${name}\"; did you mean \"${hint}\"?`\n : `[theokit-sdk] personality \"${opts?.personalityName ?? \"?\"}\" references unknown tool \"${name}\" (not exposed)`;\n warnOnce(\n `personality-tool-missing|${opts?.agentId ?? \"?\"}|${opts?.personalityName ?? \"?\"}|${name}`,\n message,\n );\n }\n\n return kept;\n}\n\n/**\n * Return the name in `pool` with Levenshtein distance ≤2 to `target`,\n * or undefined if none is close enough.\n *\n * Keeps cognitive complexity low: short-circuits on equal length, runs\n * the standard DP only when both names are non-trivial.\n *\n * @internal\n */\nfunction suggestClosest(target: string, pool: ReadonlySet<string>): string | undefined {\n let best: { name: string; dist: number } | undefined;\n for (const candidate of pool) {\n if (Math.abs(candidate.length - target.length) > 2) continue;\n const d = levenshtein(target, candidate);\n if (d > 2) continue;\n if (best === undefined || d < best.dist) best = { name: candidate, dist: d };\n }\n return best?.name;\n}\n\nfunction levenshtein(a: string, b: string): number {\n if (a === b) return 0;\n if (a.length === 0) return b.length;\n if (b.length === 0) return a.length;\n const prev: number[] = [];\n for (let j = 0; j <= b.length; j++) prev[j] = j;\n for (let i = 1; i <= a.length; i++) {\n let prevDiag = prev[0]!;\n prev[0] = i;\n for (let j = 1; j <= b.length; j++) {\n const tmp = prev[j]!;\n prev[j] = Math.min(\n prev[j]! + 1,\n prev[j - 1]! + 1,\n prevDiag + (a.charCodeAt(i - 1) === b.charCodeAt(j - 1) ? 0 : 1),\n );\n prevDiag = tmp;\n }\n }\n return prev[b.length]!;\n}\n","/**\n * Custom-tool assembly for the real local run (extracted from `real-local-run.ts`\n * for the G8 LoC budget — SRP: everything that builds the effective tool catalog\n * for a run lives here).\n *\n * Merges, in order: caller/agent `tools`, declarative subagent delegation tools\n * (file-based + inline), plugin tools, and — SE37 — the internal `think` tool when\n * `reasoning: true` (guarded against a native reasoning model). Binds parent\n * credentials onto delegation tools and applies the personality whitelist.\n *\n * @internal\n */\n\nimport { subAgentToolsFromDefinitions } from \"../../a2a/subagent.js\";\nimport type {\n AgentDefinition,\n AgentOptions,\n CustomTool,\n ModelSelection,\n} from \"../../types/agent.js\";\nimport type { CustomToolSpec } from \"../agent-loop/loop-types.js\";\nimport type { InheritedCredentials } from \"../runtime/concurrency/subagent-credentials.js\";\nimport { createThinkTool, reasoningActive } from \"../runtime/reasoning/native-reasoning.js\";\nimport { applyPersonalityFilter } from \"../tool-registry/personality-filter.js\";\n\n/**\n * Declarative subagents become delegation tools for the local runtime — each\n * child inherits the parent's apiKey/model (via the run's credential scope) and is\n * scoped to the whitelisted subset of the parent's tools. `agents` is the merged\n * set from `loadSubagents` (`.theokit/agents/*.md` + inline `agentOptions.agents`),\n * so a subagent defined only on disk is callable against a real model — not just\n * in fixture mode.\n */\nfunction declarativeSubagentTools(\n agents: Record<string, AgentDefinition> | undefined,\n parentTools: ReadonlyArray<CustomTool>,\n): CustomTool[] {\n if (agents === undefined || Object.keys(agents).length === 0) return [];\n return subAgentToolsFromDefinitions(agents, parentTools);\n}\n\n/**\n * The credentials a delegated child inherits from this parent: its apiKey (else `Agent.create`\n * throws \"Missing API key\"), its model, its plugins and its sandbox posture.\n *\n * theokit#148 — this used to be pushed onto each subagent tool OBJECT\n * (`inheritSubAgentCredentials`), which meant any layer that rebuilt the object dropped it and the\n * child failed with `provider_unresolved`. It is now published on the run's async scope by\n * `createRealLocalRun`, so the value travels with the CALL. This function only computes it; the\n * scope is established at the run boundary, which is also the correct lifetime for it.\n *\n * @internal\n */\nexport function resolveInheritedCredentials(agentOptions: AgentOptions): InheritedCredentials {\n // #55 — hand the parent's code-registered plugins (array form carries the\n // PermissionPlugin) down so the child runs under the same permission gate.\n const parentPlugins = Array.isArray(agentOptions.plugins) ? agentOptions.plugins : undefined;\n // M33 — hand down the parent's sandbox posture so a child of a sandboxed parent stays sandboxed unless\n // its role opts out. A role's own `sandbox` (spec.sandbox) overrides this in buildChildCreateOptions.\n const parentSandbox = agentOptions.local?.sandboxOptions?.enabled;\n return {\n ...(agentOptions.apiKey !== undefined ? { apiKey: agentOptions.apiKey } : {}),\n ...(typeof agentOptions.model === \"object\" ? { model: agentOptions.model } : {}),\n ...(parentPlugins !== undefined ? { plugins: parentPlugins } : {}),\n ...(parentSandbox !== undefined ? { sandbox: parentSandbox } : {}),\n };\n}\n\nexport function buildCustomToolsInput(\n agentOptions: AgentOptions,\n sendOptions: { tools?: CustomTool[] } | undefined,\n pluginManager: import(\"../plugins/manager.js\").PluginManager | undefined,\n personalityToolWhitelist: ReadonlyArray<string> | undefined,\n agentId: string,\n personalityName: string | undefined,\n subagents: Record<string, AgentDefinition> | undefined,\n effectiveModel: ModelSelection | undefined,\n): { customTools: ReadonlyArray<CustomToolSpec> } | Record<string, never> {\n const baseTools = sendOptions?.tools ?? agentOptions.tools ?? [];\n // Prefer the resolved set (file-based + inline) when present; fall back to the\n // inline `agentOptions.agents` for callers that don't thread resolvedSubagents.\n const agentsForTools =\n subagents !== undefined && Object.keys(subagents).length > 0 ? subagents : agentOptions.agents;\n const subagentTools = declarativeSubagentTools(agentsForTools, baseTools);\n // T4.1: concat plugin-registered tools onto the effective catalog. Plugin\n // tools are merged unconditionally (no override semantics — name collision\n // would be caught by the registry validator if used).\n const pluginTools = pluginManager?.aggregated.tools ?? [];\n // SE37 — `reasoning: true` auto-attaches the internal `think` tool, unless a\n // native reasoning model is configured (guard + one-time warn). Guards on the\n // EFFECTIVE model (per-send override applied), matching the preamble path in\n // local-assembly so both agree on native-vs-not (no split double-reasoning).\n const reasoningTools = reasoningActive(agentOptions.reasoning, effectiveModel)\n ? [createThinkTool()]\n : [];\n if (\n baseTools.length === 0 &&\n subagentTools.length === 0 &&\n pluginTools.length === 0 &&\n reasoningTools.length === 0\n ) {\n return {};\n }\n const allTools = [...baseTools, ...subagentTools, ...pluginTools, ...reasoningTools];\n // theokit#148 — note this very `map`: the SDK rebuilds each tool from four fields, so any\n // credential channel riding the tool object is dropped right here. It only used to survive\n // because the pre-rebuild sink mutated the original handler's closure. Credentials now travel on\n // the run's async scope, which this rebuild cannot touch.\n const merged: CustomToolSpec[] = allTools.map((tool) => ({\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema,\n handler: tool.handler,\n }));\n // Phase 4.1 / ADR D167 — advisory narrowing by active personality.\n const customTools = applyPersonalityFilter(merged, personalityToolWhitelist, {\n agentId,\n personalityName,\n }) as ReadonlyArray<CustomToolSpec>;\n if (customTools.length === 0 && personalityToolWhitelist === undefined) return {};\n return { customTools };\n}\n","import { ConfigurationError } from \"../../errors.js\";\nimport type { AgentDefinition, AgentOptions, ModelSelection } from \"../../types/agent.js\";\nimport type { SDKMessage } from \"../../types/messages.js\";\nimport type { Run, RunOperation, RunStatus, SDKUserMessage, SendOptions } from \"../../types/run.js\";\nimport { emitRunEvent } from \"../../types/run-events.js\";\nimport { type AgentLoopInputs, runAgentLoop } from \"../agent-loop/loop.js\";\nimport type { MemoryToolSpec } from \"../agent-loop/loop-types.js\";\nimport { LOCAL_RUNTIME_MOCK_KEY } from \"../auth/api-key-validator.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { FallbackLlmClient } from \"../llm/fallback-client.js\";\nimport { parseModelId } from \"../llm/model-identifier.js\";\nimport { resolveProviderChain } from \"../llm/router.js\";\nimport { createMcpClient, type McpClient } from \"../mcp/client.js\";\nimport { getProviderProfile, registerBuiltins } from \"../providers/index.js\";\nimport { registerPluginProviderProfiles } from \"../providers/register-plugin-providers.js\";\nimport { withToolWhitelist } from \"../runtime/concurrency/async-local-storage.js\";\nimport {\n type InheritedCredentials,\n withInheritedSubAgentCredentials,\n} from \"../runtime/concurrency/subagent-credentials.js\";\nimport { isFixtureApiKey } from \"../runtime/fixtures/fixture-mode.js\";\nimport { FixtureRunBase, prepareRunContext } from \"../runtime/fixtures/fixture-run-base.js\";\nimport type { FixtureScript } from \"../runtime/fixtures/fixture-types.js\";\nimport type { HooksExecutor } from \"../runtime/hooks/hooks-executor.js\";\nimport { registerRun } from \"../runtime/registry/run-registry.js\";\nimport type { SessionMessage } from \"../session/index.js\";\nimport { createTelemetry } from \"../telemetry/tracer.js\";\nimport { McpClientPool } from \"./mcp-pool.js\";\nimport { detectPrimaryProvider, inferProviderFromApiKey } from \"./real-local-run-provider.js\";\nimport { buildCustomToolsInput, resolveInheritedCredentials } from \"./real-local-run-tools.js\";\n\n/**\n * Real local Run. When the local agent has a non-fixture API key plus at\n * least one provider env credential, the agent loop drives a real LLM and\n * dispatches real tools. The output is materialized into the same\n * `FixtureScript` shape used by the fixture runtime so the `Run` surface\n * stays uniform.\n *\n * @internal\n */\n\nexport interface CreateRealLocalRunOptions {\n agentId: string;\n model: ModelSelection | undefined;\n message: string | SDKUserMessage;\n agentOptions: AgentOptions;\n /**\n * File-based + inline subagents merged by `loadSubagents` (`.theokit/agents/*.md`\n * plus `agentOptions.agents`). When present, these — not just the inline\n * `agentOptions.agents` — become the delegation toolset, so a subagent defined\n * only on disk is callable against a real model (not fixture-only).\n */\n subagents?: Record<string, AgentDefinition>;\n sendOptions: SendOptions;\n workspaceCwd: string;\n hooks: HooksExecutor;\n /** T4.1 — PluginManager threaded from LocalAgent for plugin tools + pre_tool_call hooks. */\n pluginManager?: import(\"../plugins/manager.js\").PluginManager;\n /** Pre-resolved system prompt threaded by `LocalAgent.send`. */\n systemPrompt?: string;\n onStep?: SendOptions[\"onStep\"];\n onDelta?: SendOptions[\"onDelta\"];\n /** Prior conversation history (excluding the current user message). */\n priorMessages?: ReadonlyArray<SessionMessage>;\n /** Memory tools to register with the LLM (Phase 6 of memory-system-peer-project-parity). */\n memoryTools?: ReadonlyArray<MemoryToolSpec>;\n /**\n * Active personality tool whitelist (T4.1, ADR D167). When defined,\n * `customTools` are filtered to this subset; missing entries log a\n * one-shot warn. Undefined = no filter.\n */\n personalityToolWhitelist?: ReadonlyArray<string>;\n /** Active personality slug — used in personality-filter warnings. */\n personalityName?: string;\n}\n\nexport function createRealLocalRun(options: CreateRealLocalRunOptions): Run {\n const { userText, userImages, id, startTime } = prepareRunContext(options.message);\n const supported = new Set<RunOperation>([\"stream\", \"wait\", \"cancel\", \"conversation\"]);\n // The base Run class accepts a FixtureScript for shape; the real LLM run does\n // not REPLAY it (`buildLoopInputs` drives the real agent loop instead of\n // replaying events) — but result-metadata fields set here (SE3 `origin`) ARE\n // read back by `buildResult → applyScriptMetrics` and surface on RunResult.\n // So this is the run's result-metadata script, not a throwaway.\n const runScript: FixtureScript = {\n events: [],\n finalStatus: \"running\",\n cancellable: false,\n conversation: [],\n // SE3 — carry the turn's provenance so buildResult forwards it onto RunResult.origin.\n ...(options.sendOptions.origin !== undefined ? { origin: options.sendOptions.origin } : {}),\n };\n\n const handle = new RealLocalRun(\n {\n id,\n agentId: options.agentId,\n model: options.model,\n script: runScript,\n supportedOps: supported,\n startTime,\n },\n () => buildLoopInputs(options, id, userText, userImages),\n runOwnsMcpClients(options.agentOptions),\n resolveInheritedCredentials(options.agentOptions),\n );\n handle.bootstrap();\n registerRun(handle);\n return handle;\n}\n\n// Module-level one-shot: the observability line fires once per process, not\n// once per run, to avoid log spam when many agents are created.\nlet pluginProvidersAnnounced = false;\n\n/** Test-only reset for the one-shot announcement. @internal */\nexport function _resetPluginProviderAnnounce(): void {\n pluginProvidersAnnounced = false;\n}\n\n/**\n * Resolve the run's primary provider + effective model id.\n *\n * Registers builtins AND any plugin-contributed `kind: \"model-provider\"`\n * profiles FIRST, so the prefix-inference lookup (`model: { id: \"myprov/...\" }`)\n * can see a plugin-supplied provider. The aggregated profiles were otherwise\n * never registered (half-wired path). Extracted from `buildLoopInputs` (SRP)\n * and exported `@internal` so the plugin-provider wiring is regression-covered.\n *\n * ADR D182 / T1.2: explicit `providers.routes[0].provider` wins, then prefix\n * inference, then env-var heuristics (`detectPrimaryProvider`).\n *\n * @internal\n */\nexport function resolveRunProvider(options: CreateRealLocalRunOptions): {\n primary: string;\n effectiveModelId: string;\n} {\n registerBuiltins();\n const profiles = options.pluginManager?.aggregated.providerProfiles ?? [];\n const registered = registerPluginProviderProfiles(profiles);\n // Wiring-triad pillar (c): one-shot observability that plugin providers were\n // wired this process. Silent on the zero-plugin happy path.\n if (registered > 0 && !pluginProvidersAnnounced) {\n pluginProvidersAnnounced = true;\n const names = profiles.map((e) => e.profile.name).join(\", \");\n diag(`[theokit-sdk] registered ${registered} plugin provider profile(s): ${names}\\n`);\n }\n const parsedModel = parseModelId(options.model?.id);\n const modelInferredProvider =\n parsedModel.provider !== undefined && getProviderProfile(parsedModel.provider) !== undefined\n ? parsedModel.provider\n : undefined;\n // M4 (plan m4-provider-routing-apikey-fix): the explicitly-passed API key is\n // the ground-truth credential of which endpoint will be called, so it outranks\n // model-prefix inference for `primary` — a `sk-or-` key + an `openai/gpt-4o-mini`\n // model MUST route to OpenRouter, not the OpenAI provider. An explicit\n // `providers.routes[0].provider` still wins (user override).\n const keyInferredProvider = inferProviderFromApiKey(options.agentOptions.apiKey);\n const primary =\n options.agentOptions.providers?.routes?.[0]?.provider ??\n keyInferredProvider ??\n modelInferredProvider ??\n detectPrimaryProvider();\n // Strip the vendor prefix ONLY when the model's own prefix names the resolved\n // primary (anthropic/claude → claude for the anthropic provider). When primary\n // is an aggregator (openrouter) whose slug legitimately embeds a `vendor/`\n // segment (openai/gpt-4o-mini), pass the id through unstripped.\n const effectiveModelId =\n modelInferredProvider !== undefined && modelInferredProvider === primary\n ? parsedModel.name\n : (options.model?.id ?? \"claude-sonnet-4-6\");\n return { primary, effectiveModelId };\n}\n\n/**\n * M4: thread the single `Agent.create({ apiKey })` credential into the router's\n * per-provider pool for the resolved `primary`, so an explicitly-passed key is\n * used even when the matching env var is unset. An existing `providers.apiKeys`\n * pool for the provider wins (it is the more-specific config); fixture and\n * `local` sentinels are never threaded (they are not real credentials). @internal\n */\nexport function mergeExplicitApiKey(\n pools: Record<string, string[]> | undefined,\n primary: string,\n apiKey: string | undefined,\n): Record<string, string[]> | undefined {\n if (apiKey === undefined || apiKey.length === 0) return pools;\n if (isFixtureApiKey(apiKey) || apiKey === LOCAL_RUNTIME_MOCK_KEY) return pools;\n const existing = pools?.[primary];\n if (existing !== undefined && existing.length > 0) return pools;\n return { ...(pools ?? {}), [primary]: [apiKey] };\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: spread-conditional builders for optional fields (systemPrompt, onStep, onDelta, priorMessages, memoryTools, customTools, pluginManager) are the canonical pattern for shaping AgentLoopInputs; splitting hurts readability.\nfunction buildLoopInputs(\n options: CreateRealLocalRunOptions,\n runId: string,\n userText: string,\n userImages: import(\"../../types/run.js\").SDKUserMessage[\"images\"],\n): AgentLoopInputs {\n // M1-2: per-send iteration ceiling. Validate at the boundary so an invalid\n // knob fails fast with a clear message instead of producing a degenerate budget.\n const maxIterations = options.sendOptions.maxIterations;\n if (maxIterations !== undefined && (!Number.isInteger(maxIterations) || maxIterations < 1)) {\n throw new ConfigurationError(\n `SendOptions.maxIterations must be a positive integer, got ${maxIterations}`,\n { code: \"invalid_max_iterations\" },\n );\n }\n const { primary, effectiveModelId } = resolveRunProvider(options);\n const fallback = options.agentOptions.providers?.fallback;\n // M4: thread the single explicit `apiKey` into the pool for `primary` so an\n // explicitly-passed credential is used even without the matching env var.\n const apiKeys = mergeExplicitApiKey(\n options.agentOptions.providers?.apiKeys,\n primary,\n options.agentOptions.apiKey,\n );\n const credentialPoolStrategy = options.agentOptions.providers?.credentialPoolStrategy;\n // theokit#58 follow-up: the chat route may opt into leaked-dialect recovery.\n // Mirrors how `primary` derives from routes[0]; applied to the resolved chain.\n const extractToolCallsFromContent =\n options.agentOptions.providers?.routes?.[0]?.extractToolCallsFromContent;\n // SE2 — when the caller subscribed via `onRunEvent`, a 429 retry surfaces a\n // typed `rate_limit` RunEvent (the pool-aware client calls this before backing off).\n const rateLimitSink = options.sendOptions.onRunEvent;\n const chain = resolveProviderChain({\n primary,\n ...(fallback !== undefined ? { fallback } : {}),\n ...(apiKeys !== undefined ? { apiKeys } : {}),\n ...(credentialPoolStrategy !== undefined ? { credentialPoolStrategy } : {}),\n ...(extractToolCallsFromContent === true ? { extractToolCallsFromContent: true } : {}),\n ...(rateLimitSink !== undefined\n ? {\n onRateLimit: (info: { attempt: number; retryAfterMs?: number }) =>\n emitRunEvent(rateLimitSink, { type: \"rate_limit\", ...info }),\n }\n : {}),\n });\n const llm =\n chain.length === 1 ? (chain[0] as (typeof chain)[number]) : new FallbackLlmClient(chain);\n return {\n agentId: options.agentId,\n runId,\n // issue #47: carry ModelSelection.params (the reasoning `thinking` param) into the loop so the\n // request can forward reasoning. The id is stripped/normalized above; params pass through as-is.\n model: {\n id: effectiveModelId,\n ...(options.model?.params !== undefined ? { params: options.model.params } : {}),\n },\n userMessage: userText,\n ...(userImages !== undefined ? { userImages } : {}),\n llm,\n mcp: buildMcpMap(options),\n hooks: options.hooks,\n shellCwd: options.workspaceCwd,\n shellSandbox: options.agentOptions.local?.sandboxOptions?.enabled === true,\n ...(options.systemPrompt !== undefined ? { systemPrompt: options.systemPrompt } : {}),\n ...(options.onStep !== undefined ? { onStep: options.onStep } : {}),\n ...(options.onDelta !== undefined ? { onDelta: options.onDelta } : {}),\n ...(options.sendOptions.toolChoice !== undefined\n ? { toolChoice: options.sendOptions.toolChoice }\n : {}),\n ...(options.sendOptions.activeTools !== undefined\n ? { activeTools: options.sendOptions.activeTools }\n : {}),\n // SE1 — resolve the run's permission mode: per-send wins over creation-time.\n ...((options.sendOptions.permissionMode ?? options.agentOptions.permissionMode) !== undefined\n ? {\n permissionMode: options.sendOptions.permissionMode ?? options.agentOptions.permissionMode,\n }\n : {}),\n ...(options.priorMessages !== undefined ? { priorMessages: options.priorMessages } : {}),\n ...(options.memoryTools !== undefined && options.memoryTools.length > 0\n ? { memoryTools: options.memoryTools }\n : {}),\n ...buildCustomToolsInput(\n options.agentOptions,\n options.sendOptions,\n options.pluginManager,\n options.personalityToolWhitelist,\n options.agentId,\n options.personalityName,\n options.subagents,\n options.model,\n ),\n ...(options.pluginManager !== undefined ? { pluginManager: options.pluginManager } : {}),\n // D318 — forward SendOptions.signal to the agent loop so streamLlmTurn\n // can attach it to the LLM `fetch({ signal })` call.\n ...(options.sendOptions.signal !== undefined ? { signal: options.sendOptions.signal } : {}),\n // M7 — forward SendOptions.context to the loop so every tool handler receives\n // it on `ctx.context` (shared run config set once, e.g. projectRoot).\n ...(options.sendOptions.context !== undefined ? { context: options.sendOptions.context } : {}),\n // SE2 — forward the opt-in typed runtime-event sink to the loop.\n ...(options.sendOptions.onRunEvent !== undefined\n ? { runEventSink: options.sendOptions.onRunEvent }\n : {}),\n // #58 / #57 — forward the per-tool timeout + tool-result guard so a consumer\n // can enable them via SendOptions (not only internal AgentLoopInputs).\n ...(options.sendOptions.perToolTimeoutMs !== undefined\n ? { perToolTimeoutMs: options.sendOptions.perToolTimeoutMs }\n : {}),\n ...(options.sendOptions.toolResultGuard !== undefined\n ? { toolResultGuard: options.sendOptions.toolResultGuard }\n : {}),\n // M1-2: per-send iteration ceiling (validated above). The loop reads\n // inputs.maxIterations (default 8 when unset).\n ...(maxIterations !== undefined ? { maxIterations } : {}),\n // Doom-loop guard config (default on; `false` disables, object tunes thresholds).\n ...(options.sendOptions.doomLoop !== undefined\n ? { doomLoop: options.sendOptions.doomLoop }\n : {}),\n // D315-D317 — tool lifecycle hooks (cost tracking + audit + retry/alert)\n ...(options.agentOptions.onToolStart !== undefined\n ? { onToolStart: options.agentOptions.onToolStart }\n : {}),\n ...(options.agentOptions.onToolEnd !== undefined\n ? { onToolEnd: options.agentOptions.onToolEnd }\n : {}),\n ...(options.agentOptions.onToolError !== undefined\n ? { onToolError: options.agentOptions.onToolError }\n : {}),\n telemetry: createTelemetry(options.agentOptions.telemetry),\n // SDK 2.0 Phase 2 / T2.1: thread the optional BudgetTracker from\n // Agent.create options down to the loop. Runtime `track()` / `check()`\n // calls land in a follow-up iteration; for now the field is plumbed\n // so future enablement requires no further type changes.\n ...(options.agentOptions.budgetTracker !== undefined\n ? { budgetTracker: options.agentOptions.budgetTracker }\n : {}),\n // SDK 2.0 Phase 1 / T1.4: thread the optional MemoryProvider from\n // Agent.create options down to the loop. Runtime `init()` /\n // `buildTools()` / `runActivePass()` / `dispose()` calls land in\n // T1.5; for now the field is plumbed so the runtime wiring requires\n // no further type changes.\n ...(options.agentOptions.memoryProvider !== undefined\n ? { memoryProvider: options.agentOptions.memoryProvider }\n : {}),\n };\n}\n\n/**\n * Resolve the effective custom-tool catalog for this run.\n *\n * Precedence (matches the mcpServers semantics — \"fully replaces, not merged\"):\n * - `sendOptions.tools === undefined` → fall back to `agentOptions.tools`\n * - `sendOptions.tools = []` → explicitly clear (no custom tools)\n * - `sendOptions.tools = [t1, ...]` → use exactly these for this run\n */\n\n/**\n * M77 — the process-wide pool backing `mcpLifecycle: 'session'`.\n *\n * Keyed by `(agentId, server, config)`, so it is session-scoped despite being a module-level object:\n * `agentId` IS the session identity here (it is what `getSessionMessages` keys the transcript cache\n * by), and `LocalAgent.dispose()` releases its own entries. Two agents never see each other's\n * clients.\n */\nconst sessionMcpPool = new McpClientPool<McpClient>();\n\n/** M77 — release one session's pooled MCP clients. Called from `LocalAgent.dispose()`. */\nexport function disposeSessionMcpClients(agentId: string): void {\n sessionMcpPool.disposeSession(agentId, (client) => {\n void client.close();\n });\n}\n\n/**\n * M77 — the production seam, exported for the wiring test.\n *\n * Exported (`_` prefix, `@internal`) rather than left private because the pool is only worth having\n * if `buildMcpMap` actually reaches it. Testing the pool class alone would prove the CLASS reuses,\n * not that the SYSTEM does — the exact gap the M76 review found in the ask-bridge.\n *\n * @internal\n */\nexport function _buildMcpMapForTests(options: CreateRealLocalRunOptions): Map<string, McpClient> {\n return buildMcpMap(options);\n}\n\n/**\n * theokit#155 — does THIS RUN own the MCP clients it was handed?\n *\n * Under the default `'run'` lifecycle the client is built for this send and dies with it, so the\n * run closes it. Under `'session'` the pool owns it: closing it at the end of the turn SIGTERMs the\n * child process, and the next turn spawns a new one — which is exactly why the option measured\n * 0 ms of savings. Ownership is derived here, once, so `buildMcpMap` and the run's `finally` cannot\n * disagree about who releases the resource.\n */\nfunction runOwnsMcpClients(agentOptions: AgentOptions): boolean {\n return agentOptions.mcpLifecycle !== \"session\";\n}\n\nfunction buildMcpMap(options: CreateRealLocalRunOptions): Map<string, McpClient> {\n const map = new Map<string, McpClient>();\n const inline = options.sendOptions.mcpServers ?? options.agentOptions.mcpServers;\n if (inline === undefined) return map;\n\n // M77 — `'run'` stays the default: a client per send, dropped with the run. Only an explicit\n // `mcpLifecycle: 'session'` reaches the pool, because pooling changes the failure model (see the\n // option's docblock). The reap runs on acquisition rather than on a timer: a timer would keep the\n // process alive, and a pool nobody touches has nothing worth reaping.\n const pooled = !runOwnsMcpClients(options.agentOptions);\n if (pooled) sessionMcpPool.reapIdle((c) => void c.close());\n\n for (const [name, config] of Object.entries(inline)) {\n map.set(\n name,\n pooled\n ? sessionMcpPool.acquire(options.agentId, name, config, () => createMcpClient(name, config))\n : createMcpClient(name, config),\n );\n }\n return map;\n}\n\nclass RealLocalRun extends FixtureRunBase {\n private readonly buildInputs: () => AgentLoopInputs;\n /** theokit#155 — whether this turn releases its MCP clients, or the session pool does. */\n private readonly ownsMcpClients: boolean;\n /** theokit#148 — what a delegated child inherits from this parent, scoped to the loop. */\n private readonly inheritedCredentials: InheritedCredentials;\n\n constructor(\n options: ConstructorParameters<typeof FixtureRunBase>[0],\n buildInputs: () => AgentLoopInputs,\n ownsMcpClients: boolean,\n inheritedCredentials: InheritedCredentials,\n ) {\n super(options);\n this.buildInputs = buildInputs;\n this.ownsMcpClients = ownsMcpClients;\n this.inheritedCredentials = inheritedCredentials;\n }\n\n bootstrap(): void {\n setTimeout(() => {\n void this.driveLoop();\n }, 0);\n }\n\n protected override notifyImmediately(): boolean {\n return true;\n }\n\n private async driveLoop(): Promise<void> {\n if (this.terminated) return;\n const inputs = this.tryBuildInputs();\n if (inputs === undefined) return;\n await this.initializeMcp(inputs);\n await this.executeAgentLoop(inputs);\n }\n\n private tryBuildInputs(): AgentLoopInputs | undefined {\n try {\n return this.buildInputs();\n } catch (cause) {\n this.emitErrorEvent(cause, \"Failed to build agent loop inputs\", \"\", \"build_inputs_failed\");\n this.transitionTo(\"error\" satisfies RunStatus);\n return undefined;\n }\n }\n\n private async initializeMcp(inputs: AgentLoopInputs): Promise<void> {\n for (const [name, client] of inputs.mcp.entries()) {\n try {\n await client.initialize();\n } catch (cause) {\n this.emitErrorEvent(\n cause,\n `MCP server ${name} failed to initialize`,\n `MCP server ${name} failed to initialize: `,\n \"mcp_init_failed\",\n );\n }\n }\n }\n\n /**\n * theokit#140 - events already handed to stream() by the live subscriber.\n *\n * The loop still RETURNS its full event list, and that batch path is deliberately kept: it is the\n * fallback if a live event is ever lost, and removing it would make the live channel a single\n * point of failure for the whole transcript.\n */\n private readonly liveDelivered = new Set<SDKMessage>();\n\n private async executeAgentLoop(inputs: AgentLoopInputs): Promise<void> {\n // theokit#140 - subscribe BEFORE the loop runs, so nothing is missed between start and the\n // first await. Events now reach stream() in true order as they happen, instead of arriving as\n // one post-completion batch while onDelta streamed tokens on a separate clock.\n // theokit#140 - whether a text delta has crossed since the last assistant message was reported.\n // This is the FACT that lets the timeline say `textAlreadyStreamed` instead of leaving the\n // consumer to infer it by comparing text - the inference that produced the `callId`-namespace\n // and timestamp-fallback bugs. Scoped per run, reset at each assistant message so a multi-step\n // run answers the question per message rather than once for the whole run.\n let textStreamedSinceLastMessage = false;\n inputs.onLoopEvent = (event: SDKMessage) => {\n this.liveDelivered.add(event);\n this.script.events.push(event);\n // theokit#140 - the same event on the complete timeline. Both views are fed from the one\n // place the loop reports, so they cannot disagree about order or contents.\n const carriesText =\n event.type === \"assistant\" && event.message.content.some((b) => b.type === \"text\");\n this.pushTimeline(\n carriesText\n ? { kind: \"message\", message: event, textAlreadyStreamed: textStreamedSinceLastMessage }\n : // No text ⇒ the question does not apply. Marking a tool-only or structural message\n // would be a claim the consumer acts on by HIDING content it was never shown.\n { kind: \"message\", message: event },\n );\n if (carriesText) textStreamedSinceLastMessage = false;\n this.notifyNewEvents();\n };\n // theokit#140 - the OTHER half of the timeline. Deltas were only ever reachable through the\n // caller's own `onDelta`, which is why a consumer had to fuse two surfaces to see tokens and\n // tool calls in one order. The caller's callback is preserved and still fires first: this wraps\n // it, never replaces it.\n const callerOnDelta = inputs.onDelta;\n inputs.onDelta = (delta) => {\n callerOnDelta?.(delta);\n if (delta.update.type === \"text-delta\") textStreamedSinceLastMessage = true;\n this.pushTimeline({ kind: \"delta\", update: delta.update });\n };\n try {\n // SE18 — when the send set `activeTools`, run the loop inside a tool-whitelist\n // scope so a call to a tool outside the set is vetoed at dispatch (same path as\n // `Agent.fork`'s `allowedTools`). Absent ⇒ the full toolset is available.\n const runLoop = (): Promise<Awaited<ReturnType<typeof runAgentLoop>>> =>\n inputs.activeTools !== undefined\n ? withToolWhitelist(new Set(inputs.activeTools), () => runAgentLoop(inputs))\n : runAgentLoop(inputs);\n // theokit#148 — publish the parent's delegation credentials for the duration of the loop.\n // A subagent tool reads them at dispatch, so they survive every layer that rebuilds the tool\n // object (including the SDK's own rebuild in `real-local-run-tools.ts`), and two concurrent\n // runs sharing one tool instance each see their own.\n const output = await withInheritedSubAgentCredentials(this.inheritedCredentials, runLoop);\n this.applyAgentLoopOutput(output);\n this.transitionTo(output.finalStatus);\n } catch (cause) {\n this.emitErrorEvent(cause, \"Agent loop failed\", \"\", \"agent_loop_failed\");\n this.transitionTo(\"error\" satisfies RunStatus);\n } finally {\n // theokit#155 — release only what this TURN owns. Under `mcpLifecycle: 'session'` the pool\n // owns the client and releases it via `disposeSessionMcpClients` (`LocalAgent.dispose()`) plus\n // `reapIdle` on the next acquire; closing it here would kill the child the next turn expects\n // to still be running.\n if (this.ownsMcpClients) {\n for (const client of inputs.mcp.values()) {\n await client.close().catch(() => undefined);\n }\n }\n }\n }\n\n /**\n * Copy runAgentLoop output into the script (events + conversation +\n * usage/cost + errorDetail). Extracted to keep executeAgentLoop below\n * the complexity-10 cap (D422 / sdk-biome-cleanup-plan).\n *\n * D376/D377: usage/cost surfaced for RunResult.usage / RunResult.cost.\n * Finding-B fix (sdk-error-packaging v1.1): set-once errorDetail copy.\n */\n private applyAgentLoopOutput(output: Awaited<ReturnType<typeof runAgentLoop>>): void {\n this.deliverUndeliveredEvents(output.events);\n this.script.conversation.push(...output.conversation);\n if (output.result.length > 0) this.script.result = output.result;\n if (output.usage !== undefined) this.script.usage = output.usage;\n if (output.cost !== undefined) this.script.cost = output.cost;\n // M1-2 (T2.2): surface the silent-truncation signal onto the RunResult.\n if (output.stoppedAtIterationLimit === true) this.script.stoppedAtIterationLimit = true;\n // Doom-loop guard: surface the identical-repeat stop signal onto the RunResult.\n if (output.stoppedByDoomLoop === true) this.script.stoppedByDoomLoop = true;\n if (output.error !== undefined && this.script.errorDetail === undefined) {\n this.script.errorDetail = {\n message: output.error.message,\n ...(output.error.code !== undefined ? { code: output.error.code } : {}),\n cause: output.error.cause,\n };\n }\n }\n\n /**\n * theokit#140 - deliver only what the live subscriber has NOT already handed to `stream()`.\n *\n * The loop now reports each event as it happens, so this batch is the SAME list, replayed.\n * Without the guard every event would reach `stream()` twice: once live, once here.\n *\n * Identity, not deep equality: these are the very objects the live sink saw, and two genuinely\n * distinct events can be structurally identical (the same tool called twice with the same args\n * is not a duplicate).\n *\n * Extracted because the guard pushed `applyAgentLoopOutput` past the cognitive-complexity cap.\n */\n private deliverUndeliveredEvents(events: readonly SDKMessage[]): void {\n for (const event of events) {\n if (this.liveDelivered.has(event)) continue;\n this.script.events.push(event);\n this.notifyNewEvents();\n }\n }\n\n private emitErrorEvent(cause: unknown, fallback: string, prefix = \"\", code?: string): void {\n // Finding-B fix (sdk-error-packaging-fix-plan v1.1): surface infra\n // failures (MCP init, build-inputs, agent_loop_failed outer-catch) via\n // the structured `errorDetail` channel ONLY — never as assistant\n // content. Downstream `buildResult()` copies this onto RunResult.error,\n // and `Run.stream()` will emit a typed `{ type: \"error\" }` event when\n // the runtime observes errorDetail (Phase 2). Set-once.\n if (this.script.errorDetail === undefined) {\n const message = cause instanceof Error ? cause.message : String(cause);\n const display = prefix.length > 0 ? `${prefix}${message}` : message || fallback;\n this.script.errorDetail = {\n message: display,\n ...(code !== undefined ? { code } : {}),\n cause,\n };\n }\n this.notifyNewEvents();\n }\n}\n","/**\n * Dispatch helpers extracted from `LocalAgent` to keep its file under\n * G8 (≤400 LoC). Builds the args for real-LLM and fixture run paths.\n *\n * @internal\n */\n\nimport { readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type { AgentDefinition, AgentOptions, ModelSelection } from \"../../types/agent.js\";\nimport type { Run, SDKUserMessage, SendOptions } from \"../../types/run.js\";\nimport type { MemoryToolSpec } from \"../agent-loop/loop-types.js\";\nimport { resolveApiKey } from \"../env.js\";\nimport type { PersonalityPreset } from \"../personality/types.js\";\nimport type { PluginManager } from \"../plugins/manager.js\";\nimport { shouldUseRealLocalRuntime } from \"../runtime/fixtures/fixture-mode.js\";\nimport type { HooksExecutor } from \"../runtime/hooks/hooks-executor.js\";\nimport type { MemoryFact } from \"../runtime/memory/memory-store.js\";\nimport { getSessionMessages } from \"../session/index.js\";\nimport { createLocalRun } from \"./local-run.js\";\nimport { createRealLocalRun } from \"./real-local-run.js\";\n\nexport interface DispatchInputs {\n agentId: string;\n model: ModelSelection | undefined;\n options: AgentOptions;\n workspaceCwd: string;\n hooksExecutor: HooksExecutor;\n pluginManager: PluginManager;\n resolvedSubagents: Record<string, AgentDefinition>;\n settingSourcesIncludeProject: boolean;\n}\n\nexport function buildRealRunOptions(args: {\n inputs: DispatchInputs;\n message: string | SDKUserMessage;\n options: SendOptions;\n systemPrompt: string | undefined;\n priorMessages: ReadonlyArray<{ role: \"user\" | \"assistant\"; text: string }>;\n memoryTools: ReadonlyArray<MemoryToolSpec> | undefined;\n personalityToolWhitelist?: ReadonlyArray<string>;\n personalityName?: string;\n}): Parameters<typeof createRealLocalRun>[0] {\n return {\n agentId: args.inputs.agentId,\n model: args.inputs.model,\n message: args.message,\n agentOptions: args.inputs.options,\n subagents: args.inputs.resolvedSubagents,\n sendOptions: args.options,\n workspaceCwd: args.inputs.workspaceCwd,\n hooks: args.inputs.hooksExecutor,\n pluginManager: args.inputs.pluginManager,\n ...(args.systemPrompt !== undefined ? { systemPrompt: args.systemPrompt } : {}),\n ...(args.options.onStep !== undefined ? { onStep: args.options.onStep } : {}),\n ...(args.options.onDelta !== undefined ? { onDelta: args.options.onDelta } : {}),\n ...(args.priorMessages.length > 0 ? { priorMessages: args.priorMessages } : {}),\n ...(args.memoryTools !== undefined && args.memoryTools.length > 0\n ? { memoryTools: args.memoryTools }\n : {}),\n ...(args.personalityToolWhitelist !== undefined\n ? { personalityToolWhitelist: args.personalityToolWhitelist }\n : {}),\n ...(args.personalityName !== undefined ? { personalityName: args.personalityName } : {}),\n };\n}\n\nexport async function createFixtureRunHelper(args: {\n inputs: DispatchInputs;\n message: string | SDKUserMessage;\n options: SendOptions;\n systemPrompt: string | undefined;\n memoryFacts: ReadonlyArray<MemoryFact>;\n}): Promise<Run> {\n const sessionMessages = getSessionMessages(args.inputs.agentId);\n const projectMcpServers = args.inputs.settingSourcesIncludeProject\n ? await readProjectMcpServers(args.inputs.workspaceCwd)\n : {};\n return createLocalRun({\n agentId: args.inputs.agentId,\n model: args.inputs.model,\n message: args.message,\n agentOptions: args.inputs.options,\n sendOptions: args.options,\n workspaceCwd: args.inputs.workspaceCwd,\n subagents: args.inputs.resolvedSubagents,\n settingSourcesIncludeProject: args.inputs.settingSourcesIncludeProject,\n memoryFacts: [...args.memoryFacts],\n sessionMessages,\n projectMcpServers,\n ...(args.systemPrompt !== undefined ? { systemPrompt: args.systemPrompt } : {}),\n });\n}\n\nexport async function dispatchLocalRun(args: {\n inputs: DispatchInputs;\n message: string | SDKUserMessage;\n sendOptions: SendOptions;\n systemPrompt: string | undefined;\n memoryFacts: ReadonlyArray<MemoryFact>;\n priorMessages: ReadonlyArray<{ role: \"user\" | \"assistant\"; text: string }>;\n memoryTools: ReadonlyArray<MemoryToolSpec> | undefined;\n activePreset: PersonalityPreset | undefined;\n}): Promise<Run> {\n const apiKey = resolveApiKey(args.inputs.options.apiKey);\n if (shouldUseRealLocalRuntime(apiKey)) {\n return createRealLocalRun(\n buildRealRunOptions({\n inputs: args.inputs,\n message: args.message,\n options: args.sendOptions,\n systemPrompt: args.systemPrompt,\n priorMessages: args.priorMessages,\n memoryTools: args.memoryTools,\n ...(args.activePreset?.tools !== undefined\n ? { personalityToolWhitelist: args.activePreset.tools }\n : {}),\n ...(args.activePreset !== undefined ? { personalityName: args.activePreset.name } : {}),\n }),\n );\n }\n return createFixtureRunHelper({\n inputs: args.inputs,\n message: args.message,\n options: args.sendOptions,\n systemPrompt: args.systemPrompt,\n memoryFacts: args.memoryFacts,\n });\n}\n\nasync function readProjectMcpServers(cwd: string): Promise<Record<string, unknown>> {\n const path = join(cwd, \".theokit\", \"mcp.json\");\n try {\n const raw = await readFile(path, \"utf8\");\n const parsed = JSON.parse(raw) as { servers?: Record<string, unknown> };\n return parsed.servers ?? {};\n } catch {\n return {};\n }\n}\n","import { diag } from \"../diagnostics.js\";\n/**\n * `Agent.invalidateCache` helpers extracted from LocalAgent (T3.2 / T4.3,\n * ADR D94). Keeps `local-agent.ts` under the 400-LoC gate while providing\n * the deferred-vs-applyNow semantics + EC-7 failure-path cleanup.\n *\n * @internal\n */\n\nexport interface InvalidationPending {\n reason: string;\n at: number;\n}\n\n/**\n * Run refresh + ALWAYS clear pending (EC-7).\n * @internal\n */\nexport async function applyDeferredInvalidation(\n agentId: string,\n pending: InvalidationPending,\n refresh: () => Promise<void>,\n): Promise<void> {\n diag(`[theokit-sdk] applying deferred cache invalidation (${agentId}): ${pending.reason}\\n`);\n try {\n await refresh();\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n diag(`[theokit-sdk] invalidateCache reload failed (continuing): ${msg}\\n`);\n }\n}\n\n/**\n * `Agent.invalidateCache` body — handles `applyNow` short-circuit OR\n * records pending state.\n * @internal\n */\nexport async function invalidateCacheImpl(\n agentId: string,\n reason: string,\n options: { applyNow?: boolean },\n disposed: boolean,\n dispose: () => Promise<void>,\n setPending: (p: InvalidationPending) => void,\n): Promise<void> {\n if (disposed) return;\n if (options.applyNow === true) {\n diag(`[theokit-sdk] invalidateCache applyNow disposing agent (${agentId}): ${reason}\\n`);\n await dispose();\n return;\n }\n setPending({ reason, at: Date.now() });\n}\n\n/**\n * T4.3 — consume pending invalidation. EC-7-safe: pending cleared\n * regardless of refresh outcome.\n * @internal\n */\nexport async function consumePending(\n agentId: string,\n pending: InvalidationPending | undefined,\n clear: () => void,\n refresh: () => Promise<void>,\n): Promise<void> {\n if (pending === undefined) return;\n clear();\n await applyDeferredInvalidation(agentId, pending, refresh);\n}\n","/**\n * Live-agent cache for production deploys (Production-Readiness #2, ADRs D307-D310).\n *\n * Caches `SDKAgent` instances by id with LRU eviction (when `size > maxAgents`)\n * and an idle-timeout sweep (configurable interval, default 60s). Solves the\n * \"OOM at some point\" failure mode of long-running Node servers that keep\n * spawning fresh agents per conversation.\n *\n * **Distinct from `agent-registry.ts`** (the metadata registry that persists\n * `RegisteredAgent` to `registry.json` per cwd). That module is the \"address\n * book\"; this module is the \"live cache\". Conflating them violates SRP — see\n * ADR D307.\n *\n * Defaults (ADR D308): `maxAgents: 100`, `idleTimeoutMs: 30 min`, sweep `60s`.\n * Calibrated for indie/small-team Node deploys; high-traffic SaaS should\n * `configure({ maxAgents: 1000 })`.\n *\n * @public (singleton exposed via `Agent.registry`)\n */\n\nimport type { SDKAgent } from \"../../../types/agent.js\";\nimport { diag } from \"../../diagnostics.js\";\n\nexport type EvictReason = \"lru\" | \"idle\" | \"explicit\";\n\nexport interface AgentRegistryOptions {\n /**\n * Maximum number of agents kept alive simultaneously. LRU eviction when\n * exceeded. Default: 100.\n *\n * Setting `0` disables the cache entirely — every `Agent.getOrCreate`\n * re-initializes (high cost, but predictable memory).\n */\n maxAgents?: number;\n\n /**\n * Idle timeout in milliseconds. Agents not used for this duration are\n * evicted on the next sweep tick. Default: 1_800_000 (30 minutes).\n * Set `0` to disable idle eviction.\n */\n idleTimeoutMs?: number;\n\n /**\n * Sweep interval in milliseconds. Default: 60_000 (60s).\n * Lower = more responsive eviction but more CPU. Higher = staler entries.\n */\n sweepIntervalMs?: number;\n\n /**\n * Called whenever an agent is evicted. Listener errors are swallowed\n * with a one-shot stderr warn (do not crash the eviction loop).\n */\n onEvict?: (id: string, reason: EvictReason) => void;\n}\n\ninterface CacheEntry {\n agent: SDKAgent;\n lastUsedAt: number;\n}\n\nconst DEFAULT_MAX_AGENTS = 100;\nconst DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1000; // 30 minutes\nconst DEFAULT_SWEEP_INTERVAL_MS = 60_000;\n\nexport class LiveAgentRegistry {\n readonly #agents = new Map<string, CacheEntry>();\n #maxAgents = DEFAULT_MAX_AGENTS;\n #idleTimeoutMs = DEFAULT_IDLE_TIMEOUT_MS;\n #sweepIntervalMs = DEFAULT_SWEEP_INTERVAL_MS;\n #onEvict: ((id: string, reason: EvictReason) => void) | undefined;\n #sweepTimer: NodeJS.Timeout | undefined;\n\n /**\n * Reconfigure registry behavior. Process-wide singleton (D310) — last\n * configure call wins for all subsequent operations.\n */\n configure(opts: AgentRegistryOptions): void {\n if (opts.maxAgents !== undefined) this.#maxAgents = Math.max(0, opts.maxAgents);\n if (opts.idleTimeoutMs !== undefined) this.#idleTimeoutMs = Math.max(0, opts.idleTimeoutMs);\n if (opts.sweepIntervalMs !== undefined)\n this.#sweepIntervalMs = Math.max(1_000, opts.sweepIntervalMs);\n this.#onEvict = opts.onEvict;\n // Reset sweep with new config.\n this.#stopSweep();\n if (this.#idleTimeoutMs > 0) this.#startSweep();\n }\n\n /**\n * Lookup a cached agent. `get` is a use — refreshes `lastUsedAt` so the\n * entry survives LRU eviction.\n */\n get(id: string): SDKAgent | undefined {\n const entry = this.#agents.get(id);\n if (entry === undefined) return undefined;\n entry.lastUsedAt = Date.now();\n return entry.agent;\n }\n\n /**\n * Insert or overwrite an agent in the cache. Triggers fire-and-forget LRU\n * eviction when `size > maxAgents`.\n *\n * EC-4: when `id` already maps to a DIFFERENT agent instance, dispose the\n * old one before overwriting (race protection against two `getOrCreate`\n * calls creating two agents but only the second being cached — the first\n * would leak file handles + lifecycle controllers).\n */\n set(id: string, agent: SDKAgent): void {\n if (this.#maxAgents === 0) return; // cache disabled\n const existing = this.#agents.get(id);\n if (existing !== undefined && existing.agent !== agent) {\n // Dispose the old entry off the hot path. Errors swallowed per D309.\n void existing.agent.dispose().catch(() => {\n diag(`[theokit-sdk] dispose during overwrite failed (${id})\\n`);\n });\n }\n this.#agents.set(id, { agent, lastUsedAt: Date.now() });\n if (this.#agents.size > this.#maxAgents) void this.#evictLRU();\n }\n\n /**\n * Remove the entry from the cache WITHOUT calling `dispose()` or\n * `onEvict`. Used by `LocalAgent.dispose()` itself so the disposed\n * instance can never be returned by a subsequent `get(id)` (dispose-cache\n * race fix). Idempotent — calling on an unknown id is a no-op.\n *\n * @internal\n */\n forget(id: string): void {\n this.#agents.delete(id);\n }\n\n /**\n * Explicitly evict an agent by id. Returns `true` when the entry was\n * present (false = already gone). Calls `agent.dispose()` + `onEvict`\n * with reason `\"explicit\"`.\n */\n async evict(id: string): Promise<boolean> {\n const entry = this.#agents.get(id);\n if (entry === undefined) return false;\n this.#agents.delete(id);\n await this.#disposeAndNotify(id, entry.agent, \"explicit\");\n return true;\n }\n\n /**\n * Evict every cached agent. Used by graceful shutdown (`process.on('SIGTERM')`)\n * or end-of-test cleanup.\n */\n async evictAll(): Promise<void> {\n const entries = Array.from(this.#agents.entries());\n this.#agents.clear();\n this.#stopSweep();\n for (const [id, entry] of entries) {\n await this.#disposeAndNotify(id, entry.agent, \"explicit\");\n }\n }\n\n /** Number of currently cached agents. */\n size(): number {\n return this.#agents.size;\n }\n\n /** Ids of cached agents, newest first (by lastUsedAt). */\n ids(): readonly string[] {\n return Array.from(this.#agents.entries())\n .sort((a, b) => b[1].lastUsedAt - a[1].lastUsedAt)\n .map(([id]) => id);\n }\n\n /**\n * LRU eviction: drop the entry with the smallest `lastUsedAt`. Runs only\n * when `size > maxAgents`. Asynchronous because `dispose()` is a Promise;\n * the hot-path caller (`set`) does not await.\n *\n * @internal\n */\n async #evictLRU(): Promise<void> {\n if (this.#agents.size <= this.#maxAgents) return; // size may have shrunk\n let oldestId: string | undefined;\n let oldestAt = Infinity;\n for (const [id, entry] of this.#agents) {\n if (entry.lastUsedAt < oldestAt) {\n oldestAt = entry.lastUsedAt;\n oldestId = id;\n }\n }\n if (oldestId === undefined) return;\n const entry = this.#agents.get(oldestId);\n if (entry === undefined) return;\n this.#agents.delete(oldestId);\n await this.#disposeAndNotify(oldestId, entry.agent, \"lru\");\n }\n\n /** Background sweep — drops entries whose `lastUsedAt < now - idleTimeoutMs`. */\n async #sweepIdle(): Promise<void> {\n if (this.#idleTimeoutMs === 0) return;\n const threshold = Date.now() - this.#idleTimeoutMs;\n const toEvict: Array<[string, CacheEntry]> = [];\n for (const [id, entry] of this.#agents) {\n if (entry.lastUsedAt < threshold) toEvict.push([id, entry]);\n }\n for (const [id, entry] of toEvict) {\n // EC-8 race safety: re-check the entry identity. If `set(id, newAgent)`\n // landed during the previous await, the newer entry's `lastUsedAt` is\n // recent and we must NOT delete it.\n const current = this.#agents.get(id);\n if (current === undefined || current.agent !== entry.agent) continue;\n this.#agents.delete(id);\n await this.#disposeAndNotify(id, entry.agent, \"idle\");\n }\n }\n\n #startSweep(): void {\n this.#sweepTimer = setInterval(() => void this.#sweepIdle(), this.#sweepIntervalMs);\n // unref so the sweep does not keep the event loop alive on process exit.\n this.#sweepTimer.unref?.();\n }\n\n #stopSweep(): void {\n if (this.#sweepTimer !== undefined) {\n clearInterval(this.#sweepTimer);\n this.#sweepTimer = undefined;\n }\n }\n\n /** Dispose + notify with errors swallowed (D309). Single chokepoint. */\n async #disposeAndNotify(id: string, agent: SDKAgent, reason: EvictReason): Promise<void> {\n try {\n await agent.dispose();\n } catch (cause) {\n const msg = cause instanceof Error ? cause.message : String(cause);\n diag(`[theokit-sdk] dispose during eviction failed (${id}): ${msg}\\n`);\n }\n if (this.#onEvict !== undefined) {\n try {\n this.#onEvict(id, reason);\n } catch (cause) {\n const msg = cause instanceof Error ? cause.message : String(cause);\n diag(`[theokit-sdk] onEvict listener threw (${id}): ${msg}\\n`);\n }\n }\n }\n}\n\n/** Process-wide singleton (ADR D310). */\nexport const liveAgentRegistry = new LiveAgentRegistry();\n","/**\n * Lifecycle helpers for {@link import(\"./local-agent.js\").LocalAgent} — writer-lease\n * acquisition/release, `dispose()` teardown, and `reload()` re-discovery.\n *\n * Extracted from `local-agent.ts` to keep that file under the 400-LoC guard (G8),\n * mirroring `local-agent-runtime-extensions.ts`. The grouping is by CONCEPT, not by\n * leftover: all four helpers below answer \"what does this agent own outside a single\n * run, and how is it handed back?\" — the store lease, the pooled MCP clients, the\n * pending disk writes, and the file-discovered submanagers.\n *\n * @internal\n */\n\nimport type { AgentDefinition, AgentOptions } from \"../../types/agent.js\";\nimport type { SessionStore } from \"../../types/session-store.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { withCwdMutex } from \"../persistence/cwd-mutex.js\";\nimport type { FileContextManager } from \"../runtime/context/context-manager.js\";\nimport type { PluginsManager } from \"../runtime/plugins/plugins-manager.js\";\nimport { flushRegistrySaves } from \"../runtime/registry/agent-registry.js\";\nimport { liveAgentRegistry } from \"../runtime/registry/live-agent-registry.js\";\nimport type { SkillsManager } from \"../runtime/skills/skills-manager.js\";\nimport { loadSubagents } from \"../runtime/skills/subagents-loader.js\";\nimport { discardSession } from \"../session/agent-session.js\";\nimport { flushSessionWrites } from \"../session/index.js\";\nimport { disposeSessionMcpClients } from \"./real-local-run.js\";\n\n/**\n * Takes the writer lease when the store knows how to take one.\n *\n * Testing for the capability rather than requiring it in the interface keeps the two-method port\n * `types/session-store.ts` declares — an external store (Postgres, S3) has no file lease and does not\n * must not be forced to pretend it has one (ISP).\n *\n * @internal\n */\nexport async function acquireLeaseIfPossible(store: unknown, agentId: string): Promise<void> {\n const a = (store as { acquire?: (id: string) => Promise<void> }).acquire;\n if (typeof a !== \"function\") return;\n try {\n await a.call(store, agentId);\n } catch (err) {\n // `SessionBusyError` PROPAGATES — that is the whole point: another process holds the session, and whoever\n // called it needs to decide (`exec` forks to a new id).\n if (err instanceof Error && err.name === \"SessionBusyError\") throw err;\n // Any other I/O failure (EACCES in a read-only directory, ENOSPC) is **not** contention: there\n // is no second writer, there is a place where nothing can be written. Failing init in that case\n // would trade \"no concurrency protection\" for \"the agent does not start\" — and the write itself\n // is best-effort by contract, so the turn would proceed the same without the lease.\n //\n // Measured: nine personality tests use a `baseDir` under `/var/empty`, where the lease's\n // the lease fails. They never write a transcript; requiring the lease there would mean\n // requiring permission to protect a file that does not exist.\n diag(\n `[theokit-sdk] writer lease unavailable for ${agentId} (${\n err instanceof Error ? err.message : String(err)\n }) — proceeding without single-writer protection\\n`,\n );\n }\n}\n\n/**\n * Releases an agent's lease, when the store knows how to release one by id.\n *\n * `SessionStore` is a **two-method** port by contract (`types/session-store.ts`), and a store\n * injected by the consumer is not required to have a lifecycle. Testing for the capability rather\n * than requiring it in the interface keeps the port small — widening it would force every external\n * store to implement a method most do not need (ISP).\n *\n * @internal\n */\nexport async function releaseLeaseIfPossible(store: unknown, agentId: string): Promise<void> {\n const r = (store as { release?: (id: string) => Promise<void> }).release;\n if (typeof r === \"function\") await r.call(store, agentId);\n}\n\nasync function disposeSessionStore(store: unknown): Promise<void> {\n const d = (store as { dispose?: () => Promise<void> }).dispose;\n if (typeof d === \"function\") await d.call(store);\n}\n\n/**\n * What {@link disposeLocalAgentSession} needs off the agent. Structural (not the class) so the\n * teardown order stays testable without constructing a whole `LocalAgent`.\n *\n * @internal\n */\nexport interface LocalAgentDisposeTarget {\n readonly agentId: string;\n readonly workspaceCwd: string;\n readonly lifecycleAbortController: AbortController;\n readonly sessionStore: SessionStore;\n}\n\n/**\n * Tear down everything the agent holds beyond a single run. The CALLER owns the\n * `disposed` flag (idempotence guard) — this function assumes it was already flipped.\n *\n * Order is load-bearing and is the reason this is one function rather than inline steps:\n * flush disk writes BEFORE releasing the store, or the lease is handed back with a write\n * still pending.\n *\n * @internal\n */\nexport async function disposeLocalAgentSession(agent: LocalAgentDisposeTarget): Promise<void> {\n // Evict from live cache so the next Agent.getOrCreate(id) builds fresh.\n liveAgentRegistry.forget(agent.agentId);\n // D319: fire the lifecycle abort so any in-flight LLM `fetch()` cancels.\n // `abort()` is idempotent — safe to call even when already aborted.\n agent.lifecycleAbortController.abort();\n // Wait for any in-flight send + post-run lifecycle to release the per-agent send mutex.\n // Without this, `dispose()` could return before `writeSessionSummary` finishes, leaving the\n // caller to read a partially-written `.theokit/memory/sessions/<runId>.md` file.\n await withCwdMutex(`agent-send:${agent.agentId}`, () => Promise.resolve());\n // M77 — release this session's pooled MCP clients (`mcpLifecycle: 'session'`). A pooled client\n // outlives the run by design; without this it would outlive the AGENT too, leaving an orphan\n // child process per server for the life of the host. No-op for the default `'run'` lifecycle,\n // which never puts anything in the pool.\n disposeSessionMcpClients(agent.agentId);\n // Now flush any remaining disk writes so the on-disk state matches the in-memory state\n // before the caller proceeds (ADR D17 + D18).\n await flushSessionWrites();\n await flushRegistrySaves(agent.workspaceCwd);\n // M95 — releases the writer lease and erases this agent's FOUR module caches.\n //\n // Order matters: after `flushSessionWrites`, otherwise we would release the lease with a write\n // pending. `invalidateSessionCache` cleared two of the four maps; `pendingWrites` and\n // `recordCounts` were never erased by id and grew for the life of the process.\n await disposeSessionStore(agent.sessionStore);\n discardSession(agent.workspaceCwd, agent.agentId);\n}\n\n/**\n * What {@link reloadLocalAgent} needs off the agent.\n *\n * @internal\n */\nexport interface LocalAgentReloadTarget {\n readonly workspaceCwd: string;\n readonly settingSourcesIncludeProject: boolean;\n readonly options: AgentOptions;\n readonly context?: FileContextManager;\n readonly skillsManager: SkillsManager | undefined;\n readonly pluginsManager: PluginsManager | undefined;\n}\n\n/**\n * Re-read every file-discovered source and return the freshly resolved subagents (the one\n * piece of reload state that lives on the agent, so the caller assigns it).\n *\n * @internal\n */\nexport async function reloadLocalAgent(\n agent: LocalAgentReloadTarget,\n): Promise<Record<string, AgentDefinition>> {\n if (agent.context !== undefined) await agent.context.refresh();\n if (agent.skillsManager !== undefined) await agent.skillsManager.refresh();\n if (agent.pluginsManager !== undefined) await agent.pluginsManager.refresh();\n return await loadSubagents(\n agent.workspaceCwd,\n agent.settingSourcesIncludeProject,\n agent.options.agents,\n );\n}\n","import { join } from \"node:path\";\nimport { diag } from \"../../diagnostics.js\";\nimport { atomicWriteJson } from \"../../persistence/atomic-write.js\";\nimport { memoryDir } from \"./markdown-store.js\";\n\n/**\n * Optional on-disk persistence for Active Memory recall transcripts (ADR D6).\n *\n * Writes one JSON file per run under\n * `.theokit/memory/transcripts/active-memory/<runId>.json` when the agent\n * passes `persistTranscripts: true`. Failures are swallowed with a stderr\n * warning so transcript IO never crashes the agent run.\n *\n * @internal\n */\n\nexport interface ActiveMemoryTranscript {\n runId: string;\n startedAtMs: number;\n userText: string;\n queryMode: string;\n status: string;\n durationMs: number;\n summary: string | undefined;\n hits: ReadonlyArray<{\n path: string;\n startLine: number;\n endLine: number;\n score: number;\n snippet: string;\n }>;\n}\n\nexport async function persistActiveMemoryTranscript(\n cwd: string,\n transcript: ActiveMemoryTranscript,\n): Promise<void> {\n try {\n const dir = join(memoryDir(cwd), \"transcripts\", \"active-memory\");\n const file = join(dir, `${transcript.runId}.json`);\n // atomicWriteJson auto-creates the parent directory + writes atomically\n // (no torn writes during crash).\n await atomicWriteJson(file, transcript);\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : String(cause);\n diag(`[theokit-sdk] active-memory transcript persist failed: ${message}\\n`);\n }\n}\n","import { diag } from \"../diagnostics.js\";\nimport type { CircuitBreaker } from \"../resilience/circuit-breaker.js\";\nimport { HISTOGRAM_NAMES, SPAN_NAMES } from \"../telemetry/span-names.js\";\nimport { NOOP_SPAN, type OTelSpan, type TelemetryHandle } from \"../telemetry/tracer.js\";\nimport type { ActiveMemoryCache, TenantContext } from \"./active-memory-cache.js\";\n// T4.1 / D438 — `ActiveMemoryResult` and its helpers moved to `./active-memory-types.ts`\n// so `./active-memory-cache.ts` can reach them without cycling back here (cycle #10).\n// Re-exported below for back-compat with in-tree consumers.\nimport type {\n ActiveMemoryQueryMode,\n ActiveMemoryResult,\n ActiveMemoryStatus,\n} from \"./active-memory-types.js\";\nimport type { MemorySearchHit } from \"./index-manager.js\";\nimport type { MemoryIndex } from \"./memory-index.js\";\nimport { persistActiveMemoryTranscript } from \"./storage/transcript-store.js\";\n\nexport type { ActiveMemoryQueryMode, ActiveMemoryResult, ActiveMemoryStatus };\n\n/**\n * Active Memory blocking recall (ADR D6 of memory-system-peer-project-parity).\n *\n * Runs BEFORE `agent.send()` assembles the system prompt. Issues a direct\n * call to `IndexManager.search` with the user message (and optional recent\n * turns per `queryMode`).\n *\n * Returns a `summary` string capped at `maxSummaryChars` (default 220 to\n * match peer-project's `DEFAULT_MAX_SUMMARY_CHARS`) which the system-prompt\n * pipeline prepends as a `<active-memory>` block (priority 5).\n *\n * @internal\n */\n\n// T4.1 / D438 — `ActiveMemoryQueryMode`, `ActiveMemoryStatus`, and\n// `ActiveMemoryResult` now live in `./active-memory-types.ts` and are\n// re-exported at the top of this module for back-compat.\n\nexport interface ActiveMemoryOptions {\n /** Whether active recall is enabled. Default `false`. */\n enabled?: boolean;\n /** Query construction strategy. Default `\"recent\"`. */\n queryMode?: ActiveMemoryQueryMode;\n /** Hard timeout in ms. Default `15000`. */\n timeoutMs?: number;\n /** Max chars in the summary. Default `220`. */\n maxSummaryChars?: number;\n /** Number of recent user turns to include in `queryMode === \"recent\"`. Default `2`. */\n recentUserTurns?: number;\n}\n\nexport interface RunActiveMemoryArgs {\n userText: string;\n priorMessages: ReadonlyArray<{ role: \"user\" | \"assistant\"; text: string }>;\n index: MemoryIndex | undefined;\n options: ActiveMemoryOptions;\n /** Per-agent circuit breaker (Phase 8). */\n breaker?: CircuitBreaker;\n /** Per-agent result cache (Phase 8). */\n cache?: ActiveMemoryCache;\n /** Workspace root for transcript persistence. */\n cwd?: string;\n /** When true, write transcript JSON under .theokit/memory/transcripts/active-memory/. */\n persistTranscripts?: boolean;\n /** Stable key the breaker + cache key by (default `default`). */\n agentKey?: string;\n /** Run id for transcript file naming. */\n runId?: string;\n /**\n * T0.1 — optional telemetry handle. When provided AND telemetry is enabled,\n * `memory.recall` span is emitted with `{ userId, namespace, scope, queryMode,\n * hits, status }` attrs and `theokit_memory_recall_duration_ms` histogram is\n * recorded with the same dimension keys. T4.9 will pin `userId/namespace/scope`\n * to the cache-key invariant (cross-tenant leak fix).\n */\n telemetry?: TelemetryHandle;\n /** User id surfaced as a memory.recall span attr for cross-tenant tracing. */\n userId?: string;\n /** Memory namespace (e.g. `default`, `<orgId>`) for span/histogram dimensions. */\n namespace?: string;\n /** Memory scope (`session` / `user` / `global`) for span/histogram dimensions. */\n scope?: string;\n /**\n * T4.7 — AbortSignal propagation. When the caller's signal aborts,\n * the active-memory recall exits early with `status: \"skipped\"` and\n * summary `undefined`. Prevents long-running embedding calls from\n * blocking agent.dispose() or user-initiated cancellation.\n */\n signal?: AbortSignal;\n}\n\nconst DEFAULTS: Required<Omit<ActiveMemoryOptions, \"enabled\">> = {\n queryMode: \"recent\",\n timeoutMs: 15000,\n maxSummaryChars: 220,\n recentUserTurns: 2,\n};\n\nexport async function runActiveMemory(args: RunActiveMemoryArgs): Promise<ActiveMemoryResult> {\n const started = Date.now();\n // T0.1 — `memory.recall` span emitted around the entire body so skipped /\n // cached / no-recall paths still surface in telemetry with the correct status.\n // userId/namespace/scope come from `args` (LocalAgentMemory threads them).\n const span = startMemoryRecallSpan(args);\n try {\n // T4.7 — early exit on abort before any I/O (embedding / search).\n if (args.signal?.aborted === true) {\n return endRecallSpan(span, args, {\n summary: undefined,\n durationMs: 0,\n status: \"skipped\",\n hits: [],\n });\n }\n if (args.options.enabled !== true || args.index === undefined) {\n return endRecallSpan(span, args, {\n summary: undefined,\n durationMs: 0,\n status: \"skipped\",\n hits: [],\n });\n }\n const cfg = { ...DEFAULTS, ...args.options };\n const breakerKey = args.agentKey ?? \"default\";\n if (args.breaker?.shouldSkip(breakerKey) === true) {\n return endRecallSpan(span, args, {\n summary: undefined,\n durationMs: 0,\n status: \"skipped\",\n hits: [],\n });\n }\n // T4.9 wiring (#56) — pass the tenant tuple so two callers with the same\n // query text but different identity never share a cache entry. The cache\n // key infra already supports this; only the wiring was missing.\n const tenantCtx: TenantContext = {\n namespace: args.namespace,\n userId: args.userId,\n scope: args.scope,\n };\n const cached = args.cache?.get(args.userText, cfg.queryMode, tenantCtx);\n if (cached !== undefined) return endRecallSpan(span, args, cached);\n\n const query = buildQuery(args.userText, args.priorMessages, cfg.queryMode, cfg.recentUserTurns);\n if (query.trim().length === 0) {\n const finalized = await finalize(args, cfg.queryMode, {\n summary: undefined,\n durationMs: Date.now() - started,\n status: \"no-recall\",\n hits: [],\n });\n return endRecallSpan(span, args, finalized);\n }\n const result = await searchOnce(args, cfg, query, started);\n notifyBreaker(args.breaker, breakerKey, result.status);\n const finalized = await finalize(args, cfg.queryMode, result);\n return endRecallSpan(span, args, finalized);\n } catch (cause) {\n span.recordException(cause);\n span.setStatus({ code: 2, message: cause instanceof Error ? cause.message : String(cause) });\n span.end();\n throw cause;\n }\n}\n\n/** Extract optional identity attributes from recall args (shared by span + histogram). */\nfunction recallIdentityAttrs(args: RunActiveMemoryArgs): Record<string, string> {\n const attrs: Record<string, string> = {};\n if (args.userId !== undefined) attrs.userId = args.userId;\n if (args.namespace !== undefined) attrs.namespace = args.namespace;\n if (args.scope !== undefined) attrs.scope = args.scope;\n return attrs;\n}\n\nfunction startMemoryRecallSpan(args: RunActiveMemoryArgs): OTelSpan {\n const telemetry: TelemetryHandle | undefined = args.telemetry;\n if (telemetry === undefined) {\n return NOOP_SPAN;\n }\n return telemetry.startSpan(SPAN_NAMES.MEMORY_RECALL, {\n queryMode: args.options.queryMode ?? \"recent\",\n ...recallIdentityAttrs(args),\n });\n}\n\nfunction endRecallSpan(\n span: OTelSpan,\n args: RunActiveMemoryArgs,\n result: ActiveMemoryResult,\n): ActiveMemoryResult {\n span.setAttributes({\n hits: result.hits.length,\n status: result.status,\n durationMs: result.durationMs,\n });\n span.end();\n args.telemetry?.recordHistogram(HISTOGRAM_NAMES.MEMORY_RECALL_DURATION_MS, result.durationMs, {\n status: result.status,\n ...recallIdentityAttrs(args),\n });\n return result;\n}\n\ninterface ResolvedConfig {\n queryMode: ActiveMemoryQueryMode;\n timeoutMs: number;\n maxSummaryChars: number;\n recentUserTurns: number;\n}\n\nasync function searchOnce(\n args: RunActiveMemoryArgs,\n cfg: ResolvedConfig,\n query: string,\n started: number,\n): Promise<ActiveMemoryResult> {\n if (args.index === undefined) {\n return { summary: undefined, durationMs: 0, status: \"skipped\", hits: [] };\n }\n try {\n const hits = await withTimeout(args.index.search(query, { maxResults: 5 }), cfg.timeoutMs);\n if (hits === \"timeout\") {\n return { summary: undefined, durationMs: Date.now() - started, status: \"timeout\", hits: [] };\n }\n if (hits.length === 0) {\n return {\n summary: undefined,\n durationMs: Date.now() - started,\n status: \"no-recall\",\n hits: [],\n };\n }\n const summary = formatSummary(hits, cfg.maxSummaryChars);\n return { summary, durationMs: Date.now() - started, status: \"ok\", hits };\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : String(cause);\n diag(`[theokit-sdk] active-memory recall failed: ${message}\\n`);\n return { summary: undefined, durationMs: Date.now() - started, status: \"error\", hits: [] };\n }\n}\n\nfunction notifyBreaker(\n breaker: CircuitBreaker | undefined,\n key: string,\n status: ActiveMemoryStatus,\n): void {\n if (breaker === undefined) return;\n if (status === \"timeout\") breaker.recordTimeout(key);\n else if (status === \"ok\" || status === \"no-recall\") breaker.recordSuccess(key);\n}\n\nasync function finalize(\n args: RunActiveMemoryArgs,\n queryMode: ActiveMemoryQueryMode,\n result: ActiveMemoryResult,\n): Promise<ActiveMemoryResult> {\n // #56 — key the cache entry by tenant identity (see get-side wiring above).\n const tenantCtx: TenantContext = {\n namespace: args.namespace,\n userId: args.userId,\n scope: args.scope,\n };\n args.cache?.set(args.userText, queryMode, result, tenantCtx);\n if (args.persistTranscripts === true && args.cwd !== undefined) {\n await persistActiveMemoryTranscript(args.cwd, {\n runId: args.runId ?? `run-${Date.now()}`,\n startedAtMs: Date.now() - result.durationMs,\n userText: args.userText,\n queryMode,\n status: result.status,\n durationMs: result.durationMs,\n summary: result.summary,\n hits: result.hits.map((h) => ({\n path: h.path,\n startLine: h.startLine,\n endLine: h.endLine,\n score: h.score,\n snippet: h.snippet,\n })),\n });\n }\n return result;\n}\n\nfunction buildQuery(\n userText: string,\n priorMessages: ReadonlyArray<{ role: \"user\" | \"assistant\"; text: string }>,\n queryMode: ActiveMemoryQueryMode,\n recentUserTurns: number,\n): string {\n if (queryMode === \"message\") return userText;\n if (queryMode === \"full\") {\n const allUserTurns = priorMessages.filter((m) => m.role === \"user\").map((m) => m.text);\n return [...allUserTurns, userText].join(\"\\n\");\n }\n // recent\n const recent = priorMessages\n .filter((m) => m.role === \"user\")\n .slice(-recentUserTurns)\n .map((m) => m.text);\n return [...recent, userText].join(\"\\n\");\n}\n\nfunction formatSummary(hits: ReadonlyArray<MemorySearchHit>, maxChars: number): string {\n const lines = hits.map((h) => `- ${h.citation}: ${h.snippet}`);\n let summary = lines.join(\"\\n\");\n if (summary.length > maxChars) summary = `${summary.slice(0, maxChars - 1)}…`;\n return summary;\n}\n\nasync function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T | \"timeout\"> {\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<\"timeout\">((resolve) => {\n timer = setTimeout(() => resolve(\"timeout\"), timeoutMs);\n });\n try {\n const winner = await Promise.race([promise, timeout]);\n return winner;\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n}\n","import { createHash } from \"node:crypto\";\n\n// T4.1 / D438 — import from leaf to break the active-memory cluster cycle (#10).\nimport type { ActiveMemoryResult } from \"./active-memory-types.js\";\n\n/**\n * TTL-bounded cache for `runActiveMemory` results. Keyed by\n * `sha256(userText + queryMode)` so two identical sends within `cacheTtlMs`\n * (default 15s, matching peer-project's `DEFAULT_CACHE_TTL_MS`) share a single\n * search.\n *\n * Bounded size; oldest entries evicted first when capacity is exceeded.\n *\n * @internal\n */\n\nexport interface ActiveMemoryCacheOptions {\n ttlMs?: number;\n capacity?: number;\n now?: () => number;\n}\n\ninterface CacheEntry {\n expiresAtMs: number;\n result: ActiveMemoryResult;\n}\n\nconst DEFAULT_TTL_MS = 15_000;\nconst DEFAULT_CAPACITY = 1000;\n\nexport class ActiveMemoryCache {\n private readonly map = new Map<string, CacheEntry>();\n\n constructor(private readonly opts: ActiveMemoryCacheOptions = {}) {}\n\n get(\n userText: string,\n queryMode: string,\n tenantCtx?: TenantContext,\n ): ActiveMemoryResult | undefined {\n const key = cacheKey(userText, queryMode, tenantCtx);\n const entry = this.map.get(key);\n if (entry === undefined) return undefined;\n if (this.now() >= entry.expiresAtMs) {\n this.map.delete(key);\n return undefined;\n }\n // LRU bump\n this.map.delete(key);\n this.map.set(key, entry);\n return entry.result;\n }\n\n set(\n userText: string,\n queryMode: string,\n result: ActiveMemoryResult,\n tenantCtx?: TenantContext,\n ): void {\n const key = cacheKey(userText, queryMode, tenantCtx);\n if (this.map.size >= (this.opts.capacity ?? DEFAULT_CAPACITY)) {\n const oldest = this.map.keys().next().value;\n if (oldest !== undefined) this.map.delete(oldest);\n }\n this.map.set(key, {\n expiresAtMs: this.now() + (this.opts.ttlMs ?? DEFAULT_TTL_MS),\n result,\n });\n }\n\n size(): number {\n return this.map.size;\n }\n\n private now(): number {\n return this.opts.now?.() ?? Date.now();\n }\n}\n\n/**\n * T4.9 — Tenant isolation context for cache key derivation.\n * Pre-T4.9 the key was `sha256(queryMode + userText)` — two users\n * sharing a process with the same query got each other's results.\n * CRITICAL cross-tenant data leak (DR4 finding #9).\n *\n * @internal\n */\nexport interface TenantContext {\n namespace?: string;\n userId?: string;\n scope?: string;\n}\n\n// T4.9 — cache key now includes namespace, userId, scope separated by\n// NUL bytes to prevent collision between `user: \"ab\"` + `scope: \"cd\"`\n// and `user: \"a\"` + `scope: \"bcd\"` (without separator these hash identically).\nfunction cacheKey(userText: string, queryMode: string, ctx?: TenantContext): string {\n const parts = [queryMode, ctx?.namespace ?? \"\", ctx?.userId ?? \"\", ctx?.scope ?? \"\", userText];\n return createHash(\"sha256\").update(parts.join(\"\\x00\")).digest(\"hex\");\n}\n","import type { MemoryEmbeddingProviderAdapter } from \"../embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n/**\n * T4.10 — Azure OpenAI embedding adapter. Uses the OpenAI-compatible\n * factory with the Azure-specific base URL pattern and API key env.\n *\n * Azure OpenAI uses a different URL shape than OpenAI:\n * `https://{resource}.openai.azure.com/openai/deployments/{deployment}/embeddings?api-version=2024-02-01`\n *\n * The adapter accepts the base URL as `AZURE_OPENAI_ENDPOINT` env var\n * (the resource URL without the `/openai/...` suffix) and appends the\n * embeddings path at request time.\n *\n * @internal\n */\n\nexport const DEFAULT_AZURE_OPENAI_EMBEDDING_MODEL = \"text-embedding-3-small\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"text-embedding-3-small\": 1536,\n \"text-embedding-3-large\": 3072,\n \"text-embedding-ada-002\": 1536,\n};\n\nexport const azureOpenAiMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"azure-openai\",\n defaultModel: DEFAULT_AZURE_OPENAI_EMBEDDING_MODEL,\n transport: \"remote\",\n authProviderId: \"azure-openai\",\n autoSelectPriority: 25,\n create: (options) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"azure-openai\",\n defaultBaseUrl: \"https://your-resource.openai.azure.com\",\n apiKeyEnv: \"AZURE_OPENAI_API_KEY\",\n baseUrlEnv: \"AZURE_OPENAI_ENDPOINT\",\n defaultModel: DEFAULT_AZURE_OPENAI_EMBEDDING_MODEL,\n embeddingsPath: \"/openai/deployments/{model}/embeddings?api-version=2024-02-01\",\n dimensionByModel: DIMENSION_BY_MODEL,\n // theokit#159 — Azure is NOT OpenAI on the wire, despite the name. It authenticates an API\n // key with the `api-key` header (`Authorization: Bearer` is for Entra ID tokens, not for\n // AZURE_OPENAI_API_KEY), and the deployment already rides in the path, so `model` has no\n // place in the body. Sending the OpenAI shape meant every request was rejected.\n dialect: {\n authHeaders: (apiKey) => ({ \"api-key\": apiKey }),\n body: (_model, inputs) => ({ input: inputs }),\n },\n },\n options,\n ),\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"../embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n/**\n * T4.10 — Cohere embedding adapter. Cohere's v2 embed API is\n * OpenAI-compatible at `/v2/embed` with the same request/response shape.\n *\n * @internal\n */\n\nexport const DEFAULT_COHERE_EMBEDDING_MODEL = \"embed-english-v3.0\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"embed-english-v3.0\": 1024,\n \"embed-multilingual-v3.0\": 1024,\n \"embed-english-light-v3.0\": 384,\n \"embed-multilingual-light-v3.0\": 384,\n};\n\nexport const cohereMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"cohere\",\n defaultModel: DEFAULT_COHERE_EMBEDDING_MODEL,\n transport: \"remote\",\n authProviderId: \"cohere\",\n autoSelectPriority: 30,\n create: (options) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"cohere\",\n defaultBaseUrl: \"https://api.cohere.com\",\n apiKeyEnv: \"COHERE_API_KEY\",\n defaultModel: DEFAULT_COHERE_EMBEDDING_MODEL,\n embeddingsPath: \"/v2/embed\",\n dimensionByModel: DIMENSION_BY_MODEL,\n // theokit#159 — `/v2/embed` diverges in BOTH directions: it names the payload `texts`, requires\n // `input_type`, and answers `{embeddings:{float:[[...]]}}` rather than `{data:[{embedding}]}`.\n // `search_document` is the right default here because this runtime embeds material for\n // storage; a query-side embedder would use `search_query`.\n dialect: {\n body: (model, inputs) => ({\n model,\n texts: [...inputs],\n input_type: \"search_document\",\n embedding_types: [\"float\"],\n }),\n vectors: (json) => (json as { embeddings?: { float?: number[][] } }).embeddings?.float,\n },\n },\n options,\n ),\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"../embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n/**\n * DeepInfra embedding adapter — hosts open-source embedding models\n * (BGE, E5, Jina, etc.) at pay-per-token. OpenAI-compatible REST at\n * `POST /v1/openai/embeddings` (note the `/openai` segment; not the\n * canonical `/v1/embeddings`). The `embeddingsPath` override on\n * `OpenAiCompatibleConfig` REPLACES the default suffix (EC-2).\n *\n * Honors `DEEPINFRA_API_KEY` and `DEEPINFRA_API_BASE_URL`.\n *\n * @internal\n */\n\nexport const DEFAULT_DEEPINFRA_EMBEDDING_MODEL = \"BAAI/bge-large-en-v1.5\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"BAAI/bge-large-en-v1.5\": 1024,\n \"BAAI/bge-base-en-v1.5\": 768,\n \"BAAI/bge-small-en-v1.5\": 384,\n \"BAAI/bge-m3\": 1024,\n \"intfloat/e5-large-v2\": 1024,\n \"intfloat/e5-base-v2\": 768,\n \"intfloat/multilingual-e5-large\": 1024,\n \"sentence-transformers/all-MiniLM-L6-v2\": 384,\n \"thenlper/gte-large\": 1024,\n \"thenlper/gte-base\": 768,\n};\n\nexport const deepinfraMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"deepinfra\",\n defaultModel: DEFAULT_DEEPINFRA_EMBEDDING_MODEL,\n transport: \"remote\",\n authProviderId: \"deepinfra\",\n autoSelectPriority: 13,\n create: (options) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"deepinfra\",\n defaultBaseUrl: \"https://api.deepinfra.com\",\n apiKeyEnv: \"DEEPINFRA_API_KEY\",\n baseUrlEnv: \"DEEPINFRA_API_BASE_URL\",\n defaultModel: DEFAULT_DEEPINFRA_EMBEDDING_MODEL,\n dimensionByModel: DIMENSION_BY_MODEL,\n embeddingsPath: \"/v1/openai/embeddings\",\n },\n options,\n ),\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"../embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n/**\n * T4.10 — Google Gemini embedding adapter. Uses the Gemini API's\n * OpenAI-compatible endpoint at `https://generativelanguage.googleapis.com`.\n *\n * Note: Gemini's native embedding endpoint uses a different shape\n * (`POST /v1beta/models/{model}:embedContent`), but the OpenAI-compat\n * surface (`/v1/embeddings`) is available for embedding models.\n *\n * @internal\n */\n\nexport const DEFAULT_GEMINI_EMBEDDING_MODEL = \"text-embedding-004\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"text-embedding-004\": 768,\n \"embedding-001\": 768,\n};\n\nexport const geminiMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"gemini\",\n defaultModel: DEFAULT_GEMINI_EMBEDDING_MODEL,\n transport: \"remote\",\n authProviderId: \"gemini\",\n autoSelectPriority: 30,\n create: (options) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"gemini\",\n defaultBaseUrl: \"https://generativelanguage.googleapis.com\",\n apiKeyEnv: \"GEMINI_API_KEY\",\n defaultModel: DEFAULT_GEMINI_EMBEDDING_MODEL,\n // theokit#159 — the compat surface is under `/v1beta/openai/`, not the default\n // `/v1/embeddings`; the previous path 404'd on every call.\n embeddingsPath: \"/v1beta/openai/embeddings\",\n dimensionByModel: DIMENSION_BY_MODEL,\n },\n options,\n ),\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"../embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n/**\n * T4.10 — Jina AI embedding adapter. Jina's embedding API is\n * OpenAI-compatible at `https://api.jina.ai/v1/embeddings`.\n *\n * @internal\n */\n\nexport const DEFAULT_JINA_EMBEDDING_MODEL = \"jina-embeddings-v3\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"jina-embeddings-v3\": 1024,\n \"jina-embeddings-v2-base-en\": 768,\n \"jina-embeddings-v2-small-en\": 512,\n};\n\nexport const jinaMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"jina\",\n defaultModel: DEFAULT_JINA_EMBEDDING_MODEL,\n transport: \"remote\",\n authProviderId: \"jina\",\n autoSelectPriority: 35,\n create: (options) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"jina\",\n defaultBaseUrl: \"https://api.jina.ai\",\n apiKeyEnv: \"JINA_API_KEY\",\n defaultModel: DEFAULT_JINA_EMBEDDING_MODEL,\n dimensionByModel: DIMENSION_BY_MODEL,\n },\n options,\n ),\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"../embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n/**\n * Mistral embedding adapter — OpenAI-compatible REST surface\n * (`POST /v1/embeddings` against `https://api.mistral.ai`). Default model\n * `mistral-embed` (1024 dims).\n *\n * Mirrors `reference/peer-project/extensions/mistral/memory-embedding-adapter.ts`.\n *\n * @internal\n */\n\nexport const DEFAULT_MISTRAL_EMBEDDING_MODEL = \"mistral-embed\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"mistral-embed\": 1024,\n};\n\nexport const mistralMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"mistral\",\n defaultModel: DEFAULT_MISTRAL_EMBEDDING_MODEL,\n transport: \"remote\",\n authProviderId: \"mistral\",\n autoSelectPriority: 18,\n create: (options) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"mistral\",\n defaultBaseUrl: \"https://api.mistral.ai\",\n apiKeyEnv: \"MISTRAL_API_KEY\",\n baseUrlEnv: \"MISTRAL_API_BASE_URL\",\n defaultModel: DEFAULT_MISTRAL_EMBEDDING_MODEL,\n dimensionByModel: DIMENSION_BY_MODEL,\n },\n options,\n ),\n};\n","/**\n * Ollama embedding adapter (T3.1, ADR D183).\n *\n * Targets Ollama's OpenAI-compatible `/v1/embeddings` endpoint and reuses\n * the shared `createOpenAiCompatibleRuntime` factory. The differentiating\n * bits:\n *\n * - `authType: \"none\"` — Ollama local ignores `Authorization`. Sentinel\n * `\"ollama-local\"` is passed as apiKey to satisfy the factory contract\n * (mirrors peer-project `OLLAMA_DEFAULT_API_KEY = \"ollama-local\"`).\n * - `OLLAMA_HOST` overrides the default `http://localhost:11434`.\n * - `OLLAMA_API_KEY` (optional) overrides the sentinel for Ollama Cloud\n * or reverse-proxy auth setups.\n * - Default model: `nomic-embed-text` (768 dim, ~274MB). User can opt\n * into `all-minilm` (384 dim, ~45MB) or any other locally-installed\n * embedding model.\n *\n * EC-B MUST FIX (edge-case review 2026-05-21): empty text is rejected\n * upstream in the shared factory (`classifyEntry` short-circuits to a\n * zero vector). That behavior is acceptable here because the zero\n * vector is identical for any empty input — downstream similarity\n * calcs ignore zero-norm vectors via the existing `cosineSimilarity`\n * guard. No additional fail-fast needed.\n *\n * EC-A MUST FIX (edge-case review 2026-05-21): dimension is locked\n * by the `DIMENSION_BY_MODEL` table; an unknown model id throws\n * `ConfigurationError(code: \"embedding_unknown_model\")` per the\n * factory's EC-4 contract. Future model versions with different\n * dimensions are added to the table here without breaking changes.\n *\n * @internal\n */\n\nimport type { MemoryEmbeddingProviderAdapter } from \"../embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\nexport const DEFAULT_OLLAMA_EMBEDDING_MODEL = \"nomic-embed-text\";\n\n/** Sentinel forwarded as Bearer token; Ollama local ignores Authorization. */\nconst OLLAMA_LOCAL_SENTINEL_KEY = \"ollama-local\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n // Nomic — local default, recommended quality/size balance.\n \"nomic-embed-text\": 768,\n \"nomic-embed-text:latest\": 768,\n // Sentence-transformers MiniLM — smaller, faster, lower quality.\n \"all-minilm\": 384,\n \"all-minilm:latest\": 384,\n // BGE family.\n \"bge-large\": 1024,\n \"bge-large:latest\": 1024,\n \"bge-m3\": 1024,\n \"bge-m3:latest\": 1024,\n // mxbai-embed-large.\n \"mxbai-embed-large\": 1024,\n \"mxbai-embed-large:latest\": 1024,\n};\n\nexport const ollamaMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"ollama\",\n defaultModel: DEFAULT_OLLAMA_EMBEDDING_MODEL,\n transport: \"local\",\n authProviderId: \"ollama\",\n // Lower than remote providers — chosen only when explicitly requested\n // OR when no remote provider key is configured (local-first developer).\n autoSelectPriority: 10,\n create: (options) => {\n // Honor OLLAMA_API_KEY (Ollama Cloud / reverse-proxy auth), else use\n // sentinel that local Ollama silently ignores. This mirrors\n // `sentinelForNoAuth` in router.ts and peer-project's `resolveSyntheticAuth`.\n const apiKey = options.apiKey ?? process.env.OLLAMA_API_KEY ?? OLLAMA_LOCAL_SENTINEL_KEY;\n return createOpenAiCompatibleRuntime(\n {\n id: \"ollama\",\n defaultBaseUrl: \"http://localhost:11434\",\n apiKeyEnv: \"OLLAMA_API_KEY\",\n baseUrlEnv: \"OLLAMA_HOST\",\n defaultModel: DEFAULT_OLLAMA_EMBEDDING_MODEL,\n dimensionByModel: DIMENSION_BY_MODEL,\n },\n { ...options, apiKey },\n );\n },\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"../embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n/**\n * OpenAI embedding adapter (ADR D3) — built on the shared OpenAI-compatible\n * factory. Native fetch only.\n *\n * @internal\n */\n\nexport const DEFAULT_OPENAI_EMBEDDING_MODEL = \"text-embedding-3-small\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"text-embedding-3-small\": 1536,\n \"text-embedding-3-large\": 3072,\n \"text-embedding-ada-002\": 1536,\n};\n\nexport const openAiMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"openai\",\n defaultModel: DEFAULT_OPENAI_EMBEDDING_MODEL,\n transport: \"remote\",\n authProviderId: \"openai\",\n autoSelectPriority: 20,\n create: (options) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"openai\",\n defaultBaseUrl: \"https://api.openai.com\",\n apiKeyEnv: \"OPENAI_API_KEY\",\n baseUrlEnv: \"OPENAI_API_BASE_URL\",\n defaultModel: DEFAULT_OPENAI_EMBEDDING_MODEL,\n dimensionByModel: DIMENSION_BY_MODEL,\n },\n options,\n ),\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"../embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n/**\n * OpenRouter embedding adapter — routes through OpenRouter's\n * `POST /api/v1/embeddings` endpoint (OpenAI-compatible request/response\n * shape). The provider id strings follow OpenRouter's catalog\n * (e.g. `\"openai/text-embedding-3-small\"`, `\"mistralai/mistral-embed\"`).\n *\n * Honors `OPENROUTER_API_KEY` and `OPENROUTER_API_BASE_URL`. Default base\n * URL is `https://openrouter.ai/api`.\n *\n * @internal\n */\n\nexport const DEFAULT_OPENROUTER_EMBEDDING_MODEL = \"openai/text-embedding-3-small\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"openai/text-embedding-3-small\": 1536,\n \"openai/text-embedding-3-large\": 3072,\n \"openai/text-embedding-ada-002\": 1536,\n \"mistralai/mistral-embed\": 1024,\n};\n\nexport const openRouterMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"openrouter\",\n defaultModel: DEFAULT_OPENROUTER_EMBEDDING_MODEL,\n transport: \"remote\",\n authProviderId: \"openrouter\",\n autoSelectPriority: 15,\n create: (options) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"openrouter\",\n defaultBaseUrl: \"https://openrouter.ai/api\",\n apiKeyEnv: \"OPENROUTER_API_KEY\",\n baseUrlEnv: \"OPENROUTER_API_BASE_URL\",\n defaultModel: DEFAULT_OPENROUTER_EMBEDDING_MODEL,\n dimensionByModel: DIMENSION_BY_MODEL,\n },\n options,\n ),\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"../embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n/**\n * Voyage AI embedding adapter — `POST /v1/embeddings` at\n * `https://api.voyageai.com` with the OpenAI-compatible `{ model, input }`\n * request shape. Free tier (200M tokens/month) covers most SDK use.\n *\n * Honors `VOYAGE_API_KEY` and `VOYAGE_API_BASE_URL`.\n *\n * @internal\n */\n\nexport const DEFAULT_VOYAGE_EMBEDDING_MODEL = \"voyage-3-lite\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"voyage-3-lite\": 512,\n \"voyage-3\": 1024,\n \"voyage-3-large\": 1024,\n \"voyage-code-3\": 1024,\n \"voyage-multilingual-2\": 1024,\n};\n\nexport const voyageMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"voyage\",\n defaultModel: DEFAULT_VOYAGE_EMBEDDING_MODEL,\n transport: \"remote\",\n authProviderId: \"voyage\",\n autoSelectPriority: 14,\n create: (options) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"voyage\",\n defaultBaseUrl: \"https://api.voyageai.com\",\n apiKeyEnv: \"VOYAGE_API_KEY\",\n baseUrlEnv: \"VOYAGE_API_BASE_URL\",\n defaultModel: DEFAULT_VOYAGE_EMBEDDING_MODEL,\n dimensionByModel: DIMENSION_BY_MODEL,\n },\n options,\n ),\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"../embedding-adapter.js\";\nimport { azureOpenAiMemoryEmbeddingProviderAdapter } from \"./azure-openai-embedding.js\";\nimport { cohereMemoryEmbeddingProviderAdapter } from \"./cohere-embedding.js\";\nimport { deepinfraMemoryEmbeddingProviderAdapter } from \"./deepinfra-embedding.js\";\nimport { geminiMemoryEmbeddingProviderAdapter } from \"./gemini-embedding.js\";\nimport { jinaMemoryEmbeddingProviderAdapter } from \"./jina-embedding.js\";\nimport { mistralMemoryEmbeddingProviderAdapter } from \"./mistral-embedding.js\";\nimport { ollamaMemoryEmbeddingProviderAdapter } from \"./ollama-embedding.js\";\nimport { openAiMemoryEmbeddingProviderAdapter } from \"./openai-embedding.js\";\nimport { openRouterMemoryEmbeddingProviderAdapter } from \"./openrouter-embedding.js\";\nimport { voyageMemoryEmbeddingProviderAdapter } from \"./voyage-embedding.js\";\n\n/**\n * Memory embedding adapter catalog, indexed by provider id.\n *\n * Only adapters with full, tested implementations are exposed. The\n * `openrouter` provider proxies through OpenRouter to whichever embedding\n * model the caller selects via `model` (e.g.\n * `\"openai/text-embedding-3-small\"`, `\"mistralai/mistral-embed\"`).\n *\n * Locked by ADR D11: `openai`, `mistral`, `openrouter`, `voyage`, `deepinfra`\n * ship in v1.0. ADR D183: `ollama` added — first `transport: \"local\"`\n * adapter, enables 100%-local RAG (no remote API key needed).\n * `lmstudio`, `google`, `bedrock` are deferred to v1.1.\n *\n * @internal\n */\nexport const MEMORY_EMBEDDING_ADAPTERS: Readonly<Record<string, MemoryEmbeddingProviderAdapter>> = {\n openai: openAiMemoryEmbeddingProviderAdapter,\n mistral: mistralMemoryEmbeddingProviderAdapter,\n openrouter: openRouterMemoryEmbeddingProviderAdapter,\n voyage: voyageMemoryEmbeddingProviderAdapter,\n deepinfra: deepinfraMemoryEmbeddingProviderAdapter,\n ollama: ollamaMemoryEmbeddingProviderAdapter,\n // T4.10 — 4 new adapters expanding embedding provider coverage.\n \"azure-openai\": azureOpenAiMemoryEmbeddingProviderAdapter,\n cohere: cohereMemoryEmbeddingProviderAdapter,\n jina: jinaMemoryEmbeddingProviderAdapter,\n gemini: geminiMemoryEmbeddingProviderAdapter,\n};\n","import { readFile } from \"node:fs/promises\";\nimport { resolve as resolvePath } from \"node:path\";\n\nimport type { MemoryReadResult } from \"../types.js\";\n\n/**\n * Bounded read with truncation info (ADR D5 — `memory_get` foundation).\n *\n * Mirrors peer-project's `buildMemoryReadResult` semantics:\n * - `from` is 1-indexed.\n * - `lines` defaults to 200 (`DEFAULT_MEMORY_READ_LINES`).\n * - Returns up to EOF when the requested slice extends past file end.\n * - Sets `truncated: true` when fewer lines were returned than requested AND\n * there's still content past the slice. (At EOF, `truncated: false`.)\n *\n * @internal\n */\n\nexport const DEFAULT_MEMORY_READ_LINES = 200;\n\nexport interface ReadFileOptions {\n cwd: string;\n relPath: string;\n from?: number;\n lines?: number;\n}\n\nexport async function readMemoryFileBounded(opts: ReadFileOptions): Promise<MemoryReadResult> {\n const absolutePath = resolvePath(opts.cwd, opts.relPath);\n const raw = await readFile(absolutePath, \"utf8\");\n const allLines = raw.split(\"\\n\");\n // Strip a trailing empty line caused by a final \\n so totalLines reflects\n // the editor-visible line count, not the byte-level split.\n const trimmedLines =\n allLines.length > 0 && allLines[allLines.length - 1] === \"\" ? allLines.slice(0, -1) : allLines;\n const totalLines = trimmedLines.length;\n\n const requestedFrom = Math.max(1, opts.from ?? 1);\n const requestedLines = Math.max(1, opts.lines ?? DEFAULT_MEMORY_READ_LINES);\n const startIdx = requestedFrom - 1;\n const endIdx = Math.min(totalLines, startIdx + requestedLines);\n const slice = trimmedLines.slice(startIdx, endIdx);\n const linesReturned = slice.length;\n const remainingLines = Math.max(0, totalLines - endIdx);\n // truncated = \"more content exists past the returned slice\"\n const truncated = remainingLines > 0;\n\n return {\n path: opts.relPath,\n from: requestedFrom,\n linesReturned,\n totalLines,\n truncated,\n remainingLines,\n text: slice.join(\"\\n\"),\n };\n}\n","import { resolve as resolvePath } from \"node:path\";\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport type { MemorySearchHit } from \"./index-manager.js\";\nimport type { MemoryIndex } from \"./memory-index.js\";\nimport { memoryDir } from \"./storage/markdown-store.js\";\nimport { readMemoryFileBounded } from \"./storage/reader.js\";\n\n/**\n * Memory tools (`memory_search` + `memory_get`) — ADR D5 of\n * memory-system-peer-project-parity. Tool schemas mirror peer-project\n * (`reference/peer-project/extensions/memory-core/src/tools.ts:228-475`).\n *\n * Each tool is exposed as a `MemoryTool` (name + description + JSON schema +\n * async execute). The agent-loop integration wires them via the existing\n * `ResolvedTool` interface in `tool-dispatch.ts`.\n *\n * @internal\n */\n\nexport interface MemoryToolJson {\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n}\n\nexport interface MemoryTool extends MemoryToolJson {\n execute(input: Record<string, unknown>): Promise<string>;\n}\n\nconst SEARCH_DESCRIPTION =\n \"Mandatory recall step: semantically search MEMORY.md + memory/notes/*.md (and optional wiki supplements) before answering questions about prior work, decisions, dates, people, preferences, or todos. `corpus=memory` (default) restricts to indexed memory files; `corpus=wiki` restricts to read-only wiki supplements; `corpus=all` returns both. Returns ranked `{ path, startLine, endLine, score, snippet, citation }` hits.\";\n\nconst GET_DESCRIPTION =\n \"Safe exact excerpt read from MEMORY.md or memory/notes/*.md. Defaults to a bounded excerpt (200 lines). Returns `{ path, from, linesReturned, totalLines, truncated, remainingLines, text }`. Paths are resolved against the memory root — attempts to read outside `.theokit/memory/` are rejected.\";\n\nconst MEMORY_SEARCH_SCHEMA: Record<string, unknown> = {\n type: \"object\",\n required: [\"query\"],\n properties: {\n query: { type: \"string\", description: \"Natural-language query.\" },\n maxResults: { type: \"integer\", minimum: 1, maximum: 50 },\n minScore: { type: \"number\", minimum: 0, maximum: 1 },\n corpus: { type: \"string\", enum: [\"memory\", \"sessions\", \"wiki\", \"all\"] },\n },\n additionalProperties: false,\n};\n\nconst MEMORY_GET_SCHEMA: Record<string, unknown> = {\n type: \"object\",\n required: [\"path\"],\n properties: {\n path: { type: \"string\", description: \"Path relative to .theokit/memory/\" },\n from: { type: \"integer\", minimum: 1 },\n lines: { type: \"integer\", minimum: 1, maximum: 2000 },\n },\n additionalProperties: false,\n};\n\nconst DEFAULT_MAX_TOTAL_CHARS = 16384;\n\nexport interface MemorySearchToolOptions {\n index: MemoryIndex;\n /** Cap on the JSON response size (EC-10 of edge-case review). Default 16384. */\n maxTotalChars?: number;\n}\n\nexport function createMemorySearchTool(opts: MemorySearchToolOptions): MemoryTool {\n const cap = opts.maxTotalChars ?? DEFAULT_MAX_TOTAL_CHARS;\n return {\n name: \"memory_search\",\n description: SEARCH_DESCRIPTION,\n inputSchema: MEMORY_SEARCH_SCHEMA,\n async execute(input: Record<string, unknown>): Promise<string> {\n const query = readString(input.query, \"query is required\");\n const maxResults = readNumber(input.maxResults) ?? 10;\n const minScore = readNumber(input.minScore);\n const corpus = readString(input.corpus, undefined, true);\n const sources = mapCorpusToSources(corpus);\n const searchOptions = {\n maxResults,\n ...(minScore !== undefined ? { minScore } : {}),\n ...(sources !== undefined ? { sources } : {}),\n };\n const hits = await opts.index.search(query, searchOptions);\n return JSON.stringify(capByTotalChars(hits, cap));\n },\n };\n}\n\nexport interface MemoryGetToolOptions {\n cwd: string;\n}\n\nexport function createMemoryGetTool(opts: MemoryGetToolOptions): MemoryTool {\n const memoryRoot = resolvePath(memoryDir(opts.cwd));\n return {\n name: \"memory_get\",\n description: GET_DESCRIPTION,\n inputSchema: MEMORY_GET_SCHEMA,\n async execute(input: Record<string, unknown>): Promise<string> {\n const relPath = readString(input.path, \"path is required\");\n const from = readNumber(input.from);\n const lines = readNumber(input.lines);\n // EC-2: enforce that the resolved path stays inside the memory root.\n const resolved = resolvePath(memoryRoot, relPath);\n if (!isPathInside(memoryRoot, resolved)) {\n throw new ConfigurationError(\n `memory_get rejected path that escapes memory root: ${relPath}`,\n { code: \"memory_path_escapes_root\" },\n );\n }\n const readArgs: { cwd: string; relPath: string; from?: number; lines?: number } = {\n cwd: memoryRoot,\n relPath,\n };\n if (from !== undefined) readArgs.from = from;\n if (lines !== undefined) readArgs.lines = lines;\n const result = await readMemoryFileBounded(readArgs);\n return JSON.stringify(result);\n },\n };\n}\n\n// ───── helpers ──────────────────────────────────────────────────────────\n\nfunction readString(value: unknown, errorIfMissing?: string, allowUndefined = false): string {\n if (typeof value === \"string\") return value;\n if (allowUndefined && (value === undefined || value === null)) return \"\";\n if (errorIfMissing !== undefined) {\n throw new ConfigurationError(errorIfMissing, { code: \"memory_tool_bad_args\" });\n }\n return \"\";\n}\n\nfunction readNumber(value: unknown): number | undefined {\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n if (typeof value === \"string\" && value.trim().length > 0) {\n const n = Number(value);\n if (Number.isFinite(n)) return n;\n }\n return undefined;\n}\n\nfunction mapCorpusToSources(\n corpus: string,\n): ReadonlyArray<\"memory\" | \"sessions\" | \"wiki\"> | undefined {\n if (corpus === \"\" || corpus === \"all\") return undefined;\n if (corpus === \"memory\") return [\"memory\"];\n if (corpus === \"wiki\") return [\"wiki\"];\n if (corpus === \"sessions\") return [\"sessions\"];\n return undefined;\n}\n\nfunction capByTotalChars(\n hits: ReadonlyArray<MemorySearchHit>,\n maxTotalChars: number,\n): { hits: MemorySearchHit[]; truncated: boolean } {\n if (hits.length === 0) return { hits: [], truncated: false };\n const kept: MemorySearchHit[] = [];\n let runningChars = 0;\n for (const hit of hits) {\n const snippetLen = hit.snippet.length + (hit.citation?.length ?? 0) + 32; // overhead estimate\n if (kept.length > 0 && runningChars + snippetLen > maxTotalChars) {\n return { hits: kept, truncated: true };\n }\n kept.push(hit);\n runningChars += snippetLen;\n }\n return { hits: kept, truncated: false };\n}\n\nfunction isPathInside(root: string, candidate: string): boolean {\n const normalizedRoot = root.endsWith(\"/\") ? root : `${root}/`;\n return candidate === root || candidate.startsWith(normalizedRoot);\n}\n","import type { AgentOptions } from \"../../types/agent.js\";\nimport type { MemoryToolSpec } from \"../agent-loop/loop-types.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { runActiveMemory } from \"../memory/active-memory.js\";\nimport { ActiveMemoryCache } from \"../memory/active-memory-cache.js\";\nimport { MEMORY_EMBEDDING_ADAPTERS } from \"../memory/adapters/catalog.js\";\nimport type { EmbeddingRuntime } from \"../memory/embedding-adapter.js\";\nimport { IndexManager } from \"../memory/index-manager.js\";\nimport type { MemoryIndex } from \"../memory/memory-index.js\";\nimport { createMemoryGetTool, createMemorySearchTool } from \"../memory/tools.js\";\nimport { CircuitBreaker } from \"../resilience/circuit-breaker.js\";\nimport type { TelemetryHandle } from \"../telemetry/tracer.js\";\n\n/**\n * Per-agent memory glue. Owns the lazy `IndexManager`, the memory tools\n * cache, and the Active Memory circuit breaker + summary cache. Pulled out\n * of `LocalAgent` to keep that file under the G8 LoC cap.\n *\n * @internal\n */\nexport class LocalAgentMemory {\n private index: MemoryIndex | undefined;\n private toolsCache: ReadonlyArray<MemoryToolSpec> | undefined;\n private breaker: CircuitBreaker | undefined;\n private cache: ActiveMemoryCache | undefined;\n\n constructor(\n private readonly options: AgentOptions,\n private readonly workspaceCwd: string,\n private readonly agentId: string,\n ) {}\n\n /**\n * Sync view of the tool cache (SDK 2.0 Phase 1 Stage 2b — iter 19+).\n * Returns the cached MemoryToolSpec[] when `ensureTools()` has run\n * AND succeeded; undefined otherwise. Lets the\n * `createLocalAgentMemoryProvider` adapter (`buildTools` is sync per\n * the port contract) surface the same tools the legacy path would.\n *\n * Caller MUST have already awaited `ensureTools()` once\n * (adapter does this in `init()`) — otherwise the cache is empty\n * and this returns undefined (matching the \"no tools today\" semantics).\n */\n getCachedTools(): ReadonlyArray<MemoryToolSpec> | undefined {\n return this.toolsCache;\n }\n\n async ensureTools(): Promise<ReadonlyArray<MemoryToolSpec> | undefined> {\n const cfg = this.options.memory?.index;\n if (cfg?.tools === false) return undefined;\n if (this.options.memory?.enabled !== true) return undefined;\n if (this.toolsCache !== undefined) return this.toolsCache;\n try {\n const embedding = await this.maybeCreateEmbeddingRuntime();\n const openOpts: {\n cwd: string;\n embedding?: EmbeddingRuntime;\n backend?: \"sqlite-vec\" | \"lance\";\n } = { cwd: this.workspaceCwd };\n if (embedding !== undefined) openOpts.embedding = embedding;\n if (cfg?.backend !== undefined) openOpts.backend = cfg.backend;\n this.index = await IndexManager.open(openOpts);\n await this.index.sync();\n this.toolsCache = [\n createMemorySearchTool({ index: this.index }),\n createMemoryGetTool({ cwd: this.workspaceCwd }),\n ];\n return this.toolsCache;\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : String(cause);\n // Flicker-bug fix — `LocalAgentMemory` is rebuilt per Agent.create (the TUI creates one PER\n // TURN), so an unconditional WARN repeated every turn; raw stderr mid-frame also corrupts\n // Ink-style renderers. Warn ONCE per process per distinct message (globalThis — M44 B1\n // pattern, shared across bundle copies).\n const g = globalThis as unknown as Record<symbol, Set<string>>;\n const sym = Symbol.for(\"theokit-sdk.memory.warned\");\n g[sym] ??= new Set<string>();\n const warned = g[sym];\n if (!warned.has(message)) {\n warned.add(message);\n diag(`[theokit-sdk] memory tools unavailable: ${message}\\n`);\n }\n return undefined;\n }\n }\n\n async runActiveMemoryIfEnabled(\n userText: string,\n priorMessages: ReadonlyArray<{ role: \"user\" | \"assistant\"; text: string }>,\n telemetry?: TelemetryHandle,\n ): Promise<string | undefined> {\n const cfg = this.options.memory?.activeRecall;\n if (cfg?.enabled !== true || this.index === undefined) return undefined;\n if (this.breaker === undefined) this.breaker = new CircuitBreaker();\n if (this.cache === undefined) this.cache = new ActiveMemoryCache();\n const result = await runActiveMemory({\n userText,\n priorMessages,\n index: this.index,\n options: this.buildActiveMemoryOptions(cfg),\n breaker: this.breaker,\n cache: this.cache,\n agentKey: this.agentId,\n cwd: this.workspaceCwd,\n ...(cfg.persistTranscripts === true ? { persistTranscripts: true } : {}),\n runId: `${this.agentId}-${Date.now()}`,\n ...this.buildTelemetryRecallArgs(telemetry),\n });\n return result.summary;\n }\n\n private buildActiveMemoryOptions(cfg: NonNullable<AgentOptions[\"memory\"]>[\"activeRecall\"]) {\n if (cfg === undefined) return { enabled: true };\n return {\n enabled: true,\n ...(cfg.queryMode !== undefined ? { queryMode: cfg.queryMode } : {}),\n ...(cfg.timeoutMs !== undefined ? { timeoutMs: cfg.timeoutMs } : {}),\n ...(cfg.maxSummaryChars !== undefined ? { maxSummaryChars: cfg.maxSummaryChars } : {}),\n };\n }\n\n private buildTelemetryRecallArgs(telemetry?: TelemetryHandle) {\n const userId =\n typeof this.options.memoryContext?.userId === \"string\"\n ? this.options.memoryContext.userId\n : undefined;\n // #56 (GAP-A) — the cache is keyed by {namespace,userId,scope}. `namespace`\n // is the documented tenant/org partition (`e.g. default, <orgId>`), so the\n // caller MUST thread `memoryContext.tenantId` into it — otherwise two tenants\n // sharing a userId collide on one active-recall cache entry (cross-tenant leak).\n // sessionId is intentionally NOT a key dimension: recall is cross-session by design.\n const tenantId =\n typeof this.options.memoryContext?.tenantId === \"string\"\n ? this.options.memoryContext.tenantId\n : undefined;\n return {\n ...(telemetry !== undefined ? { telemetry } : {}),\n ...(userId !== undefined ? { userId } : {}),\n namespace: tenantId ?? \"default\",\n scope: \"session\",\n };\n }\n\n /**\n * Trigger a background `IndexManager.sync()` so a freshly written session\n * summary (ADR D20) is recallable via `memory_search({ corpus: \"sessions\" })`\n * on the next call. Fire-and-forget at the call site; failures degrade to\n * \"summary indexed on next regular sync\" with a stderr warning.\n *\n * @internal\n */\n async syncIfReady(): Promise<void> {\n if (this.index === undefined) return;\n try {\n await this.index.sync();\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : String(cause);\n diag(`[theokit-sdk] session index sync failed: ${message}\\n`);\n }\n }\n\n private async maybeCreateEmbeddingRuntime(): Promise<EmbeddingRuntime | undefined> {\n const cfg = this.options.memory?.index?.embedding;\n if (cfg === undefined) return undefined;\n const adapter = MEMORY_EMBEDDING_ADAPTERS[cfg.provider];\n if (adapter === undefined) return undefined;\n try {\n return await adapter.create(cfg.model !== undefined ? { model: cfg.model } : {});\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : String(cause);\n diag(`[theokit-sdk] memory embedding ${cfg.provider} unavailable: ${message}\\n`);\n return undefined;\n }\n }\n}\n","/**\n * `agent.memory` direct API implementation (T2.2, ADR D141 / D142).\n *\n * Builds an `AgentMemory` impl over whichever third-party adapters\n * the `PluginManager` aggregated. Lazy-resolves the adapter list on\n * first access (EC-I: `initialize()` fires exactly once on first\n * write/recall). Multi-adapter fan-out for writes; merge + dedupe by\n * content for recalls.\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport type {\n AgentMemory,\n MemoryAdapter,\n MemoryContext,\n MemoryFact,\n MemoryId,\n MemoryTurnMessage,\n} from \"../../types/memory-adapter.js\";\nimport type { PluginManager } from \"../plugins/manager.js\";\n\ninterface ResolvedAdapters {\n adapters: ReadonlyArray<MemoryAdapter>;\n initialized: boolean;\n}\n\n/**\n * Build a lazy `AgentMemory` accessor over the plugin-aggregated\n * memory adapters. Returns `null` when no `kind: \"memory\"` plugin\n * is registered — callers branch on `adapter() === null`.\n *\n * @internal\n */\nexport function buildAgentMemory(\n pluginManager: PluginManager,\n workspaceCwd: string,\n defaultContext: MemoryContext | undefined,\n): AgentMemory {\n let resolved: ResolvedAdapters | undefined;\n\n async function ensure(): Promise<ResolvedAdapters> {\n if (resolved !== undefined) return resolved;\n const entries = pluginManager.aggregated.memoryProviders;\n const created: MemoryAdapter[] = [];\n for (const entry of entries) {\n const instance = await entry.createProvider(workspaceCwd);\n created.push(instance);\n }\n // EC-I: initialize() each adapter exactly once on first access.\n for (const adapter of created) {\n if (adapter.initialize !== undefined) {\n await adapter.initialize();\n }\n }\n resolved = { adapters: created, initialized: true };\n return resolved;\n }\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: 6 optional fields × per-field caller-wins-over-default merge is a flat ladder; extracting helpers fragments the EC-P invariant.\n function mergeContext(partial: Partial<MemoryContext> | undefined): MemoryContext {\n // EC-P: caller's ctx.userId always wins over agent default.\n const merged: MemoryContext = {\n userId: partial?.userId ?? defaultContext?.userId ?? \"\",\n ...(partial?.agentId !== undefined\n ? { agentId: partial.agentId }\n : defaultContext?.agentId !== undefined\n ? { agentId: defaultContext.agentId }\n : {}),\n ...(partial?.sessionId !== undefined\n ? { sessionId: partial.sessionId }\n : defaultContext?.sessionId !== undefined\n ? { sessionId: defaultContext.sessionId }\n : {}),\n ...(partial?.tenantId !== undefined\n ? { tenantId: partial.tenantId }\n : defaultContext?.tenantId !== undefined\n ? { tenantId: defaultContext.tenantId }\n : {}),\n ...(partial?.tags !== undefined\n ? { tags: partial.tags }\n : defaultContext?.tags !== undefined\n ? { tags: defaultContext.tags }\n : {}),\n ...(partial?.metadata !== undefined\n ? { metadata: partial.metadata }\n : defaultContext?.metadata !== undefined\n ? { metadata: defaultContext.metadata }\n : {}),\n };\n if (merged.userId === \"\") {\n throw new ConfigurationError(\n \"agent.memory requires a userId — either set AgentOptions.memoryContext.userId or pass ctx.userId at call time.\",\n { code: \"memory_context_missing_user_id\" },\n );\n }\n return merged;\n }\n\n async function requireAdapters(): Promise<ReadonlyArray<MemoryAdapter>> {\n const r = await ensure();\n if (r.adapters.length === 0) {\n throw new ConfigurationError(\n \"No memory adapter registered. Pass a memory plugin in AgentOptions.plugins (e.g. supermemoryMemory({...})).\",\n { code: \"no_memory_adapter\" },\n );\n }\n return r.adapters;\n }\n\n return {\n async write(\n content: string | MemoryTurnMessage[],\n ctx?: Partial<MemoryContext>,\n ): Promise<MemoryId> {\n const adapters = await requireAdapters();\n const merged = mergeContext(ctx);\n // Fan-out: write to all. Return the first id; collect errors per adapter.\n const writes = await Promise.allSettled(adapters.map((a) => a.write(content, merged)));\n const firstFulfilled = writes.find((r) => r.status === \"fulfilled\");\n if (firstFulfilled === undefined) {\n // All adapters failed — surface the first error.\n const firstReason = writes[0] as PromiseRejectedResult;\n throw firstReason.reason;\n }\n return (firstFulfilled as PromiseFulfilledResult<MemoryId>).value;\n },\n\n // biome-ignore lint/complexity/noExcessiveCognitiveComplexity: settled-promise iteration + content dedupe + graceful degrade are 3 inline concerns; helpers would obscure the merge invariant.\n async recall(query: string, ctx?: Partial<MemoryContext>, k?: number): Promise<MemoryFact[]> {\n const adapters = await requireAdapters();\n const merged = mergeContext(ctx);\n // Merge + dedupe by content. Per-adapter failures degrade gracefully:\n // the caller still gets results from healthy adapters.\n const recalls = await Promise.allSettled(adapters.map((a) => a.recall(query, merged, k)));\n const out: MemoryFact[] = [];\n const seen = new Set<string>();\n for (const r of recalls) {\n if (r.status !== \"fulfilled\") continue;\n for (const fact of r.value) {\n if (seen.has(fact.content)) continue;\n seen.add(fact.content);\n out.push(fact);\n }\n }\n return out;\n },\n\n async delete(id: MemoryId): Promise<void> {\n const adapters = await requireAdapters();\n // Route by id prefix: the adapter whose id matches the MemoryId prefix.\n const prefix = id.split(\":\", 1)[0] ?? \"\";\n const target = adapters.find((a) => a.id === prefix);\n if (target === undefined) {\n throw new ConfigurationError(\n `No adapter found for MemoryId prefix \"${prefix}\" (registered: ${adapters.map((a) => a.id).join(\", \")}).`,\n { code: \"no_memory_adapter\" },\n );\n }\n await target.delete(id);\n },\n\n adapter(): MemoryAdapter | null {\n // Synchronous — only useful AFTER `ensure()` resolved at least once.\n // Callers that want adapter introspection should `await agent.memory.write/recall`\n // first to trigger initialization.\n if (resolved === undefined) return null;\n return resolved.adapters[0] ?? null;\n },\n };\n}\n","/**\n * `createLocalAgentMemoryProvider` — bridges the legacy LocalAgentMemory\n * rich impl (sdk-core's internal/memory/* subsystem) to the\n * MemoryProvider port (SDK 2.0 Phase 1 physical Stage 2a — iter 19+).\n *\n * Goal: ONE memory path inside the kernel. Today there are TWO:\n * 1. Legacy via `LocalAgentMemory` (when consumer didn't pass memoryProvider)\n * 2. Port via `MemoryProvider` (when consumer passed memoryProvider in T1.3)\n *\n * This adapter wraps path 1 as a MemoryProvider, so the kernel can use\n * the port uniformly. Stage 2b will refactor LocalAgent.send() to use\n * the port + this adapter as default. Stage 3 will move the internal/\n * memory/* sources to sdk-memory + ship a richer LanceDB-backed\n * provider replacing this adapter.\n *\n * Why a separate file (not modifying LocalAgentMemory):\n * - Preserves LocalAgentMemory's existing public API for callers that\n * haven't migrated to the port yet.\n * - Adapter pattern: the rich logic stays where it is; the adapter\n * translates between LocalAgentMemory's signature and the port's.\n * - Allows incremental migration: kernel call sites move one at a\n * time from `memoryGlue.X()` direct calls to `provider.X(handle)`\n * calls.\n *\n * @internal — sdk-core's bridging glue. Replaced by sdk-memory rich impl\n * in Stage 3.\n */\n\nimport type { AgentOptions, CustomTool, SDKAgent } from \"../../types/agent.js\";\nimport { writeSessionSummary } from \"../memory/storage/session-summary-writer.js\";\nimport type {\n ActiveMemoryPassArgs,\n ActiveMemoryPassResult,\n MemoryProvider,\n MemoryProviderHandle,\n MemoryProviderInitOptions,\n RecordSessionSummaryArgs,\n} from \"../runtime/memory/memory-provider.js\";\nimport type { TelemetryHandle } from \"../telemetry/tracer.js\";\nimport { LocalAgentMemory } from \"./local-agent-memory.js\";\n\nconst INTERNAL_LAM_KEY = Symbol(\"sdk-core.local-agent-memory-provider.glue\");\n\ninterface AdapterState {\n glue: LocalAgentMemory;\n telemetry?: TelemetryHandle;\n}\n\n/**\n * Options for `createLocalAgentMemoryProvider`. Mirrors what\n * `LocalAgentMemory`'s constructor needs.\n */\nexport interface LocalAgentMemoryProviderOptions {\n /** AgentOptions slice — required for memory subsystem config (cfg.memory). */\n readonly agentOptions: AgentOptions;\n /** Workspace cwd — used for `.theokit/memory/` paths. */\n readonly workspaceCwd: string;\n /** Agent id — required for per-agent cache + telemetry. */\n readonly agentId: string;\n /** Telemetry handle (optional) — forwarded to active-memory recall. */\n readonly telemetry?: TelemetryHandle;\n}\n\n/**\n * Build a `MemoryProvider` whose lifecycle methods delegate to an\n * underlying `LocalAgentMemory` instance.\n *\n * Mapping:\n * - `init()` → constructs LocalAgentMemory + warms tool cache via ensureTools()\n * - `buildTools()` → wraps ensureTools() result, renaming `execute` to `handler`\n * - `runActivePass()` → calls runActiveMemoryIfEnabled() with synthesized args;\n * returns the summary as `systemPromptAdditions`\n * - `sync()` → calls syncIfReady()\n * - `dispose()` → no-op (LocalAgentMemory's caches are per-agent + GC'd\n * when the agent is GC'd)\n */\nexport function createLocalAgentMemoryProvider(\n opts: LocalAgentMemoryProviderOptions,\n): MemoryProvider {\n return {\n async init(_opts: MemoryProviderInitOptions): Promise<MemoryProviderHandle> {\n const glue = new LocalAgentMemory(opts.agentOptions, opts.workspaceCwd, opts.agentId);\n // Warm the tools cache so subsequent buildTools() is sync-friendly.\n // ensureTools() returns undefined when memory is disabled — that's fine.\n await glue.ensureTools();\n const state: AdapterState = {\n glue,\n ...(opts.telemetry !== undefined ? { telemetry: opts.telemetry } : {}),\n };\n return {\n // The adapter doesn't ship a real MemoryAdapter today — kernel\n // callers reach memory via the glue methods, not the adapter.\n // Future iters can hydrate this from the IndexManager if a\n // direct read/write surface is needed.\n adapter: {\n id: \"local-agent-memory\",\n capabilities: {\n history: false,\n sessions: true,\n tenancy: false,\n reasoning: false,\n toolSchemas: true,\n prefetch: false,\n },\n isAvailable: () => true,\n write: async () => \"local-agent-memory:noop\" as never,\n recall: async () => [],\n delete: async () => undefined,\n },\n [INTERNAL_LAM_KEY]: state,\n };\n },\n buildTools(handle: MemoryProviderHandle, _agent: SDKAgent): ReadonlyArray<CustomTool> {\n const state = handle[INTERNAL_LAM_KEY] as AdapterState | undefined;\n if (state === undefined) return [];\n // Read from the sync `getCachedTools()` view (Stage 2b — iter 19+\n // — `LocalAgentMemory` added this sync accessor so the adapter\n // can surface the same memory_search + memory_get tools the\n // legacy path would). init() already awaited ensureTools() to\n // warm the cache; this is the readout.\n const cached = state.glue.getCachedTools();\n if (cached === undefined || cached.length === 0) return [];\n // Translate MemoryToolSpec (`execute`) → CustomTool (`handler`).\n // Shape compatible (name + description + inputSchema match);\n // only the handler-function key renames.\n return cached.map((memTool) => ({\n name: memTool.name,\n description: memTool.description,\n inputSchema: memTool.inputSchema,\n handler: memTool.execute,\n }));\n },\n async runActivePass(\n handle: MemoryProviderHandle,\n args: ActiveMemoryPassArgs,\n ): Promise<ActiveMemoryPassResult> {\n const state = handle[INTERNAL_LAM_KEY] as AdapterState | undefined;\n if (state === undefined) return { facts: [] };\n const priorMessages = args.history.map((m) => ({ role: m.role, text: m.content }));\n const summary = await state.glue.runActiveMemoryIfEnabled(\n args.userMessage,\n priorMessages,\n state.telemetry,\n );\n if (summary === undefined || summary.length === 0) return { facts: [] };\n return { facts: [], systemPromptAdditions: summary };\n },\n async recordSessionSummary(args: RecordSessionSummaryArgs): Promise<void> {\n // Stateless: delegate to the legacy `writeSessionSummary` directly.\n // Args are passthrough — same shape as the legacy `SessionSummaryInput`.\n await writeSessionSummary(args);\n },\n async sync(handle: MemoryProviderHandle): Promise<void> {\n const state = handle[INTERNAL_LAM_KEY] as AdapterState | undefined;\n if (state === undefined) return;\n await state.glue.syncIfReady();\n },\n dispose(_handle: MemoryProviderHandle): void {\n // LocalAgentMemory has no explicit disposal — caches are GC'd\n // when the agent reference drops. The state ref on the handle\n // is the only thing keeping the glue alive after this.\n return;\n },\n };\n}\n","/**\n * Personality preset types + Zod frontmatter schema (T1.1, ADR D161).\n *\n * **EC-C:** name regex is **lowercase-only** (NO `/i` flag) to prevent\n * `Coder` vs `coder` becoming distinct registry keys (Map verbatim).\n * Forcing lowercase eliminates the ambiguity at validation time.\n *\n * @internal\n */\n\nimport { z } from \"zod\";\n\n/**\n * Frontmatter schema for `.theokit/personalities/*.md` files.\n *\n * @internal\n */\nexport const PersonalityFrontmatterSchema = z.object({\n // EC-C: lowercase-only — prevents Coder vs coder ambiguity in registry Map keys.\n name: z\n .string()\n .min(1)\n .regex(/^[a-z0-9_-]+$/, \"Personality name must be a lowercase slug (a-z, 0-9, _, -)\"),\n description: z.string().optional(),\n tools: z.array(z.string()).optional(),\n model: z.string().optional(),\n tags: z.array(z.string()).optional(),\n});\n\nexport type PersonalityFrontmatter = z.infer<typeof PersonalityFrontmatterSchema>;\n\n/**\n * Resolved personality preset — frontmatter + body + source provenance.\n * Defined publicly in `types/agent.ts` so the DTS bundle never crosses\n * `internal/`. Re-exported here for ergonomic internal callers.\n *\n * @public\n */\nexport type { PersonalityPreset } from \"../../types/agent.js\";\n\n/** Reserved slugs that map to \"clear active preset\". @internal */\nexport const RESERVED_CLEAR_SLUGS = [\"none\", \"default\", \"neutral\"] as const;\n","/**\n * PersonalityRegistry — loads `.theokit/personalities/*.md` from project\n * + user dirs (T1.1, ADRs D161 / D162).\n *\n * Project entries win on slug collision (matches `.theokit/` family\n * convention). Reserved slugs (`none`, `default`, `neutral`) cannot be\n * registered — they map to \"clear active preset\".\n *\n * **EC-C:** name regex enforced lowercase-only by the Zod schema in\n * `types.ts`. Filenames are independent of the frontmatter `name`.\n *\n * **EC-M (documented):** body content is NOT sanitized against\n * prompt-injection — users own their preset content.\n *\n * @internal\n */\n\nimport { homedir } from \"node:os\";\nimport { join } from \"node:path\";\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { loadMarkdownEntities } from \"../persistence/markdown-config-loader.js\";\nimport { warnOnce } from \"../runtime/hooks/hooks-source.js\";\nimport {\n type PersonalityFrontmatter,\n PersonalityFrontmatterSchema,\n type PersonalityPreset,\n RESERVED_CLEAR_SLUGS,\n} from \"./types.js\";\n\nconst PROJECT_SUBDIR = \".theokit/personalities\";\nconst USER_SUBDIR = \".theokit/personalities\";\n\n/**\n * Reads project + user personality directories and exposes a\n * collision-resolved registry.\n *\n * @internal\n */\nexport class PersonalityRegistry {\n readonly #byName: Map<string, PersonalityPreset>;\n\n private constructor(presets: ReadonlyArray<PersonalityPreset>) {\n this.#byName = new Map();\n for (const p of presets) this.#byName.set(p.name, p);\n }\n\n /**\n * Load project + user dirs. Project entries override user entries on\n * slug collision (`source: \"project\"` wins).\n *\n * @internal\n */\n static async load(cwd: string): Promise<PersonalityRegistry> {\n const projectDir = join(cwd, PROJECT_SUBDIR);\n const userDir = join(homedir(), USER_SUBDIR);\n\n const [userEntities, projectEntities] = await Promise.all([\n loadMarkdownEntities({\n dir: userDir,\n schema: PersonalityFrontmatterSchema,\n pattern: \"flat\",\n errorCodePrefix: \"personality\",\n }),\n loadMarkdownEntities({\n dir: projectDir,\n schema: PersonalityFrontmatterSchema,\n pattern: \"flat\",\n errorCodePrefix: \"personality\",\n }),\n ]);\n\n const byName = new Map<string, PersonalityPreset>();\n // Load user first so project can override.\n for (const e of userEntities) addEntity(byName, e, \"user\");\n for (const e of projectEntities) addEntity(byName, e, \"project\", byName);\n\n return new PersonalityRegistry(\n [...byName.values()].sort((a, b) => a.name.localeCompare(b.name)),\n );\n }\n\n /** All loaded presets, lex-asc by name. */\n all(): ReadonlyArray<PersonalityPreset> {\n return [...this.#byName.values()];\n }\n\n /** Get by slug. Returns undefined for unknown OR reserved slugs. */\n get(name: string): PersonalityPreset | undefined {\n if (PersonalityRegistry.isReservedClearSlug(name)) return undefined;\n return this.#byName.get(name);\n }\n\n /** Reserved slugs map to \"clear active preset\". */\n static isReservedClearSlug(name: string): boolean {\n return (RESERVED_CLEAR_SLUGS as readonly string[]).includes(name);\n }\n}\n\nfunction addEntity(\n byName: Map<string, PersonalityPreset>,\n entity: { slug: string; frontmatter: PersonalityFrontmatter; body: string; source: string },\n origin: \"project\" | \"user\",\n collisionMap?: Map<string, PersonalityPreset>,\n): void {\n const fm = entity.frontmatter;\n if (PersonalityRegistry.isReservedClearSlug(fm.name)) {\n throw new ConfigurationError(\n `Personality name \"${fm.name}\" is reserved (used to clear active preset)`,\n { code: \"personality_reserved_name\" },\n );\n }\n // EC-1 of T1.1: empty body → reject.\n if (entity.body.trim().length === 0) {\n throw new ConfigurationError(\n `Personality \"${fm.name}\" has empty body (system prompt required)`,\n { code: \"personality_empty_body\" },\n );\n }\n // Project wins on collision; emit warning once per slug.\n if (origin === \"project\" && collisionMap?.has(fm.name)) {\n warnOnce(\n `personality-collision-${fm.name}`,\n `[theokit-sdk] personality \"${fm.name}\" overridden by project preset`,\n );\n }\n byName.set(fm.name, {\n name: fm.name,\n description: fm.description,\n tools: fm.tools,\n model: fm.model,\n tags: fm.tags,\n systemPrompt: entity.body,\n source: origin,\n sourcePath: entity.source,\n });\n}\n","/**\n * performPersonalitySwitch — orchestrates the full lifecycle of a\n * personality activation: store mutation, optional history reset,\n * transcript marker injection, and cache invalidation (T5.1, ADR D164).\n *\n * The marker is emitted as a **user role** message because (a) the\n * switch is a directive from the operator (not a model utterance), and\n * (b) LLMs treat user-role lines as instructions that survive history\n * compaction (EC-D from arXiv:2412.00804).\n *\n * Same-slug switches are no-ops: no marker, no cache invalidation, no\n * store write (EC-18).\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport { PersonalityRegistry } from \"./registry.js\";\nimport type { PersonalityStore } from \"./store.js\";\nimport type { PersonalityPreset } from \"./types.js\";\n\nexport interface PerformPersonalitySwitchArgs {\n agentId: string;\n /** Previous active slug (undefined = no active preset). */\n prevSlug: string | undefined;\n /** Next active slug or reserved clear alias (none / default / neutral). */\n requestedName: string;\n registry: PersonalityRegistry;\n store: PersonalityStore;\n invalidateCache: (reason: string) => Promise<void>;\n appendSessionMessage: (msg: { role: \"user\" | \"assistant\"; text: string }) => void;\n clearSession?: () => void;\n opts: { save?: boolean; reset?: boolean };\n}\n\n/**\n * Run the full personality-switch lifecycle. Returns the new preset\n * (or null when cleared). Throws `ConfigurationError` on unknown name.\n *\n * @internal\n */\nexport async function performPersonalitySwitch(\n args: PerformPersonalitySwitchArgs,\n): Promise<PersonalityPreset | null> {\n const reserved = PersonalityRegistry.isReservedClearSlug(args.requestedName);\n let nextSlug: string | undefined;\n let resolved: PersonalityPreset | null;\n\n if (reserved) {\n nextSlug = undefined;\n resolved = null;\n } else {\n const preset = args.registry.get(args.requestedName);\n if (preset === undefined) {\n const available =\n args.registry\n .all()\n .map((p) => p.name)\n .join(\", \") || \"(none)\";\n throw new ConfigurationError(\n `Personality \"${args.requestedName}\" not found. Available: ${available}`,\n { code: \"personality_not_found\" },\n );\n }\n nextSlug = preset.name;\n resolved = preset;\n }\n\n // EC-18: same slug = no-op.\n if (args.prevSlug === nextSlug) return resolved;\n\n await args.store.setActive(args.agentId, nextSlug, { save: args.opts.save === true });\n\n // EC-19: reset BEFORE marker so marker is first in the new session.\n if (args.opts.reset === true && args.clearSession !== undefined) {\n args.clearSession();\n }\n\n const marker = nextSlug === undefined ? \"[persona cleared]\" : `[persona switched to ${nextSlug}]`;\n args.appendSessionMessage({ role: \"user\", text: marker });\n\n await args.invalidateCache(\"personality-switch\");\n return resolved;\n}\n","/**\n * Personality-preset runtime extensions for {@link LocalAgent}.\n *\n * Extracted from `local-agent.ts` to keep that file under the 400-LoC\n * guard (G8). The functions here implement the personality-related\n * behaviour declared by ADRs D160-D168:\n *\n * - `resolveActivePersonalityPreset` — read the active preset honoring\n * the fork ALS snapshot (D168 / EC-A).\n * - `ensurePersonalityRegistryIfNeeded` — lazy-load registry when ANY\n * slug is active.\n * - `applyPersonalityOverlay` — overlay preset body on the base prompt.\n * - `localAgentUsePersonality` — the full `Agent.usePersonality` flow:\n * fork-scope no-op, registry lazy-load, then delegate to\n * `performPersonalitySwitch` under the per-agent send mutex (EC-E).\n *\n * @internal\n */\n\nimport { withCwdMutex } from \"../persistence/cwd-mutex.js\";\nimport {\n currentPersonalityContext,\n warnPersonalitySwitchInsideFork,\n} from \"../personality/context.js\";\nimport { PersonalityRegistry } from \"../personality/registry.js\";\nimport type { PersonalityStore } from \"../personality/store.js\";\nimport { performPersonalitySwitch } from \"../personality/switch.js\";\nimport type { PersonalityPreset } from \"../personality/types.js\";\nimport { appendSessionMessage, clearSession } from \"../session/index.js\";\n\n/**\n * Read the active personality preset (if any) for this agent — pure read.\n *\n * Inside a fork (ALS scope active), reads the snapshot slug captured at\n * fork-construction time (EC-A). Outside a fork, reads the agent's own\n * `PersonalityStore`.\n *\n * @internal\n */\nexport function resolveActivePersonalityPreset(args: {\n agentId: string;\n personalityStore: PersonalityStore;\n personalityRegistry: PersonalityRegistry | undefined;\n}): PersonalityPreset | undefined {\n const forkCtx = currentPersonalityContext();\n const slug = forkCtx !== undefined ? forkCtx.slug : args.personalityStore.active(args.agentId);\n if (slug === undefined) return undefined;\n return args.personalityRegistry?.get(slug);\n}\n\n/**\n * Lazy-load `PersonalityRegistry` when ANY personality slug is active —\n * either via the agent's own store or via fork inheritance (ALS).\n * Avoids the 10ms cold-start I/O for agents that never use personalities.\n *\n * Returns the registry (loaded or unchanged) so the caller can assign\n * it back to its private field.\n *\n * @internal\n */\nexport async function ensurePersonalityRegistryIfNeeded(args: {\n agentId: string;\n workspaceCwd: string;\n personalityStore: PersonalityStore;\n personalityRegistry: PersonalityRegistry | undefined;\n}): Promise<PersonalityRegistry | undefined> {\n if (args.personalityRegistry !== undefined) return args.personalityRegistry;\n const forkSlug = currentPersonalityContext()?.slug;\n const ownSlug = args.personalityStore.active(args.agentId);\n if (forkSlug === undefined && ownSlug === undefined) return undefined;\n return await PersonalityRegistry.load(args.workspaceCwd);\n}\n\n/**\n * Overlay the active personality preset's `systemPrompt` body on top of\n * the resolved base prompt (ADR D160). Pure read — never mutates store.\n *\n * @internal\n */\nexport function applyPersonalityOverlay(\n preset: PersonalityPreset | undefined,\n base: string | undefined,\n): string | undefined {\n if (preset === undefined) return base;\n if (base === undefined || base.length === 0) return preset.systemPrompt;\n return `${base}\\n\\n${preset.systemPrompt}`;\n}\n\n/**\n * Full `Agent.usePersonality(...)` implementation extracted from\n * `LocalAgent`. Loads the registry lazily, then delegates to\n * `performPersonalitySwitch` under the per-agent send mutex (EC-E).\n *\n * Returns the resolved preset (or null when cleared). Mutates the\n * `registryRef` callback when the registry was lazy-loaded so the agent\n * can cache it.\n *\n * @internal\n */\nexport async function localAgentUsePersonality(args: {\n agentId: string;\n workspaceCwd: string;\n disposed: boolean;\n personalityStore: PersonalityStore;\n personalityRegistry: PersonalityRegistry | undefined;\n invalidateCache: (reason: string) => Promise<void>;\n onRegistryLoaded: (reg: PersonalityRegistry) => void;\n name: string;\n opts?: { save?: boolean; reset?: boolean };\n}): Promise<PersonalityPreset | null> {\n if (args.disposed) throw new Error(\"Agent has been disposed\");\n // ADR D168 / EC-A — inside a fork, usePersonality is a no-op.\n if (currentPersonalityContext() !== undefined) {\n warnPersonalitySwitchInsideFork(args.agentId);\n return null;\n }\n let registry = args.personalityRegistry;\n if (registry === undefined) {\n registry = await PersonalityRegistry.load(args.workspaceCwd);\n args.onRegistryLoaded(registry);\n }\n // EC-E: serialize against in-flight `send` via the per-agent send mutex.\n return withCwdMutex(`agent-send:${args.agentId}`, () =>\n performPersonalitySwitch({\n agentId: args.agentId,\n prevSlug: args.personalityStore.active(args.agentId),\n requestedName: args.name,\n registry: registry as PersonalityRegistry,\n store: args.personalityStore,\n invalidateCache: (reason) => args.invalidateCache(reason),\n appendSessionMessage: (msg) => appendSessionMessage(args.agentId, msg),\n clearSession: () => clearSession(args.agentId),\n opts: args.opts ?? {},\n }),\n );\n}\n","/**\n * Background-work runtime extensions for {@link LocalAgent} (T4.2 + T4.3).\n *\n * Extracted from `local-agent.ts` to keep that file under the 400-LoC\n * guard (G8). The two helpers below implement\n * `LocalAgent.runUntil(goal, options)` and `LocalAgent.fork(options)`\n * by lazy-importing the implementation modules and resolving\n * `Agent.create` through the DI registry (see\n * `agent-factory-registry.ts` for the cycle-avoidance rationale).\n *\n * @internal\n */\n\nimport type { AgentOptions, MemorySettings, SDKAgent } from \"../../types/agent.js\";\nimport type { GoalEvent, GoalOptions, GoalResult } from \"../../types/goal-events.js\";\nimport type { RunToCompletionOptions, RunToCompletionResult } from \"../../types/run.js\";\nimport type { JudgeContext, JudgeOptions } from \"../judge/judge-call.js\";\nimport type { ForkOptions, ForkResult } from \"../runtime/lifecycle/fork-agent.js\";\nimport type { RunUntilDeps } from \"../runtime/lifecycle/run-until.js\";\nimport {\n appendMemoryFact,\n extractMemoryFact,\n isMemoryWritePrompt,\n} from \"../runtime/memory/memory-store.js\";\nimport { safeCall } from \"../runtime/system-prompt/safe-call.js\";\n\n/**\n * Drive {@link runUntilImpl} with the registered `Agent.create` so\n * `LocalAgent.runUntil` returns the canonical\n * `AsyncGenerator<GoalEvent, GoalResult, void>` shape (ADR D116).\n *\n * SE40 (v4.0) — the DURABLE objective path (SE33) was removed: `runUntil` is now\n * exclusively the ephemeral, explicit-goal judge loop. A call with no goal pauses.\n *\n * @internal\n */\nexport function localAgentRunUntil(\n agent: SDKAgent,\n goal: string | undefined,\n options: GoalOptions | undefined,\n): AsyncGenerator<GoalEvent, GoalResult, void> {\n async function* wrap(): AsyncGenerator<GoalEvent, GoalResult, void> {\n const { runUntilImpl } = await import(\"../runtime/lifecycle/run-until.js\");\n const buildDeps = async (): Promise<RunUntilDeps> => {\n const { judgeCallImpl } = await import(\"../judge/judge-call.js\");\n const { getAgentFacade } = await import(\"../runtime/registry/agent-factory-registry.js\");\n const create = getAgentFacade().create;\n return {\n judge: (ctx: JudgeContext, opts?: JudgeOptions) => judgeCallImpl(ctx, opts, { create }),\n };\n };\n\n if (goal === undefined) {\n yield {\n type: \"status_change\",\n status: \"paused\",\n reason: \"runUntil() requires an explicit goal (durable objectives removed in v4.0)\",\n };\n return { status: \"paused\", turnsUsed: 0, tokensUsed: 0, finalResponse: undefined };\n }\n return yield* runUntilImpl(agent, goal, options, await buildDeps());\n }\n return wrap();\n}\n\n/**\n * Drive {@link runToCompletionImpl} bound to this agent's stateful `send`\n * (M1 Phase 3). The agent's session preserves conversation history, so the\n * driver only re-sends a short continuation prompt after each truncated round.\n *\n * @internal\n */\nexport function localAgentRunToCompletion(\n agent: SDKAgent,\n message: string,\n options: RunToCompletionOptions | undefined,\n): Promise<RunToCompletionResult> {\n async function run(): Promise<RunToCompletionResult> {\n const { runToCompletionImpl } = await import(\"../runtime/lifecycle/run-to-completion.js\");\n return runToCompletionImpl({ send: (m, o) => agent.send(m, o) }, message, options);\n }\n return run();\n}\n\n/**\n * Drive the STREAMING continuation twin (V3-4) bound to this agent's stateful\n * `send` — yields each round's `SDKMessage`s live, reusing the M1 terminal policy.\n *\n * @internal\n */\nexport async function* localAgentStreamToCompletion(\n agent: SDKAgent,\n message: string,\n options: RunToCompletionOptions | undefined,\n): AsyncGenerator<\n import(\"../../types/messages.js\").SDKMessage,\n import(\"../../types/run.js\").StreamToCompletionResult\n> {\n const { streamToCompletionImpl } = await import(\"../runtime/lifecycle/stream-to-completion.js\");\n return yield* streamToCompletionImpl({ send: (m, o) => agent.send(m, o) }, message, options);\n}\n\n/**\n * Spawn a forked auxiliary agent (ADR D110). Reads `Agent.create` from\n * the DI registry.\n *\n * @internal\n */\nexport async function localAgentFork(\n parent: { agentId: string; options: AgentOptions; personalitySlugSnapshot: string | undefined },\n options: ForkOptions,\n): Promise<ForkResult> {\n const { forkAgentImpl } = await import(\"../runtime/lifecycle/fork-agent.js\");\n const { getAgentFacade } = await import(\"../runtime/registry/agent-factory-registry.js\");\n const { withPersonalityContext } = await import(\"../personality/context.js\");\n const create = getAgentFacade().create;\n // ADR D168 + EC-A — capture the slug ONCE at fork-construction time.\n // Subsequent parent `usePersonality` calls do NOT mutate this snapshot.\n return withPersonalityContext({ slug: parent.personalitySlugSnapshot, isFork: true }, () =>\n forkAgentImpl(parent, options, { create }),\n );\n}\n\n/**\n * Extract a memory fact from a \"Remember:\" user prompt and persist it\n * via `appendMemoryFact`. No-op when memory is disabled, the prompt is\n * not a write directive, or the extracted fact is empty (EC-3/EC-4).\n *\n * Moved here from `LocalAgent` to keep the class file under G8.\n *\n * @internal\n */\nexport async function persistMemoryFactIfWritePrompt(\n workspaceCwd: string,\n memoryConfig: MemorySettings | undefined,\n userText: string,\n): Promise<void> {\n if (memoryConfig?.enabled !== true) return;\n if (!isMemoryWritePrompt(userText)) return;\n const fact = extractMemoryFact(userText);\n if (fact.length === 0) return;\n await safeCall(\n () => appendMemoryFact(workspaceCwd, memoryConfig, { text: fact }),\n undefined,\n \"memory write\",\n );\n}\n","/**\n * `AbortSignal` composition helpers (Production-Readiness #5 / EC-5, ADR D324).\n *\n * `AbortSignal.any` is available in Node 22+ and Cloudflare Workers, but\n * some runtime environments (a peer vendor Edge subset, older Bun, embedded shells)\n * still lag. The ponyfill mirrors the spec semantics — abort on first signal,\n * propagate `reason` — without depending on the host symbol.\n *\n * @internal\n */\n\n/**\n * Compose multiple `AbortSignal`s into a single signal that fires as soon as\n * any of the inputs aborts. Uses native `AbortSignal.any` when available;\n * otherwise constructs an `AbortController` with `once: true` listeners.\n */\nexport function anySignal(signals: ReadonlyArray<AbortSignal | undefined>): AbortSignal {\n const filtered = signals.filter((s): s is AbortSignal => s !== undefined);\n if (filtered.length === 0) {\n // Never-aborting signal — caller passed nothing.\n return new AbortController().signal;\n }\n if (filtered.length === 1) {\n return filtered[0] as AbortSignal;\n }\n if (typeof AbortSignal.any === \"function\") {\n return AbortSignal.any(filtered as AbortSignal[]);\n }\n return ponyfillAny(filtered);\n}\n\nfunction ponyfillAny(signals: AbortSignal[]): AbortSignal {\n const ctrl = new AbortController();\n for (const s of signals) {\n if (s.aborted) {\n ctrl.abort(s.reason);\n return ctrl.signal;\n }\n s.addEventListener(\"abort\", () => ctrl.abort(s.reason), { once: true });\n }\n return ctrl.signal;\n}\n\n/**\n * `true` when the given (possibly undefined) signal has aborted. `undefined`\n * signal counts as not aborted (no-signal semantics).\n */\nexport function isAborted(signal: AbortSignal | undefined): boolean {\n return signal?.aborted === true;\n}\n\n/**\n * Extract the abort reason as an `Error` for wrapping into `AgentRunError`.\n * Spec: `signal.reason` is `unknown` — wrap non-Error values into a generic\n * error so callers always have a `.message` to inspect.\n */\nexport function abortReasonAsError(signal: AbortSignal): Error {\n if (signal.reason instanceof Error) return signal.reason;\n if (signal.reason !== undefined) return new Error(String(signal.reason));\n return new Error(\"AbortError: signal aborted\");\n}\n","/**\n * SE34 — wrap a {@link Run} so a finished reply is scored by the shipped\n * LLM-as-judge against {@link SendOptions.completionCheck} (`isTaskComplete`).\n * The verdict is attached to `wait()`'s {@link RunResult.completionCheck} and a\n * `completion_check` run-event is emitted. This is the finer-grained, single-\n * `send()` completion gate (contrast `runUntil`, which judges BETWEEN sends).\n *\n * Non-invasive: only wraps when `completionCheck` is set, only judges a\n * `finished` run with text, memoizes so the judge runs EXACTLY ONCE, and a\n * Proxy preserves every other Run member. A fail-safe: a judge parse failure\n * yields `complete: false` (never silently \"done\"). The judge model is injected\n * via `deps.judge` so this module stays free of the Agent façade import.\n *\n * The judge fires from `wait()` (not from `stream()`); a stream-only consumer\n * must call `wait()` to trigger the verdict + the `completion_check` event.\n *\n * @internal\n */\n\nimport type { JudgeResult } from \"../../../types/goal-events.js\";\nimport type { CompletionCheck, Run, RunResult } from \"../../../types/run.js\";\nimport { emitRunEvent, type RunEventSink } from \"../../../types/run-events.js\";\nimport type { JudgeContext, JudgeOptions } from \"../../judge/judge-call.js\";\n\nexport interface CompletionCheckDeps {\n judge: (ctx: JudgeContext, opts?: JudgeOptions) => Promise<JudgeResult>;\n}\n\nexport function wrapRunWithCompletionCheck(args: {\n run: Run;\n completionCheck: CompletionCheck | undefined;\n onRunEvent: RunEventSink | undefined;\n deps: CompletionCheckDeps;\n}): Run {\n const check = args.completionCheck;\n if (check === undefined) return args.run;\n\n const compute = async (): Promise<RunResult> => {\n const result = await args.run.wait();\n // Only a finished run with text is judged; errors/cancels pass through untouched.\n if (result.status !== \"finished\" || result.result === undefined) return result;\n\n const judgeOpts: JudgeOptions = {};\n if (check.judgeModel !== undefined) judgeOpts.judgeModel = check.judgeModel;\n if (check.apiKey !== undefined) judgeOpts.apiKey = check.apiKey;\n const verdict = await args.deps.judge(\n { goal: check.criteria, lastResponse: result.result },\n judgeOpts,\n );\n // Fail-safe: a parse failure is NOT \"complete\". Judge \"done\" ⇒ complete.\n const complete = !verdict.parseFailed && verdict.verdict === \"done\";\n emitRunEvent(args.onRunEvent, {\n type: \"completion_check\",\n complete,\n reason: verdict.reason,\n });\n return {\n ...result,\n completionCheck: { complete, reason: verdict.reason, parseFailed: verdict.parseFailed },\n };\n };\n\n // Memoize — `wait()` is idempotent, so the judge must fire EXACTLY once.\n let judged: Promise<RunResult> | undefined;\n const wrappedWait: Run[\"wait\"] = () => {\n judged ??= compute();\n return judged;\n };\n return new Proxy(args.run, {\n get(target, prop, receiver) {\n if (prop === \"wait\") return wrappedWait;\n return Reflect.get(target, prop, receiver);\n },\n });\n}\n","/**\n * SE24 — the guardrail processor runner. Runs an ordered processor pipeline over\n * a string payload (the user message for input, the model's text for output).\n * Each processor may rewrite the payload (return a string), `abort()` (→ a\n * tripwire that short-circuits the rest), or `warn()` (fire `onViolation`,\n * continue). A processor's own bug (a non-abort throw) propagates (fail-fast).\n *\n * @internal\n */\n\nimport type {\n Processor,\n ProcessorTripwire,\n ProcessorViolation,\n} from \"../../../types/processors.js\";\n\n/** Sentinel thrown by `ctx.abort()`; caught by the runner to build a tripwire. */\nclass ProcessorAbort {\n constructor(\n readonly processorId: string,\n readonly reason: string,\n ) {}\n}\n\n/** Outcome of a processor pipeline: the transformed payload, or a tripwire. @internal */\nexport type ProcessorPipelineResult =\n | { kind: \"ok\"; value: string }\n | { kind: \"tripwire\"; tripwire: ProcessorTripwire };\n\n/** Invoke a processor's `onViolation` safely — a throw here never breaks the pipeline. */\nfunction fireViolation(processor: Processor, violation: ProcessorViolation): void {\n try {\n processor.onViolation?.(violation);\n } catch {\n // Swallowed by contract — a violation-callback bug must not break the run.\n }\n}\n\n/** Build the `abort` / `warn` controls bound to one processor. */\nfunction controlsFor(processor: Processor): {\n abort(reason: string): never;\n warn(message: string, detail?: unknown): void;\n} {\n return {\n abort(reason: string): never {\n throw new ProcessorAbort(processor.id, reason);\n },\n warn(message: string, detail?: unknown): void {\n fireViolation(processor, {\n processorId: processor.id,\n message,\n ...(detail !== undefined ? { detail } : {}),\n });\n },\n };\n}\n\n/** Per-processor step outcome: the (possibly rewritten) value, or a tripwire. */\ntype StepResult = { value: string } | { tripwire: ProcessorTripwire };\n\n/** The phase handler + its discriminator, or `undefined` when the processor has none. */\ntype SelectedHandler =\n | { kind: \"input\"; fn: NonNullable<Processor[\"processInput\"]> }\n | { kind: \"output\"; fn: NonNullable<Processor[\"processOutput\"]> };\n\nfunction selectHandler(\n processor: Processor,\n phase: \"input\" | \"output\",\n): SelectedHandler | undefined {\n if (phase === \"input\") {\n return processor.processInput ? { kind: \"input\", fn: processor.processInput } : undefined;\n }\n return processor.processOutput ? { kind: \"output\", fn: processor.processOutput } : undefined;\n}\n\n/** Call the handler with a ctx of its exact phase type — no intersection/`any` cast. */\nfunction invokeHandler(\n handler: SelectedHandler,\n value: string,\n agentId: string,\n controls: ReturnType<typeof controlsFor>,\n) {\n return handler.kind === \"input\"\n ? handler.fn({ message: value, agentId, ...controls })\n : handler.fn({ text: value, agentId, ...controls });\n}\n\nasync function runOneProcessor(\n processor: Processor,\n value: string,\n agentId: string,\n phase: \"input\" | \"output\",\n): Promise<StepResult> {\n const handler = selectHandler(processor, phase);\n if (handler === undefined) return { value }; // no handler for this phase\n try {\n const out = await invokeHandler(handler, value, agentId, controlsFor(processor));\n // A processor may return void (JS) — preserve the prior value in that case.\n return { value: typeof out === \"string\" ? out : value };\n } catch (err) {\n if (!(err instanceof ProcessorAbort)) throw err; // a genuine bug propagates (Rule 8)\n fireViolation(processor, { processorId: err.processorId, message: err.reason });\n return { tripwire: { reason: err.reason, processorId: err.processorId } };\n }\n}\n\nasync function runPipeline(\n processors: ReadonlyArray<Processor>,\n initial: string,\n agentId: string,\n phase: \"input\" | \"output\",\n): Promise<ProcessorPipelineResult> {\n let value = initial;\n for (const processor of processors) {\n const step = await runOneProcessor(processor, value, agentId, phase);\n if (\"tripwire\" in step) return { kind: \"tripwire\", tripwire: step.tripwire };\n value = step.value;\n }\n return { kind: \"ok\", value };\n}\n\n/** SE24 — run the input processors over the user message. @internal */\nexport function runInputProcessors(\n processors: ReadonlyArray<Processor>,\n message: string,\n agentId: string,\n): Promise<ProcessorPipelineResult> {\n return runPipeline(processors, message, agentId, \"input\");\n}\n\n/** SE24 — run the output processors over the model's final text. @internal */\nexport function runOutputProcessors(\n processors: ReadonlyArray<Processor>,\n text: string,\n agentId: string,\n): Promise<ProcessorPipelineResult> {\n return runPipeline(processors, text, agentId, \"output\");\n}\n","/**\n * SE24 — a terminal {@link Run} born from an input-processor `abort()`. It never\n * reached the model: `wait()` resolves to a `cancelled` {@link RunResult}\n * carrying the tripwire; `stream()` yields no content messages. The `tripwire`\n * run-event is emitted by the caller via `SendOptions.onRunEvent` before this\n * run is returned.\n *\n * @internal\n */\n\nimport type { ModelSelection } from \"../../../types/agent.js\";\nimport type { SDKMessage } from \"../../../types/messages.js\";\nimport type { ProcessorTripwire } from \"../../../types/processors.js\";\nimport type { Run, RunOperation, RunResult, RunTimelineEvent } from \"../../../types/run.js\";\nimport { registerRun } from \"../registry/run-registry.js\";\n\nconst SUPPORTED: ReadonlySet<RunOperation> = new Set<RunOperation>([\n \"stream\",\n \"wait\",\n \"cancel\",\n \"conversation\",\n]);\n\n/**\n * theokit#140 - the timeline counterpart. Empty for the same fact `emptyStream` is empty for: a\n * tripwire run never executed, so it produced no events of any kind.\n */\nfunction emptyTimeline(): AsyncGenerator<RunTimelineEvent, void> {\n return emptyStream() as unknown as AsyncGenerator<RunTimelineEvent, void>;\n}\n\n/** An already-exhausted async iterator — a tripwire run streams no content. */\nfunction emptyStream(): AsyncGenerator<SDKMessage, void> {\n return {\n next: () => Promise.resolve({ done: true, value: undefined }),\n return: () => Promise.resolve({ done: true, value: undefined }),\n throw: (err: unknown) => Promise.reject(err),\n [Symbol.asyncIterator]() {\n return this;\n },\n } as AsyncGenerator<SDKMessage, void>;\n}\n\nexport function createTripwireRun(args: {\n agentId: string;\n tripwire: ProcessorTripwire;\n model: ModelSelection | undefined;\n}): Run {\n const id = globalThis.crypto.randomUUID();\n const result: RunResult = {\n id,\n status: \"cancelled\",\n tripwire: args.tripwire,\n ...(args.model !== undefined ? { model: args.model } : {}),\n };\n const run: Run = {\n id,\n agentId: args.agentId,\n status: \"cancelled\",\n ...(args.model !== undefined ? { model: args.model } : {}),\n stream: () => emptyStream(),\n // theokit#140 - a tripwire run never executed, so its timeline is empty by construction, the\n // same reason `stream()` is. Both are empty for the same fact, not by coincidence.\n events: () => emptyTimeline(),\n wait: () => Promise.resolve(result),\n cancel: () => Promise.resolve(),\n conversation: () => Promise.resolve([]),\n supports: (op: RunOperation) => SUPPORTED.has(op),\n unsupportedReason: (op: RunOperation) =>\n SUPPORTED.has(op) ? undefined : `operation \"${op}\" is not available on a tripwire run`,\n onDidChangeStatus: () => () => {}, // already terminal — status never changes\n };\n registerRun(run);\n return run;\n}\n","/**\n * SE24 — wrap a {@link Run} so its `wait()` result passes through the output\n * processors before reaching the caller. A processor may redact/rewrite the\n * final text or `abort()` → the result becomes `cancelled` with a tripwire (and\n * a `tripwire` run-event is emitted). Streaming output redaction is deferred\n * (v1 processes the buffered `wait()` path only); a Proxy preserves every other\n * Run member (`stream`, `cancel`, `conversation`, …).\n *\n * @internal\n */\n\nimport type { Processor } from \"../../../types/processors.js\";\nimport type { Run, RunResult } from \"../../../types/run.js\";\nimport { emitRunEvent, type RunEventSink } from \"../../../types/run-events.js\";\nimport { runOutputProcessors } from \"./run-processors.js\";\n\nexport function wrapRunWithOutputProcessors(args: {\n run: Run;\n processors: readonly Processor[];\n agentId: string;\n onRunEvent: RunEventSink | undefined;\n}): Run {\n if (args.processors.length === 0) return args.run;\n const compute = async (): Promise<RunResult> => {\n const result = await args.run.wait();\n // Only a finished run with text is worth processing; errors/cancels pass through.\n if (result.status !== \"finished\" || result.result === undefined) return result;\n const res = await runOutputProcessors(args.processors, result.result, args.agentId);\n if (res.kind === \"ok\") return { ...result, result: res.value };\n emitRunEvent(args.onRunEvent, {\n type: \"tripwire\",\n reason: res.tripwire.reason,\n processorId: res.tripwire.processorId,\n });\n // Suppress ONLY the model text (`result`); the run-level metadata survives on\n // purpose. An output block happens AFTER the model ran, so `usage`/`cost`/\n // `durationMs` are real and MUST reach the caller (billing honesty) — the\n // guardrail redacts the answer, it does not un-spend the tokens. `error` is\n // absent on a finished run, so no error/content field leaks through the spread.\n const { result: _suppressed, ...metadata } = result;\n return { ...metadata, status: \"cancelled\", tripwire: res.tripwire };\n };\n // Memoize so output processors run EXACTLY ONCE per run — `wait()` is idempotent\n // (the underlying run's wait() is too), so multiple wait() calls must not\n // re-redact or re-fire `onViolation`.\n let processed: Promise<RunResult> | undefined;\n const wrappedWait: Run[\"wait\"] = () => {\n processed ??= compute();\n return processed;\n };\n return new Proxy(args.run, {\n get(target, prop, receiver) {\n if (prop === \"wait\") return wrappedWait;\n return Reflect.get(target, prop, receiver);\n },\n });\n}\n","/**\n * Memory hook wiring for `LocalAgent.sendLocked` (T2.1, ADRs D141 / D145).\n *\n * Two helpers extracted to keep `local-agent.ts` under G8 (≤400 LoC):\n * - `applyPreUserSendHook` — fires `pre_user_send`, caps recalled context\n * at `maxRecallContextBytes` (EC-A), injects `<memory-context>` fence.\n * - `wrapRunWithPostReplyHook` — Proxy-wraps the Run so\n * `post_assistant_reply` fires once after `wait()` (fire-and-forget,\n * errors → stderr per EC-O).\n *\n * @internal\n */\n\nimport type { AgentOptions } from \"../../types/agent.js\";\nimport type { Run, SDKUserMessage, SendOptions } from \"../../types/run.js\";\nimport type { PluginManager } from \"../plugins/manager.js\";\n\nconst DEFAULT_MAX_RECALL_BYTES = 16_000;\n\n/**\n * EC-A + EC-G + EC-H: fire `pre_user_send` hooks, cap recalled context,\n * and prepend it as a `<memory-context>` fence around the original\n * user text. Returns the (possibly wrapped) message preserving the\n * `string | SDKUserMessage` shape the caller passed in.\n */\nexport async function applyPreUserSendHook(args: {\n pluginManager: PluginManager;\n agentId: string;\n options: AgentOptions;\n original: string | SDKUserMessage;\n userText: string;\n sendOptions: SendOptions;\n}): Promise<string | SDKUserMessage> {\n const handlers = args.pluginManager.hooksFor(\"pre_user_send\");\n if (handlers.length === 0) return args.original;\n const ctx = {\n prompt: args.userText,\n agentId: args.agentId,\n runId: \"\",\n ...(args.options.memoryContext !== undefined\n ? { memoryContext: args.options.memoryContext }\n : {}),\n ...(args.sendOptions.signal !== undefined ? { signal: args.sendOptions.signal } : {}),\n };\n const cap = args.options.maxRecallContextBytes ?? DEFAULT_MAX_RECALL_BYTES;\n const recalled = await args.pluginManager.runPreUserSendHooks(ctx, cap);\n if (recalled === undefined || recalled.length === 0) return args.original;\n const wrapped = `<memory-context>\\n${recalled}\\n</memory-context>\\n\\n${args.userText}`;\n return typeof args.original === \"string\" ? wrapped : { ...args.original, text: wrapped };\n}\n\n/**\n * Wrap a `Run` so `post_assistant_reply` fires once after `wait()`.\n * Fire-and-forget — errors are surfaced to stderr (EC-O) so the caller\n * never blocks on memory sync. Returns a Proxy preserving all other\n * Run methods (stream, cancel, conversation).\n */\nexport function wrapRunWithPostReplyHook(args: {\n pluginManager: PluginManager;\n agentId: string;\n options: AgentOptions;\n run: Run;\n userText: string;\n}): Run {\n const handlers = args.pluginManager.hooksFor(\"post_assistant_reply\");\n if (handlers.length === 0) return args.run;\n const wrappedWait: Run[\"wait\"] = async () => {\n const result = await args.run.wait();\n const replyText = (result as { result?: string }).result ?? \"\";\n const ctx = {\n prompt: args.userText,\n reply: replyText,\n agentId: args.agentId,\n runId: result.id,\n ...(args.options.memoryContext !== undefined\n ? { memoryContext: args.options.memoryContext }\n : {}),\n };\n // Fire-and-forget; never block the caller.\n void args.pluginManager.runPostAssistantReplyHooks(ctx);\n return result;\n };\n return new Proxy(args.run, {\n get(target, prop, receiver) {\n if (prop === \"wait\") return wrappedWait;\n return Reflect.get(target, prop, receiver);\n },\n });\n}\n","import { AgentDisposedError } from \"../../errors.js\";\nimport type { AgentOptions, ModelSelection } from \"../../types/agent.js\";\nimport type { Run, SDKUserMessage, SendOptions } from \"../../types/run.js\";\nimport { emitRunEvent } from \"../../types/run-events.js\";\nimport type { MemoryToolSpec } from \"../agent-loop/loop-types.js\";\nimport type { PluginManager } from \"../plugins/manager.js\";\nimport { anySignal } from \"../runtime/concurrency/abort-utils.js\";\nimport {\n type CompletionCheckDeps,\n wrapRunWithCompletionCheck,\n} from \"../runtime/lifecycle/wrap-completion-check-run.js\";\nimport {\n resolveActiveMemorySummaryForSend,\n resolveMemoryProviderForLoop,\n resolveMemoryToolsForLoop,\n shouldUsePortMemoryPath,\n} from \"../runtime/memory/memory-path-selector.js\";\nimport type { MemoryProvider } from \"../runtime/memory/memory-provider.js\";\nimport type { MemoryFact } from \"../runtime/memory/memory-store.js\";\nimport { readMemoryFacts } from \"../runtime/memory/memory-store.js\";\nimport { normalizeModel } from \"../runtime/model-selection.js\";\nimport { runInputProcessors } from \"../runtime/processors/run-processors.js\";\nimport { createTripwireRun } from \"../runtime/processors/tripwire-run.js\";\nimport { wrapRunWithOutputProcessors } from \"../runtime/processors/wrap-output-run.js\";\nimport { safeCall } from \"../runtime/system-prompt/safe-call.js\";\nimport { appendSessionMessage, getSessionMessages } from \"../session/index.js\";\nimport type { TelemetryHandle } from \"../telemetry/tracer.js\";\nimport { consumePending } from \"./local-agent-invalidate.js\";\nimport type { LocalAgentMemory } from \"./local-agent-memory.js\";\nimport { applyPreUserSendHook, wrapRunWithPostReplyHook } from \"./local-agent-memory-hooks.js\";\nimport { persistMemoryFactIfWritePrompt } from \"./local-agent-runtime-extensions.js\";\n\n/**\n * Inputs for the `executeSendLocked` helper extracted from LocalAgent.sendLocked.\n * @internal\n */\nexport interface SendLockedInputs {\n agentId: string;\n disposed: boolean;\n invalidationPending: { reason: string; at: number } | undefined;\n clearInvalidation: () => void;\n reload: () => Promise<void>;\n // SE8 — receives an already-NORMALIZED ModelSelection (the string shorthand is\n // normalized at the send boundary), decoupled from the public AgentOptions type.\n applyModelOverride: (model: ModelSelection | undefined) => void;\n options: AgentOptions;\n pluginManagerCode: PluginManager;\n memoryGlue: LocalAgentMemory;\n defaultMemoryProviderForLoop: ReturnType<\n typeof import(\"./local-agent-memory-provider.js\").createLocalAgentMemoryProvider\n >;\n workspaceCwd: string;\n telemetry: TelemetryHandle;\n lifecycleAbortController: AbortController;\n runPreHook: (userText: string) => Promise<void>;\n resolveSystemPromptForSend: (\n userText: string,\n options: SendOptions,\n memoryFacts: ReadonlyArray<MemoryFact>,\n ) => Promise<string | undefined>;\n assembleSystemPromptForSend: (\n userText: string,\n baseSystemPrompt: string | undefined,\n memoryFacts: ReadonlyArray<MemoryFact>,\n activeMemorySummary: string | undefined,\n contextPaths: readonly string[] | undefined,\n ) => Promise<string | undefined>;\n // jscpd:ignore-start — type contract mirrors LocalAgent.dispatchRun signature (not knowledge duplication)\n dispatchRun: (\n message: string | SDKUserMessage,\n options: SendOptions,\n systemPrompt: string | undefined,\n memoryFacts: ReadonlyArray<MemoryFact>,\n priorMessages: ReadonlyArray<{ role: \"user\" | \"assistant\"; text: string }>,\n memoryTools: ReadonlyArray<MemoryToolSpec> | undefined,\n memoryProviderOverride?: MemoryProvider,\n ) => Promise<Run>;\n // jscpd:ignore-end\n}\n\n/**\n * SE24 — run the input guardrail processors on the raw user text. Returns a\n * terminal `tripwireRun` when a processor blocked, else the (possibly rewritten)\n * `userText` + `effectiveMessage` to feed the rest of the send.\n */\nasync function applyInputProcessors(\n inputs: SendLockedInputs,\n message: string | SDKUserMessage,\n rawUserText: string,\n options: SendOptions,\n sendModel: ModelSelection | undefined,\n): Promise<{ tripwireRun: Run } | { userText: string; effectiveMessage: string | SDKUserMessage }> {\n const processors = inputs.options.inputProcessors;\n if (processors === undefined || processors.length === 0) {\n return { userText: rawUserText, effectiveMessage: message };\n }\n const res = await runInputProcessors(processors, rawUserText, inputs.agentId);\n if (res.kind === \"tripwire\") {\n emitRunEvent(options.onRunEvent, {\n type: \"tripwire\",\n reason: res.tripwire.reason,\n processorId: res.tripwire.processorId,\n });\n return {\n tripwireRun: createTripwireRun({\n agentId: inputs.agentId,\n tripwire: res.tripwire,\n model: sendModel,\n }),\n };\n }\n const effectiveMessage =\n typeof message === \"string\" ? res.value : { ...message, text: res.value };\n return { userText: res.value, effectiveMessage };\n}\n\n/**\n * Core send logic extracted from `LocalAgent.sendLocked` to reduce\n * the LocalAgent class LoC (G8 budget). All dependencies are injected\n * via the `inputs` parameter.\n *\n * @internal\n */\nexport async function executeSendLocked(\n inputs: SendLockedInputs,\n message: string | SDKUserMessage,\n options: SendOptions,\n): Promise<Run> {\n if (inputs.disposed) throw new AgentDisposedError(inputs.agentId);\n // biome-ignore format: keep one-liner to stay under G8 LoC.\n await consumePending(inputs.agentId, inputs.invalidationPending, inputs.clearInvalidation, inputs.reload);\n // SE8 — normalize a bare-string send-model override to `{ id }`.\n const sendModel = normalizeModel(options.model);\n inputs.applyModelOverride(sendModel);\n const rawUserText = typeof message === \"string\" ? message : message.text;\n\n // SE24 — input guardrail processors run FIRST, before any side effect; a\n // `block` short-circuits to a tripwire run, a `rewrite` flows downstream.\n const gated = await applyInputProcessors(inputs, message, rawUserText, options, sendModel);\n if (\"tripwireRun\" in gated) return gated.tripwireRun;\n const { userText, effectiveMessage } = gated;\n\n if (inputs.options.onBeforeSend !== undefined) {\n await inputs.options.onBeforeSend({\n conversationId: inputs.agentId,\n previousMessageCount: getSessionMessages(inputs.agentId).length,\n });\n }\n await inputs.runPreHook(userText);\n\n const adaptedMessage = await applyPreUserSendHook({\n pluginManager: inputs.pluginManagerCode,\n agentId: inputs.agentId,\n options: inputs.options,\n original: effectiveMessage,\n userText,\n sendOptions: options,\n });\n\n const priorMessages = [...getSessionMessages(inputs.agentId)];\n appendSessionMessage(inputs.agentId, { role: \"user\", text: userText });\n\n await persistMemoryFactIfWritePrompt(inputs.workspaceCwd, inputs.options.memory, userText);\n const memoryFacts = await readMemoryForSend(inputs.workspaceCwd, inputs.options.memory);\n const portPathActive = shouldUsePortMemoryPath();\n const legacyTools = portPathActive ? undefined : await inputs.memoryGlue.ensureTools();\n const legacySummary = portPathActive\n ? undefined\n : await inputs.memoryGlue.runActiveMemoryIfEnabled(userText, priorMessages, inputs.telemetry);\n const memoryTools = resolveMemoryToolsForLoop(legacyTools, portPathActive);\n const activeMemorySummary = resolveActiveMemorySummaryForSend(legacySummary, portPathActive);\n const effectiveMemoryProvider = resolveMemoryProviderForLoop(\n inputs.options.memoryProvider,\n inputs.defaultMemoryProviderForLoop,\n portPathActive,\n );\n const baseSystemPrompt = await inputs.resolveSystemPromptForSend(userText, options, memoryFacts);\n const assembledSystemPrompt = await inputs.assembleSystemPromptForSend(\n userText,\n baseSystemPrompt,\n memoryFacts,\n activeMemorySummary,\n options.contextPaths,\n );\n const composedOptions: SendOptions = {\n ...options,\n signal: anySignal([options.signal, inputs.lifecycleAbortController.signal]),\n };\n const run = await inputs.dispatchRun(\n adaptedMessage,\n composedOptions,\n assembledSystemPrompt,\n memoryFacts,\n priorMessages,\n memoryTools,\n effectiveMemoryProvider,\n );\n // SE24 — output processors wrap INNER (they redact/block the model text) so the\n // post_assistant_reply memory hook observes the FINAL (processed) reply.\n const outputProcessors = inputs.options.outputProcessors;\n const processedRun =\n outputProcessors !== undefined && outputProcessors.length > 0\n ? wrapRunWithOutputProcessors({\n run,\n processors: outputProcessors,\n agentId: inputs.agentId,\n onRunEvent: options.onRunEvent,\n })\n : run;\n const hookedRun = wrapRunWithPostReplyHook({\n pluginManager: inputs.pluginManagerCode,\n agentId: inputs.agentId,\n options: inputs.options,\n run: processedRun,\n userText,\n });\n // SE34 — outermost wrap: judge the FINAL reply against the per-send completion\n // criterion (opt-in). Absent `completionCheck` ⇒ returns `hookedRun` unchanged.\n return wrapRunWithCompletionCheck({\n run: hookedRun,\n completionCheck: options.completionCheck,\n onRunEvent: options.onRunEvent,\n deps: buildCompletionCheckDeps(),\n });\n}\n\n/** Resolve the LLM-judge dep from the DI registry (mirrors runUntil's judge wiring). */\nfunction buildCompletionCheckDeps(): CompletionCheckDeps {\n return {\n judge: async (ctx, opts) => {\n const { judgeCallImpl } = await import(\"../judge/judge-call.js\");\n const { getAgentFacade } = await import(\"../runtime/registry/agent-factory-registry.js\");\n return judgeCallImpl(ctx, opts, { create: getAgentFacade().create });\n },\n };\n}\n\nfunction readMemoryForSend(\n workspaceCwd: string,\n memoryConfig: AgentOptions[\"memory\"],\n): Promise<MemoryFact[]> {\n if (memoryConfig?.enabled !== true) return Promise.resolve([]);\n return safeCall(() => readMemoryFacts(workspaceCwd, memoryConfig), [], \"memory read\");\n}\n","/**\n * T3.2 — register a `Run` from `LocalAgent.send({ task: ... })` as a\n * Task in the observable registry. Extracted from `local-agent.ts`\n * to keep that file under the 400-LoC quality gate (G8).\n *\n * @internal\n */\n\nimport type { Run } from \"../../types/run.js\";\nimport { submit as taskRegistrySubmit } from \"../task/registry.js\";\n\nexport function registerRunAsTask(\n run: Run,\n agentId: string,\n taskOpt: true | { id?: string; meta?: Record<string, unknown> },\n userText: string,\n): void {\n const opts = taskOpt === true ? {} : taskOpt;\n const meta: Record<string, unknown> = {\n agentId,\n runId: run.id,\n promptPreview: userText.slice(0, 120),\n ...(opts.meta ?? {}),\n };\n void taskRegistrySubmit({\n kind: \"run\",\n work: async (ctx) => {\n ctx.signal.addEventListener(\n \"abort\",\n () => {\n void run.cancel().catch(() => {\n /* swallow — run may already be terminal */\n });\n },\n { once: true },\n );\n const result = await run.wait();\n ctx.emit({ status: result.status, runId: run.id });\n return { status: result.status, result: result.result };\n },\n ...(opts.id !== undefined ? { id: opts.id } : {}),\n meta,\n });\n}\n","import {\n agentGenerate,\n type GenerateOptions,\n type GenerateRunResult,\n} from \"../../agent-generate.js\";\nimport { ConfigurationError, UnsupportedRunOperationError } from \"../../errors.js\";\nimport type {\n AgentDefinition,\n AgentOptions,\n ModelSelection,\n SDKAgent,\n SDKArtifact,\n} from \"../../types/agent.js\";\nimport type { Run, SDKUserMessage, SendOptions } from \"../../types/run.js\";\nimport type { SessionStore } from \"../../types/session-store.js\";\nimport type { MemoryToolSpec } from \"../agent-loop/loop-types.js\";\nimport { generateLocalAgentId } from \"../ids.js\";\nimport { withCwdMutex } from \"../persistence/cwd-mutex.js\";\nimport { FsSessionStore } from \"../persistence/fs-session-store.js\";\nimport { defaultBaseDir, expandTilde } from \"../persistence/session-transcript.js\";\nimport type { PersonalityRegistry } from \"../personality/registry.js\";\nimport { PersonalityStore } from \"../personality/store.js\";\nimport type { PersonalityPreset } from \"../personality/types.js\";\nimport { PluginManager } from \"../plugins/manager.js\";\nimport { extractCodePlugins } from \"../plugins/plugin-guards.js\";\nimport type { ProvidersManagerImpl } from \"../runtime/config/providers-manager.js\";\nimport type { FileContextManager } from \"../runtime/context/context-manager.js\";\nimport { HooksExecutor } from \"../runtime/hooks/hooks-executor.js\";\nimport { runPostRunLifecycle } from \"../runtime/lifecycle/post-run-lifecycle.js\";\nimport {\n resolveMemoryProviderForLoop,\n shouldUsePortMemoryPath,\n} from \"../runtime/memory/memory-path-selector.js\";\nimport type { MemoryFact } from \"../runtime/memory/memory-store.js\";\nimport { normalizeModel } from \"../runtime/model-selection.js\";\nimport type { PluginMetadata, PluginsManager } from \"../runtime/plugins/plugins-manager.js\";\nimport { updateRegisteredAgent } from \"../runtime/registry/agent-registry.js\";\nimport type { SkillsHandle, SkillsManager } from \"../runtime/skills/skills-manager.js\";\nimport { loadSubagents } from \"../runtime/skills/subagents-loader.js\";\nimport {\n assembleSystemPromptForSend as assembleSystemPromptForSendHelper,\n buildSystemPromptContext as buildSystemPromptContextHelper,\n type LocalAssemblyInputs,\n} from \"../runtime/system-prompt/local-assembly.js\";\nimport { SystemPromptPipeline } from \"../runtime/system-prompt/pipeline.js\";\nimport { resolveSystemPromptForSend } from \"../runtime/system-prompt/system-prompt.js\";\nimport { validateToolCatalog } from \"../runtime/validation/validate-agent-options.js\";\nimport { hydrateSession } from \"../session/index.js\";\nimport { SPAN_NAMES } from \"../telemetry/span-names.js\";\nimport { createTelemetry, type OTelSpan, type TelemetryHandle } from \"../telemetry/tracer.js\";\nimport { bootstrapSubmanagers, registerLocalAgent } from \"./local-agent-bootstrap.js\";\nimport { dispatchLocalRun } from \"./local-agent-dispatch.js\";\nimport { invalidateCacheImpl } from \"./local-agent-invalidate.js\";\nimport {\n acquireLeaseIfPossible,\n disposeLocalAgentSession,\n releaseLeaseIfPossible,\n reloadLocalAgent,\n} from \"./local-agent-lifecycle.js\";\nimport { LocalAgentMemory } from \"./local-agent-memory.js\";\nimport { buildAgentMemory } from \"./local-agent-memory-direct.js\";\nimport { createLocalAgentMemoryProvider } from \"./local-agent-memory-provider.js\";\nimport {\n applyPersonalityOverlay,\n ensurePersonalityRegistryIfNeeded,\n localAgentUsePersonality,\n resolveActivePersonalityPreset,\n} from \"./local-agent-personality-extensions.js\";\nimport {\n localAgentFork,\n localAgentRunToCompletion,\n localAgentRunUntil,\n localAgentStreamToCompletion,\n} from \"./local-agent-runtime-extensions.js\";\nimport { executeSendLocked } from \"./local-agent-send.js\";\nimport { registerRunAsTask } from \"./local-agent-task-wrap.js\";\n\n/**\n * Local SDKAgent implementation. Owns the workspace cwd plus the file-based\n * loaders (context, hooks, MCP, subagents, plugins, skills). Routes runs\n * through the in-process fixture responder.\n *\n * @internal\n */\nexport class LocalAgent implements SDKAgent {\n readonly agentId: string;\n model: ModelSelection | undefined;\n context?: FileContextManager;\n providers?: ProvidersManagerImpl;\n skills?: SkillsHandle;\n plugins?: { list: () => Promise<PluginMetadata[]> };\n memory?: import(\"../../types/memory-adapter.js\").AgentMemory;\n\n readonly options: AgentOptions;\n readonly workspaceCwd: string;\n /**\n * SE40 — base dir for the native Claude-shaped session transcript. Default\n * `~/.theokit`; set `local.baseDir: \"~/.claude\"` for Claude Code CLI interop.\n */\n private readonly transcriptBaseDir: string;\n /**\n * SE41 — the session record store. Defaults to the FS transcript store (byte-\n * identical to SE40); `local.sessionStore` injects an external store (Postgres /\n * Redis / KV) so resume works on serverless (ephemeral FS) and multi-host.\n */\n readonly sessionStore: SessionStore;\n /**\n * D319: lifecycle AbortController fired on `dispose()`. Composed with the\n * caller's `SendOptions.signal` via `anySignal` so the LLM `fetch()`\n * aborts on either signal (user cancel OR dispose).\n */\n readonly lifecycleAbortController = new AbortController();\n readonly settingSourcesIncludeProject: boolean;\n private readonly settingSourcesIncludePlugins: boolean;\n private resolvedSubagents: Record<string, AgentDefinition> = {};\n private disposed = false;\n private invalidationPending: { reason: string; at: number } | undefined;\n readonly skillsManager: SkillsManager | undefined;\n readonly pluginsManager: PluginsManager | undefined;\n private readonly hooksExecutor: HooksExecutor;\n private readonly systemPromptPipeline: SystemPromptPipeline = SystemPromptPipeline.default();\n private readonly memoryGlue: LocalAgentMemory;\n /**\n * SDK 2.0 Phase 1 physical Stage 2b — iter 19+: pre-built adapter\n * wrapping `memoryGlue` as a MemoryProvider impl. Constructed eagerly\n * so future iters can flip `inputs.memoryProvider` to default to\n * THIS adapter when consumer didn't supply one. NOT YET used by\n * `send()` — the kernel flip lands in Stage 2b proper after equivalence\n * regression coverage.\n *\n * Accessible to tests via `_defaultMemoryProviderForLoop()` helper.\n * @internal\n */\n private readonly defaultMemoryProviderForLoop: ReturnType<typeof createLocalAgentMemoryProvider>;\n /** T4.1 — PluginManager for code plugins (kind: general/model-provider/memory). @internal */\n private readonly pluginManagerCode: PluginManager = new PluginManager();\n /** Personality presets — lazy-loaded on first `usePersonality` call (ADRs D160-D164). @internal */\n private personalityRegistry: PersonalityRegistry | undefined;\n private readonly personalityStore: PersonalityStore;\n /** T0.1 — telemetry handle shared with sendLocked + memory recall path. */\n private readonly _telemetry: TelemetryHandle;\n\n constructor(options: AgentOptions) {\n this.agentId = options.agentId ?? generateLocalAgentId();\n this._telemetry = createTelemetry(options.telemetry);\n this.model = normalizeModel(options.model);\n this.options = options;\n this.workspaceCwd = resolveCwd(options.local?.cwd);\n this.transcriptBaseDir = resolveBaseDir(options.local?.baseDir);\n // SE41 — external store if injected, else the FS default (byte-identical to SE40).\n this.sessionStore =\n options.local?.sessionStore ??\n new FsSessionStore({ baseDir: this.transcriptBaseDir, cwd: this.workspaceCwd });\n this.settingSourcesIncludeProject = includesSetting(options, \"project\");\n this.settingSourcesIncludePlugins = includesSetting(options, \"plugins\");\n\n const sub = bootstrapSubmanagers({\n options,\n workspaceCwd: this.workspaceCwd,\n settingSourcesIncludeProject: this.settingSourcesIncludeProject,\n settingSourcesIncludePlugins: this.settingSourcesIncludePlugins,\n });\n if (sub.context !== undefined) this.context = sub.context;\n if (sub.providers !== undefined) this.providers = sub.providers;\n this.skillsManager = sub.skillsManager;\n if (sub.skills !== undefined) this.skills = sub.skills;\n this.pluginsManager = sub.pluginsManager;\n if (sub.plugins !== undefined) this.plugins = sub.plugins;\n\n this.hooksExecutor = new HooksExecutor(this.workspaceCwd);\n this.memoryGlue = new LocalAgentMemory(options, this.workspaceCwd, this.agentId);\n // SDK 2.0 Phase 1 physical Stage 2b — iter 19+: build the adapter\n // alongside the legacy glue. Same underlying rich impl; the adapter\n // exposes it through the MemoryProvider port. NOT YET wired into\n // send() — agent-loop still consumes `memoryGlue` directly via\n // `inputs.memoryTools` + `activeMemorySummary` concat path.\n this.defaultMemoryProviderForLoop = createLocalAgentMemoryProvider({\n agentOptions: options,\n workspaceCwd: this.workspaceCwd,\n agentId: this.agentId,\n ...(this._telemetry !== undefined ? { telemetry: this._telemetry } : {}),\n });\n this.personalityStore = new PersonalityStore(this.workspaceCwd);\n // ADR D141 / D142: `agent.memory.*` direct API over plugin-aggregated adapters.\n // Built unconditionally; `requireAdapters` throws ConfigurationError when called\n // without any registered memory plugin.\n this.memory = buildAgentMemory(\n this.pluginManagerCode,\n this.workspaceCwd,\n this.options.memoryContext,\n );\n\n registerLocalAgent({\n agentId: this.agentId,\n model: this.model,\n options,\n workspaceCwd: this.workspaceCwd,\n });\n }\n\n async initialize(): Promise<void> {\n await this.hooksExecutor.initialize(this.settingSourcesIncludeProject);\n if (this.context !== undefined) await this.context.initialize();\n if (this.skillsManager !== undefined) await this.skillsManager.initialize();\n if (this.pluginsManager !== undefined) await this.pluginsManager.initialize();\n // T4.1 (ADRs D97-D101 + EC-1): wire code plugins. extractCodePlugins\n // discriminates new Plugin[] from legacy `{ enabled }` metadata; the\n // latter returns empty so v1.2 callers continue to work.\n const codePlugins = extractCodePlugins(this.options.plugins);\n await this.pluginManagerCode.initialize(codePlugins);\n this.resolvedSubagents = await loadSubagents(\n this.workspaceCwd,\n this.settingSourcesIncludeProject,\n this.options.agents,\n );\n // SE40 — hydrate persisted session history from the native transcript so a\n // resumed agent sees the conversation from the previous process.\n // M95 — the writer lease is taken at INIT, before any turn.\n //\n // Here, and not in `appendRecords`: the `SessionStore` contract makes an append rejection\n // best-effort (logged to stderr, not thrown), so acquiring there made the `SessionBusyError`\n // get swallowed and the user's turn vanish silently. At init the error reaches whoever can\n // decide — `exec` forks to a new id, which is what the error message prescribes.\n await acquireLeaseIfPossible(this.sessionStore, this.agentId);\n // Everything after the acquisition runs under `try`: an init failing AFTER taking the lease would leave\n // the lock held by this very process — alive, same host — and `reclaimable` would be `false` forever.\n // The session would stay locked for the process's lifetime, with no crash and no recovery: the\n // same class this milestone exists to remove, coming in through another door.\n //\n // Measured with an unreadable transcript (EACCES), which `readRecords` must throw on by contract.\n try {\n await hydrateSession(this.agentId, { store: this.sessionStore, cwd: this.workspaceCwd });\n // ADR D163 — hydrate previously-active personality slug (no-op if none).\n await this.personalityStore.hydrate(this.agentId);\n } catch (err) {\n // Releases THIS agent's lease, not all of the store's: an injected store may serve several\n // agents, and an init that fails for B must not free A's lease, which is still writing.\n await releaseLeaseIfPossible(this.sessionStore, this.agentId);\n throw err;\n }\n }\n\n /** T4.2 — expose PluginManager so agent-loop can fire pre_tool_call hooks. @internal */\n pluginManager(): PluginManager {\n return this.pluginManagerCode;\n }\n\n /** Expose the hooks executor so the agent loop can fire PreToolUse/etc. */\n hooks(): HooksExecutor {\n return this.hooksExecutor;\n }\n\n // SE9 — integrated structured output; delegates to the shared helper.\n generate<T extends import(\"zod\").ZodType>(\n message: string | SDKUserMessage,\n options: GenerateOptions<T>,\n ): Promise<GenerateRunResult<import(\"zod\").z.infer<T>>> {\n const { apiKey, local } = this.options;\n return agentGenerate(this, this.model, apiKey, local, message, options);\n }\n\n async send(message: string | SDKUserMessage, options: SendOptions = {}): Promise<Run> {\n // Per-call tools: run the same name/schema/dedupe checks as creation.\n // (Cloud agents reject per-call tools in CloudAgent.send.)\n if (options.tools !== undefined && options.tools.length > 0) {\n validateToolCatalog(options.tools);\n }\n // T0.1: `agent.send` parent span spans the FULL lifecycle (mutex acquire +\n // dispatch + post-run). Child step spans (`agent.send.<step>`) land in T1.7.\n const sendSpan = this._telemetry.startSpan(SPAN_NAMES.AGENT_SEND, {\n agentId: this.agentId,\n ...(this.model?.id !== undefined ? { model: this.model.id } : {}),\n });\n // ADR D19 (EC-8): per-agent send mutex keyed by `agent-send:${agentId}`.\n // The lock spans the FULL run lifecycle — dispatch + run.wait() + post-run\n // assistant-turn append + session summary write + disk flush — so\n // concurrent sends to the SAME agentId cannot interleave user/assistant\n // records mid-turn AND `agent.dispose()` can never return before the\n // summary write finishes (ADR D20).\n return new Promise<Run>((resolve, reject) => {\n void withCwdMutex(`agent-send:${this.agentId}`, () =>\n this.runLockedSendCycle(message, options, sendSpan, resolve, reject),\n );\n });\n }\n\n /**\n * The context window declared on the model selection, in conditional-spread form.\n *\n * M94 — without this, `resolveEffectiveContextWindow`'s `override` had existed since M77 and no\n * production call site passed it: a 400k model with no catalog entry was budgeted against the\n * 128k floor. Its own method because the inline spread pushed `runLockedSendCycle` past the\n * project's cognitive-complexity ceiling.\n */\n #declaredWindow(): { contextWindow?: number } {\n const declared = this.model?.contextWindow;\n return declared !== undefined ? { contextWindow: declared } : {};\n }\n\n private async runLockedSendCycle(\n message: string | SDKUserMessage,\n options: SendOptions,\n sendSpan: OTelSpan,\n resolve: (run: Run) => void,\n reject: (err: unknown) => void,\n ): Promise<void> {\n const userText = typeof message === \"string\" ? message : message.text;\n let run: Run;\n try {\n run = await this.sendLocked(message, options);\n } catch (err) {\n sendSpan.recordException(err);\n sendSpan.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });\n sendSpan.end();\n reject(err);\n return;\n }\n // T3.2: opt-in Task wrapping (ADRs D363/D374).\n // biome-ignore format: one-liner to stay under G8 LoC budget.\n if (options.task !== undefined) registerRunAsTask(run, this.agentId, options.task, userText);\n resolve(run);\n try {\n // SDK 2.0 Phase 1 physical Stage 3 prep — iter 28: thread the\n // resolved memoryProvider into post-run-lifecycle so the\n // recordSessionSummary port method can be invoked (when defined).\n // Consumer-supplied `options.memoryProvider` always wins; otherwise\n // when port path is active, the auto-installed adapter takes over.\n // When neither: undefined → legacy writeSessionSummary path runs.\n const postRunProvider = resolveMemoryProviderForLoop(\n this.options.memoryProvider,\n this.defaultMemoryProviderForLoop,\n shouldUsePortMemoryPath(),\n );\n await runPostRunLifecycle({\n run,\n userText,\n agentId: this.agentId,\n workspaceCwd: this.workspaceCwd,\n sessionStore: this.sessionStore,\n model: this.model?.id ?? \"unknown\",\n ...this.#declaredWindow(),\n // M50 — the auto-compaction summarizer resolves credentials like the run itself.\n ...(this.options.apiKey !== undefined ? { apiKey: this.options.apiKey } : {}),\n ...(options.onRunEvent !== undefined ? { onRunEvent: options.onRunEvent } : {}),\n hooksExecutor: this.hooksExecutor,\n memoryGlue: this.memoryGlue,\n ...(postRunProvider !== undefined ? { memoryProvider: postRunProvider } : {}),\n });\n } finally {\n sendSpan.end();\n }\n }\n\n private async sendLocked(message: string | SDKUserMessage, options: SendOptions): Promise<Run> {\n return executeSendLocked(\n {\n agentId: this.agentId,\n disposed: this.disposed,\n invalidationPending: this.invalidationPending,\n clearInvalidation: () => {\n this.invalidationPending = undefined;\n },\n reload: () => this.reload(),\n applyModelOverride: (m) => this.applyModelOverride(m),\n options: this.options,\n pluginManagerCode: this.pluginManagerCode,\n memoryGlue: this.memoryGlue,\n defaultMemoryProviderForLoop: this.defaultMemoryProviderForLoop,\n workspaceCwd: this.workspaceCwd,\n telemetry: this._telemetry,\n lifecycleAbortController: this.lifecycleAbortController,\n runPreHook: (ut) => this.runPreHook(ut),\n // biome-ignore format: G8 budget — callbacks wire to private methods.\n resolveSystemPromptForSend: (ut, o, mf) => this.resolveSystemPrompt(ut, o, mf),\n assembleSystemPromptForSend: (ut, bp, mf, ams, cp) =>\n assembleSystemPromptForSendHelper(this.assemblyInputs(), ut, bp, mf, ams, cp),\n dispatchRun: (msg, o, sp, mf, pm, mt, mp) => this.dispatchRun(msg, o, sp, mf, pm, mt, mp),\n },\n message,\n options,\n );\n }\n\n // biome-ignore format: G8 budget — thin accessor for the assembly inputs.\n private assemblyInputs(): LocalAssemblyInputs { return { agentId: this.agentId, workspaceCwd: this.workspaceCwd, model: this.model, options: this.options, context: this.context, skillsManager: this.skillsManager, settingSourcesIncludeProject: this.settingSourcesIncludeProject, systemPromptPipeline: this.systemPromptPipeline }; }\n\n private async resolveSystemPrompt(\n userText: string,\n options: SendOptions,\n memoryFacts: ReadonlyArray<MemoryFact>,\n ): Promise<string | undefined> {\n const base = await resolveSystemPromptForSend(\n this.options.systemPrompt,\n options.systemPrompt,\n () => buildSystemPromptContextHelper(this.assemblyInputs(), userText, memoryFacts),\n );\n this.personalityRegistry = await ensurePersonalityRegistryIfNeeded({\n agentId: this.agentId,\n workspaceCwd: this.workspaceCwd,\n personalityStore: this.personalityStore,\n personalityRegistry: this.personalityRegistry,\n });\n return applyPersonalityOverlay(this.activePreset(), base);\n }\n\n /** @internal — read-only personality lookup (composes the helper, honors fork ALS). */\n // biome-ignore format: keep one-liner so the personality lookup stays under G8.\n private activePreset(): PersonalityPreset | undefined { return resolveActivePersonalityPreset({ agentId: this.agentId, personalityStore: this.personalityStore, personalityRegistry: this.personalityRegistry }); }\n\n private applyModelOverride(overrideModel: ModelSelection | undefined): void {\n if (overrideModel === undefined) return;\n this.model = overrideModel;\n updateRegisteredAgent(this.agentId, { model: overrideModel });\n }\n\n private async runPreHook(userText: string): Promise<void> {\n const preRun = await this.hooksExecutor.run({\n event: \"preRun\",\n input: { message: userText },\n agentId: this.agentId,\n });\n if (preRun.blocked) {\n throw new ConfigurationError(\n `preRun hook denied execution: ${preRun.reason ?? \"unspecified\"}`,\n { code: \"hook_denied\" },\n );\n }\n }\n\n private dispatchRun(\n message: string | SDKUserMessage,\n options: SendOptions,\n systemPrompt: string | undefined,\n memoryFacts: ReadonlyArray<MemoryFact>,\n priorMessages: ReadonlyArray<{ role: \"user\" | \"assistant\"; text: string }>,\n memoryTools: ReadonlyArray<MemoryToolSpec> | undefined,\n memoryProviderOverride?: import(\"../runtime/memory/memory-provider.js\").MemoryProvider,\n ): Promise<Run> {\n // SDK 2.0 Phase 1 physical Stage 2b — iter 23 KERNEL FLIP:\n // When `memoryProviderOverride` is supplied (env-flag path), inject\n // it via a shallow-cloned `agentOptions` so agent-loop's iter 18\n // T1.3 wiring threads it into `inputs.memoryProvider` automatically.\n // When undefined: pass `this.options` verbatim (zero behavior change\n // — the existing consumer-supplied `options.memoryProvider` path\n // wins unchanged).\n const effectiveAgentOptions =\n memoryProviderOverride !== undefined && this.options.memoryProvider === undefined\n ? { ...this.options, memoryProvider: memoryProviderOverride }\n : this.options;\n return dispatchLocalRun({\n inputs: {\n agentId: this.agentId,\n model: this.model,\n options: effectiveAgentOptions,\n workspaceCwd: this.workspaceCwd,\n hooksExecutor: this.hooksExecutor,\n pluginManager: this.pluginManagerCode,\n resolvedSubagents: this.resolvedSubagents,\n settingSourcesIncludeProject: this.settingSourcesIncludeProject,\n },\n message,\n sendOptions: options,\n systemPrompt,\n memoryFacts,\n priorMessages,\n memoryTools,\n activePreset: this.activePreset(),\n });\n }\n\n close(): void {\n this.disposed = true;\n }\n\n async reload(): Promise<void> {\n this.resolvedSubagents = await reloadLocalAgent(this);\n }\n\n async dispose(): Promise<void> {\n if (this.disposed) return;\n this.disposed = true;\n await disposeLocalAgentSession(this);\n }\n\n [Symbol.asyncDispose](): Promise<void> {\n return this.dispose();\n }\n\n // biome-ignore format: multi-line layout would push file past G8 LoC cap.\n /** T3.2 / ADR D94 — public `invalidateCache` API. @internal */\n invalidateCache = (reason: string, opts: { applyNow?: boolean } = {}): Promise<void> =>\n invalidateCacheImpl(this.agentId, reason, opts, this.disposed, () => this.dispose(), (p) => { this.invalidationPending = p; });\n\n /**\n * Activate a personality preset (Hermes #26, ADRs D160-D164).\n *\n * Reserved names `none`, `default`, `neutral` clear the active preset.\n *\n * - `opts.save: true` → persist across process restarts (delete on clear,\n * never write null — EC-B).\n * - `opts.reset: true` → also clear session history (preserves by default).\n *\n * Always invalidates the prompt cache (D94 deferred default).\n *\n * @public\n */\n usePersonality(\n name: string,\n opts?: { save?: boolean; reset?: boolean },\n ): Promise<PersonalityPreset | null> {\n return localAgentUsePersonality({\n agentId: this.agentId,\n workspaceCwd: this.workspaceCwd,\n disposed: this.disposed,\n personalityStore: this.personalityStore,\n personalityRegistry: this.personalityRegistry,\n invalidateCache: (reason) => this.invalidateCache(reason),\n onRegistryLoaded: (reg) => {\n this.personalityRegistry = reg;\n },\n name,\n ...(opts !== undefined ? { opts } : {}),\n });\n }\n\n // biome-ignore format: G8 budget — artifact stubs (local agents have no artifacts); kept 1-line each.\n listArtifacts(): Promise<SDKArtifact[]> { return Promise.resolve([]); }\n // biome-ignore format: G8 budget — see listArtifacts.\n downloadArtifact(_path: string): Promise<Buffer> { return Promise.reject(new UnsupportedRunOperationError(\"Artifacts are not supported for local agents\", \"downloadArtifact\")); }\n\n // biome-ignore format: G8 budget — delegates to `local-agent-runtime-extensions.ts`; kept 1-line.\n runUntil(goal?: string, options?: import(\"../../types/goal-events.js\").GoalOptions): import(\"../../types/goal-events.js\").RunUntilIterator { return localAgentRunUntil(this, goal, options); }\n // biome-ignore format: G8 budget — see runUntil comment above.\n fork(options: import(\"../runtime/lifecycle/fork-agent.js\").ForkOptions): Promise<import(\"../runtime/lifecycle/fork-agent.js\").ForkResult> { return localAgentFork({ agentId: this.agentId, options: this.options, personalitySlugSnapshot: this.personalityStore.active(this.agentId) }, options); }\n // biome-ignore format: G8 budget — see runUntil comment above.\n runToCompletion(message: string, options?: import(\"../../types/run.js\").RunToCompletionOptions): Promise<import(\"../../types/run.js\").RunToCompletionResult> { return localAgentRunToCompletion(this, message, options); }\n // biome-ignore format: G8 budget — see runUntil comment above.\n streamToCompletion(message: string, options?: import(\"../../types/run.js\").RunToCompletionOptions): AsyncGenerator<import(\"../../types/messages.js\").SDKMessage, import(\"../../types/run.js\").StreamToCompletionResult> { return localAgentStreamToCompletion(this, message, options); }\n}\n\nfunction resolveCwd(cwd: string | string[] | undefined): string {\n return (Array.isArray(cwd) ? cwd[0] : cwd) ?? process.cwd();\n}\n\n/** SE40 — the transcript base dir (`local.baseDir` or `~/.theokit` default), with `~` expanded. */\nfunction resolveBaseDir(baseDir: string | undefined): string {\n return baseDir === undefined ? defaultBaseDir() : expandTilde(baseDir);\n}\n\nfunction includesSetting(options: AgentOptions, source: string): boolean {\n const sources = options.local?.settingSources;\n return (\n sources !== undefined && (sources.includes(source as never) || sources.includes(\"all\" as never))\n );\n}\n","import { stat } from \"node:fs/promises\";\n\nimport { AuthenticationError, ConfigurationError, UnknownAgentError } from \"./errors.js\";\nimport { validateApiKeyShape } from \"./internal/auth/api-key-validator.js\";\nimport { CloudAgent, validateCloudToolParity } from \"./internal/cloud-agent/index.js\";\nimport { resolveApiKey } from \"./internal/env.js\";\nimport { httpRequest } from \"./internal/http.js\";\nimport { isLocalAgentId } from \"./internal/ids.js\";\nimport { LocalAgent } from \"./internal/local-agent/index.js\";\nimport { discoverProviderPlugins } from \"./internal/providers/discovery.js\";\nimport {\n getConfiguredBaseUrl,\n isFixtureApiKey,\n shouldUseRealLocalRuntime,\n} from \"./internal/runtime/fixtures/fixture-mode.js\";\nimport { normalizeModel } from \"./internal/runtime/model-selection.js\";\nimport {\n flushRegistrySaves,\n getRegisteredAgent,\n hydrateRegistryFromDisk,\n updateRegisteredAgent,\n} from \"./internal/runtime/registry/agent-registry.js\";\nimport { validateAgentOptions } from \"./internal/runtime/validation/validate-agent-options.js\";\nimport type { OTelSpan } from \"./internal/telemetry/tracer.js\";\nimport type { AgentOptions, CustomTool, SDKAgent, SDKAgentInfo } from \"./types/agent.js\";\n\n// ───── agent creation helpers ─────────────────────────────────────────\n\n/** @internal */\nexport async function runCreateUnderSpan(options: AgentOptions, span: OTelSpan): Promise<SDKAgent> {\n // SE8 — normalize a bare-string model id to `{ id }` at this one create seam,\n // so validation + every runtime downstream keeps seeing a `ModelSelection`.\n options = { ...options, model: normalizeModel(options.model) };\n validateAgentOptions(options);\n validateCloudToolParity(options);\n await guardAgainstIdCollision(options);\n await runOnBeforeCreateGate(options);\n const optionsWithHandoffs = await maybeInjectHandoffTools(options);\n const agent =\n optionsWithHandoffs.cloud !== undefined\n ? await createCloudAgent(optionsWithHandoffs)\n : await createLocalAgent(optionsWithHandoffs);\n span.setAttribute(\"agentId\", agent.agentId);\n span.setAttribute(\"workspaceCwd\", resolveWorkspaceCwdForAttr(optionsWithHandoffs.local?.cwd));\n return agent;\n}\n\nasync function guardAgainstIdCollision(options: AgentOptions): Promise<void> {\n if (options.agentId === undefined) return;\n const persistenceCwd = resolveAgentPersistenceCwd(options);\n await hydrateRegistryFromDisk(persistenceCwd);\n if (getRegisteredAgent(options.agentId) !== undefined) {\n throw new ConfigurationError(\n `Agent \"${options.agentId}\" already exists. Use Agent.resume(\"${options.agentId}\") to reattach, or pick a different agentId.`,\n { code: \"agent_id_already_exists\" },\n );\n }\n}\n\nasync function runOnBeforeCreateGate(options: AgentOptions): Promise<void> {\n if (options.onBeforeCreate === undefined) return;\n const userId = typeof options.metadata?.userId === \"string\" ? options.metadata.userId : undefined;\n await options.onBeforeCreate({\n conversationId: options.agentId ?? \"auto\",\n ...(userId !== undefined ? { userId } : {}),\n });\n}\n\nfunction resolveWorkspaceCwdForAttr(cwd: string | string[] | undefined): string {\n if (Array.isArray(cwd)) return cwd[0] ?? process.cwd();\n return cwd ?? process.cwd();\n}\n\nfunction providerFromModelId(modelId: string | undefined): string | undefined {\n if (modelId === undefined) return undefined;\n const slash = modelId.indexOf(\"/\");\n if (slash <= 0) return undefined;\n return modelId.slice(0, slash);\n}\n\nasync function maybeInjectHandoffTools(options: AgentOptions): Promise<AgentOptions> {\n const handoffs = options.handoffs;\n if (handoffs === undefined || handoffs.length === 0) return options;\n if (options.maxHandoffDepth === 0) return options;\n\n interface ToolInjectorModule {\n normalizeHandoffs(\n parentAgentId: string,\n entries: ReadonlyArray<unknown>,\n ): ReadonlyArray<{ descriptor: unknown }>;\n buildHandoffTool(parentAgentId: string, descriptor: unknown, maxDepth: number): CustomTool;\n }\n let mod: ToolInjectorModule;\n try {\n // Dynamic specifier kept in a variable so tsc/bundlers can't statically\n // resolve it at build time — @theokit/sdk-handoff is an optional peer\n // loaded at runtime, and resolving its types here would create a build\n // cycle (sdk-handoff depends on @theokit/sdk). Local ToolInjectorModule\n // mirrors the surface. Same pattern as internal/memory/sdk-memory-peer-loader.ts.\n const spec = \"@theokit/sdk-handoff/internal/tool-injector\";\n mod = (await import(spec)) as unknown as ToolInjectorModule;\n } catch (err) {\n throw new ConfigurationError(\n \"Agent.create({ handoffs: [...] }) requires @theokit/sdk-handoff. \" +\n \"Install it: pnpm add @theokit/sdk-handoff. \" +\n \"Or migrate to the preferred plugin pattern: \" +\n \"plugins: [Handoff.asPlugin({ targets: [...] })] (see docs/migration/1-x-to-2-0.md#handoff).\",\n { code: \"handoff_package_missing\", cause: err },\n );\n }\n const parentAgentId = options.agentId ?? options.name ?? \"anonymous\";\n const normalized = mod.normalizeHandoffs(parentAgentId, handoffs);\n const maxDepth = options.maxHandoffDepth ?? 5;\n const handoffTools = normalized.map(({ descriptor }) =>\n mod.buildHandoffTool(parentAgentId, descriptor, maxDepth),\n );\n const existingTools = options.tools ?? [];\n return {\n ...options,\n tools: [...existingTools, ...handoffTools],\n };\n}\n\nasync function createLocalAgent(options: AgentOptions): Promise<SDKAgent> {\n const apiKey = resolveApiKey(options.apiKey);\n if (apiKey === undefined) {\n throw new AuthenticationError(\"Missing API key\", { code: \"missing_api_key\" });\n }\n const willFlowToProvider = !isFixtureApiKey(apiKey) && !shouldUseRealLocalRuntime(apiKey);\n const shape = validateApiKeyShape(apiKey, {\n strict: willFlowToProvider,\n // `options.model` is already normalized by `runCreateUnderSpan`; `normalizeModel`\n // here is the idempotent narrowing of the widened public type (`{id}` passes\n // through by reference) — cleaner than an `as` cast.\n ...(willFlowToProvider\n ? { provider: providerFromModelId(normalizeModel(options.model)?.id) }\n : {}),\n });\n if (shape.malformed) {\n throw new AuthenticationError(shape.message, { code: \"malformed_api_key\" });\n }\n if (\n !isFixtureApiKey(apiKey) &&\n getConfiguredBaseUrl() === undefined &&\n !shouldUseRealLocalRuntime(apiKey)\n ) {\n throw new AuthenticationError(\"Invalid API key\", {\n code: \"authentication_error\",\n });\n }\n const agent = new LocalAgent(options);\n await agent.initialize();\n return agent;\n}\n\nasync function createCloudAgent(options: AgentOptions): Promise<SDKAgent> {\n const apiKey = resolveApiKey(options.apiKey);\n if (apiKey === undefined) {\n throw new ConfigurationError(\"Missing API key for cloud agent\", {\n code: \"missing_api_key\",\n });\n }\n const shape = validateApiKeyShape(apiKey);\n if (shape.malformed) {\n throw new AuthenticationError(shape.message, { code: \"malformed_api_key\" });\n }\n\n const baseUrl = getConfiguredBaseUrl();\n if (baseUrl === undefined) {\n return new CloudAgent(options);\n }\n\n type CreateResponse = { agentId: string; model?: { id: string } };\n const response = await httpRequest<CreateResponse>(\"/v1/agents\", {\n apiKey,\n method: \"POST\",\n body: {\n model: options.model,\n name: options.name,\n cloud: options.cloud,\n mcpServers: options.mcpServers,\n agents: options.agents,\n },\n });\n const mergedOptions: AgentOptions = {\n ...options,\n agentId: response.agentId,\n ...(response.model !== undefined ? { model: response.model } : {}),\n };\n return new CloudAgent(mergedOptions, response.agentId);\n}\n\n// ───── resume/rehydrate helpers ───────────────────────────────────────\n\n/** @internal */\nexport function resolveAgentPersistenceCwd(options: Partial<AgentOptions>): string {\n const localCwd = options.local?.cwd;\n if (typeof localCwd === \"string\") return localCwd;\n if (Array.isArray(localCwd) && typeof localCwd[0] === \"string\") return localCwd[0];\n return process.cwd();\n}\n\ntype RegisteredAgent = ReturnType<typeof getRegisteredAgent> & object;\n\n/** @internal */\nexport async function rehydrateExistingAgent(\n agentId: string,\n existing: RegisteredAgent,\n options: Partial<AgentOptions>,\n): Promise<SDKAgent> {\n // M47 review F1 — Agent.resume never flows through runCreateUnderSpan, so discovery must ALSO run\n // here: a fresh process resuming a persisted agent whose model targets a plugin provider would\n // otherwise fail provider resolution (the router contract expects discovery to have run upfront).\n await discoverProviderPlugins();\n await validateRehydratedAgent(agentId, existing);\n const mergedLocal =\n options.local !== undefined && existing.options.local !== undefined\n ? { ...existing.options.local, ...options.local }\n : (options.local ?? existing.options.local);\n const mergedOptions: AgentOptions = {\n ...existing.options,\n ...options,\n ...(mergedLocal !== undefined ? { local: mergedLocal } : {}),\n // SE8 — normalize a caller-supplied bare-string model override at this resume\n // boundary (Agent.resume never flows through runCreateUnderSpan). Cloud resume\n // honors it; local resume forces the persisted model below.\n model: normalizeModel(options.model ?? existing.options.model),\n mcpServers: undefined,\n agentId,\n };\n if (existing.runtime === \"cloud\") {\n return new CloudAgent(mergedOptions, agentId);\n }\n // Local resume uses the PERSISTED model (already a normalized `{ id }` from the\n // registry) — a model override on local resume is intentionally not applied.\n const agent = new LocalAgent({ ...mergedOptions, model: existing.options.model });\n await agent.initialize();\n return agent;\n}\n\nasync function validateRehydratedAgent(\n agentId: string,\n entry: { runtime: \"local\" | \"cloud\"; cwd?: string; options: AgentOptions },\n): Promise<void> {\n if (entry.runtime !== \"local\") return;\n const candidate = entry.options.local?.cwd ?? entry.cwd;\n if (typeof candidate !== \"string\") return;\n try {\n const info = await stat(candidate);\n if (!info.isDirectory()) {\n throw new Error(`Workspace path is not a directory: ${candidate}`);\n }\n } catch (cause) {\n throw new UnknownAgentError(\n `Agent \"${agentId}\" cannot be rehydrated — workspace cwd \"${candidate}\" is missing or inaccessible.`,\n { code: \"agent_rehydration_failed\", cause },\n );\n }\n}\n\n// ───── registry info helpers ──────────────────────────────────────────\n\n/** @internal */\nexport function toAgentInfo(agent: RegisteredAgent): SDKAgentInfo {\n return isLocalAgentId(agent.agentId) ? toLocalAgentInfo(agent) : toCloudAgentInfo(agent);\n}\n\nfunction commonAgentInfo(agent: RegisteredAgent, fallbackSummary: string) {\n return {\n agentId: agent.agentId,\n name: agent.name ?? \"Untitled agent\",\n summary: agent.summary ?? fallbackSummary,\n lastModified: agent.lastModified,\n createdAt: agent.createdAt,\n ...(agent.status !== undefined ? { status: agent.status } : {}),\n };\n}\n\nfunction toLocalAgentInfo(agent: RegisteredAgent): SDKAgentInfo {\n return {\n ...commonAgentInfo(agent, \"Local contract fixture\"),\n runtime: \"local\",\n ...(agent.cwd !== undefined ? { cwd: agent.cwd } : {}),\n };\n}\n\nfunction toCloudAgentInfo(agent: RegisteredAgent): SDKAgentInfo {\n return {\n ...commonAgentInfo(agent, \"Cloud contract fixture\"),\n archived: agent.archived,\n runtime: \"cloud\",\n env: { type: \"cloud\" },\n ...(agent.repos !== undefined ? { repos: agent.repos } : {}),\n };\n}\n\n/** @internal */\nexport async function setArchivedFlag(agentId: string, archived: boolean): Promise<void> {\n await getRegisteredAgentOrThrow(agentId);\n updateRegisteredAgent(agentId, { archived });\n await flushRegistrySaves();\n}\n\n/**\n * Set the human-facing `name` on a registered agent (used by `Agent.rename`). Mirrors\n * {@link setArchivedFlag} — validates the agent exists, mutates the registry `name` field, and flushes.\n * @internal\n */\nexport async function setAgentName(agentId: string, name: string): Promise<void> {\n await getRegisteredAgentOrThrow(agentId);\n updateRegisteredAgent(agentId, { name });\n await flushRegistrySaves();\n}\n\n/** @internal */\nexport async function getRegisteredAgentOrThrow(agentId: string): Promise<RegisteredAgent> {\n let agent = getRegisteredAgent(agentId);\n if (agent === undefined) {\n await hydrateRegistryFromDisk(process.cwd());\n agent = getRegisteredAgent(agentId);\n }\n if (agent === undefined) {\n throw new UnknownAgentError(`Agent ${agentId} not found`, { code: \"unknown_agent\" });\n }\n return agent;\n}\n","import { AgentBuilder } from \"./agent-builder.js\";\nimport {\n getRegisteredAgentOrThrow,\n rehydrateExistingAgent,\n resolveAgentPersistenceCwd,\n runCreateUnderSpan,\n setAgentName,\n setArchivedFlag,\n toAgentInfo,\n} from \"./agent-helpers.js\";\nimport {\n AgentRunError,\n ConfigurationError,\n coerceToKnownAgentRunErrorCode,\n UnknownAgentError,\n} from \"./errors.js\";\nimport { enabledPluginNames } from \"./internal/plugins/enabled-names.js\";\nimport { discoverProviderPlugins } from \"./internal/providers/discovery.js\";\nimport { setAgentFacade } from \"./internal/runtime/registry/agent-factory-registry.js\";\nimport {\n flushRegistrySaves,\n getRegisteredAgent,\n hydrateRegistryFromDisk,\n listRegisteredAgents,\n removeRegisteredAgent,\n} from \"./internal/runtime/registry/agent-registry.js\";\nimport {\n type LiveAgentRegistry,\n liveAgentRegistry,\n} from \"./internal/runtime/registry/live-agent-registry.js\";\nimport {\n getRun as getRegisteredRun,\n listRunsByAgent,\n} from \"./internal/runtime/registry/run-registry.js\";\nimport { enqueueSessionWrite } from \"./internal/session/agent-session.js\";\nimport { SPAN_NAMES } from \"./internal/telemetry/span-names.js\";\nimport { createTelemetry, type OTelSpan } from \"./internal/telemetry/tracer.js\";\nimport type {\n AgentDescription,\n AgentOperationOptions,\n AgentOptions,\n GetAgentOptions,\n GetRunOptions,\n ListAgentsOptions,\n ListResult,\n ListRunsOptions,\n SDKAgent,\n SDKAgentInfo,\n} from \"./types/agent.js\";\nimport type { Run, RunResult } from \"./types/run.js\";\nimport type { SessionMessage } from \"./types/session-message.js\";\n\n// T1.8 — memoized dynamic import for streamObject so the second+ call\n// skips the promise resolution chain entirely. Module-level so it\n// survives across Agent.streamObject invocations.\nlet streamObjectImport: Promise<typeof import(\"./stream-object.js\")> | undefined;\n\n/**\n * Result of a one-shot {@link Agent.prompt} call.\n *\n * @public\n */\nexport type AgentPromptResult = RunResult;\n\n/**\n * Static façade for creating and managing Theo agents.\n *\n * @public\n */\nexport class Agent {\n private constructor() {\n // Static-only façade.\n }\n\n /**\n * Live-agent cache for production deploys (Production-Readiness #2, ADRs D307-D310).\n *\n * Caches `SDKAgent` instances by id with LRU eviction (when `size > maxAgents`)\n * and an idle-timeout sweep. Solves the OOM failure mode for long-running\n * Node servers spawning fresh agents per conversation.\n *\n * Defaults: `maxAgents: 100`, `idleTimeoutMs: 30 min`, sweep `60s`.\n * Configure for high-traffic SaaS:\n *\n * ```ts\n * Agent.registry.configure({ maxAgents: 1000, idleTimeoutMs: 15 * 60_000 });\n * process.on(\"SIGTERM\", () => Agent.registry.evictAll());\n * ```\n *\n * Cache hits are automatic in `Agent.getOrCreate` (T2.6). Disable the cache\n * entirely via `configure({ maxAgents: 0 })` — every getOrCreate then\n * re-initializes.\n *\n * @public\n */\n static readonly registry: LiveAgentRegistry = liveAgentRegistry;\n\n /**\n * Create a new agent. Pass either `local` or `cloud` to pick a runtime.\n *\n * @public\n */\n static async create(options: AgentOptions): Promise<SDKAgent> {\n // T0.1: emit `agent.create` span around the FULL factory body so validation\n // throws and quota-gate rejections are recorded with ERROR status before\n // propagating to the caller.\n const telemetry = createTelemetry(options.telemetry);\n const runtime: \"local\" | \"cloud\" = options.cloud !== undefined ? \"cloud\" : \"local\";\n const span: OTelSpan = telemetry.startSpan(SPAN_NAMES.AGENT_CREATE, {\n runtime,\n pluginCount: enabledPluginNames(options.plugins).length,\n });\n try {\n // M47 wiring — provider-plugin discovery runs upfront (the `resolveProviderChain`\n // contract). Idempotent per process; fail-tolerant by design (never throws).\n await discoverProviderPlugins();\n const agent = await runCreateUnderSpan(options, span);\n return agent;\n } catch (err) {\n span.recordException(err);\n span.setStatus({ code: 2, message: err instanceof Error ? err.message : String(err) });\n throw err;\n } finally {\n span.end();\n }\n }\n\n /**\n * One-shot prompt: create an agent, send a single message, wait, dispose.\n *\n * When `options.throwOnError === true`, rejects with `AgentRunError` if\n * the run terminates with `status: 'error'` (instead of resolving with the\n * error wrapped in the RunResult). Cancelled runs still resolve normally.\n *\n * @public\n */\n static async prompt(message: string, options: AgentOptions): Promise<AgentPromptResult> {\n const agent = await Agent.create(options);\n try {\n const run = await agent.send(message);\n const result = await run.wait();\n if (\n options.throwOnError === true &&\n result.status === \"error\" &&\n result.error !== undefined\n ) {\n throw new AgentRunError(result.error.message, {\n code: coerceToKnownAgentRunErrorCode(result.error.code),\n cause: result.error.cause,\n });\n }\n return result;\n } finally {\n // T1.9 — dispose error MUST NOT mask the original error from\n // the try block. A failing dispose is cleanup, not business\n // logic — swallow silently so the consumer always sees the\n // real error (or the real result) from agent.send().\n try {\n await agent.dispose();\n } catch {\n // Swallowed — dispose cleanup must not propagate.\n }\n }\n }\n\n /**\n * Reattach to an existing agent by ID.\n *\n * @public\n */\n static async resume(agentId: string, options: Partial<AgentOptions> = {}): Promise<SDKAgent> {\n let existing = getRegisteredAgent(agentId);\n if (existing === undefined) {\n // D21: fall back to the persisted registry. Different cwds get isolated\n // registry.json files; we read the cwd the caller is operating in.\n const persistenceCwd = resolveAgentPersistenceCwd(options);\n await hydrateRegistryFromDisk(persistenceCwd);\n existing = getRegisteredAgent(agentId);\n }\n if (existing !== undefined) {\n return await rehydrateExistingAgent(agentId, existing, options);\n }\n // Cold miss: throw UnknownAgentError so chat-assistant bots can\n // explicitly branch to `Agent.create({ agentId, ...full options })` on\n // first contact. The previous silent cold-create with the caller's\n // partial options was a footgun — it persisted incomplete agents\n // (no model, no system prompt) that then failed at first send.\n //\n // Migration: callers that want the OLD \"always succeed\" behaviour\n // should catch `UnknownAgentError` and call `Agent.create` themselves.\n throw new UnknownAgentError(\n `Agent \"${agentId}\" not found. Use Agent.create({ agentId, ... }) for first-time setup, or catch UnknownAgentError to branch resume-vs-create.`,\n { code: \"unknown_agent\" },\n );\n }\n\n /**\n * Start building an {@link AgentOptions} via fluent chain. See ADR D25.\n * Terminals: `.build()`, `.create()`, `.getOrCreate(id)`.\n *\n * The builder receives `create` + `getOrCreate` as injected callbacks so\n * that `agent-builder.ts` doesn't need a static import of `Agent` — keeps\n * the module graph acyclic (G6).\n *\n * @public\n */\n static builder(): AgentBuilder {\n return new AgentBuilder({\n create: (options) => Agent.create(options),\n getOrCreate: (agentId, options) => Agent.getOrCreate(agentId, options),\n });\n }\n\n /**\n * Generate a typed object matching a Zod schema via a synthetic forced\n * tool call (ADR D33). One-shot: create transient agent → send prompt →\n * model calls `output` tool → parse args via Zod → return typed.\n *\n * @public\n */\n static async generateObject<T extends import(\"zod\").ZodType>(\n options: import(\"./generate-object.js\").GenerateObjectOptions<T>,\n ): Promise<import(\"./generate-object.js\").GenerateObjectResult<import(\"zod\").z.infer<T>>> {\n const { generateObjectImpl } = await import(\"./generate-object.js\");\n return generateObjectImpl(options, {\n create: (opts) => Agent.create(opts),\n delete: (agentId) => Agent.delete(agentId),\n });\n }\n\n /**\n * Stream a structured output object alongside intermediate `partial`\n * deltas as the model accumulates its response (ADR D39). Returns an\n * `AsyncIterator<StreamObjectEvent<T>>` that yields zero or more\n * `partial` events and exactly one `complete` event at the end.\n *\n * The `complete` event carries the same `object: z.infer<T>` you would get\n * from `Agent.generateObject` — same prompt + schema + model produces\n * the same final object.\n *\n * @public\n */\n static streamObject<T extends import(\"zod\").ZodType>(\n options: import(\"./stream-object.js\").StreamObjectOptions<T>,\n ): AsyncGenerator<\n import(\"./stream-object.js\").StreamObjectEvent<import(\"zod\").z.infer<T>>,\n void,\n void\n > {\n // T1.8 — Lazy-import the implementation; memoized so the second+\n // call skips the promise chain entirely. Consumers that never call\n // streamObject don't pay the import cost at all.\n const deps = {\n create: (opts: import(\"./types/agent.js\").AgentOptions) => Agent.create(opts),\n delete: (agentId: string) => Agent.delete(agentId),\n };\n async function* wrapper() {\n // T1.8 — memoized dynamic import: first call resolves the module;\n // subsequent calls reuse the cached promise (no re-await overhead).\n streamObjectImport ??= import(\"./stream-object.js\");\n const { streamObjectImpl } = await streamObjectImport;\n yield* streamObjectImpl(options, deps);\n }\n return wrapper();\n }\n\n /**\n * Run N prompts in parallel with bounded concurrency (ADRs D134-D140).\n *\n * Each prompt gets a fresh agent (create → send → wait → dispose). Failures\n * are isolated per-prompt; the batch never throws on a single failure —\n * inspect `result.ok` to discriminate success vs error. Default\n * concurrency is 4. When `options.providers.apiKeys` has ≥2 keys per\n * provider, all in-flight agents share a single credential pool via\n * `AsyncLocalStorage` (EC-A) so rate-limit cooldowns are observed once\n * instead of duplicated per agent.\n *\n * Streaming progress is opt-in via `onResult` / `onProgress`. `AbortSignal`\n * cancels pending prompts; in-flight ones continue to completion (Node\n * AbortSignal semantics). `signal.reason` propagates to `error` when set.\n *\n * @public\n */\n static async batch(\n prompts: ReadonlyArray<string | import(\"./types/batch.js\").BatchItem>,\n options: import(\"./types/batch.js\").BatchOptions,\n ): Promise<import(\"./types/batch.js\").BatchResult[]> {\n const { batchImpl } = await import(\"./batch.js\");\n return batchImpl(prompts, options, { create: (opts) => Agent.create(opts) });\n }\n\n /**\n * Get an existing agent by ID, or create one with the supplied options if\n * the ID is not yet registered. Eliminates the resume-vs-create boilerplate\n * common to chat bots and other long-running agent consumers. See ADR D22.\n *\n * Resolution:\n * 1. Try `Agent.resume(agentId, options)`. Return on success.\n * 2. On `UnknownAgentError`, fall through to `Agent.create({ ...options, agentId })`.\n * 3. On same-process race (`ConfigurationError(code: \"agent_id_already_exists\")`\n * during step 2), retry `Agent.resume` once and return the winner's handle.\n * 4. Any other error propagates verbatim.\n *\n * Caveats:\n * - The function-level `agentId` always wins over `options.agentId`.\n * - Options differ between calls? Last-call-wins for this handle (matches `Agent.resume`).\n * - A DISPOSED agent is replaced automatically. `dispose()` evicts the id from the\n * live cache (`liveAgentRegistry.forget`), so the next `getOrCreate(id)` builds a\n * fresh handle — no `Agent.delete(agentId)` needed.\n *\n * This bullet used to say the opposite (\"Disposed agents are NOT auto-deleted...\n * call `Agent.delete(agentId)` first\"). It was measured false in M91:\n * `tests/m91-getorcreate-after-dispose.test.ts` builds an agent, disposes it, and\n * gets a different instance back. The claim was about the PERSISTENT registry and\n * read as being about the live cache — and consumers built around the wrong half.\n * The agent-builder's M85 interrupt rotates the session id to work around a\n * constraint that does not exist.\n *\n * - `close()` marks the handle disposed WITHOUT evicting the cache entry. It is\n * internal and unused today; if it becomes reachable, this bullet stops being true\n * for that path.\n *\n * @public\n */\n static async getOrCreate(agentId: string, options: AgentOptions): Promise<SDKAgent> {\n // T2.6: live-agent cache hit. `get` refreshes lastUsedAt so the entry\n // resists LRU eviction. Cache disabled via `Agent.registry.configure({ maxAgents: 0 })`\n // — set is no-op, get always returns undefined, so re-initialization runs.\n const cached = Agent.registry.get(agentId);\n if (cached !== undefined) return cached;\n\n const fresh = await getOrCreateUncached(agentId, options);\n Agent.registry.set(agentId, fresh);\n return fresh;\n }\n\n /**\n * List agents (local or cloud). M107 — `cwd` is READ now, not ignored;\n * `limit`/`cursor` still are not (see `tests/agent-list-cwd.test.ts`).\n *\n * @public\n */\n static async list(options: ListAgentsOptions = {}): Promise<ListResult<SDKAgentInfo>> {\n const cwd = (\"cwd\" in options ? options.cwd : undefined) ?? process.cwd();\n await hydrateRegistryFromDisk(cwd);\n const items = listRegisteredAgents(options.runtime, cwd).map((agent) => toAgentInfo(agent));\n return { items };\n }\n\n /**\n * Get metadata for a single agent.\n *\n * @public\n */\n static async get(agentId: string, _options: GetAgentOptions = {}): Promise<SDKAgentInfo> {\n const agent = await getRegisteredAgentOrThrow(agentId);\n return toAgentInfo(agent);\n }\n\n /**\n * List runs for an agent.\n *\n * @public\n */\n static async listRuns(agentId: string, _options: ListRunsOptions = {}): Promise<ListResult<Run>> {\n await getRegisteredAgentOrThrow(agentId);\n return { items: listRunsByAgent(agentId) };\n }\n\n /**\n * Get a single run.\n *\n * @public\n */\n static async getRun(runId: string, options: GetRunOptions = {}): Promise<Run> {\n if (options.runtime === \"cloud\") {\n throw new ConfigurationError(\n \"Cloud runtime is pre-release. Theo PaaS endpoints are not wired yet — getRun({ runtime: 'cloud' }) will be enabled when the PaaS ships.\",\n { code: \"cloud_runtime_pre_release\" },\n );\n }\n const existing = getRegisteredRun(runId);\n if (existing !== undefined) return existing;\n throw new UnknownAgentError(\n `Run ${runId} is not in this process's registry. It may have been disposed, persisted in a previous process, or never created.`,\n { code: \"run_not_found\" },\n );\n }\n\n /**\n * Archive a cloud agent.\n *\n * @public\n */\n static archive(agentId: string, _options: AgentOperationOptions = {}): Promise<void> {\n return setArchivedFlag(agentId, true);\n }\n\n /**\n * Restore an archived cloud agent.\n *\n * @public\n */\n static unarchive(agentId: string, _options: AgentOperationOptions = {}): Promise<void> {\n return setArchivedFlag(agentId, false);\n }\n\n /**\n * Set the human-facing `name` of a registered agent (the label `Agent.list()` returns). The registry\n * already carries a `name` field; this is the missing public mutator for it. Runtime-agnostic (mutates\n * the local per-cwd registry for local agents; the cloud registry for cloud agents).\n *\n * @public\n */\n static async rename(\n agentId: string,\n name: string,\n _options: AgentOperationOptions = {},\n ): Promise<void> {\n await setAgentName(agentId, name);\n }\n\n /**\n * M50 — compact a LOCAL agent's persisted session transcript (Codex `/compact` parity): the\n * history is summarized (recent user messages preserved verbatim + one marker'd summary) and an\n * append-only `compact_boundary` + replacement chain is written — resume replays only the\n * replacement + later turns. The summarizer defaults to the compression subsystem's aux-LLM\n * (its first real caller); tests/consumers may inject their own.\n *\n * @public\n */\n static async compact(\n agentId: string,\n options: {\n trigger?: \"manual\" | \"auto\";\n summarize?: (\n messages: readonly import(\"./compaction.js\").CompressibleMessage[],\n ) => Promise<string>;\n } = {},\n ): Promise<import(\"./internal/session/compact-session.js\").CompactResult> {\n let reg = getRegisteredAgent(agentId);\n if (reg === undefined) {\n // Fresh process (e.g. a TUI /compact before any turn): hydrate the per-cwd registry from disk,\n // exactly like Agent.resume does (D21).\n await hydrateRegistryFromDisk(process.cwd());\n reg = getRegisteredAgent(agentId);\n }\n if (reg === undefined || reg.runtime !== \"local\") {\n throw new UnknownAgentError(\n `No local agent \"${agentId}\" registered — compact targets local sessions.`,\n );\n }\n const { compactSessionTranscript, buildDefaultSummarizer } = await import(\n \"./internal/session/compact-session.js\"\n );\n const { cwd, model, store } = await openLocalStore(reg);\n // M50 review F5 — serialize on the per-agent write chain so a manual compact never interleaves\n // with an in-flight turn's persistence.\n return enqueueSessionWrite(cwd, agentId, () =>\n compactSessionTranscript({\n store,\n loc: { cwd, agentId, model },\n sessionId: agentId,\n trigger: options.trigger ?? \"manual\",\n summarize:\n options.summarize ??\n buildDefaultSummarizer({\n agentModel: model,\n ...(reg.options.apiKey !== undefined ? { apiKey: reg.options.apiKey } : {}),\n }),\n }),\n );\n }\n\n /**\n * M51 — inject a SYNTHETIC user+assistant pair into a LOCAL session's persisted transcript WITHOUT\n * running an LLM turn (the Codex review-exit mechanism: the parent thread \"learns\" a result — e.g.\n * review findings — so follow-ups work). Appends onto the DAG leaf and invalidates the in-memory\n * cache; serialized on the per-agent write chain.\n *\n * @public\n */\n static async injectSessionTurn(\n agentId: string,\n turn: { userText: string; assistantText: string },\n ): Promise<void> {\n let reg = getRegisteredAgent(agentId);\n if (reg === undefined) {\n await hydrateRegistryFromDisk(process.cwd());\n reg = getRegisteredAgent(agentId);\n }\n if (reg === undefined || reg.runtime !== \"local\") {\n throw new UnknownAgentError(\n `No local agent \"${agentId}\" registered — injectSessionTurn targets local sessions.`,\n );\n }\n const { injectSessionTurn } = await import(\"./internal/session/inject-session.js\");\n const { cwd, model, store } = await openLocalStore(reg);\n await injectSessionTurn({\n store,\n loc: { cwd, agentId, model },\n sessionId: agentId,\n userText: turn.userText,\n assistantText: turn.assistantText,\n });\n }\n\n /**\n * theokit#146 — read a LOCAL agent's persisted transcript as STRUCTURE, for rendering.\n *\n * A resumed session already replays correctly to the model, but a host had no way to draw it:\n * the only projection available folded a tool call to the string `[tool call] NAME`, dropping the\n * call id and every argument. A card UI got prose, so cross-restart resume was worth less than\n * starting fresh — which is what at least one consumer did.\n *\n * Each returned message carries both projections: `text` (unchanged, what the model replay uses)\n * and `parts` (`text` / `tool_use` / `tool_result` with ids, names, arguments and the\n * `toolUseId` that correlates a result back to its call).\n *\n * Read-only and local-only: it opens the agent's session store and walks the transcript, exactly\n * as {@link Agent.compact} and {@link Agent.injectSessionTurn} do. It appends nothing.\n *\n * @throws UnknownAgentError when `agentId` names no local agent.\n * @public\n */\n static async transcript(agentId: string): Promise<readonly SessionMessage[]> {\n let reg = getRegisteredAgent(agentId);\n if (reg === undefined) {\n // Fresh process (e.g. a TUI restoring its scrollback before any turn): hydrate the per-cwd\n // registry from disk, exactly like Agent.resume does (D21).\n await hydrateRegistryFromDisk(process.cwd());\n reg = getRegisteredAgent(agentId);\n }\n if (reg === undefined || reg.runtime !== \"local\") {\n throw new UnknownAgentError(\n `No local agent \"${agentId}\" registered — transcript targets local sessions.`,\n );\n }\n const { readSessionMessages } = await import(\"./internal/session/agent-session-store.js\");\n const { store } = await openLocalStore(reg);\n return readSessionMessages(store, agentId);\n }\n\n /**\n * theokit#123 — read-only introspection of a registered agent's tools and subagents.\n *\n * `Agent.list()` / `Agent.get()` enumerate agents and `agent.skills.list()` covers skills, but\n * tools and subagents lived only on `RegisteredAgent.options` — an internal contract. A\n * reflection endpoint (theokit-studio's `theokit dev`) therefore had to report empty lists for\n * both, and say so with an `unavailable_reason`.\n *\n * A PROJECTION, not the options object. Tool handlers and subagent prompts are stripped: a\n * handler is an executable that cannot cross a process boundary, and a prompt is the agent's\n * instructions rather than its signature — a reflection endpoint serializes what it is handed.\n *\n * @throws UnknownAgentError when `agentId` names no registered agent.\n * @public\n */\n static async describe(agentId: string): Promise<AgentDescription> {\n const agent = await getRegisteredAgentOrThrow(agentId);\n // theokit#123 — subagents are RESOLVED, not read off the declaration.\n //\n // The runtime's set is `loadSubagents(cwd, project?, inline)`: file-based roles from\n // `.theokit/agents/*.md` merged with the inline `agentOptions.agents`, and it is never written\n // back into `options`. Projecting `options.agents` therefore reported a disk-defined subagent as\n // absent — and because this shape promises arrays so a caller can tell \"none\" from \"unknown\",\n // that under-report was indistinguishable from an honest empty. The exact ambiguity the issue\n // asked to remove.\n const { loadSubagents } = await import(\"./internal/runtime/skills/subagents-loader.js\");\n const settingSources = agent.options.local?.settingSources;\n const subagents = await loadSubagents(\n agent.cwd ?? process.cwd(),\n settingSources === undefined || settingSources.includes(\"project\"),\n agent.options.agents,\n );\n return {\n agentId: agent.agentId,\n runtime: agent.runtime,\n ...(agent.model !== undefined ? { model: agent.model } : {}),\n // Always arrays, so a caller can tell \"this agent has none\" from \"the SDK did not say\".\n //\n // Honest limit, stated because the alternative is an implied claim: `tools` is still the\n // DECLARED catalog. Plugin tools and the reasoning `think` tool are assembled per run by\n // `buildCustomToolsInput`, so they are not knowable from the registry alone. Documented on\n // `AgentDescription.tools`.\n tools: (agent.options.tools ?? []).map((tool) => ({\n name: tool.name,\n description: tool.description,\n inputSchema: tool.inputSchema,\n })),\n subagents: Object.entries(subagents).map(([name, def]) => ({\n name,\n description: def.description,\n ...(def.model !== undefined ? { model: def.model } : {}),\n ...(def.tools !== undefined ? { tools: def.tools } : {}),\n })),\n };\n }\n\n /**\n * Permanently delete a cloud agent.\n *\n * @public\n */\n static async delete(agentId: string, _options: AgentOperationOptions = {}): Promise<void> {\n removeRegisteredAgent(agentId);\n await flushRegistrySaves();\n }\n}\n\nasync function getOrCreateUncached(agentId: string, options: AgentOptions): Promise<SDKAgent> {\n try {\n return await Agent.resume(agentId, options);\n } catch (err) {\n if (!(err instanceof UnknownAgentError)) throw err;\n }\n try {\n return await Agent.create({ ...options, agentId });\n } catch (err) {\n if (err instanceof ConfigurationError && err.code === \"agent_id_already_exists\") {\n return await Agent.resume(agentId, options);\n }\n throw err;\n }\n}\n\n// Module-init registration so internal subsystems (LocalAgent.runUntil /\n// LocalAgent.fork, eval, scorers, cron) can invoke the public facade without\n// inverting the public-api -> internal dependency direction. See\n// `internal/runtime/registry/agent-factory-registry.ts` for rationale.\nsetAgentFacade({\n create: (options) => Agent.create(options),\n delete: (agentId) => Agent.delete(agentId),\n prompt: (message, options) => Agent.prompt(message, options),\n get: (agentId) => Agent.get(agentId),\n resume: (agentId, options) => Agent.resume(agentId, options),\n batch: (prompts, options) => Agent.batch(prompts, options),\n});\n\n/**\n * Opens the local session store of a registered agent.\n *\n * This was duplicated across `Agent.compact` and `Agent.injectSessionTurn` — both resolved `cwd` and\n * `model` (with the same three-level fallback) and built the `FsSessionStore` with the same\n * `baseDir`. That is duplicated KNOWLEDGE: \"how to locate a local agent's transcript\" is ONE rule,\n * and fixing one copy without the other would make `compact` and `injectSessionTurn` operate on\n * different files — silent corruption, not an error.\n */\nasync function openLocalStore(reg: {\n cwd?: string;\n model?: { id: string };\n options: { model?: string | { id: string }; local?: { baseDir?: string } };\n}): Promise<{\n cwd: string;\n model: string;\n store: import(\"./internal/persistence/fs-session-store.js\").FsSessionStore;\n}> {\n const cwd = reg.cwd ?? process.cwd();\n const optModel = reg.options.model;\n const model =\n reg.model?.id ?? (typeof optModel === \"string\" ? optModel : optModel?.id) ?? \"unknown\";\n const { FsSessionStore } = await import(\"./internal/persistence/fs-session-store.js\");\n const { defaultBaseDir, expandTilde } = await import(\n \"./internal/persistence/session-transcript.js\"\n );\n const baseDir =\n reg.options.local?.baseDir !== undefined\n ? expandTilde(reg.options.local.baseDir)\n : defaultBaseDir();\n return { cwd, model, store: new FsSessionStore({ baseDir, cwd }) };\n}\n"]}