@theokit/sdk 5.1.0 → 5.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +88 -0
- package/dist/{agent-ARLOD4JX.cjs → agent-GACKKINM.cjs} +7 -7
- package/dist/{agent-ARLOD4JX.cjs.map → agent-GACKKINM.cjs.map} +1 -1
- package/dist/{agent-N6WJ54ML.js → agent-VUNM33WJ.js} +6 -6
- package/dist/{agent-N6WJ54ML.js.map → agent-VUNM33WJ.js.map} +1 -1
- package/dist/{chunk-OYD3U3LY.js → chunk-43H4EBS2.js} +7 -7
- package/dist/{chunk-OYD3U3LY.js.map → chunk-43H4EBS2.js.map} +1 -1
- package/dist/{chunk-AW6F6HZR.js → chunk-AI4MXACC.js} +3 -3
- package/dist/{chunk-AW6F6HZR.js.map → chunk-AI4MXACC.js.map} +1 -1
- package/dist/{chunk-D3CCY3A2.cjs → chunk-DEJCKB65.cjs} +39 -39
- package/dist/{chunk-D3CCY3A2.cjs.map → chunk-DEJCKB65.cjs.map} +1 -1
- package/dist/{chunk-OQRGVTQF.js → chunk-DLFWMJE3.js} +3 -3
- package/dist/{chunk-OQRGVTQF.js.map → chunk-DLFWMJE3.js.map} +1 -1
- package/dist/{chunk-NYQ3IS7K.cjs → chunk-DWB3CN46.cjs} +8 -3
- package/dist/chunk-DWB3CN46.cjs.map +1 -0
- package/dist/{chunk-QYLZQ43D.cjs → chunk-IQBDR5YZ.cjs} +5 -5
- package/dist/{chunk-QYLZQ43D.cjs.map → chunk-IQBDR5YZ.cjs.map} +1 -1
- package/dist/{chunk-67SBTGMA.cjs → chunk-PEAOQMWE.cjs} +4 -4
- package/dist/{chunk-67SBTGMA.cjs.map → chunk-PEAOQMWE.cjs.map} +1 -1
- package/dist/{chunk-WMWEI3NS.js → chunk-RP3VXJMA.js} +8 -3
- package/dist/chunk-RP3VXJMA.js.map +1 -0
- package/dist/{chunk-KGANQYP7.cjs → chunk-SSIRPWWD.cjs} +5 -5
- package/dist/{chunk-KGANQYP7.cjs.map → chunk-SSIRPWWD.cjs.map} +1 -1
- package/dist/{chunk-XU6MLSC6.js → chunk-WHTMFN4Q.js} +3 -3
- package/dist/{chunk-XU6MLSC6.js.map → chunk-WHTMFN4Q.js.map} +1 -1
- package/dist/{context-4QOEWRDF.cjs → context-3YMZDEX5.cjs} +7 -7
- package/dist/{context-4QOEWRDF.cjs.map → context-3YMZDEX5.cjs.map} +1 -1
- package/dist/context-XNREEC7M.js +6 -0
- package/dist/{context-Z3CFTT3H.js.map → context-XNREEC7M.js.map} +1 -1
- package/dist/cron.cjs +6 -6
- package/dist/cron.js +5 -5
- package/dist/eval.cjs +5 -5
- package/dist/eval.js +4 -4
- package/dist/index.cjs +55 -21
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +66 -1
- package/dist/index.d.ts +66 -1
- package/dist/index.js +41 -8
- package/dist/index.js.map +1 -1
- package/dist/internal/persistence/index.cjs +4 -4
- package/dist/internal/persistence/index.js +1 -1
- package/dist/internal/runtime/compat/foreign-config-sources.d.ts +16 -6
- package/dist/subagents-loader-7G76XOZU.cjs +16 -0
- package/dist/{subagents-loader-GEHYCMEX.cjs.map → subagents-loader-7G76XOZU.cjs.map} +1 -1
- package/dist/subagents-loader-PAZVOZHI.js +7 -0
- package/dist/{subagents-loader-DOBTTICM.js.map → subagents-loader-PAZVOZHI.js.map} +1 -1
- package/dist/subagents-loader.cjs +3 -3
- package/dist/subagents-loader.js +2 -2
- package/docs/harness-capability-map.md +4 -1
- package/package.json +1 -1
- package/dist/chunk-NYQ3IS7K.cjs.map +0 -1
- package/dist/chunk-WMWEI3NS.js.map +0 -1
- package/dist/context-Z3CFTT3H.js +0 -6
- package/dist/subagents-loader-DOBTTICM.js +0 -7
- package/dist/subagents-loader-GEHYCMEX.cjs +0 -16
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/agent-factory.ts","../src/approval-policy.ts","../src/blast-radius.ts","../src/internal/budget/calendar-window.ts","../src/internal/budget/ledger.ts","../src/internal/budget/registry.ts","../src/internal/budget/enforcement.ts","../src/internal/budget/normalize-usage.ts","../src/budget.ts","../src/built-in-processors.ts","../src/create-skill.ts","../src/credential-presence.ts","../src/define-provider.ts","../src/define-skill-read-tool.ts","../src/env-reachability.ts","../src/event-bus.ts","../src/goal-loop.ts","../src/internal/budget/tracker/budget-tracker-counter.ts","../src/internal/plugins/types.ts","../src/internal/runtime/memory-glue/memory-provider-noop.ts","../src/job-queue.ts","../src/layer-fold.ts","../src/internal/memory/dreaming/phases.ts","../src/internal/memory/dreaming/run.ts","../src/internal/memory/sdk-memory-peer-loader.ts","../src/memory.ts","../src/memory-adapter-helpers.ts","../src/migrate.ts","../src/permission-engine.ts","../src/permission-plugin.ts","../src/project-env.ts","../src/reap-plan.ts","../src/schema-normalizer.ts","../src/security.ts","../src/security-floor.ts","../src/session-guard.ts","../src/session-messages.ts","../src/session-scope.ts","../src/squad.ts","../src/task.ts","../src/internal/catalog/fixtures.ts","../src/internal/catalog/local-models.ts","../src/theokit.ts","../src/tool-blast-radius.ts","../src/trajectory-helpers.ts","../src/trust-posture.ts","../src/wiring-record.ts"],"names":["Agent","withCwdMutex","list","ConfigurationError","BudgetExceededError","diag","estimateTokens","CHARS_PER_TOKEN","createHash","registerBuiltins","listProviders","parseModelId","z","toJsonSchema","fn","randomUUID","TheokitAgentError","kept","resolveMemoryRoot","readFactsFromMarkdown","appendDiaryEntry","join","mkdir","replaceFileAtomic","MEMORY_EMBEDDING_ADAPTERS","MemoryAdapterError","migrateSqliteToLance","redactSecrets","addPattern","readSessionMessages","resolveSessionDir","FsSessionStore","Workflow","agentStep","configure","submit","get","cancel","subscribe","DEFAULT_AGENTIC_MODEL_ID","mapOllamaTransportError","readErrorResponseBody","mapOllamaHttpError","getCatalogCapabilities","discoverProviderPlugins","getProviderProfile","resolveApiKey","AuthenticationError","shouldUseFixtureMode","isFixtureApiKey","htt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AAA,GAAO,wBAAA;AAC3B;AAoEO,SAAS,aACd,KAAA,EACkC;AAClC,EAAA,MAAM,SAAS,EAAC;AAChB,EAAA,KAAA,MAAW,CAAC,YAAY,SAAS,CAAA,IAAK,OAAO,OAAA,CAAQ,KAAA,CAAM,SAAS,CAAA,EAG/D;AACH,IAAA,MAAM,OAAA,GAAU,KAAA,CAAM,OAAA,CAAQ,MAAA,CAAO,UAAU,CAAA;AAC/C,IAAA,IAAI,YAAY,MAAA,EAAW;AAIzB,MAAA,MAAM,IAAI,sBAAA;AAAA,QACR,CAAA,aAAA,EAAgB,UAAU,CAAA,mFAAA,EACG,MAAA,CAAO,IAAA,CAAK,KAAA,CAAM,OAAA,CAAQ,MAAM,CAAA,CAAE,IAAA,CAAK,IAAI,CAAA,IAAK,QAAQ,CAAA;AAAA,OACvF;AAAA,IACF;AACA,IAAA,MAAA,CAAO,UAAU,CAAA,GAAI;AAAA;AAAA,MAEnB,QAAQ,OAAA,GAAU,CAAC,GAAG,SAAS,IAAI,EAAC;AAAA,MACpC,SAAA,EAAW,CAAC,GAAG,SAAS,CAAA;AAAA,MACxB,iBAAA,EAAmB,CAAC,OAAA,IAAW,SAAA,CAAU,MAAA,GAAS;AAAA,KACpD;AAAA,EACF;AACA,EAAA,OAAO,MAAA;AACT","file":"index.cjs","sourcesContent":["import { Agent } from \"./agent.js\";\nimport type { AgentOptions, SDKAgent } from \"./types/agent.js\";\n\n/**\n * Handle returned by {@link createAgentFactory}. See ADR D23 for merge\n * semantics.\n *\n * @public\n */\nexport interface AgentFactory {\n /**\n * Create a fresh agent for this session. Equivalent to `Agent.create(merged)`\n * where `merged` is `common` ⊕ `overrides` ⊕ `{ agentId }`.\n */\n forSession(agentId: string, overrides?: Partial<AgentOptions>): Promise<SDKAgent>;\n /**\n * Resume an existing agent for this session, or create one if the ID is\n * unknown. Equivalent to `Agent.getOrCreate(agentId, merged)`.\n */\n getOrCreate(agentId: string, overrides?: Partial<AgentOptions>): Promise<SDKAgent>;\n}\n\n/**\n * Capture a common {@link AgentOptions} prefix and produce per-session agents\n * with focused overrides. Useful for chat-bot patterns where most config is\n * shared across users/sessions.\n *\n * Merge rules (ADR D23):\n * - Top-level shallow merge with `overrides` winning.\n * - Deep merge for `local`, `memory`, `cloud` (configuration objects with\n * non-conflicting flat keys).\n * - Total replace for `mcpServers`, `agents`, `tools`, `providers`,\n * `plugins`, `skills`, `context` (collection-shaped).\n * - The function-level `agentId` always wins over both `common.agentId` and\n * `overrides.agentId`.\n *\n * The factory holds `common` by reference — mutating it after construction\n * leaks to subsequent `forSession` calls (documented caveat).\n *\n * @public\n */\nfunction createAgentFactory(common: Partial<AgentOptions>): AgentFactory {\n return {\n forSession: (agentId, overrides) => Agent.create(mergeAgentOptions(common, overrides, agentId)),\n getOrCreate: (agentId, overrides) =>\n Agent.getOrCreate(agentId, mergeAgentOptions(common, overrides, agentId)),\n };\n}\n\n/**\n * Merge factory `common` config with per-session `overrides`, forcing the\n * function-level `agentId`. Deep-merges the 3 configuration-shaped fields\n * (`local`, `memory`, `cloud`); replaces collection-shaped fields.\n *\n * @internal\n */\nfunction mergeAgentOptions(\n common: Partial<AgentOptions>,\n overrides: Partial<AgentOptions> | undefined,\n agentId: string,\n): AgentOptions {\n const o = overrides ?? {};\n const merged: Partial<AgentOptions> = { ...common, ...o };\n const local = deepMergeLocal(common.local, o.local);\n if (local !== undefined) merged.local = local;\n const memory = deepMergeMemory(common.memory, o.memory);\n if (memory !== undefined) merged.memory = memory;\n const cloud = deepMergeCloud(common.cloud, o.cloud);\n if (cloud !== undefined) merged.cloud = cloud;\n merged.agentId = agentId;\n return merged as AgentOptions;\n}\n\nfunction deepMergeLocal(\n base: AgentOptions[\"local\"],\n top: AgentOptions[\"local\"],\n): AgentOptions[\"local\"] | undefined {\n if (base === undefined && top === undefined) return undefined;\n return { ...(base ?? {}), ...(top ?? {}) };\n}\n\nfunction deepMergeMemory(\n base: AgentOptions[\"memory\"],\n top: AgentOptions[\"memory\"],\n): AgentOptions[\"memory\"] | undefined {\n if (base === undefined && top === undefined) return undefined;\n return {\n ...(base ?? {}),\n ...(top ?? {}),\n enabled: top?.enabled ?? base?.enabled ?? false,\n };\n}\n\nfunction deepMergeCloud(\n base: AgentOptions[\"cloud\"],\n top: AgentOptions[\"cloud\"],\n): AgentOptions[\"cloud\"] | undefined {\n if (base === undefined && top === undefined) return undefined;\n return { ...(base ?? {}), ...(top ?? {}) };\n}\n\n/** SE36 — `AgentFactory.create` replaces `createAgentFactory` (ADR 0015). Merges with the `AgentFactory` interface. @public */\n// biome-ignore lint/suspicious/noUnsafeDeclarationMerging: SE36 namespace class merges with the `AgentFactory` instance interface (ADR 0015) — intentional; `create()` returns the interface type, `new` is blocked by the private ctor.\nexport class AgentFactory {\n private constructor() {}\n static create(common: Partial<AgentOptions>): AgentFactory {\n return createAgentFactory(common);\n }\n}\n","/**\n * Decide whether a tool call proceeds, and say WHY — as a typed signal rather than a tool result.\n *\n * When a veto is delivered as an ordinary tool result, the MODEL reads it as output: it sees a\n * string, concludes the tool failed for some reason, and retries or works around it. A denial, an\n * error, and a tool that legitimately returned the word \"denied\" become indistinguishable to\n * everything downstream — including the surface that should be telling the user what happened.\n *\n * ## What is generic, and what is not\n *\n * The RULE is a precedence: an explicit per-tool decision outranks the mode, a convenience mode does\n * not overturn an explicit refusal, and anything undecided falls to the mode. The VOCABULARY is not\n * — which tools exist belongs to the product and arrives as data. Nothing here names one.\n *\n * Deliberately separate from the blast-radius policy: that one answers \"what does this action\n * reach\", this one answers \"who said yes\". Keeping them apart is what lets a product gate on reach\n * without re-implementing the mode ladder, and compose both where it needs to.\n *\n * @public\n */\n\n/** What the operator chose for everything not decided per tool. @public */\nexport type ApprovalMode = \"ask\" | \"never-ask\" | \"refuse-all\";\n\n/**\n * The three answers a policy can give: proceed, put the call in front of a human, or stop it.\n *\n * `ask` is not a softer `deny`. A surface with no way to reach a human must treat it as a refusal,\n * because treating it as permission is how an unattended run approves everything it was meant to\n * pause on.\n *\n * @public\n */\nexport type ApprovalOutcome = \"allow\" | \"ask\" | \"deny\";\n\n/**\n * Which rule produced the outcome.\n *\n * The `explicitly-` pair means a per-tool list decided it; the `mode-` triple means no list named\n * the tool and the operator's mode decided instead. Worth rendering alongside the outcome: \"you\n * denied this tool\" and \"your mode refuses everything\" send the operator to different settings.\n *\n * @public\n */\nexport type ApprovalReason =\n | \"explicitly-allowed\"\n | \"explicitly-denied\"\n | \"mode-ask\"\n | \"mode-never-ask\"\n | \"mode-refuse-all\";\n\n/**\n * One tool call to decide on, plus the operator's configuration.\n *\n * `tool` is matched against `denied` and `allowed` by exact string equality — there is no pattern\n * or prefix rule. Both lists default to empty, so with neither supplied every call is decided by\n * `mode` alone.\n *\n * @public\n */\nexport interface ApprovalInput {\n readonly tool: string;\n readonly mode: ApprovalMode;\n /** Tools the operator allowed once and for all. */\n readonly allowed?: readonly string[];\n /** Tools the operator refused. Outranks `allowed` and every mode. */\n readonly denied?: readonly string[];\n}\n\n/**\n * The answer, the rule that produced it, and the tool it was about.\n *\n * @public\n */\nexport interface ApprovalDecision {\n readonly outcome: ApprovalOutcome;\n readonly reason: ApprovalReason;\n /** The tool the decision was about, so a surface names it without re-deriving it. */\n readonly tool: string;\n}\n\nconst BY_MODE: Readonly<\n Record<ApprovalMode, { outcome: ApprovalOutcome; reason: ApprovalReason }>\n> = {\n ask: { outcome: \"ask\", reason: \"mode-ask\" },\n \"never-ask\": { outcome: \"allow\", reason: \"mode-never-ask\" },\n \"refuse-all\": { outcome: \"deny\", reason: \"mode-refuse-all\" },\n};\n\n/**\n * Decide one tool call against the operator's lists and mode.\n *\n * The precedence is fixed and each step short-circuits: `denied` is consulted first, then\n * `allowed`, then `mode`. A tool named in BOTH lists is therefore denied — a contradictory config\n * is read restrictively, because the usual cause is an allow-entry that outlived the denial meant\n * to replace it.\n *\n * This answers only who said yes. What the call REACHES is a separate question with a separate\n * policy — `evaluateBlastRadius` — and neither consults the other, so a product that wants both\n * gates calls both and combines the outcomes itself.\n *\n * @returns the outcome, why it was reached, and the tool it was about.\n * @public\n */\nexport function decideApproval(input: ApprovalInput): ApprovalDecision {\n const { tool } = input;\n\n // Denial first, and it outranks everything. A contradictory config — a tool in both lists — is a\n // product bug, and the safe reading is the restrictive one: silently taking the permissive side is\n // how a stale allow-entry outlives the denial that was meant to replace it.\n if ((input.denied ?? []).includes(tool)) {\n return { outcome: \"deny\", reason: \"explicitly-denied\", tool };\n }\n if ((input.allowed ?? []).includes(tool)) {\n return { outcome: \"allow\", reason: \"explicitly-allowed\", tool };\n }\n\n const fromMode = BY_MODE[input.mode];\n return { outcome: fromMode.outcome, reason: fromMode.reason, tool };\n}\n","/**\n * Decide an action by what it REACHES and whether it can be undone — not by its name.\n *\n * A sandbox answers \"which files may this process touch\", and that is a different question from the\n * one that decides whether an action is safe. A tool that drops a production database touches no\n * file the sandbox cares about; a tool that lists pods reaches an entire cluster while writing\n * nothing. Confinement covers the disk, not the reach.\n *\n * With nothing better available, every product gates on the tool's NAME: an allowlist of strings\n * that says nothing about what the tool does, drifts the moment one is renamed, and cannot be\n * reasoned about by anyone who did not write it. A guard each product re-implements is a guard some\n * product forgets.\n *\n * ## What is generic here, and what is not\n *\n * The RULE is: an action declares the scope it reaches and whether it is reversible, and a policy\n * decides from those two facts plus what the operator granted. The VOCABULARY is not — which scopes\n * exist (\"cluster:prod\", \"billing-account\", \"the laptop\") belongs to the product and arrives as\n * data. Nothing in this module names a scope, the same way the security floor names no sandbox mode\n * and the trust posture names no capability.\n *\n * ## Why the reason is part of the answer\n *\n * \"The sandbox stopped this\" and \"you never granted reach to that scope\" are different facts with\n * different fixes, and an operator told the wrong one widens the wrong thing. So a decision carries\n * WHY — the same reason a trust posture reports its `source` and a wiring record distinguishes\n * withheld-by-trust from never-configured.\n *\n * @public\n */\n\n/** What an action reaches, and whether it can be taken back. @public */\nexport interface DeclaredAction {\n /**\n * The product's name for what this action reaches. An empty string is treated as UNDECLARED and\n * refused: a tool that forgot to declare is not a tool that reaches nothing.\n */\n readonly scope: string;\n /**\n * Whether the action can be undone. Reversible actions inside a granted scope proceed;\n * irreversible ones ask, because granting reach is not granting destruction.\n */\n readonly reversible: boolean;\n}\n\n/**\n * The action to decide on, plus what the operator granted.\n *\n * `granted` is matched against `action.scope` by exact string equality: there is no prefix or\n * wildcard rule, so granting `cluster:prod` does not grant `cluster:prod:kube-system`. A product\n * that wants hierarchical scopes expands them itself before calling.\n *\n * `irreversibleAllowed` defaults to empty, so an irreversible action inside a granted scope asks\n * for approval unless its scope was pre-approved for destruction as well.\n *\n * @public\n */\nexport interface BlastRadiusInput {\n readonly action: DeclaredAction;\n /** Scopes the operator granted reach to. Empty grants nothing — never everything. */\n readonly granted: readonly string[];\n /** Scopes where the operator pre-approved irreversible actions, so an unattended run can work. */\n readonly irreversibleAllowed?: readonly string[];\n}\n\n/**\n * What the policy decided.\n *\n * `require-approval` means a human has to say yes before the action runs; a caller with no way to\n * ask must treat it as a refusal. `refuse` is not appealable through this policy at all — the\n * operator has to grant the scope first, which is deliberately a configuration change rather than\n * a prompt.\n *\n * @public\n */\nexport type BlastRadiusOutcome = \"allow\" | \"require-approval\" | \"refuse\";\n\n/** Why the decision came out that way. Rendered to the operator and read by an audit. @public */\nexport type BlastRadiusReason =\n | \"within-granted-scope\"\n | \"irreversible\"\n | \"scope-not-granted\"\n | \"scope-undeclared\";\n\n/**\n * The outcome, the rule that produced it, and the scope it was decided about.\n *\n * `scope` echoes what the action declared, so it is the empty string when the reason is\n * `scope-undeclared` — the decision names what it saw rather than substituting a placeholder.\n *\n * @public\n */\nexport interface BlastRadiusDecision {\n readonly outcome: BlastRadiusOutcome;\n readonly reason: BlastRadiusReason;\n /** The scope the decision was made about, so a surface can name it without re-deriving it. */\n readonly scope: string;\n}\n\n/**\n * Decide one declared action against the scopes the operator granted.\n *\n * Four checks, in this order, each short-circuiting: an empty `scope` is refused as undeclared\n * before any comparison happens; a scope absent from `granted` is refused; an irreversible action\n * whose scope is not in `irreversibleAllowed` escalates to approval; anything left is allowed.\n *\n * Refusal outranking escalation is a decision, not an accident. Asking a human to approve a scope\n * the operator never granted trains them to approve by reflex, which is how an approval prompt\n * stops being a control.\n *\n * This decides reach only. Whether the operator permitted the tool at all is `decideApproval`, and\n * the two are independent.\n *\n * @returns the outcome with the reason and the scope it was decided on.\n * @public\n */\nexport function evaluateBlastRadius(input: BlastRadiusInput): BlastRadiusDecision {\n const { scope, reversible } = input.action;\n\n // Undeclared first: a tool that forgot to declare must not fall through to a scope comparison\n // against `\"\"`, which any product using an empty-string scope would accidentally satisfy.\n if (scope.length === 0) {\n return { outcome: \"refuse\", reason: \"scope-undeclared\", scope };\n }\n\n // Refusal outranks approval, deliberately. Asking a human to approve something the operator never\n // granted reach for teaches them to approve by reflex, which is how an approval prompt stops\n // being a control.\n if (!input.granted.includes(scope)) {\n return { outcome: \"refuse\", reason: \"scope-not-granted\", scope };\n }\n\n if (!reversible && !(input.irreversibleAllowed ?? []).includes(scope)) {\n return { outcome: \"require-approval\", reason: \"irreversible\", scope };\n }\n\n return { outcome: \"allow\", reason: \"within-granted-scope\", scope };\n}\n","/**\n * UTC-aligned calendar window helpers (ADR D382).\n *\n * - `1h` — relative (now - 1 hour).\n * - `1d` — UTC midnight (current UTC day).\n * - `1w` — UTC monday 00:00:00 (current UTC week, Monday is week start).\n * - `30d` — relative 30 days.\n * - `365d` — relative 365 days.\n *\n * `1d` and `1w` are calendar-aligned because users expect \"1 USD per day\"\n * = \"since midnight UTC\", not a rolling 24h.\n * `30d`/`365d` are relative because nobody expects \"since the 1st\".\n *\n * @internal\n */\n\nimport type { BudgetWindow } from \"../../types/budget.js\";\n\nexport function startOfDayUtc(now: Date = new Date()): Date {\n return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));\n}\n\nexport function startOfWeekUtc(now: Date = new Date()): Date {\n // ISO 8601 week starts on Monday. getUTCDay() returns 0 (Sun) .. 6 (Sat).\n const dayOfWeek = now.getUTCDay();\n const daysSinceMonday = (dayOfWeek + 6) % 7; // Mon=0, Sun=6\n const start = startOfDayUtc(now);\n start.setUTCDate(start.getUTCDate() - daysSinceMonday);\n return start;\n}\n\nconst MS_PER_HOUR = 60 * 60 * 1000;\nconst MS_PER_DAY = 24 * MS_PER_HOUR;\n\n/** Returns the inclusive start timestamp (ms) for the given window relative to `now`. */\nexport function windowStartMs(window: BudgetWindow, now: Date = new Date()): number {\n switch (window) {\n case \"1h\":\n return now.getTime() - MS_PER_HOUR;\n case \"1d\":\n return startOfDayUtc(now).getTime();\n case \"1w\":\n return startOfWeekUtc(now).getTime();\n case \"30d\":\n return now.getTime() - 30 * MS_PER_DAY;\n case \"365d\":\n return now.getTime() - 365 * MS_PER_DAY;\n default: {\n const _exhaustive: never = window;\n throw new Error(`unreachable window: ${_exhaustive as string}`);\n }\n }\n}\n","/**\n * In-process Budget ledger (ADR D385).\n *\n * Singleton mutex-protected. Stores per-budget ChargeLog[] arrays;\n * `spentIn(window)` filters by timestamp.\n *\n * EC-6: GC eviction runs INSIDE the same mutex as charge — no race.\n * EC-9: charge() is called inside the same critical section as preflight\n * check by Budget enforcement.\n *\n * Persistence cross-restart: deferred to v0.2 (JsonFile pattern).\n *\n * @internal\n */\n\nimport type { BudgetWindow } from \"../../types/budget.js\";\nimport { withCwdMutex } from \"../persistence/cwd-mutex.js\";\nimport { windowStartMs } from \"./calendar-window.js\";\n\ninterface ChargeLog {\n timestamp: number;\n amountUsd: number;\n}\n\nconst MS_PER_YEAR = 365 * 24 * 60 * 60 * 1000;\nconst GC_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes\nconst GC_LOGS_THRESHOLD = 10_000;\n\ninterface LedgerState {\n readonly logs: Map<string, ChargeLog[]>;\n lastGcAt: number;\n}\n\nlet state: LedgerState = {\n logs: new Map(),\n lastGcAt: Date.now(),\n};\n\nconst MUTEX_KEY = \"budget-ledger\";\n\nfunction shouldGc(now: number): boolean {\n if (now - state.lastGcAt < GC_INTERVAL_MS) return false;\n let totalLogs = 0;\n for (const arr of state.logs.values()) totalLogs += arr.length;\n return totalLogs > GC_LOGS_THRESHOLD;\n}\n\nfunction gcOlderThanOneYear(now: number): void {\n const cutoff = now - MS_PER_YEAR;\n for (const [name, arr] of state.logs.entries()) {\n const kept = arr.filter((l) => l.timestamp >= cutoff);\n if (kept.length === 0) state.logs.delete(name);\n else state.logs.set(name, kept);\n }\n state.lastGcAt = now;\n}\n\n/** Charge a budget. Idempotent across concurrent calls via withCwdMutex. */\nexport async function charge(name: string, amountUsd: number): Promise<void> {\n if (amountUsd <= 0) return;\n await withCwdMutex(MUTEX_KEY, async () => {\n const now = Date.now();\n const list = state.logs.get(name) ?? [];\n list.push({ timestamp: now, amountUsd });\n state.logs.set(name, list);\n if (shouldGc(now)) gcOlderThanOneYear(now);\n });\n}\n\n/** Return total spend in the given window for `name`. Snapshot read (no mutex needed). */\nexport function spentIn(name: string, window: BudgetWindow, now: Date = new Date()): number {\n const arr = state.logs.get(name);\n if (arr === undefined) return 0;\n const sinceMs = windowStartMs(window, now);\n let total = 0;\n for (const log of arr) {\n if (log.timestamp >= sinceMs) total += log.amountUsd;\n }\n return total;\n}\n\n/** Diagnostic — total logs across all budgets. */\nexport function __getLogCountForTests(name?: string): number {\n if (name !== undefined) return state.logs.get(name)?.length ?? 0;\n let total = 0;\n for (const arr of state.logs.values()) total += arr.length;\n return total;\n}\n\nexport function __resetLedgerForTests(): void {\n state = { logs: new Map(), lastGcAt: Date.now() };\n}\n\n/** Force GC manually (tests only). */\nexport async function __evictNowForTests(): Promise<void> {\n await withCwdMutex(MUTEX_KEY, async () => {\n gcOlderThanOneYear(Date.now());\n });\n}\n\n/** Force-insert a log at a specific timestamp (tests only). */\nexport function __injectLogForTests(name: string, timestamp: number, amountUsd: number): void {\n const list = state.logs.get(name) ?? [];\n list.push({ timestamp, amountUsd });\n state.logs.set(name, list);\n}\n","/**\n * Internal Budget registry — keeps live `BudgetOptions` per name.\n * Singleton; no persistence (D385).\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport type {\n BudgetHandle,\n BudgetMode,\n BudgetOptions,\n BudgetSnapshot,\n BudgetWindow,\n} from \"../../types/budget.js\";\nimport { spentIn } from \"./ledger.js\";\n\nconst NAME_GRAMMAR = /^[a-z0-9][a-z0-9_-]*$/;\n\nconst registry = new Map<string, BudgetOptions>();\n\nexport function __resetRegistryForTests(): void {\n registry.clear();\n}\n\nexport function validateBudgetName(name: string): void {\n if (typeof name !== \"string\" || name.length === 0) {\n throw new ConfigurationError(\"Budget name must be a non-empty string\", {\n code: \"invalid_budget_name\",\n });\n }\n if (!NAME_GRAMMAR.test(name)) {\n throw new ConfigurationError(\n `Budget name \"${name}\" must match ^[a-z0-9][a-z0-9_-]*$ (lowercase + dash/underscore, start alphanumeric)`,\n { code: \"invalid_budget_name\" },\n );\n }\n}\n\n/**\n * Refuse a `BudgetScope` this version does not implement.\n *\n * `BudgetScope` declares `\"agent\" | \"call\" | \"process\"` and `scope` is REQUIRED, so every caller must\n * pick from a union two-thirds of which is unbuilt. Measured 2026-09-02: nothing outside this file\n * reads `scope` at all — `buildHandle` copies it onto the handle and the tracker never consults it —\n * so `scope: \"agent\"` was ACCEPTED and silently ignored. A caller asking for per-agent accounting got\n * process-wide accounting and no signal of any kind.\n *\n * That is the failure `rules/error-handling.md` § 2 exists to prevent, and it is worse than the\n * unbuilt feature: a limit believed to be per-agent, applied globally, is a cost control that reports\n * the wrong number. Refusing is honest; narrowing the union to `\"process\"` would be honest too and is\n * a breaking change to a published type, so it belongs to a major rather than to this fix.\n *\n * @internal\n */\nfunction assertImplementedScope(scope: BudgetOptions[\"scope\"]): void {\n if (scope === \"process\") return;\n throw new ConfigurationError(\n `Budget scope \"${scope}\" is declared but not implemented — only \"process\" is honoured. ` +\n \"A budget created with it would have been accounted process-wide with no warning.\",\n { code: \"unimplemented_budget_scope\" },\n );\n}\n\nexport function createBudget(opts: BudgetOptions): BudgetHandle {\n // EC-7: name validation\n validateBudgetName(opts.name);\n assertImplementedScope(opts.scope);\n if (registry.has(opts.name)) {\n // EC-16: duplicate throws (vs Task.submit idempotent return)\n throw new ConfigurationError(`Budget \"${opts.name}\" already exists`, {\n code: \"invalid_budget_name\",\n });\n }\n registry.set(opts.name, opts);\n return buildHandle(opts);\n}\n\nexport function getBudget(name: string): BudgetHandle | undefined {\n const opts = registry.get(name);\n if (opts === undefined) return undefined;\n return buildHandle(opts);\n}\n\nexport function listBudgets(): readonly BudgetHandle[] {\n return [...registry.values()].map(buildHandle);\n}\n\nexport function deleteBudget(name: string): boolean {\n return registry.delete(name);\n}\n\nexport function snapshotAll(): readonly BudgetSnapshot[] {\n const result: BudgetSnapshot[] = [];\n for (const opts of registry.values()) {\n for (const lim of opts.limits) {\n const spent = spentIn(opts.name, lim.window);\n result.push({\n name: opts.name,\n window: lim.window,\n spentUsd: spent,\n limitUsd: lim.limitUsd,\n ratio: lim.limitUsd > 0 ? spent / lim.limitUsd : 0,\n });\n }\n }\n return result;\n}\n\nexport function getBudgetOptionsRaw(name: string): BudgetOptions | undefined {\n return registry.get(name);\n}\n\nexport function defaultMode(opts: BudgetOptions): BudgetMode {\n return opts.mode ?? \"warn\";\n}\n\nfunction buildHandle(opts: BudgetOptions): BudgetHandle {\n return {\n name: opts.name,\n mode: defaultMode(opts),\n scope: opts.scope,\n limits: opts.limits,\n spentIn: (window: BudgetWindow) => spentIn(opts.name, window),\n remainingIn: (window: BudgetWindow) => {\n const lim = opts.limits.find((l) => l.window === window);\n if (lim === undefined) return Number.POSITIVE_INFINITY;\n return Math.max(0, lim.limitUsd - spentIn(opts.name, window));\n },\n };\n}\n","/**\n * Budget enforcement (ADRs D383, D386, EC-7/8/9).\n *\n * - `preflightCheck(name, estimatedUsd)` — in `block` mode, throw\n * `BudgetExceededError` before the LLM call if any limit would be\n * exceeded (EC-9 — the caller invokes it inside the mutex section).\n * - `chargeAndCheckThresholds(name, actualUsd)` — apply the charge to the\n * ledger + invoke onThreshold/onExceed callbacks isolated in\n * try/catch (EC-8).\n *\n * @internal\n */\n\nimport { BudgetExceededError } from \"../../errors.js\";\nimport type { BudgetMode, BudgetOptions } from \"../../types/budget.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { charge, spentIn } from \"./ledger.js\";\nimport { defaultMode, getBudgetOptionsRaw } from \"./registry.js\";\n\nconst THRESHOLDS = [0.8, 0.95] as const;\ntype Threshold = (typeof THRESHOLDS)[number];\n\n/**\n * Throws BudgetExceededError if `mode === \"block\"` and any limit\n * would be exceeded. No-op for audit/warn modes (post-charge checks\n * handle those).\n *\n * Caller invokes this BEFORE the LLM call.\n */\nexport function preflightCheck(name: string, estimatedUsd: number): void {\n const opts = getBudgetOptionsRaw(name);\n if (opts === undefined) return; // EC-20: budget deleted; charge becomes no-op\n if (defaultMode(opts) !== \"block\") return;\n for (const lim of opts.limits) {\n const currentSpent = spentIn(opts.name, lim.window);\n if (currentSpent + estimatedUsd > lim.limitUsd) {\n throw new BudgetExceededError({\n budgetName: opts.name,\n window: lim.window,\n spentUsd: currentSpent + estimatedUsd,\n limitUsd: lim.limitUsd,\n mode: \"block\",\n });\n }\n }\n}\n\n/**\n * Charge the budget + dispatch threshold/exceed callbacks (EC-8 isolated).\n *\n * - In `audit` mode: charge only, no callbacks.\n * - In `warn` mode: charge + onThreshold (80/95) + onExceed (100). No throw.\n * - In `block` mode: charge + onThreshold + onExceed. No throw post-call\n * (preflightCheck already prevented exceed for the upcoming call;\n * this protects against simultaneous-call races where multiple sends\n * each pass preflight independently — last one to charge may still\n * tip a limit. We document the case rather than retroactively throw).\n */\nexport async function chargeAndCheckThresholds(name: string, actualUsd: number): Promise<void> {\n const opts = getBudgetOptionsRaw(name);\n if (opts === undefined) {\n // EC-20: budget deleted during in-flight call. Charge is silent no-op.\n diag(\n `[budget] charge for deleted budget \"${name}\" is a no-op (was the budget removed during in-flight send?)\\n`,\n );\n return;\n }\n const mode = defaultMode(opts);\n\n await charge(opts.name, actualUsd);\n\n if (mode === \"audit\") return;\n await dispatchCallbacksFor(opts, mode);\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: 3-mode × 3-threshold dispatch table inherently branchy; pulling out helpers loses local context.\nasync function dispatchCallbacksFor(opts: BudgetOptions, mode: BudgetMode): Promise<void> {\n for (const lim of opts.limits) {\n const spent = spentIn(opts.name, lim.window);\n if (lim.limitUsd <= 0) {\n if (spent > 0) await dispatchExceed(opts, lim.window, spent, lim.limitUsd, mode);\n continue;\n }\n const ratio = spent / lim.limitUsd;\n if (ratio >= 1) {\n await dispatchExceed(opts, lim.window, spent, lim.limitUsd, mode);\n } else {\n // Iterate descending so the HIGHEST matched threshold fires (0.95 not 0.8)\n for (const t of [...THRESHOLDS].reverse() as Threshold[]) {\n if (ratio >= t) {\n await dispatchThreshold(opts, lim.window, spent, lim.limitUsd, t);\n break;\n }\n }\n }\n }\n}\n\nasync function dispatchThreshold(\n opts: BudgetOptions,\n window: BudgetOptions[\"limits\"][number][\"window\"],\n spentUsd: number,\n limitUsd: number,\n threshold: Threshold,\n): Promise<void> {\n if (opts.onThreshold === undefined) return;\n try {\n await opts.onThreshold({\n budgetName: opts.name,\n window,\n threshold,\n spentUsd,\n limitUsd,\n });\n } catch (err) {\n // EC-8: callback throw isolated\n const msg = err instanceof Error ? err.message : String(err);\n diag(`[budget] onThreshold callback threw: ${msg}\\n`);\n }\n}\n\nasync function dispatchExceed(\n opts: BudgetOptions,\n window: BudgetOptions[\"limits\"][number][\"window\"],\n spentUsd: number,\n limitUsd: number,\n mode: BudgetMode,\n): Promise<void> {\n if (opts.onExceed === undefined) {\n if (mode === \"warn\") {\n diag(\n `[budget] \"${opts.name}\" exceeded ${window} limit: $${spentUsd.toFixed(4)} > $${limitUsd.toFixed(4)}\\n`,\n );\n }\n return;\n }\n try {\n await opts.onExceed({\n budgetName: opts.name,\n window,\n spentUsd,\n limitUsd,\n mode,\n });\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n diag(`[budget] onExceed callback threw: ${msg}\\n`);\n }\n}\n","/**\n * normalizeUsage — convert provider-shaped raw `usage` object to\n * canonical `TokenUsage`. Ports Hermes Agent's `normalize_usage`\n * (reference/peer-agent/agent/usage_pricing.py:672-742).\n *\n * Handles 3 API shapes:\n * - Anthropic Messages: 4 explicit buckets (input/output/cache_read/cache_creation).\n * - OpenAI Chat Completions: prompt_tokens INCLUDES cache; subtract cached_tokens.\n * - OpenAI Responses (Codex): input_tokens INCLUDES cache; same subtraction.\n *\n * Edge cases:\n * - a peer#10266 — OpenAI-compat proxies (OpenRouter, a peer vendor AI Gateway,\n * a peer) routing Claude expose Anthropic-style top-level fields\n * (cache_read_input_tokens / cache_creation_input_tokens). Both\n * locations are checked with top-level fallback.\n * - Null/undefined fields → 0 via `int()` coerce.\n * - String token counts → parsed via int.\n * - Negative values → clamped to 0 (defensive against proxy bugs).\n *\n * @internal\n */\n\nimport type { TokenUsage } from \"../../types/usage.js\";\n\nexport type ApiMode = \"anthropic_messages\" | \"openai_chat_completions\" | \"openai_responses\";\n\nfunction int(v: unknown): number {\n if (typeof v === \"number\") return Number.isFinite(v) ? Math.max(0, Math.trunc(v)) : 0;\n if (typeof v === \"string\") {\n const n = Number.parseInt(v, 10);\n return Number.isFinite(n) ? Math.max(0, n) : 0;\n }\n return 0;\n}\n\nfunction buildTotal(buckets: {\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens: number;\n cacheWriteTokens: number;\n}): number {\n // total = visible input + cache buckets + output (reasoning counted via output)\n return (\n buckets.inputTokens + buckets.outputTokens + buckets.cacheReadTokens + buckets.cacheWriteTokens\n );\n}\n\nfunction omitUndefined(usage: {\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens: number;\n cacheWriteTokens: number;\n reasoningTokens: number;\n totalTokens: number;\n}): TokenUsage {\n return {\n inputTokens: usage.inputTokens,\n outputTokens: usage.outputTokens,\n ...(usage.cacheReadTokens > 0 ? { cacheReadTokens: usage.cacheReadTokens } : {}),\n ...(usage.cacheWriteTokens > 0 ? { cacheWriteTokens: usage.cacheWriteTokens } : {}),\n ...(usage.reasoningTokens > 0 ? { reasoningTokens: usage.reasoningTokens } : {}),\n totalTokens: usage.totalTokens,\n };\n}\n\n/**\n * Guess which usage shape a provider reports, from its name alone.\n *\n * Matching is case-insensitive and exact — `\"anthropic\"`, `\"claude\"` and `\"bedrock_anthropic\"`\n * give `\"anthropic_messages\"`; `\"openai-codex\"` and `\"codex\"` give `\"openai_responses\"`. Every\n * other name, including ones this SDK has never seen, falls through to\n * `\"openai_chat_completions\"`. There is no unknown result, so a wrong guess is silent: it is\n * read as a Chat Completions payload, whose fields are absent, and the tokens come back as 0.\n *\n * The default is right for the OpenAI-compatible majority (openai, openrouter, deepseek, and the\n * compat endpoints of google, ollama and lmstudio). When it is not, pass `apiMode` to\n * `normalizeUsage` explicitly instead of relying on the name.\n */\nexport function inferApiMode(provider: string): ApiMode {\n const p = provider.toLowerCase();\n if (p === \"anthropic\" || p === \"claude\" || p === \"bedrock_anthropic\") {\n return \"anthropic_messages\";\n }\n if (p === \"openai-codex\" || p === \"codex\") return \"openai_responses\";\n // openai, openrouter, deepseek, google (compat), ollama (compat), lmstudio (compat), etc\n return \"openai_chat_completions\";\n}\n\ninterface RawRecord {\n [k: string]: unknown;\n}\n\n/**\n * Convert a provider's raw `usage` object into the SDK's canonical `TokenUsage`.\n *\n * Never throws and never reports failure. `null`, `undefined` and any non-object argument return\n * all-zero usage, which is indistinguishable from a real response that used no tokens — so this\n * is not the place to detect a malformed payload.\n *\n * `opts.apiMode` selects the reader; when omitted it is derived from `opts.provider` via\n * `inferApiMode`, whose fallback is Chat Completions. Pass it explicitly for any provider whose\n * name does not identify its wire shape.\n *\n * The shapes differ in one way that matters: Anthropic reports cache tokens in buckets separate\n * from `input_tokens`, while both OpenAI shapes report a prompt total that already includes\n * them. For the OpenAI readers the cache buckets are subtracted, so `inputTokens` is always the\n * uncached portion and `inputTokens + cacheReadTokens + cacheWriteTokens` reconstructs the\n * provider's prompt total. The subtraction is floored at 0, so a payload whose cache counts\n * exceed its prompt total yields 0 rather than a negative.\n *\n * Every field is coerced: numbers are truncated toward zero, numeric strings are parsed, negative\n * and non-finite values become 0, and anything else becomes 0.\n *\n * `totalTokens` is computed here as input + output + both cache buckets; a `total_tokens` the\n * provider sent is ignored. Reasoning tokens are reported separately but are NOT added again —\n * providers already count them inside output. `cacheReadTokens`, `cacheWriteTokens` and\n * `reasoningTokens` are omitted from the result when they are 0, so absent means zero, not\n * unknown.\n *\n * Chat Completions also accepts Anthropic-style top-level `cache_read_input_tokens` /\n * `cache_creation_input_tokens`, which OpenAI-compatible proxies emit when they route Claude.\n * The nested `prompt_tokens_details` values win; the top-level fields are consulted only when\n * those are 0 or missing.\n */\nexport function normalizeUsage(\n rawUsage: unknown,\n opts: { provider: string; apiMode?: ApiMode },\n): TokenUsage {\n if (rawUsage === null || rawUsage === undefined) {\n return { inputTokens: 0, outputTokens: 0, totalTokens: 0 };\n }\n if (typeof rawUsage !== \"object\") {\n return { inputTokens: 0, outputTokens: 0, totalTokens: 0 };\n }\n const raw = rawUsage as RawRecord;\n const mode = opts.apiMode ?? inferApiMode(opts.provider);\n\n if (mode === \"anthropic_messages\") return normalizeAnthropic(raw);\n if (mode === \"openai_responses\") return normalizeOpenAIResponses(raw);\n return normalizeOpenAIChat(raw);\n}\n\nfunction normalizeAnthropic(raw: RawRecord): TokenUsage {\n const inputTokens = int(raw.input_tokens);\n const outputTokens = int(raw.output_tokens);\n const cacheReadTokens = int(raw.cache_read_input_tokens);\n const cacheWriteTokens = int(raw.cache_creation_input_tokens);\n const usage = {\n inputTokens,\n outputTokens,\n cacheReadTokens,\n cacheWriteTokens,\n reasoningTokens: 0,\n totalTokens: buildTotal({ inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens }),\n };\n return omitUndefined(usage);\n}\n\nfunction normalizeOpenAIResponses(raw: RawRecord): TokenUsage {\n const inputTotal = int(raw.input_tokens);\n const outputTokens = int(raw.output_tokens);\n const inputDetails = (raw.input_tokens_details as RawRecord | undefined) ?? {};\n const outputDetails = (raw.output_tokens_details as RawRecord | undefined) ?? {};\n const cacheReadTokens = int(inputDetails.cached_tokens);\n const cacheWriteTokens = int(inputDetails.cache_creation_tokens);\n const reasoningTokens = int(outputDetails.reasoning_tokens);\n const inputTokens = Math.max(0, inputTotal - cacheReadTokens - cacheWriteTokens);\n const usage = {\n inputTokens,\n outputTokens,\n cacheReadTokens,\n cacheWriteTokens,\n reasoningTokens,\n totalTokens: buildTotal({ inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens }),\n };\n return omitUndefined(usage);\n}\n\nfunction normalizeOpenAIChat(raw: RawRecord): TokenUsage {\n const promptTotal = int(raw.prompt_tokens);\n const outputTokens = int(raw.completion_tokens);\n const promptDetails = (raw.prompt_tokens_details as RawRecord | undefined) ?? {};\n const completionDetails = (raw.completion_tokens_details as RawRecord | undefined) ?? {};\n\n // a peer#10266 fallback — proxies expose Anthropic-style top-level fields when routing Claude\n const cacheReadTokens = int(promptDetails.cached_tokens) || int(raw.cache_read_input_tokens);\n const cacheWriteTokens =\n int(promptDetails.cache_write_tokens) || int(raw.cache_creation_input_tokens);\n\n const reasoningTokens = int(completionDetails.reasoning_tokens);\n const inputTokens = Math.max(0, promptTotal - cacheReadTokens - cacheWriteTokens);\n const usage = {\n inputTokens,\n outputTokens,\n cacheReadTokens,\n cacheWriteTokens,\n reasoningTokens,\n totalTokens: buildTotal({ inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens }),\n };\n return omitUndefined(usage);\n}\n","/**\n * `Budget` — token cost enforcement primitive (Adoption Roadmap #1\n * post-Tasks, ADRs D375-D388).\n *\n * Static facade delegating to the in-process registry + ledger.\n * 3 modes: `audit` (log-only), `warn` (callbacks + log), `block`\n * (preflight throw before LLM call).\n *\n * @public\n *\n * @deprecated since SDK 2.0 (iter 18+) — import this facade from\n * `@theokit/sdk-budget` instead. The sources backing this facade have\n * been physically extracted to `@theokit/sdk-budget/internal/` per\n * ADR-008. The sdk-core copies are retained for the v1.x sync API\n * contract; consumers MUST migrate before sdk-core v3.0.\n *\n * Migration:\n *\n * ```ts\n * // Before (sdk-core, deprecated):\n * import { Budget, computeCost } from \"@theokit/sdk\";\n *\n * // After (sdk-budget, authoritative):\n * import {\n * chargeAndCheckThresholds,\n * createBudget,\n * computeUsdCost, // replaces computeCost\n * createUsdBudgetTracker,\n * } from \"@theokit/sdk-budget\";\n * ```\n */\n\nimport { computeCost } from \"./internal/budget/compute-cost.js\";\nimport { chargeAndCheckThresholds, preflightCheck } from \"./internal/budget/enforcement.js\";\nimport { inferApiMode, normalizeUsage } from \"./internal/budget/normalize-usage.js\";\nimport { getPricingEntry } from \"./internal/budget/pricing-registry.js\";\nimport {\n createBudget,\n deleteBudget,\n getBudget,\n listBudgets,\n snapshotAll,\n} from \"./internal/budget/registry.js\";\nimport { UsageAccumulator } from \"./internal/budget/usage-accumulator.js\";\nimport type { BudgetHandle, BudgetOptions, BudgetSnapshot } from \"./types/budget.js\";\n\n// Re-exports for caller-side composition until auto-wire-up in v0.2 (T4.2 deferred).\nexport {\n chargeAndCheckThresholds,\n computeCost,\n getPricingEntry,\n inferApiMode,\n normalizeUsage,\n preflightCheck,\n UsageAccumulator,\n};\n\nexport class Budget {\n // D375 — static class with private constructor.\n private constructor() {\n throw new Error(\"Budget is static; do not instantiate\");\n }\n\n /**\n * Create a budget. `name` must match `^[a-z0-9][a-z0-9_-]*$` (EC-7).\n * Throws `ConfigurationError` if name is invalid OR already exists\n * (EC-16: duplicate surface caller bug).\n *\n * `limits` is stacked (D384) — ANY exceeded triggers enforcement.\n * Empty `limits[]` is valid: pure tracking, no thresholds/exceed\n * callbacks fire (EC-19).\n *\n * Default `mode` is `\"warn\"` (D383). For emergency stop, use\n * `mode: \"block\", limits: [{ window: \"1d\", limitUsd: 0 }]` (EC-18).\n */\n static create(options: BudgetOptions): BudgetHandle {\n return createBudget(options);\n }\n\n /** Returns the handle for an active budget, or `undefined`. */\n static get(name: string): BudgetHandle | undefined {\n return getBudget(name);\n }\n\n /** Returns all active budgets. */\n static list(): readonly BudgetHandle[] {\n return listBudgets();\n }\n\n /**\n * Deletes a budget from the registry. Returns `true` if it existed.\n * In-flight `agent.send` calls referencing the name treat the\n * subsequent charge as a silent no-op + stderr warn (EC-20).\n */\n static delete(name: string): boolean {\n return deleteBudget(name);\n }\n\n /**\n * Returns per-window spend snapshot for all active budgets. Each\n * entry has `{ name, window, spentUsd, limitUsd, ratio }`.\n */\n static snapshot(): readonly BudgetSnapshot[] {\n return snapshotAll();\n }\n}\n","/**\n * SE25 — deterministic, no-LLM guardrail processors built on the SE24\n * {@link Processor} seam. Cheap and churn-free (no provider/model deltas), so\n * they are safe to own in-core — unlike the LLM-classifier processors, which are\n * delegated (see the guardrails ADR). All are OPT-IN: add them to\n * `AgentOptions.inputProcessors` / `outputProcessors`.\n *\n * @public\n */\n\n/**\n * Approximate token count from string length. This is an ESTIMATE\n * (≈ UTF-16-code-units / 4, NOT Unicode code points, NOT an exact per-model\n * tokenizer count) — good enough for a coarse cap, and dependency-free.\n *\n * Re-exported rather than reimplemented: the ratio lives in `compaction.ts`, which is where the\n * heuristic is load-bearing. The name and the behaviour here are unchanged.\n */\nimport { CHARS_PER_TOKEN, estimateTokens } from \"./compaction.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport type { Processor, ProcessorControls } from \"./types/processors.js\";\n\nexport { CHARS_PER_TOKEN, estimateTokens };\n\n/** Options for {@link createUnicodeNormalizer}. @public */\nexport interface UnicodeNormalizerOptions {\n /** Remove C0 + C1 control chars + DEL (keeps tab / newline / carriage-return). Default `false`. */\n stripControlChars?: boolean;\n /** Collapse runs of intra-line whitespace to one space, 3+ blank lines to one, and trim. Default `false`. Uses legacy `\\s`; Unicode-only whitespace (U+00A0 NBSP, U+FEFF BOM, U+2000–U+200A) is NOT collapsed. */\n collapseWhitespace?: boolean;\n}\n\n// C0 controls (U+0000–U+001F) + DEL (U+007F) + C1 controls (U+0080–U+009F),\n// EXCLUDING tab (U+0009), line feed (U+000A), and carriage return (U+000D) so\n// line structure survives. C1 is included (matching a peer framework's Cc-category strip)\n// since C1 controls are invisible noise / prompt-injection vectors in LLM input.\n// biome-ignore lint/suspicious/noControlCharactersInRegex: intentional — this processor's whole job is to strip control characters (written with \\u escapes, no literal control char in source).\nconst CONTROL_CHARS = /[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F\\u007F-\\u009F]/g;\n\n/**\n * SE25 — an input processor that normalizes user text: Unicode NFC (so\n * canonically-equivalent sequences compare equal) plus optional control-char\n * stripping and whitespace collapsing. Pure + deterministic; no LLM. Mirrors\n * a peer framework's `UnicodeNormalizer`.\n *\n * @public\n */\nexport function createUnicodeNormalizer(opts: UnicodeNormalizerOptions = {}): Processor {\n const stripControlChars = opts.stripControlChars ?? false;\n const collapseWhitespace = opts.collapseWhitespace ?? false;\n return {\n id: \"unicode-normalizer\",\n processInput(ctx) {\n let s = ctx.message.normalize(\"NFC\");\n if (stripControlChars) s = s.replace(CONTROL_CHARS, \"\");\n if (collapseWhitespace) {\n s = s\n .replace(/[^\\S\\n]+/g, \" \") // runs of intra-line whitespace -> one space\n .replace(/ *\\n */g, \"\\n\") // drop spaces hugging a newline\n .replace(/\\n{3,}/g, \"\\n\\n\") // 3+ blank lines -> one blank line\n .trim();\n }\n return s;\n },\n };\n}\n\n/** Options for {@link createTokenLimiter}. @public */\nexport interface TokenLimiterOptions {\n /** Positive integer token budget (estimate — see {@link estimateTokens}). */\n limit: number;\n /** Over the limit: `\"truncate\"` (default, cut to fit) or `\"block\"` (abort with a tripwire). */\n strategy?: \"truncate\" | \"block\";\n}\n\n/**\n * SE25 — a processor that caps text to a token budget. Placed in\n * `inputProcessors` it limits the prompt; in `outputProcessors` it limits the\n * response. Uses a char-based estimate (no tokenizer dep). `truncate` cuts to\n * fit; `block` aborts (tripwire). Mirrors a peer framework's `TokenLimiterProcessor`.\n *\n * @public\n */\nexport function createTokenLimiter(opts: TokenLimiterOptions): Processor {\n if (!Number.isInteger(opts.limit) || opts.limit <= 0) {\n throw new ConfigurationError(\"createTokenLimiter: `limit` must be a positive integer.\", {\n code: \"invalid_processor_options\",\n });\n }\n const limit = opts.limit;\n const strategy = opts.strategy ?? \"truncate\";\n const cap = (text: string, controls: Pick<ProcessorControls, \"abort\">): string => {\n const estimated = estimateTokens(text);\n if (estimated <= limit) return text;\n if (strategy === \"block\") {\n controls.abort(`exceeds token limit ${limit} (~${estimated} estimated)`);\n }\n // Truncate on CODE POINTS (not UTF-16 code units) so a cut never splits a\n // surrogate pair into a lone surrogate (invalid UTF-8 → rejected by LLM APIs).\n return [...text].slice(0, limit * CHARS_PER_TOKEN).join(\"\");\n };\n return {\n id: \"token-limiter\",\n processInput: (ctx) => cap(ctx.message, ctx),\n processOutput: (ctx) => cap(ctx.text, ctx),\n };\n}\n\n/** SE36 — `TokenLimiter.create` replaces `createTokenLimiter` (ADR 0015). @public *\n * `TokenLimiter.create` returns a **`Processor`**, not a `TokenLimiter`. The class is\n * the namespace; the processor is the product.\n */\nexport class TokenLimiter {\n private constructor() {}\n static create(opts: TokenLimiterOptions): Processor {\n return createTokenLimiter(opts);\n }\n}\n/** SE36 — `UnicodeNormalizer.create` replaces `createUnicodeNormalizer` (ADR 0015). @public *\n * `UnicodeNormalizer.create` returns a **`Processor`**, not a `UnicodeNormalizer`. The\n * class is the namespace; the processor is the product.\n */\nexport class UnicodeNormalizer {\n private constructor() {}\n static create(opts: UnicodeNormalizerOptions = {}): Processor {\n return createUnicodeNormalizer(opts);\n }\n}\n","/**\n * M22 — `createSkill`: define a skill in TypeScript, without a `SKILL.md` file on disk.\n *\n * An inline skill is usable ALONGSIDE filesystem skills (`AgentOptions.skills.inline`), and points\n * an agent at code-defined capabilities without a `.theokit/skills/<name>/SKILL.md`. Like file\n * skills, its `name` + `description` surface in the `<skills>` system-prompt block; its\n * `instructions` (the body) travel on the object for the consumer (the SDK injects name+description,\n * not bodies — inline and file skills are symmetric there). Inline skills override file skills on a\n * name conflict (mirrors the subagents-loader precedent).\n */\n\nimport { ConfigurationError } from \"./errors.js\";\nimport type { Skill as SkillShape } from \"./internal/runtime/skills/discover-skills.js\";\n\n/** A code-defined skill (from {@link createSkill}) — a {@link Skill} plus its inline body. */\nexport interface InlineSkill extends SkillShape {\n /** The skill body/instructions (inline skills carry it here instead of a SKILL.md file). */\n instructions: string;\n /**\n * SE21 — supporting documents bundled with the skill (filename → content),\n * mirroring a filesystem skill's `references/` directory. Surfaced to the app\n * via `agent.skills.get(name)`; not injected into the model prompt.\n */\n references?: Record<string, string>;\n}\n\n/** Spec accepted by {@link createSkill}. */\nexport interface CreateSkillSpec {\n name: string;\n description: string;\n instructions: string;\n category?: string;\n dependencies?: string[];\n /** SE21 — supporting documents (filename → content), like a filesystem skill's `references/`. */\n references?: Record<string, string>;\n}\n\n/**\n * Build an {@link InlineSkill} from a code spec. Fails fast on an empty `name`/`description`\n * (error-handling.md). The synthetic `source` (`inline://<name>`) marks it as file-less.\n */\nfunction createSkill(spec: CreateSkillSpec): InlineSkill {\n if (!spec.name) {\n throw new ConfigurationError(\"createSkill: `name` is required.\", {\n code: \"invalid_skill_spec\",\n });\n }\n if (!spec.description) {\n throw new ConfigurationError(\"createSkill: `description` is required.\", {\n code: \"invalid_skill_spec\",\n });\n }\n return {\n name: spec.name,\n description: spec.description,\n source: `inline://${spec.name}`,\n instructions: spec.instructions,\n ...(spec.category !== undefined ? { category: spec.category } : {}),\n ...(spec.dependencies !== undefined ? { dependencies: spec.dependencies } : {}),\n ...(spec.references !== undefined ? { references: spec.references } : {}),\n };\n}\n\n/** SE36 — `Skill.create` replaces `createSkill` (ADR 0015). @public *\n * `Skill.create` returns an **`InlineSkill`**, not a `Skill`. The class is the namespace;\n * the inline skill descriptor is the product.\n */\nexport class Skill {\n private constructor() {}\n static create(spec: CreateSkillSpec): InlineSkill {\n return createSkill(spec);\n }\n}\n","/**\n * Report whether a credential resolved — never what it is.\n *\n * Every agent product grows a \"why can't I use this model?\" surface: a doctor command, a status\n * panel, a startup diagnostic. Each needs to know whether a credential resolved, and each is one\n * careless line from printing it. The line is careless precisely because it is convenient — the\n * value is right there, and whoever is debugging a routing problem wants to see it.\n *\n * So presence-only is the DEFAULT here rather than each consumer's discipline. Discipline is what\n * every product has until the day it does not, and a leaked key is not a defect anyone can withdraw.\n *\n * ## Why a fingerprint and not a prefix\n *\n * A report has to be actionable: two people asking \"is it the same key?\" need something to compare.\n * The convenient answer — the first eight characters — is still the secret, and it is enough to\n * identify a key in a breach corpus. A hash is not.\n *\n * @public\n */\n\nimport { createHash } from \"node:crypto\";\n\n/**\n * One provider's credential lookup, as the product resolved it.\n *\n * `value` is the secret itself. It is hashed and dropped inside `describeCredential` — it never\n * reaches the report, and nothing here stores it.\n *\n * @public\n */\nexport interface CredentialInput {\n /** The product's name for the provider. This module never knows one of its own. */\n readonly provider: string;\n /** The resolved secret, or `undefined`/empty when nothing resolved. */\n readonly value: string | undefined;\n /** Where it came from, in the product's vocabulary — `env`, `file`, `keychain`, `oauth`. */\n readonly source: string;\n}\n\n/**\n * A presence-only view of one credential, safe to print, log, or attach to a support bundle.\n *\n * `fingerprint` is the first eight hex characters of the SHA-256 of the trimmed secret: enough for\n * two people to agree they are holding the same key, and not a substring of it. It is absent\n * whenever `present` is false.\n *\n * @public\n */\nexport interface CredentialReport {\n readonly provider: string;\n readonly present: boolean;\n readonly source: string;\n /** Eight hex characters of a hash. Absent when no credential resolved. Never a prefix. */\n readonly fingerprint?: string;\n}\n\n/**\n * Turn a resolved credential into something you can show a user.\n *\n * The value is trimmed before the emptiness test, so `undefined`, `\"\"` and whitespace all report\n * `present: false` with no fingerprint. That matters because an environment variable that expanded\n * to nothing arrives as an empty string, and calling that \"present\" sends whoever is debugging to\n * hunt for a routing bug instead of a missing secret.\n *\n * @returns a report safe to log, render and attach to a support bundle.\n * @public\n */\nexport function describeCredential(input: CredentialInput): CredentialReport {\n // Trimmed before the emptiness test: an unset variable read through a shell expansion arrives as\n // `\"\"` or whitespace, and reporting that as present claims a working credential where there is\n // none — the same shape B-118 measured with an npm token resolving to empty.\n const secret = (input.value ?? \"\").trim();\n if (secret.length === 0) {\n return { provider: input.provider, present: false, source: input.source };\n }\n\n return {\n provider: input.provider,\n present: true,\n source: input.source,\n fingerprint: createHash(\"sha256\").update(secret).digest(\"hex\").slice(0, 8),\n };\n}\n","import { parseModelId } from \"./internal/llm/model-identifier.js\";\nimport type { Plugin } from \"./internal/plugins/types.js\";\nimport { registerBuiltins } from \"./internal/providers/builtin/index.js\";\nimport { listProviders } from \"./internal/providers/registry.js\";\nimport type { ProviderProfile } from \"./internal/providers/types.js\";\n\n/**\n * Options for {@link defineProvider}.\n *\n * @public\n */\nexport interface DefineProviderOptions {\n /** Plugin version surfaced in diagnostics. Default `\"1.0.0\"`. */\n version?: string;\n}\n\n/**\n * Canonical factory for a custom LLM provider, mirroring {@link Tool.create} and\n * {@link definePlugin} (Inviolable Rule 9 — every agentic capability ships as a\n * factory function).\n *\n * A {@link ProviderProfile} is data-only: it declares the provider name, the\n * HTTP dialect (`apiMode`), auth, base URL and fallback models. The transport\n * is selected from `apiMode` by the router, so any OpenAI-/Anthropic-compatible\n * endpoint (Groq, Together, Fireworks, a private gateway) is expressible as a\n * profile with no new code.\n *\n * Reached through {@link Provider.create}, which is the exported façade — this function\n * itself is internal. The docblock used to show `defineProvider(...)` as the call to write,\n * and it is not exported from any entry point, so following it produced\n * `TypeError: defineProvider is not a function`.\n *\n * One door rather than two, deliberately: `Provider` already owns `create`, `builtins` and\n * `forModel`, and a second exported way to build the same plugin would be a choice nobody\n * needs to make.\n *\n * Pass the result to `Agent.create({ plugins: [...] })` and route to it with\n * the `provider/model` id prefix or `providers.routes`:\n *\n * ```ts\n * const groq = Provider.create({\n * name: \"groq\",\n * apiMode: \"chat_completions\",\n * authType: \"api_key\",\n * envVars: [\"GROQ_API_KEY\"],\n * baseUrl: \"https://api.groq.com/openai/v1\",\n * fallbackModels: [\"groq/llama-3.1-8b-instant\"],\n * });\n * const agent = await Agent.create({\n * model: { id: \"groq/llama-3.1-8b-instant\" },\n * plugins: [groq],\n * });\n * ```\n *\n * @public\n */\nfunction defineProvider(profile: ProviderProfile, opts?: DefineProviderOptions): Plugin {\n return {\n name: profile.name,\n version: opts?.version ?? \"1.0.0\",\n kind: \"model-provider\",\n profile,\n };\n}\n\n/** SE36 — uniform namespace API. `Provider.create` replaces `defineProvider` (ADR 0015). @public */\nexport class Provider {\n private constructor() {}\n static create(profile: ProviderProfile, opts?: DefineProviderOptions): Plugin {\n return defineProvider(profile, opts);\n }\n\n /**\n * Every first-party builtin provider (anthropic, openai, openrouter, gemini, ollama, the ChatGPT/Codex\n * `openai-chatgpt`, …) as model-provider plugins, ready to hand to `Agent.create({ plugins })` or any\n * runtime that consumes model-provider plugins (e.g. the `theokit` agent server / `@theokit/agents`, whose\n * own model resolution does NOT share this registry). Enables a consumer to route to ANY SDK builtin —\n * including one added later in a single SDK file — with ZERO provider-specific code: just\n * `.plugins(Provider.builtins())` once, then pick a `provider/model` id. @public\n */\n static builtins(): Plugin[] {\n registerBuiltins();\n return listProviders().map((profile) => defineProvider(profile));\n }\n\n /**\n * The builtin serving `modelId`, or `undefined` when none does.\n *\n * The grammar of a model id — `provider/model` — now has **one** owner. M94: the consumer\n * redid it by hand with `modelId.slice(0, modelId.indexOf('/'))`, which on an id **without a slash** returns the\n * id minus its last character (`claude-opus-5` -> `claude-opus-`): it matches no provider and the\n * caller fell through to the default, without distinguishing that from a hit. A non-routable model was\n * indistinguishable from the happy path.\n *\n * Returns `undefined` instead of throwing: the caller decides whether absence is an error, and only they\n * know whether the model came from an explicit `--model` (an error) or from the default (normal).\n *\n * @public\n */\n static forModel(modelId: string): Plugin | undefined {\n // Delegates to `parseModelId`, the grammar's canonical owner — M94's DoD asked for\n // exactly that (\"reusing the SDK's own id parser so the grammar has ONE\n // owner\") and the first version redid `indexOf`/`slice` inline, reinventing the owner right next to it.\n //\n // Adversarial review measured the cost: 7 of 8 divergences. `lm-studio/qwen3` resolves to the\n // real `lmstudio` builtin via the parser and to NOTHING via the slice — and since the consumer now\n // throwing when there is no provider, a custom command that worked before M94 would start\n // fails. `Anthropic/...`, ` openai/...`, `llama.cpp/...` likewise. And the inverse: `openai/` (empty name) the\n // the parser rejects and the slice used to accept.\n const { provider } = parseModelId(modelId);\n if (provider === undefined) return undefined;\n return Provider.builtins().find((p) => p.name === provider);\n }\n}\n","/**\n * SE23 — `defineSkillReadTool`: an OPT-IN factory that gives the MODEL on-demand\n * access to a skill's full body + references via a `skill_read` tool.\n *\n * TheoKit discloses skills eagerly through the `<skills>` system-prompt block\n * (name + description only). This factory is the LAZY read path: the consumer\n * explicitly adds the returned {@link CustomTool} to `tools`, and when the model\n * calls it with a skill name, it gets that skill's `instructions` (+ SE21\n * `references`). The SDK NEVER auto-injects it — bring-your-own-tools stays\n * intact (sibling of `defineSubAgent` / `workflowAsTool`). See ADR 0007.\n *\n * import { Agent, createSkill, defineSkillReadTool } from \"@theokit/sdk\";\n *\n * const skills = [createSkill({ name: \"release\", description: \"…\", instructions: \"…\" })];\n * const agent = await Agent.create({\n * model: { id: \"openai/gpt-4o-mini\" },\n * skills: { inline: skills },\n * tools: [defineSkillReadTool(skills)],\n * });\n *\n * @public\n */\n\nimport { z } from \"zod\";\nimport type { InlineSkill } from \"./create-skill.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { toJsonSchema } from \"./internal/zod-to-json-schema.js\";\nimport type { CustomTool } from \"./types/agent.js\";\n\nconst SkillReadInputSchema = z.object({\n name: z.string().min(1, \"skill_read: `name` is required.\"),\n});\n\n/**\n * Render a skill's body (+ references) into a single model-facing string.\n * `skill.name` is expected to be a short identifier-like token (no newlines /\n * Markdown headings) — the consumer controls both the names and the tool, so\n * this is a formatting assumption, not a trust boundary.\n */\nfunction renderSkill(skill: InlineSkill): string {\n const parts = [`# Skill: ${skill.name}`, \"\", skill.instructions];\n const refs = skill.references;\n if (refs !== undefined && Object.keys(refs).length > 0) {\n parts.push(\"\", \"## References\");\n for (const [file, content] of Object.entries(refs)) {\n parts.push(\"\", `### ${file}`, content);\n }\n }\n return parts.join(\"\\n\");\n}\n\n/**\n * SE23 — build an OPT-IN `skill_read` {@link CustomTool} over the given inline\n * skills. When the model calls it with `{ name }`, the handler returns that\n * skill's body + references. An UNKNOWN (but well-formed) name returns a typed\n * \"not found\" string the model can act on — NOT a throw that kills the run.\n * Malformed input (missing `name`) fails at the trust boundary via the schema.\n *\n * The consumer controls exposure by choosing which skills to pass; the SDK\n * never auto-injects this tool.\n *\n * @public\n */\nfunction defineSkillReadTool(skills: ReadonlyArray<InlineSkill>): CustomTool {\n // Fail fast on duplicate names (Rule 8): a shadowed skill would be silently\n // unreachable and the \"not found\" list would show the name twice. Names are\n // addressed by exact, case-sensitive match — the same identity the <skills>\n // block uses — so a collision is a construction-time error, not a runtime one.\n const seen = new Set<string>();\n for (const skill of skills) {\n if (seen.has(skill.name)) {\n throw new ConfigurationError(`defineSkillReadTool: duplicate skill name \"${skill.name}\".`, {\n code: \"duplicate_skill_name\",\n });\n }\n seen.add(skill.name);\n }\n return {\n name: \"skill_read\",\n description:\n \"Read a skill's full instructions (and any bundled reference documents) by its name. \" +\n \"Use this to load the body of a skill listed in the <skills> block before acting on it.\",\n inputSchema: toJsonSchema(SkillReadInputSchema),\n handler: (input: Record<string, unknown>): string => {\n const { name } = SkillReadInputSchema.parse(input);\n const skill = skills.find((s) => s.name === name);\n if (skill === undefined) {\n const available = skills.map((s) => s.name).join(\", \");\n return `Skill \"${name}\" not found. Available skills: ${available.length > 0 ? available : \"(none)\"}.`;\n }\n return renderSkill(skill);\n },\n };\n}\n\n/** SE36 — `SkillReadTool.create` replaces `defineSkillReadTool` (ADR 0015). @public *\n * `SkillReadTool.create` returns a **`CustomTool`** — a skill-reading tool, not a\n * `SkillReadTool` instance.\n */\nexport class SkillReadTool {\n private constructor() {}\n static create(skills: ReadonlyArray<InlineSkill>): CustomTool {\n return defineSkillReadTool(skills);\n }\n}\n","/**\n * Audit whether every configuration key can be set from the environment, or says why not.\n *\n * A key settable only by editing a file cannot be set in CI, in a container, or for a single\n * invocation. That is usually an oversight rather than a decision, and it is invisible — nothing\n * fails, the key simply has no environment path, and nobody notices until someone needs one.\n *\n * The opposite failure rots more quietly. An opt-out written for a key that has since gained an\n * environment path, or for a key that no longer exists, still reads as a considered decision while\n * exempting nothing. Both questions are answered by one call so a consumer cannot check the gap and\n * forget the rot: they fail for opposite reasons, and a suite that asks only one looks complete.\n *\n * ## Why the framework owns the rule and not the keys\n *\n * A framework cannot enumerate a consumer's configuration keys, and should not try. Which keys exist\n * is that product's vocabulary — the same reason the security floor takes its permissiveness order\n * as data and the trust posture takes its capability list. So the consumer ranges over its own keys\n * with this, rather than registering them here.\n *\n * That is a narrower claim than \"reachability is checked in the framework\", and it is the honest\n * one: the failure still surfaces in the consumer's own suite. What the consumer no longer writes is\n * the detector, which is where the subtlety lives — the stale-opt-out half is the part everyone\n * forgets.\n *\n * @public\n */\n\n/** A key deliberately left off the environment, with the reason and what would reverse it. @public */\nexport interface EnvOptOut {\n readonly key: string;\n /** Why an environment variable is the wrong shape for this key. */\n readonly reason: string;\n /** What would make this opt-out obsolete. An opt-out with no exit is a permanent excuse. */\n readonly exitCriterion: string;\n}\n\n/**\n * The three lists the audit compares: every key the product declares, the subset an environment\n * variable can set, and the documented exemptions.\n *\n * All three are matched by exact string equality, and `reachable` and `optOuts` are read as subsets\n * of `keys` — an entry in either that is not in `keys` is what makes an opt-out stale, and an entry\n * in `reachable` that is not in `keys` is simply ignored.\n *\n * @public\n */\nexport interface EnvReachabilityInput {\n /** Every configuration key the product declares. */\n readonly keys: readonly string[];\n /** The subset that an environment variable can set. */\n readonly reachable: readonly string[];\n /** Documented exemptions for keys that deliberately have no environment path. */\n readonly optOuts: readonly EnvOptOut[];\n}\n\n/**\n * The two failures, reported separately because they have opposite fixes.\n *\n * A key in `unreachable` needs either an environment path or a documented opt-out. A key in\n * `staleOptOuts` needs its opt-out DELETED — it exempts nothing, either because the key gained an\n * environment path or because the key no longer exists. Both lists empty is the passing state.\n *\n * @public\n */\nexport interface EnvReachabilityAudit {\n /** Keys with neither an environment path nor a documented opt-out. */\n readonly unreachable: readonly string[];\n /** Opt-outs that exempt nothing: the key gained an environment path, or no longer exists. */\n readonly staleOptOuts: readonly string[];\n}\n\n/**\n * Answer both halves of the reachability question in one call.\n *\n * A key counts as covered when it is in `reachable` OR carries an opt-out, so an opt-out silences\n * the gap it was written for and nothing else. Assert on both returned lists: a suite that checks\n * only `unreachable` still passes while the opt-outs rot, which is the half everyone forgets.\n *\n * This performs no I/O and reads no environment. The caller supplies its own key vocabulary,\n * because a framework cannot enumerate a consumer's configuration keys.\n *\n * @returns both axes, in the order the caller declared them — a stable order so a failure message\n * does not change between runs for reasons unrelated to the code.\n * @public\n */\nexport function auditEnvReachability(input: EnvReachabilityInput): EnvReachabilityAudit {\n const reachable = new Set(input.reachable);\n const exempt = new Set(input.optOuts.map((o) => o.key));\n const declared = new Set(input.keys);\n\n return {\n unreachable: input.keys.filter((k) => !reachable.has(k) && !exempt.has(k)),\n staleOptOuts: input.optOuts\n .filter((o) => !declared.has(o.key) || reachable.has(o.key))\n .map((o) => o.key),\n };\n}\n","/**\n * `EventBus` — typed EventEmitter wrapper.\n *\n * Provides type-safe publish/subscribe with automatic unsubscribe cleanup.\n * Each handler is try-caught (EC-2) so one failing handler cannot break others.\n */\n\nimport { diag } from \"./internal/diagnostics.js\";\n\ntype EventHandler<T> = (payload: T) => void;\n\n/**\n * A typed publish/subscribe bus, parameterised by a map of event name to payload type.\n *\n * `publish` is SYNCHRONOUS: handlers run in subscription order before it returns, so a slow handler\n * blocks the publisher. Each handler is invoked inside its own try/catch, so one that throws cannot\n * stop the others — the error is written to the diagnostics channel and counted on\n * `handlerErrorCount`. Assert on that counter in tests; a subscriber failing on every event is\n * otherwise invisible.\n *\n * `subscribe` returns the unsubscribe function, which is the only way to detach a handler — there\n * is no `off` taking the handler back. Handlers are held in a `Set` per event, so subscribing the\n * same function reference twice registers it once.\n *\n * Payload objects are passed by reference to every handler; nothing here copies them, so a handler\n * that mutates a payload mutates it for the handlers after it.\n */\nexport class EventBus<Events extends Record<string, unknown>> {\n private handlers = new Map<keyof Events, Set<EventHandler<never>>>();\n // M3 #64 — a swallowed handler error used to vanish without a trace (fail-loud\n // violation). We now log it AND expose an observable count so ops/tests can see\n // that a subscriber is silently failing, without breaking the EC-2 contract.\n #handlerErrorCount = 0;\n\n /** M3 #64 — number of handler invocations that threw (and were logged). */\n get handlerErrorCount(): number {\n return this.#handlerErrorCount;\n }\n\n /**\n * Subscribe to an event. Returns an unsubscribe function.\n */\n subscribe<K extends keyof Events>(event: K, handler: EventHandler<Events[K]>): () => void {\n if (!this.handlers.has(event)) {\n this.handlers.set(event, new Set());\n }\n const set = this.handlers.get(event)!;\n set.add(handler as EventHandler<never>);\n return () => {\n set.delete(handler as EventHandler<never>);\n };\n }\n\n /**\n * Publish an event to all subscribers. EC-2: try-catch per handler.\n */\n publish<K extends keyof Events>(event: K, payload: Events[K]): void {\n const set = this.handlers.get(event);\n if (!set) return;\n for (const handler of set) {\n try {\n (handler as EventHandler<Events[K]>)(payload);\n } catch (cause) {\n // EC-2: an error in one handler MUST NOT break the others — but M3 #64\n // makes it fail-loud: log with the event key + message and count it,\n // instead of the pre-M3 empty catch that discarded it without a trace.\n this.#handlerErrorCount += 1;\n const message = cause instanceof Error ? cause.message : String(cause);\n // theokit#147 — through the interceptable channel, not straight at the terminal: a TUI\n // host installs a diagnostics sink precisely so a stray write cannot corrupt its frame.\n diag(`[theokit-sdk] event-bus: handler for \"${String(event)}\" threw: ${message}\\n`);\n }\n }\n }\n\n /**\n * Subscribe to an event for a single firing. Returns an unsubscribe function.\n */\n once<K extends keyof Events>(event: K, handler: EventHandler<Events[K]>): () => void {\n const wrapped: EventHandler<Events[K]> = (payload) => {\n unsub();\n handler(payload);\n };\n const unsub = this.subscribe(event, wrapped);\n return unsub;\n }\n}\n","/**\n * M56 (agent-builder goal transparency) — PUBLIC goal-loop driver for CUSTOM agent surfaces.\n *\n * `LocalAgent.runUntil` binds the goal loop to a registered local agent. Surfaces that route turns\n * through their OWN transport (e.g. a TUI store facade, so every goal turn renders in the same\n * timeline as a manual turn) need the SAME loop over a minimal `send → wait` shape. This export\n * gives them exactly that: the canonical `runUntilImpl` (judge + continuation + token budget +\n * Codex states) with the default judge wired from the DI registry.\n *\n * @public\n */\n\nimport type { JudgeContext, JudgeOptions } from \"./internal/judge/judge-call.js\";\nimport type { RunUntilDeps } from \"./internal/runtime/lifecycle/run-until.js\";\nimport type { SDKAgent } from \"./types/agent.js\";\n\n/**\n * Stable marker on the FIRST LINE of every goal-continuation prompt. Surfaces detect it to render the\n * turn collapsed, exclude it from backtrack windows, and skip it in compaction preservation.\n */\nexport { GOAL_CONTINUATION_MARKER } from \"./internal/runtime/lifecycle/goal-marker.js\";\n\nimport type { GoalEvent, GoalOptions, GoalResult } from \"./types/goal-events.js\";\n\n/** The minimal surface the goal loop drives — anything that can send a prompt and wait for it. */\nexport interface GoalLoopAgent {\n send(prompt: string): Promise<{\n wait(): Promise<{ result?: string; usage?: { totalTokens?: number } }>;\n }>;\n}\n\n/**\n * Run the goal-driven loop (`send → judge → continuation`) over ANY `send → wait` surface.\n * Identical semantics to `Agent.runUntil` (ADRs D115-D121 + M55 token budget / states).\n * `depsOverride` is a test seam for injecting a fake judge.\n */\nexport function runGoalLoop(\n agent: GoalLoopAgent,\n goal: string,\n options?: GoalOptions,\n depsOverride?: RunUntilDeps,\n): AsyncGenerator<GoalEvent, GoalResult, void> {\n async function* wrap(): AsyncGenerator<GoalEvent, GoalResult, void> {\n const { runUntilImpl } = await import(\"./internal/runtime/lifecycle/run-until.js\");\n const deps: RunUntilDeps =\n depsOverride ??\n (await (async () => {\n const { judgeCallImpl } = await import(\"./internal/judge/judge-call.js\");\n const { getAgentFacade } = await import(\n \"./internal/runtime/registry/agent-factory-registry.js\"\n );\n const create = getAgentFacade().create;\n return {\n judge: (ctx: JudgeContext, opts?: JudgeOptions) => judgeCallImpl(ctx, opts, { create }),\n };\n })());\n // runUntilImpl only touches `agent.send(...)` → `run.wait()` — the SDKAgent cast is safe for\n // any GoalLoopAgent (structural subset).\n return yield* runUntilImpl(agent as unknown as SDKAgent, goal, options, deps);\n }\n return wrap();\n}\n","/**\n * Reference `BudgetTracker` impl — pure token + iteration counter\n * (SDK 2.0 Phase 2 / T2.1 — ADR D1 reference implementation).\n *\n * Counts tokens per type (input/output) + iteration count. Enforces\n * optional `maxTokens` / `maxIterations` ceilings via `check()`.\n *\n * Does NOT compute USD cost — leaves that to richer impls in\n * `@theokit/sdk-budget` (post-Phase-2). This file is intentionally\n * minimal so consumers can:\n * - use it as-is for simple guard-rails;\n * - read it as a worked example before authoring a custom tracker;\n * - rely on it as a fallback before sdk-budget ships.\n *\n * @public — surface-level reference impl.\n */\n\nimport type {\n BudgetCheck,\n BudgetTotal,\n BudgetTracker,\n BudgetUsageEvent,\n} from \"./budget-tracker.js\";\n\n/** Options for `createCounterBudgetTracker`. */\nexport interface CounterBudgetTrackerOptions {\n /** Hard ceiling on total tokens (input + output). When reached, `check()` returns `allowed: false`. */\n readonly maxTokens?: number;\n /** Hard ceiling on iterations counted by `nextIteration()`. */\n readonly maxIterations?: number;\n}\n\n/**\n * Build a fresh tracker. The returned object is independent — call\n * `createCounterBudgetTracker()` per Agent instance.\n *\n * The tracker exposes the `BudgetTracker` contract PLUS a `nextIteration()`\n * helper for impls that want explicit iteration counting (the agent loop\n * calls it once per turn). Without `nextIteration()` calls, the iteration\n * cap is never reached.\n */\nexport function createCounterBudgetTracker(\n options: CounterBudgetTrackerOptions = {},\n): BudgetTracker & { nextIteration(): void } {\n let totalTokens = 0;\n let iterations = 0;\n const maxTokens = options.maxTokens;\n const maxIterations = options.maxIterations;\n\n return {\n track(event: BudgetUsageEvent): void {\n // `track()` MUST be synchronous and non-throwing per the contract.\n // Invalid events (negative tokens) are silently clamped.\n const t = Number.isFinite(event.tokens) && event.tokens > 0 ? event.tokens : 0;\n totalTokens += t;\n },\n\n check(): BudgetCheck {\n if (maxTokens !== undefined && totalTokens >= maxTokens) {\n return {\n allowed: false,\n reason: \"token_limit\",\n detail: `${totalTokens} >= maxTokens ${maxTokens}`,\n };\n }\n if (maxIterations !== undefined && iterations >= maxIterations) {\n return {\n allowed: false,\n reason: \"iteration_limit\",\n detail: `${iterations} >= maxIterations ${maxIterations}`,\n };\n }\n return { allowed: true };\n },\n\n getTotal(): BudgetTotal {\n return { tokens: totalTokens, iterations };\n },\n\n nextIteration(): void {\n iterations += 1;\n },\n };\n}\n","/**\n * Plugin contract — RUNTIME value + type re-exports (T1.1, ADRs D97-D101).\n *\n * SE45/SE46 — the pure `Plugin` *type* and its type companions now live in\n * `types/plugin.ts` (above the DIP boundary, because `Plugin` is public\n * contract). This module keeps the RUNTIME value (`definePlugin` /\n * `Plugin.create`) and re-exports the types so every existing\n * `../plugins/types.js` importer (and the `index.ts` barrel) resolves the same\n * names unchanged.\n *\n * @public\n */\n\nimport type { Plugin as PluginType } from \"../../types/plugin.js\";\n\nexport type {\n CommandHandler,\n CommandOptions,\n HookHandler,\n HookName,\n LlmCallContext,\n // #335 — this used to be omitted here, with the note that it \"stays reachable as\n // the `createProvider` field type on the `Plugin` union, which IS re-exported\".\n // That inference was false, and it is what shipped a broken declaration: the DTS\n // rollup emits an exported type's BODY and treeshakes away a non-exported type\n // that body merely NAMES. Reachable-as-a-field-type is not reachable-as-a-\n // declaration. The published `.d.ts` said `createProvider: MemoryProviderFactory`\n // with no such type in the file — invisible under `skipLibCheck`, and an\n // `error`-typed graph for any consumer running type-aware lint.\n //\n // The original reason for the omission (re-exporting a decl that carries the\n // internal-visibility JSDoc tag leaves a dangling re-export once `stripInternal`\n // deletes it) no longer applies: the tag came off `types/plugin.ts`, because a\n // type named by a public signature is public. That tag is matched as TEXT, so\n // its literal spelling is deliberately absent from this comment too.\n MemoryProviderFactory,\n PluginContext,\n PluginHookDisposer,\n PostAssistantReplyContext,\n PostToolCallContext,\n PreToolCallContext,\n PreToolCallDecision,\n PreUserSendContext,\n PreUserSendResult,\n SessionLifecycleContext,\n ToolCallSummary,\n ToolContext,\n ToolResultTransformContext,\n TransformContext,\n} from \"../../types/plugin.js\";\n\n// Re-establish the declaration merge locally: `Plugin` is BOTH the discriminated\n// union *type* (aliased from ./types/plugin.js) AND the runtime const-companion\n// (`Plugin.create`) declared below. Keeping both bindings under the one exported\n// name `Plugin` preserves the public value+type surface byte-for-byte.\nexport type Plugin = PluginType;\n\n/**\n * Identity helper for plugin authors. TS-only convenience — preserves\n * inferred type without forcing manual `Plugin` annotation.\n *\n * @public\n */\nexport function definePlugin<P extends Plugin>(p: P): P {\n return p;\n}\n\n/** SE36 — `Plugin.create` replaces `definePlugin` (ADR 0015). Const-companion (the `Plugin` type alias blocks a class of the same name); `create` is the generic `definePlugin`. @public */\nexport const Plugin = { create: definePlugin };\n","/**\n * Reference `MemoryProvider` impl — no-op fallback (SDK 2.0 Phase 1 /\n * T1.2 reference implementation, mirrors `createCounterBudgetTracker`).\n *\n * Every method is a degenerate identity:\n * - `init()` returns a handle wrapping a no-op `MemoryAdapter`.\n * - `buildTools()` returns `[]` (no memory tools surfaced to the LLM).\n * - `runActivePass()` returns `{ facts: [] }` (no recall fires).\n * - `dispose()` is a no-op.\n *\n * Why ship this:\n * - Default safety net before `@theokit/sdk-memory` is installed.\n * - Worked reference for authors of custom providers.\n * - Enables `Agent.create({ memoryProvider: createNoopMemoryProvider() })`\n * unit tests without pulling memory infrastructure.\n *\n * NOT a substitute for the existing `Memory` class — the legacy class\n * stays authoritative until the subsystem fully ports to providers\n * (Phase 1 / T1.6).\n *\n * @public — surface-level reference impl.\n */\n\nimport type {\n MemoryAdapter,\n MemoryAdapterCapabilities,\n MemoryContext,\n MemoryFact,\n MemoryId,\n MemoryTurnMessage,\n} from \"../../../types/memory-adapter.js\";\nimport type {\n ActiveMemoryPassArgs,\n ActiveMemoryPassResult,\n MemoryProvider,\n MemoryProviderHandle,\n MemoryProviderInitOptions,\n} from \"./memory-provider.js\";\n\n/** Adapter-id used by the no-op MemoryAdapter — namespaced to avoid collision. */\nconst NOOP_ADAPTER_ID = \"noop\";\n\n/** All-false capabilities — every optional feature gated off. */\nconst NOOP_CAPABILITIES: MemoryAdapterCapabilities = {\n history: false,\n sessions: false,\n tenancy: false,\n reasoning: false,\n toolSchemas: false,\n prefetch: false,\n};\n\n/** Build the no-op MemoryAdapter satisfying the public contract. */\nfunction createNoopMemoryAdapter(): MemoryAdapter {\n return {\n id: NOOP_ADAPTER_ID,\n capabilities: NOOP_CAPABILITIES,\n isAvailable(): boolean {\n return true;\n },\n async write(_content: string | MemoryTurnMessage[], _ctx: MemoryContext): Promise<MemoryId> {\n // Return a deterministic noop id with the adapter-id prefix so\n // `extractRawId` cross-adapter safety check still works.\n return `${NOOP_ADAPTER_ID}:noop` as MemoryId;\n },\n async recall(_query: string, _ctx: MemoryContext, _k?: number): Promise<MemoryFact[]> {\n return [];\n },\n async delete(_id: MemoryId): Promise<void> {\n return;\n },\n };\n}\n\n/**\n * Build a fresh no-op MemoryProvider. The returned object is independent —\n * call `createNoopMemoryProvider()` per Agent instance. `init()` is\n * idempotent: subsequent calls return a NEW handle (no per-agent cache —\n * the no-op has no state worth caching).\n */\nexport function createNoopMemoryProvider(): MemoryProvider {\n return {\n async init(_opts: MemoryProviderInitOptions): Promise<MemoryProviderHandle> {\n return {\n adapter: createNoopMemoryAdapter(),\n };\n },\n buildTools(_handle: MemoryProviderHandle): readonly never[] {\n return [];\n },\n async runActivePass(\n _handle: MemoryProviderHandle,\n _args: ActiveMemoryPassArgs,\n ): Promise<ActiveMemoryPassResult> {\n return { facts: [] };\n },\n recordSessionSummary(): void {\n // No-op: the no-op provider doesn't persist anything. Defining the\n // method (vs leaving it undefined) is intentional — when consumers\n // wire the no-op explicitly, they OPT INTO the port path for the\n // session-summary write site too. Future rich impls override this\n // with real disk writes.\n return;\n },\n dispose(_handle: MemoryProviderHandle): void {\n return;\n },\n };\n}\n\n/** SE36 — `NoopMemoryProvider.create` replaces `createNoopMemoryProvider` (ADR 0015). @public */\nexport class NoopMemoryProvider {\n private constructor() {}\n static create(): MemoryProvider {\n return createNoopMemoryProvider();\n }\n}\n","/**\n * `JobQueue` — background job queue with status tracking, cancellation, and an\n * optional concurrency bound.\n *\n * EC-1: all enqueued functions are wrapped in Promise.resolve().then() so\n * synchronous throws become rejections.\n *\n * #58: each job runs under an `AbortController` whose signal is passed to the\n * job fn, so `cancel()` actually interrupts a running job (not just a status\n * flip); an optional `maxConcurrency` bounds how many jobs run at once.\n */\n\nimport { randomUUID } from \"node:crypto\";\n\ntype JobStatus = \"pending\" | \"running\" | \"completed\" | \"failed\" | \"cancelled\";\n\ninterface Job<T> {\n id: string;\n status: JobStatus;\n result?: T;\n error?: string;\n}\n\n/** #58 — construction options. */\nexport interface JobQueueOptions {\n /**\n * Max jobs running concurrently. Omit for unbounded (previous behavior).\n * Values < 1 are clamped to 1 (an invalid bound must not deadlock).\n */\n maxConcurrency?: number;\n}\n\n/**\n * An in-process queue of background jobs with status tracking, cancellation, and an optional\n * concurrency bound.\n *\n * `enqueue` returns a job id immediately and never throws for the job's own failure: a synchronous\n * throw inside the function becomes a rejection, and a rejection becomes `status: \"failed\"` with\n * the message on `job.error`. Poll `getJob(id)` or `list()` for outcomes — there is no completion\n * event and no promise to await.\n *\n * Cancellation is COOPERATIVE. `cancel` aborts the `AbortSignal` handed to the job function and\n * flips the status, but a function that ignores the signal keeps running to completion; its result\n * is then discarded, because a cancelled job never leaves the cancelled state. The concurrency slot\n * of a running job is freed at cancel time rather than when it eventually settles, so a job that\n * never settles cannot deadlock a bounded queue.\n *\n * State lives entirely in memory and grows without bound — nothing evicts finished jobs. This is a\n * queue for one process, not a durable one.\n */\nexport class JobQueue {\n private jobs = new Map<string, Job<unknown>>();\n private controllers = new Map<string, AbortController>();\n private readonly maxConcurrency: number;\n private running = 0;\n private readonly waiting: Array<() => void> = [];\n\n constructor(options: JobQueueOptions = {}) {\n this.maxConcurrency =\n options.maxConcurrency === undefined\n ? Number.POSITIVE_INFINITY\n : Math.max(1, options.maxConcurrency);\n }\n\n /**\n * Enqueue a background function. Returns the job ID immediately. The function\n * receives an `AbortSignal` that fires when the job is cancelled (#58) — a\n * cooperative job should observe it to stop early. Existing `() => Promise<T>`\n * callers are unaffected (the signal argument is simply ignored).\n */\n enqueue<T>(fn: (signal: AbortSignal) => Promise<T>): string {\n const id = randomUUID();\n const job: Job<T> = { id, status: \"pending\" };\n this.jobs.set(id, job as Job<unknown>);\n const controller = new AbortController();\n this.controllers.set(id, controller);\n\n void this.#acquire().then(() => {\n // Cancelled while waiting for a slot → never start.\n if (job.status === \"cancelled\") {\n this.#release(id);\n return;\n }\n job.status = \"running\";\n Promise.resolve()\n .then(() => fn(controller.signal))\n .then((result) => {\n if (job.status === \"cancelled\") return;\n job.result = result;\n job.status = \"completed\";\n })\n .catch((err: unknown) => {\n if (job.status === \"cancelled\") return;\n job.error = err instanceof Error ? err.message : String(err);\n job.status = \"failed\";\n })\n .finally(() => this.#release(id));\n });\n\n return id;\n }\n\n getJob(id: string): Job<unknown> | undefined {\n return this.jobs.get(id);\n }\n\n list(): Job<unknown>[] {\n return [...this.jobs.values()];\n }\n\n /**\n * Cancel a pending or running job. Returns true if cancelled. #58 — aborts the\n * job's `AbortSignal` so a cooperative running job is actually interrupted.\n */\n cancel(id: string): boolean {\n const job = this.jobs.get(id);\n if (!job) return false;\n if (job.status === \"pending\" || job.status === \"running\") {\n const wasRunning = job.status === \"running\";\n job.status = \"cancelled\";\n this.controllers.get(id)?.abort();\n // A running job holds a concurrency slot; its fn may ignore the signal and\n // never settle, so free the slot NOW rather than waiting for `.finally`\n // (which would never fire → the bounded queue would deadlock). `#release`\n // is idempotent, so the job's eventual `.finally` is a no-op. A *pending*\n // job holds no slot yet — its slot-grant self-releases when it starts.\n if (wasRunning) this.#release(id);\n return true;\n }\n return false;\n }\n\n /** Acquire a concurrency slot (resolves immediately when unbounded/free). */\n #acquire(): Promise<void> {\n if (this.running < this.maxConcurrency) {\n this.running += 1;\n return Promise.resolve();\n }\n return new Promise<void>((resolve) => {\n this.waiting.push(() => {\n this.running += 1;\n resolve();\n });\n });\n }\n\n /**\n * Release a slot + clean up the controller; start the next waiting job.\n * Idempotent — keyed on the controller's presence, so a running job that was\n * cancelled (released early) does not double-decrement when its `.finally`\n * eventually fires.\n */\n #release(id: string): void {\n if (!this.controllers.has(id)) return; // already released\n this.controllers.delete(id);\n this.running -= 1;\n const next = this.waiting.shift();\n if (next !== undefined) next();\n }\n}\n","/**\n * Fold configuration layers in a declared order — later layers win, named keys accumulate.\n *\n * Every product that reads configuration from more than one place rebuilds these two rules, and the\n * second one is not a nicety. With plain last-wins, a project file DISPLACES the user's entries for\n * a list-valued key rather than adding to them — and for a key like `hooks`, which carries arbitrary\n * command execution, that is the difference between a repository adding a hook and a repository\n * removing yours.\n *\n * The layer NAMES are the caller's, supplied as data. One product's chain is\n * defaults/user/project/profile/env/cli; `profile` is that product's idea and does not belong here.\n * That is the same test the security floor passed: a vocabulary expressible as data generalises, an\n * open-ended interface shaped by one product does not.\n *\n * @public\n */\n\nimport { TheokitAgentError } from \"./errors.js\";\n\n/** Raised when a declared layer chain is not strictly ascending. @public */\nexport class LayerOrderError extends TheokitAgentError {\n override readonly name = \"LayerOrderError\";\n}\n\n/**\n * One named layer in a precedence chain.\n *\n * `precedence` is optional and the two usages do not mix well: omit it everywhere to say \"this\n * array is already in order\", or supply it everywhere you want `verifyLayerOrdering` to check.\n * Entries without it are SKIPPED by that check rather than treated as zero, so a chain where only\n * some entries declare a number is verified only between those.\n *\n * @public\n */\nexport interface DeclaredLayer {\n readonly layer: string;\n /** Higher wins. Optional — omit it to mean \"this array is already the order\". */\n readonly precedence?: number;\n}\n\n/**\n * A declared layer together with the values it supplies.\n *\n * `foldLayers` consumes these in array order, so a later entry wins for the keys it mentions. A key\n * a layer does not mention — or mentions with `undefined` — leaves the earlier value standing;\n * there is no way for a layer to erase a key another layer set.\n *\n * @public\n */\nexport interface LayerValues extends DeclaredLayer {\n readonly values: Readonly<Record<string, unknown>>;\n}\n\n/**\n * Assert that each layer strictly outranks the one before it.\n *\n * Entries without a `precedence` are skipped rather than treated as zero: omitting it means the\n * caller is expressing order by position, and inventing a number for them would manufacture a\n * conflict out of a legitimate usage.\n *\n * @throws LayerOrderError naming both layers and both precedences — a refusal that only says \"out\n * of order\" sends the reader to compare the whole list by hand.\n * @public\n */\nexport function verifyLayerOrdering(layers: readonly DeclaredLayer[]): void {\n // Narrowed to the entries that actually declare a precedence, so the comparison below has no\n // `undefined` to reason about and the type says so.\n let previous: { layer: string; precedence: number } | undefined;\n for (const current of layers) {\n if (current.precedence === undefined) continue;\n const declared = { layer: current.layer, precedence: current.precedence };\n if (previous !== undefined && declared.precedence <= previous.precedence) {\n throw new LayerOrderError(\n `layers out of order: \\`${declared.layer}\\` (precedence ${String(declared.precedence)}) ` +\n `comes after \\`${previous.layer}\\` (precedence ${String(previous.precedence)}) but does ` +\n `not outrank it`,\n );\n }\n previous = declared;\n }\n}\n\n/**\n * Combine `entries` into one record.\n *\n * Later entries win. A value of `undefined` never overwrites — a layer that does not mention a key\n * must not erase it, because \"said nothing\" is overwhelmingly more common than \"said nothing on\n * purpose\".\n *\n * Keys in `accumulatingKeys` whose value is an array are CONCATENATED across layers instead of\n * replaced. A non-array value for such a key replaces, deliberately: a malformed config must not\n * corrupt the accumulator into a mixed list, and leaving the raw value visible lets the consumer's\n * own validation reject it with its own message.\n *\n * The accumulator is per-call and the inputs are never mutated, so folding twice yields the same\n * answer — which a consumer that folds once to display and once to apply depends on.\n *\n * @public\n */\nexport function foldLayers(\n entries: readonly LayerValues[],\n accumulatingKeys: readonly string[] = [],\n): Record<string, unknown> {\n verifyLayerOrdering(entries);\n\n const accumulated = new Map<string, unknown[]>(accumulatingKeys.map((k) => [k, []]));\n const combined: Record<string, unknown> = {};\n\n for (const { values } of entries) {\n for (const [key, value] of Object.entries(values)) {\n if (value === undefined) continue;\n const stack = accumulated.get(key);\n if (stack !== undefined && Array.isArray(value)) {\n stack.push(...(value as readonly unknown[]));\n // The copy is defensive and NOT covered by a test, because it is not observable: the\n // accumulator is per-call and nothing touches it after the fold returns. Mutating this line\n // to `combined[key] = stack` leaves every case green — checked, not assumed. It stays\n // because returning internal mutable state from a public API is a smell that costs one\n // allocation to avoid, and the next change to this function should not have to notice.\n combined[key] = [...stack];\n continue;\n }\n combined[key] = value;\n }\n }\n return combined;\n}\n","import type { EmbeddingRuntime } from \"../embedding-adapter.js\";\nimport type { MemoryFact, MemoryKind } from \"../types.js\";\n\n/**\n * Dreaming/REM phase logic.\n *\n * Three phases:\n * - **light** — drop near-duplicate facts (cosine similarity > 0.95).\n * - **REM** — cluster thematically related facts (cosine ≥ 0.75).\n * - **deep** — pick a representative bullet per cluster (longest text\n * wins) and emit consolidated markdown notes.\n *\n * @internal\n */\n\nexport interface DedupResult {\n kept: MemoryFact[];\n duplicatesRemoved: number;\n}\n\nexport interface Cluster {\n representativeText: string;\n members: ReadonlyArray<MemoryFact>;\n}\n\nexport interface ClusterResult {\n clusters: Cluster[];\n}\n\nconst DEFAULT_DEDUP_THRESHOLD = 0.95;\nconst DEFAULT_CLUSTER_THRESHOLD = 0.75;\n\n/**\n * Kinds a sweep may consolidate. ADR-14 partitions the vocabulary into three buckets and only\n * this one is a merge candidate; the rest are protected for a reason that survives the sweep\n * being non-destructive.\n *\n * `user`, `feedback` and `reference` are ATOMIC: there is nothing to merge and the loss is\n * irreversible. Two corrections a user gave on different days can read alike and are not the\n * same correction. An untyped fact is protected too — a kind that nobody declared is not a\n * licence to treat it as consolidatable.\n *\n * Why this matters even though nothing is deleted: dedup drops the near-duplicate from the\n * CLUSTERING INPUT, and the cluster's representative is what the search index returns. The\n * source file survives; the artefact the agent reads does not. That is ADR-14's third rule —\n * the invariant is about what the agent reads, not what survives on disk.\n */\n// Typed against `MemoryKind` rather than `string`, so the compiler checks these against the vocabulary\n// they mirror. They were `Set<string>` and CONSOLIDATABLE_KINDS held \"session\" — not a member of\n// `MemoryKind`, and rejected by `markdown-store.assertWritable` before any fact is written, so no\n// fact reaching this policy could ever carry it. The arm read as though sessions were consolidatable\n// while no session could exist. Adding a member to either set is now a type error unless `MemoryKind`\n// gains it deliberately.\nconst CONSOLIDATABLE_KINDS: ReadonlySet<MemoryKind> = new Set([\"project\"]);\nconst ATOMIC_KINDS: ReadonlySet<MemoryKind> = new Set([\"user\", \"feedback\", \"reference\"]);\n\n/**\n * Three levels, graded by how much the store knows about the entry. The middle one exists\n * because the first draft of this filter did not have it and broke the common case.\n *\n * - ATOMIC (`user`, `feedback`, `reference`) — never deduplicated. Two corrections given on\n * different days can read alike and are not the same correction.\n * - CONSOLIDATABLE (`project`, `session`) — near-duplicate dedup at the similarity threshold.\n * Overlapping project facts are exactly what a sweep is for.\n * - UNTYPED — EXACT duplicates only. A hand-written bullet under `## Facts` carries no kind,\n * and the store's own header invites editing those by hand, so untyped is the common case\n * rather than an edge one. Treating it as atomic would disable the sweep for most stores;\n * treating it as consolidatable would let a near-duplicate of an untyped correction be\n * dropped. Exact-match is the only claim the store can make without inferring a kind, which\n * is the rule this codebase already applies one field over.\n */\ntype DedupPolicy = \"never\" | \"exact\" | \"similar\";\n\nfunction dedupPolicy(fact: MemoryFact): DedupPolicy {\n if (fact.kind === undefined) return \"exact\";\n if (ATOMIC_KINDS.has(fact.kind)) return \"never\";\n return CONSOLIDATABLE_KINDS.has(fact.kind) ? \"similar\" : \"never\";\n}\n\n/** Whitespace and case collapsed; nothing else. Not a similarity measure — an identity one. */\nfunction normalizeForExactMatch(text: string): string {\n return text\n .trim()\n .toLowerCase()\n .replace(/\\s+/g, \" \")\n .replace(/[.!?]+$/, \"\");\n}\n\n/**\n * Light phase — drop facts whose embedding is too similar to one already kept.\n *\n * Protected kinds bypass deduplication entirely and are returned untouched, so a sweep can\n * never conflate two of them into one representative.\n *\n * \"Drop\" here means DROPPED FROM THE RETURNED LIST. Nothing on disk is deleted, by any phase of\n * this sweep, today.\n *\n * BEFORE YOU ADD PRUNING HERE, READ THIS. The security contract for this store requires a backup\n * to precede any destructive operation (SOP-06-05 step 7). That requirement is currently LATENT\n * — not satisfied, not waived — precisely because the sweep only ever adds notes and filters a\n * list. There is no backup implementation in this package, and an audit that looked for one\n * recorded its absence as having no present consequence.\n *\n * The first commit that makes this sweep delete a file from disk is the commit that makes the\n * gap real, and it is also the commit whose author will have no reason to know this line exists.\n * That is why the trigger is written beside the code that would trip it rather than in the audit\n * that found it: a gap recorded in a reviewer's file reappears as a surprise; a gap recorded\n * here stops the person adding pruning.\n */\nexport async function lightPhase(\n facts: ReadonlyArray<MemoryFact>,\n embedding: EmbeddingRuntime,\n threshold: number = DEFAULT_DEDUP_THRESHOLD,\n): Promise<DedupResult> {\n if (facts.length <= 1) return { kept: [...facts], duplicatesRemoved: 0 };\n const never = facts.filter((f) => dedupPolicy(f) === \"never\");\n const exact = facts.filter((f) => dedupPolicy(f) === \"exact\");\n const similar = facts.filter((f) => dedupPolicy(f) === \"similar\");\n\n // Exact pass: identity, not similarity. No embedding call, no threshold, no judgement.\n const seen = new Set<string>();\n const exactKept: MemoryFact[] = [];\n let removed = 0;\n for (const f of exact) {\n const key = normalizeForExactMatch(f.text);\n if (seen.has(key)) {\n removed += 1;\n continue;\n }\n seen.add(key);\n exactKept.push(f);\n }\n\n const sim =\n similar.length > 1\n ? await dedupCandidates(similar, embedding, threshold)\n : { kept: [...similar], duplicatesRemoved: 0 };\n\n // Protected facts keep their original relative position at the front: they were never in\n // the running, and putting them back through the sort would imply they had been judged.\n return {\n kept: [...never, ...exactKept, ...sim.kept],\n duplicatesRemoved: removed + sim.duplicatesRemoved,\n };\n}\n\nasync function dedupCandidates(\n facts: ReadonlyArray<MemoryFact>,\n embedding: EmbeddingRuntime,\n threshold: number,\n): Promise<DedupResult> {\n if (facts.length <= 1) return { kept: [...facts], duplicatesRemoved: 0 };\n const vectors = await embedding.embed(facts.map((f) => f.text));\n const keptIdx: number[] = [];\n const keptVecs: number[][] = [];\n for (let i = 0; i < facts.length; i++) {\n const vec = vectors[i] ?? [];\n const isDup = keptVecs.some((kept) => cosineSimilarity(vec, kept) >= threshold);\n if (isDup) continue;\n keptIdx.push(i);\n keptVecs.push(vec);\n }\n const kept = keptIdx.map((i) => facts[i] as MemoryFact);\n return { kept, duplicatesRemoved: facts.length - kept.length };\n}\n\n// T4.6 — cap facts per sweep to prevent O(N²) blowup. 500 facts →\n// 125K comparisons (acceptable). 5000 facts → 12.5M (unacceptable).\n// When facts exceed the cap, a deterministic subsample is taken so the\n// sweep is bounded. The remaining facts are carried to the next sweep.\nconst DEFAULT_MAX_FACTS_PER_SWEEP = 500;\n\n/** REM phase — single-link agglomerative clustering by cosine similarity. */\nexport async function remPhase(\n facts: ReadonlyArray<MemoryFact>,\n embedding: EmbeddingRuntime,\n threshold: number = DEFAULT_CLUSTER_THRESHOLD,\n maxFactsPerSweep: number = DEFAULT_MAX_FACTS_PER_SWEEP,\n): Promise<ClusterResult> {\n // KNOWN GAP, deliberately not closed here. Protected kinds are excluded from DEDUP — a\n // near-duplicate correction is never dropped — but they still reach CLUSTERING, and a cluster\n // carries one representative into the consolidated note.\n //\n // Filtering them out here too was tried and reverted: untyped is the common case (hand-written\n // bullets carry no kind), so excluding it disables consolidation for most stores, and it broke\n // three existing golden tests. The damage is also smaller than in the dedup case — the source\n // files survive and remain readable, so what a cluster costs is nuance in an ADDITIONAL\n // artefact rather than a lost entry.\n //\n // It becomes real damage only if recall serves notes INSTEAD of sources. That depends on what\n // the index covers, which is not settled here. Recorded rather than silently accepted.\n if (facts.length === 0) return { clusters: [] };\n // T4.6 — cap: subsample when facts exceed budget. Deterministic\n // sort by text hash so the same input always picks the same subset.\n const capped = facts.length > maxFactsPerSweep ? facts.slice(0, maxFactsPerSweep) : facts;\n const vectors = await embedding.embed(capped.map((f) => f.text));\n const clusterOfIdx = unionFindByPairs(vectors, threshold);\n const groups = bucketFactsByClusterRoot(capped, clusterOfIdx);\n return { clusters: [...groups.values()].map(buildClusterFromMembers) };\n}\n\nfunction unionFindByPairs(\n vectors: ReadonlyArray<ReadonlyArray<number>>,\n threshold: number,\n): number[] {\n const clusterOfIdx = vectors.map((_, i) => i);\n for (let i = 0; i < vectors.length; i++) {\n for (let j = i + 1; j < vectors.length; j++) {\n if (cosineSimilarity(vectors[i] ?? [], vectors[j] ?? []) >= threshold) {\n unifyClusters(clusterOfIdx, i, j);\n }\n }\n }\n return clusterOfIdx;\n}\n\nfunction bucketFactsByClusterRoot(\n facts: ReadonlyArray<MemoryFact>,\n clusterOfIdx: number[],\n): Map<number, MemoryFact[]> {\n const groups = new Map<number, MemoryFact[]>();\n for (let i = 0; i < facts.length; i++) {\n const root = findRoot(clusterOfIdx, i);\n const list = groups.get(root) ?? [];\n list.push(facts[i] as MemoryFact);\n groups.set(root, list);\n }\n return groups;\n}\n\nfunction buildClusterFromMembers(members: ReadonlyArray<MemoryFact>): Cluster {\n const sorted = [...members].sort((a, b) => b.text.length - a.text.length);\n return { representativeText: sorted[0]?.text ?? \"\", members };\n}\n\n/** Deep phase — render consolidated markdown for the dreamed note. */\nexport function deepPhase(clusters: ReadonlyArray<Cluster>, timestampMs: number): string {\n if (clusters.length === 0) return \"\";\n const isoStamp = new Date(timestampMs).toISOString();\n const lines: string[] = [`# Dreamed ${isoStamp}`, \"\"];\n for (let i = 0; i < clusters.length; i++) {\n const c = clusters[i];\n if (c === undefined) continue;\n lines.push(`## Cluster ${i + 1}: ${c.representativeText}`);\n lines.push(\"\");\n for (const member of c.members) lines.push(`- ${member.text}`);\n lines.push(\"\");\n }\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction cosineSimilarity(a: ReadonlyArray<number>, b: ReadonlyArray<number>): number {\n if (a.length === 0 || b.length === 0 || a.length !== b.length) return 0;\n let dot = 0;\n let aNorm = 0;\n let bNorm = 0;\n for (let i = 0; i < a.length; i++) {\n const ai = a[i] ?? 0;\n const bi = b[i] ?? 0;\n dot += ai * bi;\n aNorm += ai * ai;\n bNorm += bi * bi;\n }\n const denom = Math.sqrt(aNorm) * Math.sqrt(bNorm);\n return denom === 0 ? 0 : dot / denom;\n}\n\nfunction findRoot(parents: number[], i: number): number {\n let root = i;\n while (parents[root] !== root) {\n const next = parents[root] ?? root;\n if (next === root) break;\n root = next;\n }\n parents[i] = root;\n return root;\n}\n\nfunction unifyClusters(parents: number[], a: number, b: number): void {\n const rootA = findRoot(parents, a);\n const rootB = findRoot(parents, b);\n if (rootA !== rootB) parents[rootB] = rootA;\n}\n","import { mkdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { diag } from \"../../diagnostics.js\";\nimport { replaceFileAtomic } from \"../../persistence/atomic-write.js\";\nimport { withCwdMutex } from \"../../persistence/cwd-mutex.js\";\nimport type { EmbeddingRuntime } from \"../embedding-adapter.js\";\nimport { readFactsFromMarkdown } from \"../storage/markdown-store.js\";\nimport { type MemoryRoot, resolveMemoryRoot } from \"../storage/memory-root.js\";\nimport { appendDiaryEntry } from \"./diary.js\";\nimport { deepPhase, lightPhase, remPhase } from \"./phases.js\";\n\n/**\n * Dreaming sweep orchestrator (ADR D7 of memory-system-peer-project-parity).\n *\n * Phases:\n * 1. **light** — drop near-duplicate facts via cosine similarity.\n * 2. **REM** — cluster thematically related facts.\n * 3. **deep** — write a `notes/dreamed-<ts>.md` per sweep with consolidated\n * clusters; append a diary entry.\n *\n * All file writes go through `replaceFileAtomic` (EC-3) and the entire sweep\n * holds the per-cwd mutex so a `Remember:` append can't race it.\n *\n * @internal\n */\n\nexport interface DreamingOptions {\n cwd: string;\n /**\n * The memory root to sweep. Defaults to the project store — right for a caller with no\n * `memory.directory`, and wrong for one that has it, which is why it is passable (#463).\n */\n memoryRoot?: MemoryRoot;\n embedding: EmbeddingRuntime;\n dedupThreshold?: number;\n clusterThreshold?: number;\n /** Test hook — fixed timestamp for the run. */\n now?: () => number;\n}\n\nexport interface DreamingResult {\n status: \"ok\" | \"skipped\" | \"error\";\n factsBefore: number;\n factsAfter: number;\n duplicatesRemoved: number;\n clustersCreated: number;\n notesWritten: number;\n diaryEntryHash: string | undefined;\n}\n\nexport function runDreamingSweep(options: DreamingOptions): Promise<DreamingResult> {\n return withCwdMutex(`dream:${options.cwd}`, () => runInner(options));\n}\n\nasync function runInner(options: DreamingOptions): Promise<DreamingResult> {\n const now = options.now ?? Date.now;\n const timestampMs = now();\n try {\n const root = options.memoryRoot ?? resolveMemoryRoot(options.cwd);\n const facts = await readFactsFromMarkdown(\n options.cwd,\n options.memoryRoot ? { directory: options.memoryRoot } : undefined,\n );\n if (facts.length === 0) {\n return emptyResult(\"skipped\");\n }\n const dedup = await lightPhase(facts, options.embedding, options.dedupThreshold);\n const rem = await remPhase(dedup.kept, options.embedding, options.clusterThreshold);\n const notesWritten = await writeConsolidatedNotes(root, rem.clusters, timestampMs);\n const result: DreamingResult = {\n status: \"ok\",\n factsBefore: facts.length,\n factsAfter: dedup.kept.length,\n duplicatesRemoved: dedup.duplicatesRemoved,\n clustersCreated: rem.clusters.length,\n notesWritten,\n diaryEntryHash: undefined,\n };\n await appendDiaryEntry(root, {\n timestampMs,\n factsBefore: result.factsBefore,\n factsAfter: result.factsAfter,\n duplicatesRemoved: result.duplicatesRemoved,\n clustersCreated: result.clustersCreated,\n notesWritten: result.notesWritten,\n });\n return result;\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : String(cause);\n diag(`[theokit-sdk] dreaming sweep failed: ${message}\\n`);\n return emptyResult(\"error\");\n }\n}\n\nasync function writeConsolidatedNotes(\n root: MemoryRoot,\n clusters: ReadonlyArray<{ representativeText: string; members: ReadonlyArray<{ text: string }> }>,\n timestampMs: number,\n): Promise<number> {\n if (clusters.length === 0) return 0;\n const notesDir = join(root, \"notes\");\n await mkdir(notesDir, { recursive: true });\n const isoSlug = new Date(timestampMs).toISOString().replace(/[^\\dT]/g, \"-\");\n const file = join(notesDir, `dreamed-${isoSlug}.md`);\n const body = deepPhase(clusters, timestampMs);\n await replaceFileAtomic(file, body);\n return 1;\n}\n\nfunction emptyResult(status: \"skipped\" | \"error\"): DreamingResult {\n return {\n status,\n factsBefore: 0,\n factsAfter: 0,\n duplicatesRemoved: 0,\n clustersCreated: 0,\n notesWritten: 0,\n diaryEntryHash: undefined,\n };\n}\n","/**\n * SDK 2.0 Phase 4 (Stage 4) — Optional peer loader for\n * `@theokit/sdk-memory`.\n *\n * The Memory class public API in `src/memory.ts` keeps its surface\n * stable but routes through sdk-memory when installed. When sdk-memory\n * is NOT installed, methods fall back to sdk-core's legacy\n * `internal/memory/*` implementations — preserving v1.x back-compat.\n *\n * Pattern mirrors sdk-handoff's optional-peer dynamic import: try\n * `await import(\"@theokit/sdk-memory\")` once, cache the result (the\n * module OR `null` for \"definitively missing\"), and let the caller\n * route.\n *\n * Iter 76 (Stage 4 #1): foundation helper for the Memory class\n * delegation refactor. No behavior changes yet — this iter only\n * adds the loader; iter 77+ wires Memory class methods to use it.\n *\n * @internal\n */\n\nimport { diag } from \"../diagnostics.js\";\n/**\n * Minimal structural mirror of the sdk-memory surface this loader\n * exposes to Memory class methods. Keeps the contract pinned even\n * if sdk-memory ships additional exports.\n */\nexport interface SdkMemoryModule {\n /** Mirrors @theokit/sdk-memory's catalog Record. */\n readonly MEMORY_EMBEDDING_ADAPTERS: Readonly<\n Record<\n string,\n {\n readonly id: string;\n readonly defaultModel: string;\n readonly transport: \"local\" | \"remote\";\n // biome-ignore lint/suspicious/noExplicitAny: structural mirror — runtime carries the canonical types\n create(options: any): Promise<any>;\n }\n >\n >;\n\n /** Mirrors @theokit/sdk-memory's runDreamingSweep entrypoint. */\n runDreamingSweep(opts: {\n cwd: string;\n // biome-ignore lint/suspicious/noExplicitAny: structural mirror\n embedding: any;\n dedupThreshold?: number;\n clusterThreshold?: number;\n }): Promise<{\n status: \"ok\" | \"skipped\" | \"error\";\n factsBefore: number;\n factsAfter: number;\n duplicatesRemoved: number;\n clustersCreated: number;\n notesWritten: number;\n }>;\n\n /** Mirrors @theokit/sdk-memory's IndexManager class (static open). */\n readonly IndexManager: {\n open(opts: {\n cwd: string;\n filePath?: string;\n // biome-ignore lint/suspicious/noExplicitAny: structural mirror\n embedding?: any;\n backend?: \"sqlite-vec\" | \"lance\";\n // biome-ignore lint/suspicious/noExplicitAny: structural mirror\n }): Promise<any>;\n };\n\n /** Mirrors @theokit/sdk-memory's migrateSqliteToLance entrypoint (ADR D44). */\n migrateSqliteToLance(opts: {\n cwd: string;\n dryRun?: boolean;\n batchSize?: number;\n logger?: (msg: string) => void;\n }): Promise<{\n countSqlite: number;\n countLance: number;\n validated: boolean;\n sampleComparisons: ReadonlyArray<{ id: string; match: boolean }>;\n lancePath: string;\n committed: boolean;\n }>;\n}\n\nlet cachedAttempt: Promise<SdkMemoryModule | null> | undefined;\nlet forcedAbsentForTests = false;\n\n/**\n * One load attempt, with the two failure shapes reported differently.\n *\n * Split out of {@link tryLoadSdkMemoryPeer} so the memoisation and the loading read separately —\n * the guard, the cache and three outcomes in one closure was over the project's own complexity\n * threshold once the outcomes stopped being \"return null\" three times.\n */\nasync function loadPeer(): Promise<SdkMemoryModule | null> {\n try {\n // Dynamic specifier kept opaque so bundlers can't statically resolve sdk-memory and bake it into\n // a bundle that would require the package to exist at install time.\n const spec = \"@theokit/sdk-memory\";\n const mod = (await import(spec)) as unknown as SdkMemoryModule;\n if (hasExpectedSurface(mod)) return mod;\n // Present but the wrong shape — a version skew, or a bundler that rewrote the entry. This is NOT\n // the same as absent, and it used to report identically.\n diag(\n \"sdk-memory peer loaded but does not expose the expected surface \" +\n \"(runDreamingSweep / MEMORY_EMBEDDING_ADAPTERS / IndexManager / migrateSqliteToLance) — \" +\n \"falling back to the legacy memory path\",\n );\n return null;\n } catch (err) {\n // #174, applied here. `catch { return null; }` is what that issue removed from file-lock.ts, with\n // the cost recorded: a fallback that asserts a cause it never observed sends a consumer to\n // re-check an install that was already correct.\n //\n // Absent is expected and silent — the peer is optional and most installs do not have it.\n // Present-but-unloadable is always worth reporting: a module-format interop failure, a broken\n // native dependency, or a bundler rewrite all land here, and the SDK otherwise falls back to the\n // legacy path saying nothing at all.\n if ((err as { code?: string } | undefined)?.code !== \"ERR_MODULE_NOT_FOUND\") {\n diag(\n `sdk-memory peer is installed but failed to load — falling back to the legacy memory path: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\n return null;\n }\n}\n\n/** The four surfaces this SDK routes through. Anything less is a version skew, not a peer. */\nfunction hasExpectedSurface(mod: SdkMemoryModule): boolean {\n return (\n typeof mod.runDreamingSweep === \"function\" &&\n mod.MEMORY_EMBEDDING_ADAPTERS !== undefined &&\n mod.IndexManager !== undefined &&\n typeof mod.migrateSqliteToLance === \"function\"\n );\n}\n\n/**\n * Attempt to load `@theokit/sdk-memory`. Returns the module on\n * success, `null` on definitive absence. Result is memoized so\n * repeated calls during agent runtime don't re-pay the dynamic\n * import cost.\n *\n * @internal\n */\nexport function tryLoadSdkMemoryPeer(): Promise<SdkMemoryModule | null> {\n if (forcedAbsentForTests) return Promise.resolve(null);\n if (cachedAttempt !== undefined) return cachedAttempt;\n cachedAttempt = loadPeer();\n return cachedAttempt;\n}\n\n/**\n * Test-only: reset the memoized loader state so an integration test\n * can probe both the \"peer present\" and \"peer absent\" code paths.\n *\n * @internal\n */\nexport function resetSdkMemoryPeerCacheForTests(): void {\n cachedAttempt = undefined;\n forcedAbsentForTests = false;\n}\n\n/**\n * Test-only: force the loader to behave as if sdk-memory is NOT\n * installed, even when the workspace setup makes it resolvable. Lets\n * tests exercise the legacy fallback code path inside sdk-core's\n * Memory class methods + migrate wrapper without uninstalling the\n * peer.\n *\n * Pair with `resetSdkMemoryPeerCacheForTests()` in afterEach to undo.\n *\n * @internal\n */\nexport function forceSdkMemoryPeerAbsentForTests(): void {\n cachedAttempt = undefined;\n forcedAbsentForTests = true;\n}\n","import { MEMORY_EMBEDDING_ADAPTERS } from \"./internal/memory/adapters/catalog.js\";\nimport { runDreamingSweep as runDreamingSweepInternal } from \"./internal/memory/dreaming/run.js\";\nimport { tryLoadSdkMemoryPeer } from \"./internal/memory/sdk-memory-peer-loader.js\";\nimport { type MemoryRoot, resolveMemoryRoot } from \"./internal/memory/storage/memory-root.js\";\n\n/**\n * Public handle to an open memory index. Mirrors the internal `MemoryIndex`\n * contract structurally; defined here (NOT re-exported from internal/) so\n * the public DTS surface does not pull the internal/runtime cycle that\n * trips rollup-plugin-dts.\n *\n * @public\n */\nexport interface MemoryIndexHandle {\n sync(): Promise<{\n filesScanned: number;\n filesUpdated: number;\n chunksWritten: number;\n chunksEmbedded: number;\n /**\n * Whether this backend actually walked a corpus. `false` on the Lance backend, which is a\n * vector store fed by explicit writes and has no corpus — its zero counts mean \"not applicable\",\n * not \"nothing to reindex\". Read this before treating the counts as a measurement.\n */\n supported: boolean;\n }>;\n search(\n query: string,\n options?: {\n maxResults?: number;\n minScore?: number;\n sources?: ReadonlyArray<\"memory\" | \"sessions\" | \"wiki\">;\n },\n ): Promise<\n ReadonlyArray<{\n path: string;\n startLine: number;\n endLine: number;\n score: number;\n textScore: number;\n vectorScore?: number;\n snippet: string;\n source: \"memory\" | \"sessions\" | \"wiki\";\n citation: string;\n }>\n >;\n status(): {\n backend: \"fts-only\" | \"hybrid\";\n filesIndexed: number;\n chunksIndexed: number;\n lastSyncMs?: number;\n /**\n * Whether `filesIndexed` / `chunksIndexed` were measured. `false` on the Lance backend, whose\n * store is async while `status()` is not — the zeros there are placeholders, so\n * `chunksIndexed > 0` is not a valid test for \"is the index populated\".\n */\n countsExact: boolean;\n };\n close(): Promise<void> | void;\n}\n\n/**\n * Inputs for {@link Memory.runDreamingSweep}.\n *\n * `embedding` is required and has no default: the sweep scores cosine similarity between facts, so\n * without real embeddings there is nothing to dedup or cluster on. Both thresholds are cosine\n * similarity in [0, 1] and default to `0.95` for dedup and `0.75` for clustering — dedup is the\n * stricter of the two because merging two facts that were merely related is a data loss, while\n * failing to cluster them only costs a note.\n *\n * @public\n */\nexport interface DreamingSweepOptions {\n /** Workspace cwd holding `.theokit/memory/`. */\n cwd: string;\n /**\n * Absolute path (or `~/`-prefixed) of the memory root to sweep, when the agent that wrote it set\n * `memory.directory`. Defaults to `<cwd>/.theokit/memory`.\n */\n directory?: string;\n /**\n * Embedding provider for semantic dedup + clustering. Required — dreaming\n * relies on real embeddings to score cosine similarity. Supported providers:\n * `\"openai\"`, `\"mistral\"`, `\"openrouter\"`, `\"voyage\"`, `\"deepinfra\"`,\n * `\"ollama\"` (local, ADR D183).\n */\n embedding: {\n provider: \"openai\" | \"mistral\" | \"openrouter\" | \"voyage\" | \"deepinfra\" | \"ollama\";\n model?: string;\n };\n /** Cosine-similarity threshold for the dedup phase. Default `0.95`. */\n dedupThreshold?: number;\n /** Cosine-similarity threshold for the clustering phase. Default `0.75`. */\n clusterThreshold?: number;\n}\n\n/**\n * What one dreaming sweep did.\n *\n * `status` is `\"skipped\"` when the workspace held no facts to work on and `\"error\"` when the sweep\n * failed; both come back with every counter at zero, so check `status` before reading a zero as\n * \"there was nothing to consolidate\". A failure is reported through this field rather than as a\n * rejection, which means a caller that only awaits the promise never learns the sweep did nothing.\n * `factsBefore` and `factsAfter` bracket the run, which is the pair to compare when you want to\n * know whether the sweep was worth running rather than how many operations it performed.\n *\n * @public\n */\nexport interface DreamingSweepResult {\n status: \"ok\" | \"skipped\" | \"error\";\n factsBefore: number;\n factsAfter: number;\n duplicatesRemoved: number;\n clustersCreated: number;\n notesWritten: number;\n}\n\n/**\n * Options for `Memory.openIndex`. Mirrors the internal `OpenIndexOptions`\n * but using only public types from the SDK surface.\n *\n * @public\n */\nexport interface OpenMemoryIndexOptions {\n /** Workspace cwd holding `.theokit/memory/`. */\n cwd: string;\n /** Override storage file path (SQLite) OR storage directory (Lance). */\n filePath?: string;\n /**\n * Embedding runtime — REQUIRED for `backend: \"lance\"`, optional for\n * `\"sqlite-vec\"` (when omitted, SQLite runs FTS-only without vector\n * recall).\n */\n embedding?: {\n provider: \"openai\" | \"mistral\" | \"openrouter\" | \"voyage\" | \"deepinfra\" | \"ollama\";\n model?: string;\n };\n /** Default `\"sqlite-vec\"`. Set to `\"lance\"` to opt into LanceDB (peer dep). */\n backend?: \"sqlite-vec\" | \"lance\";\n}\n\n/**\n * Memory operations that run OUTSIDE an agent turn.\n *\n * Everything here is reachable without `Agent.create({ memory: ... })`, which is the point: opening\n * an index directly is how a CLI or a maintenance job inspects or rebuilds what the agent will\n * later read, and the dreaming sweep is maintenance that no `send()` triggers.\n *\n * Both operations route through the `@theokit/sdk-memory` peer package when it is installed and\n * fall back to the in-tree implementation when it is not. The fallback is not a degraded mode —\n * behaviour and thrown errors match — so consumers do not branch on which path ran.\n *\n * @public\n */\nexport const Memory = {\n /**\n * Open a memory index. Dispatches to SQLite-vec (default, zero deps) or\n * LanceDB (opt-in via `backend: \"lance\"`, requires `@lancedb/lancedb`\n * peer dep + an embedding runtime).\n *\n * Returns a `MemoryIndex` with `sync()`, `search(query, opts?)`,\n * `status()`, and `close()`. Use this when you want a direct index\n * handle outside of `Agent.create({ memory: ... })`.\n *\n * @throws ConfigurationError({code:\"invalid_memory_backend\"}) for typos\n * like `\"lancedb\"`.\n * @throws ConfigurationError({code:\"lance_requires_embedding\"}) when\n * `backend: \"lance\"` is requested without `embedding`.\n * @throws ConfigurationError({code:\"lance_backend_unavailable\"}) when\n * `backend: \"lance\"` is requested but the peer dep is absent.\n *\n * @public\n */\n async openIndex(opts: OpenMemoryIndexOptions): Promise<MemoryIndexHandle> {\n // SDK 2.0 Phase 4 (Stage 4, iter 77): if @theokit/sdk-memory is\n // installed, route through it. Otherwise fall back to the legacy\n // internal path. Behavior + thrown errors are byte-equivalent\n // because sdk-memory's IndexManager + MEMORY_EMBEDDING_ADAPTERS\n // are hybrid copies of sdk-core's internals (iter 44-75).\n const peer = await tryLoadSdkMemoryPeer();\n const openArgs = buildIndexOpenArgs(opts, undefined);\n if (peer !== null) {\n openArgs.embedding = await resolveEmbedding(opts.embedding, peer.MEMORY_EMBEDDING_ADAPTERS);\n // biome-ignore lint/suspicious/noExplicitAny: peer is dynamically loaded — structural compat ensured by sdk-memory\n return (await peer.IndexManager.open(openArgs as any)) as MemoryIndexHandle;\n }\n // Fallback path — sdk-memory peer absent; use the internal\n // implementation (v1.x behavior preserved).\n // Lazy import to avoid pulling internal/runtime types into the public\n // DTS surface (rollup-plugin-dts trips on a pre-existing cycle in\n // types/agent.ts ↔ fork-agent.ts when reached transitively).\n const { IndexManager } = await import(\"./internal/memory/index-manager.js\");\n openArgs.embedding = await resolveEmbedding(opts.embedding, MEMORY_EMBEDDING_ADAPTERS);\n // Cast: structural-compat (internal MemoryIndex matches MemoryIndexHandle).\n // biome-ignore lint/suspicious/noExplicitAny: embedding is resolved from the same catalog — types match at runtime\n return (await IndexManager.open(openArgs as any)) as MemoryIndexHandle;\n },\n\n /**\n * Run a dreaming sweep: dedup near-duplicate facts, cluster thematically\n * related ones, and write a consolidated note + diary entry.\n *\n * @public\n */\n async runDreamingSweep(opts: DreamingSweepOptions): Promise<DreamingSweepResult> {\n // SDK 2.0 Phase 4 (Stage 4, iter 77): route through sdk-memory\n // when installed; fall back to legacy internal/ path otherwise.\n const peer = await tryLoadSdkMemoryPeer();\n const catalog = peer !== null ? peer.MEMORY_EMBEDDING_ADAPTERS : MEMORY_EMBEDDING_ADAPTERS;\n const sweepArgs = await buildDreamingSweepArgs(opts, catalog);\n const result =\n peer !== null\n ? // biome-ignore lint/suspicious/noExplicitAny: peer is dynamically loaded — structural compat ensured by sdk-memory\n await peer.runDreamingSweep(sweepArgs as any)\n : // biome-ignore lint/suspicious/noExplicitAny: legacy path accepts the same shape\n await runDreamingSweepInternal(sweepArgs as any);\n return toDreamingSweepResult(result);\n },\n};\n\n// ---------------------------------------------------------------------------\n// Internal helpers — deduplicate patterns shared across peer + legacy paths.\n// ---------------------------------------------------------------------------\n\n/** Catalog shape shared between sdk-memory peer and local MEMORY_EMBEDDING_ADAPTERS. */\ninterface EmbeddingCatalog {\n [provider: string]: { create(opts: Record<string, unknown>): Promise<unknown> } | undefined;\n}\n\n/**\n * Resolve an embedding runtime from a provider catalog. Throws the canonical\n * \"Unknown embedding provider\" error when the provider is not in the catalog.\n */\nasync function resolveEmbedding(\n embeddingOpts: { provider: string; model?: string } | undefined,\n catalog: EmbeddingCatalog,\n): Promise<unknown> {\n if (embeddingOpts === undefined) return undefined;\n const adapter = catalog[embeddingOpts.provider];\n if (adapter === undefined) {\n throw new Error(\n `Unknown embedding provider \"${embeddingOpts.provider}\". Supported: ${Object.keys(catalog).join(\", \")}.`,\n );\n }\n return adapter.create(embeddingOpts.model !== undefined ? { model: embeddingOpts.model } : {});\n}\n\ninterface IndexOpenArgs {\n cwd: string;\n filePath?: string;\n embedding?: unknown;\n backend?: \"sqlite-vec\" | \"lance\";\n}\n\n/** Build the args object for IndexManager.open from user-facing options. */\nfunction buildIndexOpenArgs(opts: OpenMemoryIndexOptions, embedding: unknown): IndexOpenArgs {\n return {\n cwd: opts.cwd,\n ...(opts.filePath !== undefined ? { filePath: opts.filePath } : {}),\n ...(embedding !== undefined ? { embedding } : {}),\n ...(opts.backend !== undefined ? { backend: opts.backend } : {}),\n };\n}\n\ninterface DreamingSweepArgs {\n cwd: string;\n /** Resolved once here so the facts, the notes and the diary all land in one place (#463). */\n memoryRoot: MemoryRoot;\n embedding: unknown;\n dedupThreshold?: number;\n clusterThreshold?: number;\n}\n\n/** Build args for runDreamingSweep from user-facing options + resolved embedding. */\nasync function buildDreamingSweepArgs(\n opts: DreamingSweepOptions,\n catalog: EmbeddingCatalog,\n): Promise<DreamingSweepArgs> {\n const runtime = await resolveEmbedding(opts.embedding, catalog);\n return {\n cwd: opts.cwd,\n memoryRoot: resolveMemoryRoot(opts.cwd, { directory: opts.directory }),\n embedding: runtime,\n ...(opts.dedupThreshold !== undefined ? { dedupThreshold: opts.dedupThreshold } : {}),\n ...(opts.clusterThreshold !== undefined ? { clusterThreshold: opts.clusterThreshold } : {}),\n };\n}\n\n/** Normalize a raw dreaming sweep result into the public DreamingSweepResult shape. */\nfunction toDreamingSweepResult(result: {\n status: string;\n factsBefore: number;\n factsAfter: number;\n duplicatesRemoved: number;\n clustersCreated: number;\n notesWritten: number;\n}): DreamingSweepResult {\n return {\n status: result.status as DreamingSweepResult[\"status\"],\n factsBefore: result.factsBefore,\n factsAfter: result.factsAfter,\n duplicatesRemoved: result.duplicatesRemoved,\n clustersCreated: result.clustersCreated,\n notesWritten: result.notesWritten,\n };\n}\n","/**\n * Runtime helpers for `MemoryAdapter` (T1.1, ADR D141).\n *\n * Kept separate from `types/memory-adapter.ts` so the types module\n * stays import-free of runtime code (dep-cruise rule\n * `types-dont-import-runtime`). Adapter authors call `mkMemoryId` to\n * construct a branded id and `extractRawId` to unwrap with cross-adapter\n * safety (EC-B).\n *\n * @public\n */\n\nimport { MemoryAdapterError } from \"./errors.js\";\nimport type { MemoryId } from \"./types/memory-adapter.js\";\n\n/**\n * Construct a branded `MemoryId` for an adapter. Embeds the adapter\n * identifier so `extractRawId` can reject ids minted by other adapters.\n *\n * @public\n */\nexport function mkMemoryId(adapterId: string, rawId: string): MemoryId {\n return `${adapterId}:${rawId}` as MemoryId;\n}\n\n/**\n * Extract the raw provider id from a `MemoryId`, enforcing that the\n * prefix matches `expectedAdapterId`. Throws `MemoryAdapterError(code:\n * \"invalid_input\")` on mismatch — prevents `mem0.delete(supermemoryId)`\n * from accidentally deleting unrelated data (EC-B).\n *\n * @public\n */\nexport function extractRawId(id: MemoryId, expectedAdapterId: string): string {\n const prefix = `${expectedAdapterId}:`;\n if (!id.startsWith(prefix)) {\n const sourcePrefix = id.split(\":\", 1)[0] ?? \"<malformed>\";\n throw new MemoryAdapterError(\n `MemoryId belongs to a different adapter (expected \"${expectedAdapterId}\", got \"${sourcePrefix}\")`,\n { adapterId: expectedAdapterId, code: \"invalid_input\" },\n );\n }\n return id.slice(prefix.length);\n}\n","// Public API for memory migration (ADR D44).\n//\n// This file is the public re-export wrapper for the internal implementation.\n// Declaring types here (rather than re-exporting from internal/) avoids a\n// known rollup-dts resolution quirk with internal/ paths.\n//\n// Iter 78 (SDK 2.0 Phase 4 Stage 4 #3): routes through\n// `@theokit/sdk-memory` when the peer is installed. Falls back to\n// the legacy `internal/memory/migrate-sqlite-to-lance.js` when the\n// peer is absent. Both paths share byte-equivalent runtime behavior\n// because sdk-memory's copy is the iter 71 source-move (atomic\n// rename commit, NFC sample compare, D70 redaction logger wrap).\n\nimport { migrateSqliteToLance as _migrateSqliteToLance } from \"./internal/memory/migrate-sqlite-to-lance.js\";\nimport { tryLoadSdkMemoryPeer } from \"./internal/memory/sdk-memory-peer-loader.js\";\n\n/**\n * Options for {@link migrateSqliteToLance}.\n *\n * @public\n */\nexport interface MigrateOptions {\n cwd: string;\n dryRun?: boolean;\n batchSize?: number;\n logger?: (msg: string) => void;\n}\n\n/**\n * Outcome of {@link migrateSqliteToLance}.\n *\n * @public\n */\nexport interface MigrateResult {\n countSqlite: number;\n countLance: number;\n validated: boolean;\n sampleComparisons: ReadonlyArray<{ id: string; match: boolean }>;\n lancePath: string;\n committed: boolean;\n}\n\n/**\n * Migrate the Memory index from SQLite to LanceDB. ADR D44.\n *\n * @public\n */\nexport async function migrateSqliteToLance(options: MigrateOptions): Promise<MigrateResult> {\n // SDK 2.0 Phase 4 Stage 4 (iter 78): peer routing.\n const peer = await tryLoadSdkMemoryPeer();\n if (peer !== null) {\n return peer.migrateSqliteToLance(options);\n }\n return _migrateSqliteToLance(options);\n}\n","/**\n * `PermissionEngine` — first-match permission rules for tool invocations.\n *\n * Evaluates a tool name (and optional arguments, #55) against an ordered list\n * of rules. First matching rule wins; when no rule matches the `defaultAction`\n * is returned. #55 — the default is now `\"ask\"` (FAIL-CLOSED): a permission\n * engine that cannot positively allow must not silently allow. Opt back into\n * the previous fail-open behavior with `{ defaultAction: \"allow\" }`.\n */\n\nexport type PermissionAction = \"allow\" | \"deny\" | \"ask\";\n\n/**\n * SE1 — a per-run permission MODE that adjusts the rule-engine verdict globally.\n * A PURE post-processor of the verdict (no tool-safety metadata needed, so it fits\n * a bring-your-own-tools runtime). Grounded in a peer project (plan agent = deny-all,\n * `dangerously-skip-permissions`) + Codex (`AskForApproval`: `OnRequest` default,\n * `Never`, `UnlessTrusted`). See {@link applyMode} for the exact table.\n *\n * - `default` — verdict as-is (rules decide; unmatched ⇒ `ask`, fail-closed).\n * - `plan` — read-only: `allow` rules pass, everything else ⇒ `deny` (mutations blocked).\n * NOTE: `plan` gates on the resolved verdict, so an engine configured with\n * `{ defaultAction: \"allow\" }` still yields `allow` for UNMATCHED calls under\n * `plan` — pair `plan` with the default fail-closed engine (`defaultAction: \"ask\"`)\n * for full read-only behavior.\n * - `acceptEdits` — auto-approve the UNMATCHED verdict, but STILL honor an explicit\n * `ask` rule (a caller gates a risky tool with an ask rule). Codex `UnlessTrusted`.\n * - `bypass` (alias `bypassPermissions`, the Anthropic-exact name) — everything ⇒\n * `allow` EXCEPT an explicit `deny` rule. Never asks. a peer project\n * `dangerously-skip-permissions` / Codex `Never` / Anthropic `bypassPermissions`.\n */\nimport type { PermissionMode } from \"./types/agent-prims.js\";\n\nexport type { PermissionMode };\n\n/**\n * SE1 — apply a {@link PermissionMode} to a rule-engine verdict. Pure.\n *\n * `explicit` is `true` when the verdict came from a rule that matched by name (and\n * args), `false` when it is the fail-closed default for an unmatched call. The flag\n * is load-bearing for `acceptEdits`, which auto-approves the unmatched default but\n * keeps honoring an explicit `ask` rule (unlike `bypass`, which allows even that).\n *\n * INVARIANT (both a peer project + Codex): an explicit `deny` is immune to EVERY\n * auto-approve mode — `bypass`/`acceptEdits` never un-deny.\n */\nexport function applyMode(\n verdict: PermissionAction,\n mode: PermissionMode,\n explicit: boolean,\n): PermissionAction {\n // (a) explicit deny is terminal under every mode — fail-closed.\n if (verdict === \"deny\") return \"deny\";\n switch (mode) {\n case \"default\":\n return verdict;\n case \"plan\":\n // read-only: only allow rules pass; ask + unmatched ⇒ deny.\n return verdict === \"allow\" ? \"allow\" : \"deny\";\n case \"acceptEdits\":\n // (b) auto-approve the unmatched default; honor an explicit ask rule.\n if (verdict === \"ask\") return explicit ? \"ask\" : \"allow\";\n return verdict; // allow stays allow\n case \"bypass\":\n case \"bypassPermissions\":\n // everything that survived the deny check ⇒ allow (never asks).\n return \"allow\";\n }\n}\n\n/**\n * #55 — an argument matcher. A rule with `args` gates on the tool's argument\n * VALUES, not just its name: an exact string, a RegExp (tested against the\n * stringified value), or a predicate. Every declared arg must match for the\n * rule to apply — so `{ tool: \"shell\", args: { command: /rm\\s+-rf/ } }` denies\n * a destructive shell call while leaving `ls` to fall through.\n */\nexport type ArgMatcher = string | RegExp | ((value: unknown) => boolean);\n\n/**\n * One entry in a {@link PermissionEngine}'s ordered rule list.\n *\n * Order is the semantics. The engine walks the list and the first rule whose `tool` matches — and\n * whose `args` matchers all pass, when it declares any — decides; nothing after it is consulted. Put\n * the narrow rules first: a catch-all `tool` RegExp placed above a specific deny makes that deny\n * unreachable, and nothing warns you.\n *\n * `args` is what lets one tool name resolve differently depending on what it is asked to do —\n * `{ tool: \"shell\", args: { command: /rm\\s+-rf/ }, action: \"deny\" }` blocks the destructive call and\n * leaves `ls` to fall through to a later rule. Every declared matcher must pass.\n *\n * **A rule that declares an argument the call did not supply does not match**, whatever form the\n * matcher takes — string, RegExp or predicate. The predicate is not invoked with `undefined`; the\n * guard runs first, for every matcher form. Evaluation continues to the next rule.\n *\n * That was not always true, and the fix is the reason this paragraph is explicit (#367). A predicate\n * used to be called anyway, so `(v) => v !== \"prod\"` returned true for a missing argument and an\n * ALLOW rule authorized a call that supplied nothing, while `(v) => v.includes(\"rm\")` threw a\n * TypeError out of the permission gate. This docblock told consumers to guard every predicate by\n * hand for months after `argMatches` stopped needing it — you do not have to.\n *\n * A rule that matches yields an EXPLICIT verdict, and that is what makes it survive a permissive\n * `PermissionMode`: `acceptEdits` auto-approves the unmatched default but still honours an explicit\n * `ask` rule, and an explicit `deny` is immune to every mode, `bypass` included.\n */\nexport interface PermissionRule {\n /** Tool name (exact string) or pattern (RegExp). */\n tool: string | RegExp;\n /**\n * #55 — optional per-argument matchers. When present, the rule matches only\n * if the tool name matches AND every declared arg predicate matches the\n * corresponding call argument. A missing/undefined arg fails its predicate\n * (the rule does not match) — never throws.\n */\n args?: Record<string, ArgMatcher>;\n /** Action to take when rule matches. */\n action: PermissionAction;\n}\n\n/** Options for {@link PermissionEngine}. */\nexport interface PermissionEngineOptions {\n /**\n * Action when no rule matches. #55 — default is now `\"ask\"` (fail-closed): a\n * permission engine that cannot positively allow must not silently allow.\n * Pass `\"allow\"` to restore the previous fail-open behavior.\n */\n readonly defaultAction?: PermissionAction;\n}\n\nfunction argMatches(matcher: ArgMatcher, value: unknown): boolean {\n // The guard comes FIRST, for every matcher form including a predicate (#367). It used to sit\n // below the function branch, so a declared predicate was invoked with `undefined` — and both\n // directions of that were wrong:\n //\n // allow rule `(v) => v !== \"prod\"` returns true for undefined, so a call that supplied NO\n // argument produced an EXPLICIT allow — a matcher written to narrow, widening.\n // deny rule `(v) => v.includes(\"rm\")` raised TypeError out of the permission gate, which\n // is not a denial but an unhandled failure on the path that decides authorization.\n //\n // A rule that declares an argument is a rule about that argument. A call that omitted it has\n // not satisfied the rule, whatever shape the matcher takes.\n if (value === undefined) return false;\n if (typeof matcher === \"function\") return matcher(value);\n if (matcher instanceof RegExp) {\n // Reset `lastIndex` so a global/sticky-flag regex (`/x/g`) does not carry\n // state across `.test()` calls — otherwise the same rule would alternate\n // verdicts on identical repeated calls (non-deterministic authorization).\n matcher.lastIndex = 0;\n return matcher.test(String(value));\n }\n return matcher === value;\n}\n\n/**\n * Ordered first-match permission rules for tool invocations — the policy object you hand to\n * `PermissionPlugin.create()` to have it enforced.\n *\n * On its own it enforces nothing. `evaluate(toolName, args, mode)` is a pure function returning\n * `\"allow\" | \"deny\" | \"ask\"`, and no part of the SDK calls it until the engine is wrapped in a plugin\n * and that plugin is registered on an agent. The plugin is where a verdict becomes behaviour: `deny`\n * blocks the tool call, `allow` passes it through, and `ask` is routed to the host's `canUseTool`\n * gate — with no gate configured, `ask` blocks. So constructing an engine and never registering it\n * is a policy that does nothing, which is the mistake worth knowing about first.\n *\n * It is fail-closed by default: a call no rule matches resolves to `\"ask\"`, not `\"allow\"`, so a tool\n * the rules never mention needs a human — or an explicit `{ defaultAction: \"allow\" }` — before it\n * runs. Keep that default if you intend to use `PermissionMode: \"plan\"` for read-only behaviour,\n * because `plan` gates on the RESOLVED verdict: an engine built with `defaultAction: \"allow\"` still\n * allows every unmatched call under `plan`.\n *\n * The rules array is stored by reference and walked afresh on every `evaluate` call. Mutating the\n * array you passed in therefore changes the policy of a live engine; build a new engine when you\n * want a policy change to be a deliberate, visible event.\n */\nexport class PermissionEngine {\n private readonly defaultAction: PermissionAction;\n\n constructor(\n private readonly rules: PermissionRule[],\n options: PermissionEngineOptions = {},\n ) {\n // #55 — fail-closed by default.\n this.defaultAction = options.defaultAction ?? \"ask\";\n }\n\n /**\n * Evaluate a tool name (and optional arguments) against the rules. First\n * match wins; falls back to the configured `defaultAction` (default `\"ask\"`,\n * fail-closed) when no rule matches. #55 — a rule with `args` gates on the\n * argument values, so the same tool name can resolve to different actions\n * depending on what it is asked to do.\n */\n evaluate(\n toolName: string,\n args?: Record<string, unknown>,\n mode: PermissionMode = \"default\",\n ): PermissionAction {\n for (const rule of this.rules) {\n const nameMatches =\n typeof rule.tool === \"string\" ? rule.tool === toolName : rule.tool.test(toolName);\n if (!nameMatches) continue;\n if (rule.args !== undefined && !this.#argsMatch(rule.args, args)) continue;\n // SE1 — a matched rule is an EXPLICIT verdict; apply the mode with explicit=true.\n return applyMode(rule.action, mode, true);\n }\n // SE1 — no rule matched: the default is NOT explicit (explicit=false), so\n // `acceptEdits` auto-approves it while still honoring explicit `ask` rules above.\n return applyMode(this.defaultAction, mode, false);\n }\n\n #argsMatch(\n matchers: Record<string, ArgMatcher>,\n args: Record<string, unknown> | undefined,\n ): boolean {\n const call = args ?? {};\n for (const [key, matcher] of Object.entries(matchers)) {\n if (!argMatches(matcher, call[key])) return false;\n }\n return true;\n }\n}\n","/**\n * M7-5 — `createPermissionPlugin`: wire a {@link PermissionEngine} into the\n * `definePlugin` `pre_tool_call` veto seam. This is the canonical exemplar that\n * gives `PermissionEngine` a real caller (it was previously exported-but-unwired):\n * on each tool call the engine's verdict maps to the veto contract —\n * `\"deny\"` -> block, `\"ask\"` -> the caller's `onAsk` resolver (or block, fail-closed),\n * `\"allow\"` -> pass.\n *\n * @public\n */\n\nimport { definePlugin } from \"./internal/plugins/index.js\";\nimport type { Plugin, PreToolCallDecision } from \"./internal/plugins/types.js\";\nimport type { PermissionEngine, PermissionMode } from \"./permission-engine.js\";\n\n/**\n * SE1 — context passed to the {@link PermissionGate}. Intentionally minimal for\n * SE1; `agentId`/`runId` (for audit logging) are a documented follow-up — they are\n * available on the raw `pre_tool_call` context and can be threaded in a later slice.\n */\nexport interface PermissionGateContext {\n /** The tool being gated. */\n readonly toolName: string;\n /** The active permission mode for this run. */\n readonly mode: PermissionMode;\n}\n\n/**\n * SE1 — the resolution of an `\"ask\"` verdict by the host gate. Fail-closed: an\n * absent gate, a throwing gate, and a `\"deny\"` decision all block. Arg rewrite\n * (`updatedInput`) is intentionally NOT supported yet — the `pre_tool_call` seam\n * is veto-only (`{ block, message }`); a future enhancement can extend it.\n */\nexport type PermissionGateDecision =\n | { readonly behavior: \"allow\" }\n | { readonly behavior: \"deny\"; readonly message?: string };\n\n/**\n * SE1 — the enriched `canUseTool` gate (the Anthropic-parity shape). Invoked ONLY\n * on an `\"ask\"` verdict, it receives the tool name, its input args, and the run\n * {@link PermissionGateContext}, and resolves to allow/deny. May be async (a real\n * gate can prompt a human — the `pre_tool_call` seam awaits it).\n */\nexport type PermissionGate = (\n toolName: string,\n input: Record<string, unknown>,\n ctx: PermissionGateContext,\n) => PermissionGateDecision | Promise<PermissionGateDecision>;\n\n/** Options for {@link createPermissionPlugin}. */\nexport interface PermissionPluginOptions {\n /** Plugin name (default `\"permission-engine\"`). */\n readonly name?: string;\n /**\n * SE1 — the per-run {@link PermissionMode}. Threaded into `engine.evaluate`, so\n * `bypass` auto-allows the ask verdict (gate never consulted), `plan` blocks\n * mutations, etc. An explicit `deny` rule is immune to every mode. Default\n * `\"default\"` (rules decide; unmatched ⇒ fail-closed ask).\n */\n readonly mode?: PermissionMode;\n /**\n * SE1 — the enriched gate for the `\"ask\"` verdict. Preferred over {@link onAsk}.\n * Absent gate on an `ask` verdict ⇒ fail-closed block.\n */\n readonly canUseTool?: PermissionGate;\n /**\n * @deprecated since SE1 — use {@link canUseTool}, which receives `(toolName,\n * input, ctx)` and returns a typed decision. Honored only when `canUseTool` is\n * absent. Returns a veto (`{block,message}`) to deny or `undefined` to allow.\n */\n readonly onAsk?: (toolName: string) => PreToolCallDecision | undefined;\n}\n\n/**\n * Resolve an `\"ask\"` verdict via the gate (fail-closed). Extracted from the\n * register handler to keep its cognitive complexity in budget. Prefers\n * `canUseTool`; falls back to the deprecated `onAsk`; blocks when neither exists.\n */\nasync function resolveAsk(\n opts: PermissionPluginOptions,\n name: string,\n args: Record<string, unknown>,\n mode: PermissionMode,\n): Promise<PreToolCallDecision | undefined> {\n if (opts.canUseTool !== undefined) {\n let decision: PermissionGateDecision;\n try {\n decision = await opts.canUseTool(name, args, { toolName: name, mode });\n } catch {\n // Fail-closed: a gate that throws must not silently allow.\n return { block: true, message: `permission gate error (fail-closed): ${name}` };\n }\n // Fail-CLOSED (allow-list): only an explicit `allow` passes. Any other value\n // — `deny`, a malformed/undefined return from a JS consumer, a wrong-cased\n // behavior — blocks, so the gate can never silently allow on a bad decision.\n return decision?.behavior === \"allow\"\n ? undefined\n : { block: true, message: decision?.message ?? `denied: ${name}` };\n }\n // Deprecated back-compat: honor onAsk (undefined = allow). Fail-closed (block)\n // only when NEITHER a gate nor onAsk was supplied.\n return opts.onAsk ? opts.onAsk(name) : { block: true, message: `requires approval: ${name}` };\n}\n\n/**\n * Build a `general` plugin that vetoes tool calls per the engine's verdict, under\n * the configured {@link PermissionMode}, resolving `ask` via the {@link canUseTool}\n * gate. Register it on an agent's plugin manager (same as the ACP permission plugin).\n */\nfunction createPermissionPlugin(\n engine: PermissionEngine,\n opts: PermissionPluginOptions = {},\n): Plugin {\n return definePlugin({\n name: opts.name ?? \"permission-engine\",\n version: \"1.0.0\",\n kind: \"general\",\n register(ctx) {\n ctx.on(\"pre_tool_call\", async (rawCtx) => {\n const { name, args, permissionMode } = rawCtx as {\n name: string;\n args: Record<string, unknown>;\n permissionMode?: PermissionMode;\n };\n // SE1 — precedence: the RUN's mode (threaded from `SendOptions`/`AgentOptions`\n // via the pre_tool_call context) wins over the plugin's construction-time\n // default. `default` when neither is set.\n const mode: PermissionMode = permissionMode ?? opts.mode ?? \"default\";\n // #55 — args gate rules on the command/args, not just the tool name.\n // SE1 — the mode adjusts the verdict (bypass/plan/acceptEdits); an explicit\n // `deny` rule is immune to every auto-approve mode.\n const action = engine.evaluate(name, args, mode);\n if (action === \"deny\") {\n return { block: true, message: `denied by permission engine: ${name}` };\n }\n if (action === \"ask\") return resolveAsk(opts, name, args, mode);\n return undefined;\n });\n },\n });\n}\n\n/** SE36 — `PermissionPlugin.create` replaces `createPermissionPlugin` (ADR 0015). @public */\nexport class PermissionPlugin {\n private constructor() {}\n static create(engine: PermissionEngine, opts: PermissionPluginOptions = {}): Plugin {\n return createPermissionPlugin(engine, opts);\n }\n}\n","/**\n * Load a project's `.env` without letting it move the credential store or switch off a trust\n * decision.\n *\n * `process.loadEnvFile()` reads the PROJECT's `.env` into `process.env`. For a provider key that is\n * exactly right and is the documented way to configure a scaffolded product. For the handful of\n * variables that decide WHERE credentials live and WHAT is trusted it is a hole: a cloned\n * repository is untrusted input, and a `.env` inside it is untrusted input the runtime is about to\n * treat as configuration.\n *\n * Concretely, without this guard a repository shipping\n *\n * ```\n * THEOKIT_AUTH_HOME=/tmp/attacker-store\n * ```\n *\n * redirects the credential store the moment the product starts in that directory — before any\n * trust prompt, because locating the store is what happens first.\n *\n * ## Why it lives here\n *\n * The scaffolding template (`create-theokit`, TUI surface) calls `process.loadEnvFile()` with no\n * guard, so every product generated from it starts exposed. One consumer found this and fixed it in\n * ~30 lines of its own. A defence each consumer has to rediscover is a defence most will not have,\n * and this one is invisible when missing: nothing fails, the store simply moves.\n *\n * ## Why the set is named\n *\n * A convention — \"anything ending in `_HOME`\", \"anything with TRUST in it\" — silently changes\n * meaning as variables are added, in the direction of accidentally sovereign or accidentally not.\n * The list is explicit so that making a variable sovereign is a deliberate act, and so a reader can\n * see the security boundary without grepping for it.\n *\n * @public\n */\n\n/**\n * Variables a project-scoped source may never set. Each either locates the credential store, names\n * the config directory that is read as configuration, or carries a trust decision.\n *\n * `THEOKIT_API_KEY` is deliberately ABSENT. A project supplying its own provider key through `.env`\n * is the documented, intended path — treating it as sovereign would break every scaffolded product\n * to defend nothing, since a key the project supplies is a key the project already has.\n *\n * @public\n */\n// `THEOKIT_DIR_NAME` was listed here until #410, described as naming the project config directory.\n// It was never read — `paths.ts` hardcoded the literal — so the entry defended a variable that\n// decided nothing, and the description told a consumer they could point the SDK's config directory\n// elsewhere. Removed rather than implemented: the one concrete use anyone had for it (pointing at\n// `.claude` to share a layout with the Claude Code CLI) is now served by `projectConfigRoots()`,\n// which reads BOTH directories with no variable involved. Implementing the knob today would add a\n// public surface whose only motivating case had already been solved a better way.\n//\n// A `//` block, not a docblock: this is history about a REMOVED entry, and as JSDoc it stranded the\n// documentation for the constant below and would have shipped in its place.\nexport const SOVEREIGN_ENV_KEYS = [\n /** Locates the SDK home — sessions, and the credential store beneath it. */\n \"THEOKIT_HOME\",\n /** Locates the credential store explicitly, independently of `THEOKIT_HOME`. */\n \"THEOKIT_AUTH_HOME\",\n /** A trust decision: which providers are honoured without further checks. */\n \"THEOKIT_TRUSTED_PROVIDERS\",\n /** Turning redaction off from a repository's `.env` would put secrets into logs. */\n \"THEOKIT_REDACT_SECRETS\",\n /** Cryptographic material for the OAuth transaction cookie. */\n \"THEOKIT_OAUTH_TX_SALT\",\n] as const;\n\n/**\n * The union of {@link SOVEREIGN_ENV_KEYS} entries — the variables a project-scoped `.env` may never\n * set.\n *\n * Derived from the array rather than written out, so adding a key in one place cannot leave the\n * type behind. Use it where a caller must name one of the protected variables and a plain `string`\n * would let a typo through silently.\n *\n * @public\n */\nexport type SovereignEnvKey = (typeof SOVEREIGN_ENV_KEYS)[number];\n\n/** The mutable shape of `process.env`, narrowed so a caller can pass a plain object in tests. */\ntype MutableEnv = Record<string, string | undefined>;\n\n/**\n * Read the project's `.env` into `env`, then restore every {@link SOVEREIGN_ENV_KEYS} entry to the\n * value it had BEFORE the load — including restoring it to absent.\n *\n * Capture-then-restore rather than filtering the file: `process.loadEnvFile` offers no hook between\n * parsing and assignment, and reimplementing dotenv parsing to filter it would be a second parser\n * to keep in step with Node's. Restoring afterwards needs no parser and cannot disagree with one.\n *\n * @param env the environment to mutate. Defaults to `process.env`.\n * @param load performs the load. Defaults to `process.loadEnvFile` when the runtime has it, and to\n * `undefined` when it does not — in which case this is a no-op rather than a startup crash.\n * @public\n */\nexport function loadProjectEnv(\n env: MutableEnv = process.env,\n load: (() => void) | undefined = typeof process.loadEnvFile === \"function\"\n ? (): void => {\n process.loadEnvFile();\n }\n : undefined,\n): void {\n if (load === undefined) return;\n\n // Captured BEFORE the load, including the absent case — `undefined` here means \"was not set\",\n // and restoring that means deleting the key rather than leaving the project's value in place.\n const sovereign = new Map<string, string | undefined>(\n SOVEREIGN_ENV_KEYS.map((key) => [key, env[key]] as const),\n );\n\n try {\n load();\n } catch {\n // No `.env` on disk is the ordinary case and `loadEnvFile` throws for it. Nothing was assigned,\n // so there is nothing to restore.\n return;\n }\n\n for (const [key, original] of sovereign) {\n if (original === undefined) delete env[key];\n else env[key] = original;\n }\n}\n","/**\n * Decide which session artifacts may be deleted — and never delete them.\n *\n * This package creates session artifacts (transcripts, locks, temp files) and cleans up only what is\n * in flight in the operation doing the cleaning: a lock it just released, a `.tmp` from a failed\n * atomic write. Nothing collects the rest, so every consumer either writes its own collector or lets\n * the directory grow without bound — and a hand-rolled collector on the path that deletes a user's\n * transcript is the worst place for each product to learn the same lessons separately.\n *\n * ## Planning is not deleting, deliberately\n *\n * A function that decided AND deleted could not be tested without a filesystem, and the case that\n * matters most — \"we could not establish whether this session is live\" — would have to be simulated\n * rather than asserted. Here the decision is pure: the plan IS the dry run, and executing it is a\n * separate act on a value someone can read first. That separation is the dry-run guarantee, rather\n * than a flag that has to be remembered.\n *\n * ## The tri-state\n *\n * `keep`, `reap`, `undetermined`. An artifact whose liveness could not be established is never\n * reaped and never quietly counted as dead. Collapsing \"could not determine\" into \"not there\" is how\n * a collector deletes a session running on another machine, or behind a mount that answered slowly.\n * The third bucket costs a branch and buys the only guarantee worth having on this path.\n *\n * @public\n */\n\nimport { TheokitAgentError } from \"./errors.js\";\n\n/** Raised when a retention policy cannot be honoured as written. @public */\nexport class RetentionPolicyError extends TheokitAgentError {\n override readonly name = \"RetentionPolicyError\";\n}\n\n/**\n * One artifact the caller is considering deleting, described well enough to decide about.\n *\n * `id` is only ever compared for equality, so any stable identity works — a path, a session id, an\n * inode. `live` is the tri-state that carries the whole safety property: `\"unknown\"` means the\n * caller could not establish liveness, and it is honoured as a third answer rather than folded into\n * `false`.\n *\n * @public\n */\nexport interface ReapableArtifact {\n readonly id: string;\n /** Epoch milliseconds. Compared against an injected `nowMs`, never against a read clock. */\n readonly lastModifiedMs: number;\n /**\n * Whether a writer still holds this artifact. `\"unknown\"` when the caller could not establish it —\n * a stale lock behind a slow mount, a PID on another host — and it is honoured as a third answer\n * rather than folded into `false`.\n */\n readonly live: boolean | \"unknown\";\n}\n\n/**\n * How long artifacts are kept and how many always survive.\n *\n * The two interact as a window plus a FLOOR, not as two independent allowances: `keepLast` rescues\n * artifacts only when the window and liveness together spared fewer than that many, and rescues\n * exactly enough to reach the count. Both are refused by `planReaping` rather than clamped when\n * they are not expressible — see its `@throws`.\n *\n * @public\n */\nexport interface RetentionPolicy {\n /** Artifacts strictly older than this are candidates. The boundary itself is kept. */\n readonly maxAgeMs: number;\n /**\n * A FLOOR on how many artifacts survive: \"you will always have your last N sessions\". When\n * liveness and the retention window already spare N or more, this changes nothing; when they\n * spare fewer, the newest of the remainder are spared until the count reaches N.\n *\n * Undetermined artifacts do NOT count toward the floor. Their liveness was never established, so\n * counting them would let a transient mount failure satisfy the floor with artifacts nobody\n * confirmed exist as sessions — and quietly delete the ones that do.\n */\n readonly keepLast: number;\n}\n\n/** Why an artifact survived. @public */\nexport type KeepReason = \"live\" | \"within-retention\" | \"keep-last\";\n\n/**\n * An artifact that survived, carrying the reason it did.\n *\n * The reason is the one that spared it FIRST, in the order liveness, then the retention window,\n * then the floor — so a live artifact inside the window reports `\"live\"`, and `\"keep-last\"` only\n * appears on artifacts that had no reason of their own.\n *\n * @public\n */\nexport interface KeptArtifact extends ReapableArtifact {\n readonly reason: KeepReason;\n}\n\n/**\n * The decision, as three disjoint buckets whose union is exactly the input.\n *\n * Nothing is deleted by producing one of these — the plan IS the dry run, and executing it is a\n * separate act on a value you can read first. Delete only what is in `reap`; `undetermined` is not\n * a smaller `reap`, it is the set nobody could decide about.\n *\n * @public\n */\nexport interface ReapPlan {\n /** Safe to delete. Everything here was decided, not defaulted. */\n readonly reap: readonly ReapableArtifact[];\n readonly keep: readonly KeptArtifact[];\n /** Liveness could not be established. Never deleted, never counted as kept. */\n readonly undetermined: readonly ReapableArtifact[];\n}\n\n/**\n * Everything `planReaping` needs: the candidates, the policy, and the current time.\n *\n * `nowMs` is a parameter rather than a clock read so the same input always produces the same plan —\n * which is what lets a caller compute a plan, show it, and execute it later against the same\n * decision instead of a freshly re-derived one.\n *\n * @public\n */\nexport interface ReapPlanInput {\n readonly artifacts: readonly ReapableArtifact[];\n readonly retention: RetentionPolicy;\n /** Injected so the plan is reproducible and testable; this module never reads a clock. */\n readonly nowMs: number;\n}\n\n/**\n * Refuse a policy that cannot be honoured as written. Nonsense is not clamped: on this path a\n * clamped window deletes data the operator meant to keep.\n *\n * @internal\n */\nfunction assertPolicy(retention: RetentionPolicy): void {\n const { maxAgeMs, keepLast } = retention;\n if (!Number.isFinite(maxAgeMs) || maxAgeMs < 0) {\n throw new RetentionPolicyError(\n `retention.maxAgeMs must be a non-negative number of milliseconds, got ${String(maxAgeMs)}`,\n );\n }\n if (!Number.isInteger(keepLast) || keepLast < 0) {\n throw new RetentionPolicyError(\n `retention.keepLast must be a non-negative integer, got ${String(keepLast)}`,\n );\n }\n}\n\n/**\n * Everything spared for a reason of its own — liveness, or the retention window. What survives this\n * pass is what the floor then has to decide about.\n *\n * @internal\n */\nfunction classifyByOwnReason(input: ReapPlanInput): {\n keep: KeptArtifact[];\n atRisk: ReapableArtifact[];\n} {\n const keep: KeptArtifact[] = [];\n const atRisk: ReapableArtifact[] = [];\n\n for (const artifact of input.artifacts) {\n if (artifact.live === \"unknown\") continue;\n // Liveness first: a session that has not written for weeks is still running, and deleting its\n // transcript underneath it loses everything it has not flushed.\n if (artifact.live === true) {\n keep.push({ ...artifact, reason: \"live\" });\n continue;\n }\n // The boundary belongs to the safe side: at exactly the window, keep. Reaping there makes a\n // 30-day retention sometimes mean 29, depending on clock granularity.\n if (input.nowMs - artifact.lastModifiedMs <= input.retention.maxAgeMs) {\n keep.push({ ...artifact, reason: \"within-retention\" });\n continue;\n }\n atRisk.push(artifact);\n }\n return { keep, atRisk };\n}\n\n/**\n * The floor. `keepLast` is a promise about how many sessions survive in total, not a bonus on top of\n * the window — the standard reading of \"keep last N\", and the one explainable in a sentence. When\n * the window already spared enough, nothing more is rescued.\n *\n * @internal\n */\nfunction applyFloor(\n kept: readonly KeptArtifact[],\n atRisk: readonly ReapableArtifact[],\n keepLast: number,\n): { rescued: KeptArtifact[]; reap: ReapableArtifact[] } {\n const shortfall = Math.max(0, keepLast - kept.length);\n const newestFirst = [...atRisk].sort((a, b) => b.lastModifiedMs - a.lastModifiedMs);\n const spared = new Set(newestFirst.slice(0, shortfall).map((a) => a.id));\n\n const rescued: KeptArtifact[] = [];\n const reap: ReapableArtifact[] = [];\n for (const artifact of atRisk) {\n if (spared.has(artifact.id)) rescued.push({ ...artifact, reason: \"keep-last\" });\n else reap.push(artifact);\n }\n return { rescued, reap };\n}\n\n/**\n * Sort artifacts into keep, reap, and undetermined — and delete nothing.\n *\n * The order of decision is liveness, then the retention window, then the floor. An artifact whose\n * `live` is `\"unknown\"` leaves at the first step and is never considered again: it is not counted\n * toward `keepLast`, so a transient mount failure cannot satisfy \"keep my last two\" with artifacts\n * nobody confirmed while the confirmed ones are deleted.\n *\n * The window boundary belongs to the safe side. An artifact exactly `maxAgeMs` old is kept, so a\n * 30-day retention never means 29 depending on clock granularity.\n *\n * @returns the three buckets. Their union is exactly the input, each artifact counted once — the\n * invariant an operator reads the totals against.\n * @throws RetentionPolicyError when `maxAgeMs` is negative or not finite, or `keepLast` is negative\n * or not an integer. Nonsense is refused rather than clamped, because a clamped window on this\n * path deletes data the operator meant to keep.\n * @public\n */\nexport function planReaping(input: ReapPlanInput): ReapPlan {\n assertPolicy(input.retention);\n\n // Undetermined artifacts are set aside before anything else and never counted toward the floor: a\n // transient mount failure must not satisfy \"keep 2\" with artifacts nobody confirmed, while the\n // confirmed ones are deleted.\n const undetermined = input.artifacts.filter((a) => a.live === \"unknown\");\n const { keep, atRisk } = classifyByOwnReason(input);\n const { rescued, reap } = applyFloor(keep, atRisk, input.retention.keepLast);\n\n return { reap, keep: [...keep, ...rescued], undetermined };\n}\n","/**\n * M23 — schema normalizer: convert a schema from any supported provider to the internal JSON Schema\n * the synthetic `output` tool uses. Zod stays the DEFAULT and the documented recommendation; this is\n * a THIN adapter with no deep coupling (ADR-0041). Supported inputs:\n *\n * - **Zod** (default) — via the SDK's native `z.toJSONSchema` path.\n * - **JSON Schema** — a plain object with `type`/`properties` (or `$schema`) → passthrough.\n * - **ArkType** — any schema exposing `.toJsonSchema()` (ArkType 2.0) → called directly.\n * - **Valibot** — via the OPTIONAL `@valibot/to-json-schema` peer (dynamic import; a clear\n * error tells the user to install it — no hard dependency).\n *\n * Parse-failure handling stays uniform: the normalized JSON Schema drives the same synthetic-tool\n * validation + M14 `errorStrategy` regardless of the source library.\n */\nimport { ConfigurationError } from \"./errors.js\";\nimport { toJsonSchema } from \"./internal/zod-to-json-schema.js\";\n\n/** The internal JSON-Schema shape the synthetic `output` tool consumes. */\nexport type NormalizedJsonSchema = Record<string, unknown>;\n\n/** A plain JSON Schema object already in the target shape. */\nfunction isJsonSchemaObject(s: unknown): s is NormalizedJsonSchema {\n if (typeof s !== \"object\" || s === null) return false;\n const o = s as Record<string, unknown>;\n if (\"$schema\" in o) return true;\n return o.type === \"object\" && typeof o.properties === \"object\" && o.properties !== null;\n}\n\n/** ArkType (and any lib) exposing its own `.toJsonSchema()`. */\nfunction hasToJsonSchemaMethod(s: unknown): s is { toJsonSchema: () => NormalizedJsonSchema } {\n return (\n typeof s === \"object\" &&\n s !== null &&\n typeof (s as { toJsonSchema?: unknown }).toJsonSchema === \"function\"\n );\n}\n\n/** A Zod schema — carries `safeParse` plus the Zod internals (`_def` v3 / `def` v4). */\nfunction isZodSchema(s: unknown): boolean {\n if (typeof s !== \"object\" || s === null) return false;\n const o = s as Record<string, unknown>;\n return typeof o.safeParse === \"function\" && (\"_def\" in o || \"def\" in o);\n}\n\n/** A Valibot schema — `{ kind: 'schema', type, ... }` (no built-in JSON-Schema method). */\nfunction isValibotSchema(s: unknown): boolean {\n if (typeof s !== \"object\" || s === null) return false;\n const o = s as Record<string, unknown>;\n return o.kind === \"schema\" && \"type\" in o && typeof o.toJsonSchema !== \"function\";\n}\n\n/**\n * Whether a failed dynamic import means \"the optional peer is not installed\".\n *\n * The structural fact first: Node reports a missing module as `err.code`, and `compaction.ts`'s\n * `isContextOverflowError` already states the rule for this repo — read the code, \"never a brittle\n * message regex\". The regex survives ONLY as a fallback, because a bundler may rewrite the error and\n * drop the code; on its own it also depended on English-locale wording that neither Node nor any\n * bundler guarantees.\n */\nfunction isMissingModuleError(err: unknown): boolean {\n if ((err as NodeJS.ErrnoException | undefined)?.code === \"ERR_MODULE_NOT_FOUND\") return true;\n return (\n err instanceof Error && /Cannot find|Cannot resolve|ERR_MODULE_NOT_FOUND/.test(err.message)\n );\n}\n\n/**\n * Valibot needs its own converter, which is an optional peer. The specifier is NON-literal so TS\n * does not try to statically resolve an uninstalled package at build time.\n */\nasync function normalizeValibotSchema(schema: unknown): Promise<NormalizedJsonSchema> {\n const specifier = \"@valibot/to-json-schema\";\n try {\n const mod = (await import(specifier)) as {\n toJsonSchema: (s: unknown) => NormalizedJsonSchema;\n };\n return mod.toJsonSchema(schema);\n } catch (err) {\n if (!isMissingModuleError(err)) throw err;\n throw new ConfigurationError(\n \"normalizeSchema: a Valibot schema requires the optional '@valibot/to-json-schema' package. \" +\n \"Install it, or use a Zod schema (the default recommendation).\",\n { code: \"valibot_converter_missing\" },\n );\n }\n}\n\n/**\n * Normalize any supported schema to the internal JSON Schema. Async because the Valibot path\n * dynamically imports its optional converter. Throws a clear, typed-message error for an unsupported\n * schema or a missing Valibot peer (error-handling.md).\n */\nexport async function normalizeSchema(schema: unknown): Promise<NormalizedJsonSchema> {\n // JSON Schema — passthrough (already the target shape).\n if (isJsonSchemaObject(schema)) return schema;\n\n if (isValibotSchema(schema)) return await normalizeValibotSchema(schema);\n\n // Zod — the default path.\n if (isZodSchema(schema)) {\n return toJsonSchema(schema as never, { unrepresentable: \"any\" }) as NormalizedJsonSchema;\n }\n\n // ArkType (or any lib exposing `.toJsonSchema()`).\n if (hasToJsonSchemaMethod(schema)) return schema.toJsonSchema();\n\n // Typed, with a stable code: `normalizeSchema` is public (re-exported from the root barrel), and a\n // bare `Error` gives a caller nothing to branch on but the sentence.\n throw new ConfigurationError(\n \"normalizeSchema: unsupported schema. Supported: Zod (default), JSON Schema, ArkType (.toJsonSchema()), \" +\n \"Valibot (with @valibot/to-json-schema).\",\n { code: \"unsupported_schema\" },\n );\n}\n","/**\n * Public security namespace (T2.1, ADR D68).\n *\n * Two entry points:\n *\n * - `Security.redact(text, opts?)` — apply the canonical redactor to\n * arbitrary text. Useful when a consumer app (or example) writes its\n * own logs / metrics / paste-share artifacts that the SDK's wired\n * sinks (error metadata, telemetry, transcript, migration) don't\n * cover.\n * - `Security.addPattern(re)` — register a custom credential pattern\n * on top of the 12 builtins (OpenAI, Anthropic, GitHub PAT classic +\n * fine, GitLab, AWS, Google, Slack, Sentry, Stripe live + restricted)\n * plus the parametric `key=value` + `Bearer <token>` matchers.\n *\n * Redaction is ON by default. Disable with `THEOKIT_REDACT_SECRETS=false`\n * (a warning is emitted on stderr so the operator knows the SDK process\n * is vulnerable). The env var is snapshotted at module init — runtime\n * mutation cannot disable it, defending against prompt injection that\n * tries to flip the flag mid-run.\n */\n\nimport { ConfigurationError } from \"./errors.js\";\nimport {\n addPattern as _addPattern,\n redactSecrets as _redactSecrets,\n} from \"./internal/security/index.js\";\n\nexport class Security {\n private constructor() {}\n\n /**\n * Redact known credential patterns from `text` and return the masked\n * string. Use this at any consumer output boundary the SDK does not\n * directly own (custom stdout loggers, app-level metrics, debug-share\n * artifacts, etc.).\n *\n * Coerces non-strings (objects via JSON.stringify, null/undefined → \"\").\n * Two-bucket masking: tokens shorter than 18 chars → `***`; longer\n * tokens preserve `prefix...suffix` for debuggability without revealing\n * the secret middle.\n *\n * @param text - The value to redact. Strings, objects, primitives all OK.\n * @param opts.codeFile - When `true`, skips the parametric `key=value`\n * matcher so file content like `.env.example` placeholders is left\n * intact. Built-in pattern matches still apply.\n *\n * @example\n * console.log(`[bot] received: ${Security.redact(userText)}`);\n * // → \"[bot] received: please remember sk-abc...xyz1\"\n */\n static redact(text: unknown, opts?: { codeFile?: boolean }): string {\n return _redactSecrets(text, opts);\n }\n\n /**\n * Register a custom redaction pattern. Additive — built-in patterns\n * (OpenAI, Anthropic, GitHub PAT, AWS, etc.) cannot be removed.\n *\n * @param re - RegExp with `/g` flag. Throws if `/g` is missing\n * (without /g, only first match is replaced and the rest\n * leaks).\n *\n * Process-global mutable state. The SDK is designed for single-tenant\n * processes (Theo PaaS user runtime, local CLI). Multi-tenant\n * deployments running multiple SDK consumers in the same Node process\n * share this list — patterns added by tenant A apply to tenant B's\n * redactions. Acceptable for v1; future isolate-aware refactor would\n * thread patterns through a context if needed.\n *\n * @example\n * Security.addPattern(/MYORG-[A-Z0-9]{32}/g);\n * // → text containing \"MYORG-AAAA...AAAA\" now masks like a builtin.\n */\n static addPattern(re: RegExp): void {\n // Validated HERE rather than in the primitive. `internal/security/redact.ts` has to stay below\n // `errors.ts` — the error hierarchy imports `redactSecrets` for the anti-leak invariant on\n // `providerError` — so it cannot import ConfigurationError without closing a cycle. This is the\n // surface a consumer touches, and it can.\n //\n // Without /g, `String.replaceAll` throws and only the first match would be masked anyway: a\n // pattern registered to redact a secret would leave every occurrence after the first in clear.\n if (!re.global) {\n throw new ConfigurationError(\n \"Security.addPattern: regex must have /g flag for replace-all semantics\",\n { code: \"invalid_redaction_pattern\" },\n );\n }\n _addPattern(re);\n }\n}\n","/**\n * Resolve a security-relevant setting across configuration layers, where a lower-trust layer may\n * TIGHTEN it and never loosen it.\n *\n * Layered configuration usually resolves last-wins, and for the keys that decide confinement — a\n * sandbox mode, an approval policy — last-wins is a hole. With plain precedence a project layer\n * outranks the user's own file, so a cloned repository can hand itself the most permissive setting\n * and the operator's global choice loses silently, at the moment the directory is opened. Nothing\n * fails; the confinement is simply gone.\n *\n * ## What is generic here, and what is not\n *\n * The RULE is generic: named layers may only move the value in the confining direction, while one\n * designated layer — the operator's explicit flag — wins in both. The VOCABULARY is not: which\n * values count as more permissive, what the layers are called, and which one is the operator's are\n * all the consumer's, and are parameters.\n *\n * That distinction is what makes this extractable when a keypress router was not. Here the\n * vocabulary is DATA — two lists and a name — so a second product supplies its own without\n * inheriting the first's words. An interface shaped by one product's states would have given the\n * second consumer something to route around.\n *\n * ## Why the override is not validated\n *\n * `override` is returned verbatim, even when it is outside `permissiveness`. Validating the\n * operator's flag is the consumer's job: it owns the vocabulary, the error message and the exit\n * code. Silently dropping an unrecognised flag would be worse than passing it through — the\n * operator would see their explicit instruction ignored with no explanation.\n *\n * A value outside the vocabulary in a RESTRICTED layer is different and IS ignored: a typo in a\n * repository's config must neither become the effective setting nor be treated as maximally\n * permissive.\n *\n * @public\n */\n\n/**\n * The vocabulary, the layer names, and the values to resolve.\n *\n * Two orders matter and they are not the same one. The UNRESTRICTED layers — every key of `layers`\n * that is neither `override` nor listed in `restricted` — are resolved last-wins in the enumeration\n * order of the `layers` object. The RESTRICTED layers are applied in the order of the `restricted`\n * array, regardless of where they sit in `layers`. Put a layer in `restricted` and its position in\n * that array is what decides when it gets to tighten.\n *\n * A layer named in `restricted` but absent from `layers`, or present with `undefined`, is skipped.\n *\n * @public\n */\nexport interface SecurityFloorInput {\n /**\n * The vocabulary, ordered from most confined to least. Index is permissiveness, so\n * `[\"read-only\", \"workspace-write\", \"danger-full-access\"]` says read-only confines the most.\n */\n readonly permissiveness: readonly string[];\n /** Layers that may only tighten — typically anything a repository or environment can supply. */\n readonly restricted: readonly string[];\n /** The layer that wins outright in both directions — the operator's explicit flag. */\n readonly override: string;\n /**\n * Values per layer. Layers absent from `restricted` are unconstrained, which is how a `user`\n * layer loosens its own `defaults`.\n */\n readonly layers: Readonly<Record<string, string | undefined>>;\n}\n\n/** Index in `order`, or -1 when the value is absent or outside the vocabulary. @internal */\nfunction permissivenessOf(order: readonly string[], value: string | undefined): number {\n if (value === undefined) return -1;\n return order.indexOf(value);\n}\n\n/**\n * The value the restricted layers must not exceed, taken from the unrestricted layers in the order\n * given. Separated because it answers a different question from the floor itself: what did the\n * operator and the defaults already settle on, before any repository or environment had a say.\n *\n * @internal\n */\nfunction baseline(input: SecurityFloorInput): string | undefined {\n const { restricted, override, layers } = input;\n let value: string | undefined;\n for (const [name, candidate] of Object.entries(layers)) {\n if (name === override || restricted.includes(name)) continue;\n if (candidate !== undefined) value = candidate;\n }\n return value;\n}\n\n/**\n * Apply the restricted layers to `start`, letting each one CONFINE and never widen.\n *\n * @internal\n */\nfunction tightenOnly(input: SecurityFloorInput, start: string | undefined): string | undefined {\n const { permissiveness, restricted, layers } = input;\n let resolved = start;\n let ceiling = permissivenessOf(permissiveness, start);\n\n for (const layer of restricted) {\n const candidate = layers[layer];\n if (candidate === undefined) continue;\n const level = permissivenessOf(permissiveness, candidate);\n // Outside the vocabulary: ignored rather than trusted. See the docblock.\n if (level < 0) continue;\n // With no ceiling yet the layer is choosing, not widening.\n if (ceiling >= 0 && level > ceiling) continue;\n resolved = candidate;\n // Assigned, never max'd: the ceiling only ever descends, so a layer that hardens binds the\n // ones after it. A mutation to `Math.max` here is invisible until a later layer offers a value\n // between the old and new ceiling — which is why that case is written out in the tests.\n ceiling = level;\n }\n return resolved;\n}\n\n/**\n * Resolve a security-relevant setting so that a lower-trust layer can only tighten it.\n *\n * Two paths. When `layers[override]` holds a value, that value is returned VERBATIM and nothing\n * else is consulted — it is not checked against `permissiveness`, because validating the operator's\n * own flag belongs to the consumer that owns the vocabulary and the error message. Otherwise a\n * baseline is taken from the unrestricted layers, and each restricted layer in turn may lower it\n * and never raise it.\n *\n * Two consequences worth knowing before wiring this up. A value in a restricted layer that is not\n * in `permissiveness` is IGNORED rather than trusted, so a typo in a repository's config leaves the\n * baseline standing instead of becoming the effective setting. And the ceiling only ever descends:\n * once one restricted layer tightens, a later one cannot return to the baseline, even though it\n * could have chosen that value had it come first.\n *\n * When no layer supplied a value at all, the answer is `undefined` — the absence is reported rather\n * than filled in with the most confined member of the vocabulary.\n *\n * @returns the resolved value, or `undefined` when no layer supplied one.\n * @public\n */\nexport function applySecurityFloor(input: SecurityFloorInput): string | undefined {\n return input.layers[input.override] ?? tightenOnly(input, baseline(input));\n}\n","/**\n * Refuse to destroy a session another process is still writing.\n *\n * Every agent product that lets a user delete or overwrite a session needs this, and the failure is\n * unrecoverable in the worst way: a transcript removed underneath a running session takes with it\n * everything that session had not flushed, and nothing errors. The user sees a successful delete.\n *\n * ## The ordering is the point\n *\n * The check runs BEFORE anything is mutated. Removing a registry entry and then refusing leaves a\n * session that can be neither opened nor deleted — worse than either outcome on its own. So this is\n * a function the caller passes through rather than a flag it may consult afterwards: the throw is\n * what stops the mutation, and there is no way to read the answer and forget to act on it.\n *\n * ## What is generic, and what is not\n *\n * The RULE is: a session declared live is not destroyable, and refusing says which one and why. The\n * VOCABULARY is not — how a product decides liveness (a pointer file, the newest transcript, a\n * lease, an active registry entry) is its own. Nothing here touches a filesystem.\n *\n * @public\n */\n\nimport { TheokitAgentError } from \"./errors.js\";\n\n/** Why the destruction was refused. @public */\nexport type LiveSessionReason = \"session-is-live\" | \"liveness-undetermined\";\n\n/**\n * Raised by `guardSessionDestruction` instead of letting a session be destroyed.\n *\n * Read `reason` rather than the message when deciding what to do: `\"session-is-live\"` is fixed by\n * closing the other session, `\"liveness-undetermined\"` is fixed by making the liveness check work\n * again, and telling a user to close a session when nothing could be read sends them to close\n * nothing. `sessionId` carries the session the refusal was about.\n *\n * @public\n */\nexport class LiveSessionError extends TheokitAgentError {\n override readonly name = \"LiveSessionError\";\n readonly sessionId: string;\n readonly reason: LiveSessionReason;\n\n constructor(sessionId: string, reason: LiveSessionReason) {\n super(\n reason === \"session-is-live\"\n ? `refusing to destroy session ${sessionId}: it is live — another process is probably still ` +\n `appending to it. Switch to another session first.`\n : `refusing to destroy session ${sessionId}: the set of live sessions could not be ` +\n `determined, so this cannot be shown to be safe. Resolve that before deleting.`,\n );\n this.sessionId = sessionId;\n this.reason = reason;\n }\n}\n\n/**\n * Throw unless `sessionId` is safe to destroy.\n *\n * @param live - the sessions the product declares live, or `undefined` when it could not tell.\n * The distinction is load-bearing: an EMPTY set is a legitimate answer (nothing is open), while\n * `undefined` refuses. A product that swallowed a read error and returned `[]` would hand this\n * guard the one input that disables it entirely, on exactly the path that destroys data.\n * @throws LiveSessionError naming the session and the reason — \"close that session\" and \"the guard\n * could not read\" have different fixes, and conflating them sends the user to close nothing.\n * @public\n */\nexport function guardSessionDestruction(\n sessionId: string,\n live: readonly string[] | undefined,\n): void {\n if (live === undefined) {\n throw new LiveSessionError(sessionId, \"liveness-undetermined\");\n }\n if (live.includes(sessionId)) {\n throw new LiveSessionError(sessionId, \"session-is-live\");\n }\n}\n","import { FsSessionStore } from \"./internal/persistence/fs-session-store.js\";\nimport { resolveSessionDir } from \"./internal/persistence/session-dir.js\";\nimport { readSessionMessages as readFromStore } from \"./internal/session/agent-session-store.js\";\nimport type { SessionMessage } from \"./types/session-message.js\";\n\n/** Which session to read, in the terms a host already has. */\nexport interface ReadSessionMessagesOptions {\n /** The session's agent id — the same id `Agent` was created or resumed with. */\n sessionId: string;\n /**\n * The working directory the session belongs to. Sessions are per-cwd, so the same\n * id under a different cwd is a different session. Defaults to `process.cwd()`.\n */\n cwd?: string;\n /**\n * Where transcripts live. Only needed when the agent was created with\n * `local.sessionDir`; otherwise the SDK's default location is used.\n */\n sessionDir?: string;\n}\n\n/**\n * Read the messages a session already contains, for a surface that needs to re-render it.\n *\n * #546 — the SDK read these records to give the model its context on resume, and a host had\n * no way to read the same thing: a resumed session showed an empty screen while the model\n * demonstrably remembered. The alternative was for the host to parse\n * `<sessionDir>/projects/<encoded-cwd>/<id>.jsonl` itself, which is a private contract —\n * both the record shape and the directory encoding are the SDK's to change.\n *\n * This is deliberately narrower than the internal reader it wraps. That one takes a\n * {@link SessionStore}, and exporting it would put that interface, its record shape and its\n * lease semantics into the public surface to serve a caller that only wants to render what\n * is already there. A host that HAS a custom store can already read from it directly.\n *\n * Parsing stays tolerant, as it is on the resume path: a malformed line costs one message,\n * not the screen. A session that was never written resolves to `[]` rather than throwing —\n * a fresh session has no history, which is not an error.\n *\n * @example\n * ```ts\n * const history = await readSessionMessages({ sessionId, cwd: projectDir });\n * for (const m of history) render(m.role, m.text);\n * ```\n */\nexport async function readSessionMessages(\n options: ReadSessionMessagesOptions,\n): Promise<SessionMessage[]> {\n const cwd = options.cwd ?? process.cwd();\n const baseDir = resolveSessionDir({ sessionDir: options.sessionDir });\n return readFromStore(new FsSessionStore({ baseDir, cwd }), options.sessionId);\n}\n","/**\n * M3 #62 — scoped session state.\n *\n * A conversation id can be namespaced by SCOPE so a consumer keeps app-durable,\n * user-durable, and ephemeral (temp) session data separated in the same store:\n *\n * - `app:` — durable state shared across users (app-level memory).\n * - `user:` — durable state for one user.\n * - `temp:` — ephemeral state a consumer prunes on logout / session end.\n *\n * The scope is a prefix on the conversation id (`\"<scope>__<id>\"`). The `__`\n * separator is path-safe (unlike `:`, which the identifier guard rejects), so a\n * host can partition sessions by scope over the native transcript store.\n *\n * @public\n */\n\n/** M3 #62 — session state scope. */\nexport type SessionScope = \"app\" | \"user\" | \"temp\";\n\n/** M3 #62 — build a scope-namespaced conversation id (`\"<scope>__<id>\"`). */\nexport function scopedConversationId(scope: SessionScope, id: string): string {\n return `${scope}__${id}`;\n}\n\n/** M3 #62 — the id prefix (`\"<scope>__\"`) used to match a scope's conversations. */\nexport function sessionScopePrefix(scope: SessionScope): string {\n return `${scope}__`;\n}\n","/**\n * `createSquad` — a sequential team of agents.\n *\n * A Squad is a thin convenience that COMPOSES `Workflow` + `agentStep` — it\n * adds NO new orchestration logic. Agents run in array order; each agent's\n * output is threaded into the next agent's prompt. For branching/parallel/\n * foreach teams use `Workflow` directly; for manager→worker delegation use\n * subagents or `@theokit/sdk-handoff`.\n *\n * Mirrors the `createAgentFactory` composition-LEGO precedent (a factory over\n * existing primitives, not a new subsystem).\n *\n * @public\n */\n\nimport { ConfigurationError } from \"./errors.js\";\nimport type { AgentDefinition, SDKAgent } from \"./types/agent.js\";\nimport type { StepResult } from \"./types/workflow.js\";\nimport { agentStep, Workflow } from \"./workflow.js\";\n\n/**\n * Options for {@link createSquad}.\n *\n * @public\n */\nexport interface SquadOptions {\n /**\n * Agents run in array order (sequential pipeline). Must be non-empty.\n *\n * M81 — accepts an `AgentDefinition` (plain data) as well as a constructed `SDKAgent`. Building a\n * team used to force the caller to materialize every member by hand first: resolve the credential,\n * assemble the options, call `Agent.create`, await. That is precisely the work this milestone moves\n * into the framework elsewhere, so leaving it here would be inconsistent — and with\n * `discoverSubagents` now public (`@theokit/sdk/subagents-loader`), the data that describes an\n * agent is reachable, which closes the loop: discover → build a team, with no manual step between.\n *\n * Mixing both forms in one list is supported on purpose: a real team usually has members from\n * different origins.\n */\n agents: ReadonlyArray<SDKAgent | AgentDefinition>;\n /**\n * Orchestration process. Only `\"sequential\"` is supported (the default).\n * `\"hierarchical\"` is accepted by the type but rejected at runtime with\n * guidance — use subagents or `@theokit/sdk-handoff` for manager→worker\n * delegation (those already cover it).\n */\n process?: \"sequential\" | \"hierarchical\";\n /** Optional squad name (surfaced on the underlying workflow). Default `\"squad\"`. */\n name?: string;\n}\n\n/**\n * Result of a {@link Squad.run}. `result` is the final (last agent's) output;\n * `steps` is the per-agent trace from the underlying workflow run.\n *\n * @public\n */\nexport interface SquadRun {\n readonly result: unknown;\n readonly status: \"running\" | \"completed\" | \"failed\" | \"suspended\" | \"cancelled\";\n readonly steps: ReadonlyArray<StepResult>;\n}\n\n/**\n * A sequential agent team produced by {@link createSquad}.\n *\n * @public\n */\nexport interface Squad {\n /** Run the team over `input`, threading each agent's output to the next. */\n run(input: unknown): Promise<SquadRun>;\n}\n\n/**\n * M81 — an `SDKAgent` is recognised by having `send`; an `AgentDefinition` is plain data.\n *\n * Structural, not `instanceof`: the definition crosses package boundaries as data (that is the whole\n * interop contract the layer relies on), so an identity check would fail exactly when two copies of\n * the SDK are loaded — the failure mode M79 measured.\n */\nfunction isBuiltAgent(m: SDKAgent | AgentDefinition): m is SDKAgent {\n return typeof (m as SDKAgent).send === \"function\";\n}\n\n/**\n * M81 — turns an `AgentDefinition` into an executable agent.\n *\n * `Agent` is imported dynamically because `squad.ts` is consumed by paths that do not want to drag the\n * whole agent in just to declare a team; the cost is only paid by callers actually passing raw data.\n */\nasync function materialize(def: AgentDefinition, index: number): Promise<SDKAgent> {\n const { Agent } = await import(\"./agent.js\");\n return Agent.create({\n // `AgentDefinition.model` admits the sentinel `'inherit'`, which is not a model id. Inheriting\n // here means \"declare nothing and let the default apply\" — forwarding the literal would create\n // an agent asking for a model literally named `inherit`.\n ...(def.model !== undefined && def.model !== \"inherit\" ? { model: def.model } : {}),\n ...(def.prompt !== undefined ? { systemPrompt: def.prompt } : {}),\n agentId: `squad-member-${String(index)}`,\n local: {},\n });\n}\n\n/**\n * Build a sequential agent team. The returned {@link Squad} composes a\n * `Workflow` of `agentStep`s under the hood — all orchestration is delegated\n * to the workflow engine.\n */\nfunction createSquad(options: SquadOptions): Squad {\n const { agents } = options;\n if (!Array.isArray(agents) || agents.length === 0) {\n throw new ConfigurationError(\"createSquad requires a non-empty `agents` array\", {\n code: \"invalid_squad\",\n });\n }\n if (options.process !== undefined && options.process !== \"sequential\") {\n throw new ConfigurationError(\n `createSquad only supports process \"sequential\"; for manager→worker delegation use subagents or @theokit/sdk-handoff`,\n { code: \"squad_process_unsupported\" },\n );\n }\n\n return {\n run: async (input: unknown): Promise<SquadRun> => {\n const run = await (await buildPipeline(agents, options.name)).run(input);\n return { result: run.output, status: run.status, steps: run.stepResults };\n },\n };\n}\n\n/**\n * Builds the sequential pipeline, materializing the members that are still raw data.\n *\n * Extracted from `run` because the cognitive-complexity gate rejected the combined function — and because\n * \"building the pipeline\" and \"running it and translating the result\" are two responsibilities that were only\n * together by proximity.\n */\nasync function buildPipeline(\n agents: ReadonlyArray<SDKAgent | AgentDefinition>,\n name: string | undefined,\n): Promise<ReturnType<ReturnType<typeof Workflow.create>[\"commit\"]>> {\n // Compose Workflow + agentStep — identity threading: each agent's prompt is the previous agent's\n // output (the run input for the first agent).\n let builder = Workflow.create({ name: name ?? \"squad\" });\n for (let i = 0; i < agents.length; i++) {\n const member = agents[i];\n if (member === undefined) continue;\n // M81 — materializes at RUN time, not at construction: `Squad.create` is synchronous and an\n // `AgentDefinition` only becomes an agent with an `await`. Deferring to here keeps construction cheap and\n // avoids requiring a resolved credential to assemble a team before the first run.\n const agent = isBuiltAgent(member) ? member : await materialize(member, i);\n // SE3 — the first agent receives the human input (no peer origin); every subsequent agent\n // receives its predecessor's output, so its turn carries `{ kind: \"peer\", from: \"agent-<i-1>\" }`.\n const opts = i > 0 ? { origin: { kind: \"peer\" as const, from: `agent-${i - 1}` } } : undefined;\n builder = builder.then(agentStep(`agent-${i}`, agent, (prev) => String(prev), opts));\n }\n return builder.commit();\n}\n\n/** SE36 — `Squad.create` replaces `createSquad` (ADR 0015). Merges with the `Squad` interface. @public */\n// biome-ignore lint/suspicious/noUnsafeDeclarationMerging: SE36 namespace class merges with the `Squad` instance interface (ADR 0015) — intentional; `create()` returns the interface type, `new` is blocked by the private ctor.\nexport class Squad {\n private constructor() {}\n static create(options: SquadOptions): Squad {\n return createSquad(options);\n }\n}\n","/**\n * `Task` — observable async work registry (Adoption Roadmap gap #2,\n * ADRs D361-D374).\n *\n * Static facade delegating to the in-process `TaskRegistry` singleton.\n * The lifecycle of any task is the 5-state machine `queued | running |\n * finished | error | cancelled` (D362). Wrapping `Agent.send` /\n * `Agent.batch` / `Workflow.run` / `Cron` fires is opt-in via the\n * `{ task: true }` option on each (D363).\n *\n * @public\n */\n\nimport {\n cancel as registryCancel,\n configure as registryConfigure,\n get as registryGet,\n list as registryList,\n submit as registrySubmit,\n subscribe as registrySubscribe,\n} from \"./internal/task/registry.js\";\nimport type {\n TaskCancelResult,\n TaskEvent,\n TaskFilter,\n TaskHandle,\n TaskKind,\n TaskStoreOptions,\n TaskSubmitOptions,\n} from \"./types/task.js\";\n\nexport interface TaskWorkContext {\n readonly signal: AbortSignal;\n emit(payload: unknown): void;\n}\n\n/**\n * The unit of work handed to {@link Task.submit}.\n *\n * It receives the context rather than raw arguments: `ctx.signal` aborts on cancel and should be\n * observed by anything long-running, and `ctx.emit(payload)` produces a `progress` event for\n * subscribers. May be synchronous — the return type allows a plain value as well as a promise.\n *\n * @public\n */\nexport type TaskWorkFn<T> = (ctx: TaskWorkContext) => Promise<T> | T;\n\n/**\n * Registry-level configuration. May only be applied BEFORE the first\n * `Task.submit` of the process — see EC-13. Subsequent calls emit a\n * single stderr line and become no-ops.\n */\nexport interface TaskConfigureOptions {\n readonly store?: TaskStoreOptions;\n readonly maxConcurrent?: number;\n readonly retentionMs?: number;\n}\n\n/**\n * Static facade over the process-wide task registry — the observability layer for asynchronous\n * work.\n *\n * Not instantiable: the constructor throws, and every operation is a static that delegates to one\n * in-process singleton. Tasks are an OPT-IN wrapper. `Agent.send`, `Agent.batch`, `Workflow.run`\n * and `Cron` fires only appear here when submitted with `{ task: true }`; work you submit yourself\n * goes through `Task.submit`.\n *\n * Two ordering constraints bite in practice. `Task.configure` must run before the first `submit` of\n * the process — a later call logs one line and is otherwise a no-op. And `Task.get` returning\n * `undefined` does not mean the id never existed: retention evicts terminal tasks, so an id can go\n * from known to unknown over time.\n *\n * @public\n */\nexport class Task {\n // D361 — static class with private constructor.\n private constructor() {\n throw new Error(\"Task is static; do not instantiate\");\n }\n\n /**\n * Configure the registry. **Must be called before the first `submit`**\n * (EC-13). Available knobs: pluggable store (D364), concurrency cap\n * (D369), and retention (D373).\n */\n static configure(opts: TaskConfigureOptions): void {\n registryConfigure(opts);\n }\n\n /**\n * Submit a unit of asynchronous work to the registry.\n *\n * The `work` function receives `{ signal, emit }` — `signal` is the\n * AbortSignal honored on cancel; `emit(payload)` produces a\n * `progress` event observable via `Task.subscribe`.\n *\n * Returns a `TaskHandle` in `state: \"queued\"`. Subsequent state\n * transitions are observable via `Task.subscribe(handle.id)` OR\n * polled via `Task.get(handle.id)`.\n *\n * **Idempotency (D367):** submitting twice with the same `id` returns\n * the existing handle without re-invoking work.\n *\n * **Grammar (D368):** user-supplied ids must match\n * `^[a-z0-9][a-z0-9_-]*$` and must not start with reserved prefixes\n * `wf-` / `b-` / `cron-`. Otherwise `InvalidTaskIdError` is thrown.\n *\n * **Pre-aborted signal (EC-4):** if `options.signal` is already\n * aborted, the task short-circuits to `cancelled` without acquiring\n * a semaphore slot and without invoking `work`.\n */\n static async submit<T>(\n kind: TaskKind,\n work: TaskWorkFn<T>,\n options: TaskSubmitOptions = {},\n ): Promise<TaskHandle> {\n return registrySubmit<T>({\n kind,\n work,\n ...(options.id !== undefined ? { id: options.id } : {}),\n ...(options.meta !== undefined ? { meta: options.meta } : {}),\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n ...(options.onRunEvent !== undefined ? { onRunEvent: options.onRunEvent } : {}),\n });\n }\n\n /** Returns matching handles, capped at `filter.limit ?? 100`. */\n static list(filter: TaskFilter = {}): Promise<TaskHandle[]> {\n return registryList(filter);\n }\n\n /** Returns a single handle by id, or `undefined` if unknown / evicted. */\n static get(id: string): Promise<TaskHandle | undefined> {\n return registryGet(id);\n }\n\n /**\n * Idempotent cancel (D365). Returns:\n * - `{ cancelled: true, alreadyTerminal: false }` — transitioned\n * queued/running task to `cancelled`.\n * - `{ cancelled: false, alreadyTerminal: true }` — task already\n * terminal.\n * - `{ cancelled: false, alreadyTerminal: false }` — task unknown.\n *\n * Never throws.\n */\n static cancel(id: string, reason?: string): Promise<TaskCancelResult> {\n return registryCancel(id, reason);\n }\n\n /**\n * Subscribe to a task's event stream. The returned `AsyncIterable<TaskEvent>`\n * starts by replaying buffered events (ring buffer cap 64, D372) and\n * then yields live events until a terminal event (finished / errored\n * / cancelled) is emitted, at which point it closes automatically.\n *\n * Calling `.return()` on the iterator (or `break` in a `for await`)\n * cleans up the subscriber callback (EC-10).\n *\n * Throws `TaskNotFoundError` if the id is unknown or has been evicted.\n */\n static subscribe(id: string): AsyncIterable<TaskEvent> {\n return registrySubscribe(id);\n }\n}\n","import type { SDKProvider } from \"../../types/providers.js\";\nimport type { SDKModel, SDKRepository, SDKUser } from \"../../types/theokit.js\";\nimport { DEFAULT_AGENTIC_MODEL_ID } from \"../runtime/config/default-model.js\";\n\n/**\n * Fixture catalog data — returned when fixture-mode is active (no\n * `THEOKIT_API_BASE_URL` set + `theo_test_*` API key).\n *\n * Shapes here must match the JSON files under `tests/golden/theokit/`\n * after `normalizeForGolden()` is applied. `createdAt` is an ISO timestamp\n * normalized to `<timestamp>` by the test helper.\n *\n * @internal\n */\n\nconst FIXTURE_TIMESTAMP = \"2024-01-01T00:00:00.000Z\";\n\n/** Fixture user identity (matches `tests/golden/theokit/me.json`). */\nexport const FIXTURE_USER: SDKUser = {\n apiKeyName: \"Contract Test Key\",\n userEmail: \"sdk-contract@example.com\",\n createdAt: FIXTURE_TIMESTAMP,\n};\n\n/** Fixture model catalog (matches `tests/golden/theokit/models.json`). */\nexport const FIXTURE_MODELS: SDKModel[] = [\n {\n id: DEFAULT_AGENTIC_MODEL_ID,\n name: \"Gemini 2.0 Flash\",\n displayName: \"Gemini 2.0 Flash\",\n parameters: [\n {\n id: \"thinking\",\n displayName: \"Thinking\",\n values: [\n { value: \"low\", displayName: \"Low\" },\n { value: \"high\", displayName: \"High\" },\n ],\n },\n ],\n variants: [\n {\n displayName: \"High thinking\",\n params: [{ id: \"thinking\", value: \"high\" }],\n isDefault: false,\n },\n ],\n },\n];\n\n/** Fixture connected repos (matches `tests/golden/theokit/repositories.json`). */\nexport const FIXTURE_REPOSITORIES: SDKRepository[] = [\n { url: \"https://github.com/usetheo/example\" },\n];\n\n/**\n * Generic JSON Schema used as `setupSchema` for fixture providers. The\n * property name is intentionally generic (`credential`) so the schema never\n * contains substrings that look like environment variable names for real\n * provider tokens — fixture output must remain secret-shaped-noise-free.\n */\nconst GENERIC_SETUP_SCHEMA = {\n type: \"object\",\n description: \"Configuration values for this provider.\",\n required: [\"credential\"],\n properties: { credential: { type: \"string\" } },\n} as const;\n\n/**\n * Fixture provider catalog. Covers chat, web_search, image, and embedding\n * capabilities. The `setupSchema` is intentionally generic JSON Schema —\n * consumers drive UI from these definitions.\n *\n * Public and secret-free by design — no tokens or API key examples.\n */\nexport const FIXTURE_PROVIDERS: SDKProvider[] = [\n {\n name: \"anthropic\",\n displayName: \"Anthropic\",\n capabilities: [\"chat\"],\n isAvailable: true,\n setupSchema: GENERIC_SETUP_SCHEMA,\n },\n {\n name: \"openai\",\n displayName: \"OpenAI\",\n capabilities: [\"chat\", \"embedding\", \"image\"],\n isAvailable: false,\n setupSchema: GENERIC_SETUP_SCHEMA,\n },\n {\n name: \"openrouter\",\n displayName: \"OpenRouter\",\n capabilities: [\"chat\"],\n isAvailable: true,\n setupSchema: GENERIC_SETUP_SCHEMA,\n },\n {\n name: \"nous\",\n displayName: \"Nous Research\",\n capabilities: [\"chat\"],\n isAvailable: true,\n setupSchema: GENERIC_SETUP_SCHEMA,\n },\n {\n name: \"fixture-search\",\n displayName: \"Fixture Search\",\n capabilities: [\"web_search\"],\n isAvailable: true,\n setupSchema: GENERIC_SETUP_SCHEMA,\n },\n];\n","/**\n * Local model discovery via OpenAI-compatible `/v1/models` endpoint\n * (T2.1, ADR D184).\n *\n * Used by `Theokit.models.list({ provider: \"ollama\" })` (and any other\n * future provider with `authType: \"none\"` exposing the OpenAI-shape\n * models endpoint — LM Studio, llama.cpp `./server`, vLLM, etc.) to\n * enumerate locally-installed models without a cloud round-trip.\n *\n * Aligned with peer-project `extensions/ollama/src/provider-models.ts` which\n * targets the same endpoint shape. Mirrors the relevant Hermes\n * `models.dev` catalog behavior for local providers.\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport type { SDKModel } from \"../../types/theokit.js\";\nimport { mapOllamaHttpError, mapOllamaTransportError } from \"../error-mappers/ollama.js\";\nimport { readErrorResponseBody } from \"../http.js\";\n\ninterface OpenAiModelsResponse {\n object?: string;\n data?: Array<{ id?: string; owned_by?: string }>;\n}\n\n/**\n * Fetch and map `<baseUrl>/v1/models` → `SDKModel[]`. Throws a typed\n * `ConfigurationError` on connection failures (ECONNREFUSED → \"Run\n * `ollama serve`\"). Returns `[]` when the body is unparseable —\n * defensive choice over crashing on malformed responses from\n * non-standard local runtimes.\n */\nexport async function listLocalModelsViaOpenAiCompat(baseUrl: string): Promise<SDKModel[]> {\n const url = `${baseUrl}/v1/models`;\n let response: Response;\n try {\n response = await fetch(url, { method: \"GET\" });\n } catch (fetchErr) {\n const mapped = mapOllamaTransportError({\n providerId: \"ollama\",\n cause: fetchErr,\n endpoint: \"/v1/models\",\n });\n if (mapped !== undefined) throw mapped;\n throw new ConfigurationError(\n `Failed to reach local provider at ${baseUrl}: ${(fetchErr as Error).message}`,\n { code: \"local_provider_unreachable\" },\n );\n }\n if (!response.ok) {\n const body = await readErrorResponseBody(response);\n const mapped = mapOllamaHttpError({\n providerId: \"ollama\",\n status: response.status,\n body,\n headers: response.headers,\n endpoint: \"/v1/models\",\n });\n if (mapped !== undefined) throw mapped;\n throw new ConfigurationError(\n `Local provider at ${baseUrl} returned HTTP ${response.status} on /v1/models`,\n { code: \"local_provider_http_error\" },\n );\n }\n let parsed: OpenAiModelsResponse;\n try {\n parsed = (await response.json()) as OpenAiModelsResponse;\n } catch {\n return [];\n }\n const data = parsed.data ?? [];\n return data\n .filter(\n (entry): entry is { id: string } => typeof entry?.id === \"string\" && entry.id.length > 0,\n )\n .map((entry) => ({\n id: entry.id,\n displayName: entry.id,\n name: entry.id,\n }));\n}\n","import { AuthenticationError } from \"./errors.js\";\nimport {\n FIXTURE_MODELS,\n FIXTURE_PROVIDERS,\n FIXTURE_REPOSITORIES,\n FIXTURE_USER,\n} from \"./internal/catalog/fixtures.js\";\nimport { listLocalModelsViaOpenAiCompat } from \"./internal/catalog/local-models.js\";\nimport { resolveApiKey } from \"./internal/env.js\";\nimport { httpRequest } from \"./internal/http.js\";\nimport { MEMORY_EMBEDDING_ADAPTERS } from \"./internal/memory/adapters/catalog.js\";\nimport {\n getCatalogCapabilities,\n type ProviderCapabilities,\n} from \"./internal/providers/catalog-loader.js\";\nimport {\n discoverProviderPlugins,\n getProviderProfile,\n listProviders,\n registerBuiltins,\n} from \"./internal/providers/index.js\";\nimport { isFixtureApiKey, shouldUseFixtureMode } from \"./internal/runtime/fixtures/fixture-mode.js\";\nimport type { SDKProvider } from \"./types/providers.js\";\nimport type { SDKModel, SDKRepository, SDKUser } from \"./types/theokit.js\";\n\n/**\n * Options shared by every `Theokit.*` request.\n *\n * @public\n */\nexport interface TheokitRequestOptions {\n /** Override the `THEOKIT_API_KEY` env var for this call. */\n apiKey?: string;\n /**\n * Target a specific provider for catalog reads. When set to a provider\n * with `authType: \"none\"` (e.g. `\"ollama\"`, `\"lmstudio\"`, `\"llamacpp\"`),\n * `Theokit.models.list({ provider })` reads from the provider's local\n * `/v1/models` endpoint instead of the TheoCloud catalog. ADR D184.\n *\n * @public\n */\n provider?: string;\n}\n\n/**\n * Account-level and catalog reads. All methods accept an optional `apiKey`\n * and otherwise fall back to the `THEOKIT_API_KEY` environment variable.\n *\n * @public\n */\nexport class Theokit {\n private constructor() {\n // Static-only namespace.\n }\n\n /**\n * Return the user behind the current API key.\n *\n * @public\n */\n static me(options: TheokitRequestOptions = {}): Promise<SDKUser> {\n return executeCatalogRequest({\n apiKey: options.apiKey,\n fixture: FIXTURE_USER,\n path: \"/v1/me\",\n });\n }\n\n /**\n * Model catalog reads.\n *\n * @public\n */\n static readonly models: {\n list: (options?: TheokitRequestOptions) => Promise<SDKModel[]>;\n capabilities: (providerOrModelId: string) => ProviderCapabilities | undefined;\n } = {\n list: async (options = {}) => {\n // ADR D184: when `provider` targets an `authType: \"none\"` provider,\n // read locally instead of hitting TheoCloud. Cloud catalog path is\n // unchanged when `provider` is undefined.\n if (options.provider !== undefined) {\n const localModels = await maybeListLocalModels(options.provider);\n if (localModels !== undefined) return localModels;\n }\n return executeCatalogRequest({\n apiKey: options.apiKey,\n fixture: FIXTURE_MODELS,\n path: \"/v1/models\",\n });\n },\n capabilities: (providerOrModelId: string) => {\n registerBuiltins();\n // Extract provider name from \"provider/model\" format\n const providerId = providerOrModelId.includes(\"/\")\n ? (providerOrModelId.split(\"/\")[0] ?? providerOrModelId)\n : providerOrModelId;\n return getCatalogCapabilities(providerId);\n },\n };\n\n /**\n * Connected GitHub repositories for the calling user's team. Cloud only.\n *\n * @public\n */\n static readonly repositories: {\n list: (options?: TheokitRequestOptions) => Promise<SDKRepository[]>;\n } = {\n list: (options = {}) =>\n executeCatalogRequest({\n apiKey: options.apiKey,\n fixture: FIXTURE_REPOSITORIES,\n path: \"/v1/repositories\",\n }),\n };\n\n /**\n * Provider catalog. Lists every provider known to the platform, including\n * plugin-registered ones, with capability and availability metadata.\n *\n * @public\n */\n static readonly providers: {\n list: (options?: TheokitRequestOptions) => Promise<SDKProvider[]>;\n } = {\n list: (options = {}) =>\n executeCatalogRequest({\n apiKey: options.apiKey,\n fixture: FIXTURE_PROVIDERS,\n path: \"/v1/providers\",\n }),\n };\n\n /**\n * Local introspection of bundled SDK assets (ADR D201). Unlike the\n * cloud-catalog `providers.list()` (which hits the TheoCloud HTTP API),\n * `inspect.*` reads the SDK's own bundled registries — useful for\n * tooling (e.g. `@theokit/cli`'s `theokit inspect`) that needs to know\n * what's available WITHOUT a network round-trip.\n *\n * @public\n */\n static readonly inspect: {\n builtinProviders: () => Array<{\n readonly name: string;\n readonly apiMode: string;\n readonly authType: string;\n readonly baseUrl: string;\n readonly aliases?: ReadonlyArray<string>;\n readonly envVars: ReadonlyArray<string>;\n }>;\n embeddingAdapters: () => Array<{\n readonly id: string;\n readonly transport: string;\n readonly defaultModel: string;\n }>;\n } = {\n builtinProviders: () => {\n registerBuiltins();\n return listProviders().map((p) => ({\n name: p.name,\n apiMode: p.apiMode,\n authType: p.authType,\n baseUrl: p.baseUrl,\n ...(p.aliases !== undefined ? { aliases: p.aliases } : {}),\n envVars: p.envVars,\n }));\n },\n embeddingAdapters: () =>\n Object.entries(MEMORY_EMBEDDING_ADAPTERS).map(([id, adapter]) => ({\n id,\n transport: adapter.transport,\n defaultModel: adapter.defaultModel,\n })),\n };\n\n // NOTE: `Theokit.subscribe` is exported from `@theokit/sdk/subscription`\n // sub-path entry instead of the main `Theokit` static class to avoid\n // pulling the subscription module into the main `index.ts` DTS bundle\n // (which trips on the pre-existing `types/agent.ts ↔ fork-agent.ts` cycle\n // — same pattern as `path-safety` per ADR D425/D429 + see tsup.config.ts\n // header comment). Consumers import via:\n // `import { subscribe } from \"@theokit/sdk/subscription\"`\n // The function shape mirrors a hypothetical `Theokit.subscribe(name, input, opts)`\n // and may be promoted onto Theokit once the agent.ts cycle is broken.\n}\n\n/**\n * ADR D184: when caller passed `{ provider }` targeting a profile with\n * `authType: \"none\"`, fetch from the local provider's `/v1/models`.\n * Returns `undefined` when the provider does not exist OR has auth —\n * caller falls back to the cloud catalog path.\n */\nasync function maybeListLocalModels(providerName: string): Promise<SDKModel[] | undefined> {\n registerBuiltins();\n // M47 review F2 — this async entrypoint resolves provider profiles, so plugin discovery must run\n // here too (the sync surfaces `models.capabilities()` / `inspect.builtinProviders()` intentionally\n // remain builtins-only — they cannot await; documented limitation).\n await discoverProviderPlugins();\n const profile = getProviderProfile(providerName);\n if (profile === undefined) return undefined;\n if (profile.authType !== \"none\") return undefined;\n const baseUrl = resolveLocalProviderBaseUrl(profile.name, profile.baseUrl);\n return listLocalModelsViaOpenAiCompat(baseUrl);\n}\n\nfunction resolveLocalProviderBaseUrl(providerName: string, fallback: string): string {\n // Mirror the env override priority used in router.ts selectTransport.\n if (providerName === \"ollama\" && process.env.OLLAMA_HOST !== undefined) {\n return process.env.OLLAMA_HOST;\n }\n return fallback;\n}\n\ninterface CatalogRequest<T> {\n apiKey: string | undefined;\n fixture: T;\n path: string;\n}\n\nasync function executeCatalogRequest<T>(request: CatalogRequest<T>): Promise<T> {\n const apiKey = resolveApiKey(request.apiKey);\n if (apiKey === undefined) {\n throw new AuthenticationError(\"Missing API key\", { code: \"missing_api_key\" });\n }\n\n if (shouldUseFixtureMode(apiKey)) {\n return request.fixture;\n }\n\n // Fixture-mode is off — either an explicit base URL is set (real HTTP)\n // or a non-fixture key is being used without a backend reachable.\n if (!isFixtureApiKey(apiKey) && process.env.THEOKIT_API_BASE_URL === undefined) {\n throw new AuthenticationError(\"Invalid API key\", { code: \"authentication_error\" });\n }\n\n return httpRequest<T>(request.path, { apiKey });\n}\n","/**\n * Attach a blast-radius declaration to a tool, so the approval layer gates on what the tool DOES.\n *\n * Without this the only key available to a policy is the tool's NAME, which says nothing about the\n * action, drifts the moment a tool is renamed, and cannot be reviewed by anyone who did not write\n * it. `delete_namespace` and `list_pods` differ by a word.\n *\n * ## Why a wrapper rather than a field on the input schema\n *\n * `inputSchema` is what the MODEL sees. Blast radius is not for the model — it is for the approval\n * layer — and putting it there would leak policy into the prompt and let a model-authored argument\n * influence its own gate. The declaration rides alongside the tool instead, under a symbol so it\n * cannot collide with a tool's own properties or be serialised into a prompt by accident.\n *\n * @public\n */\n\nimport type { DeclaredAction } from \"./blast-radius.js\";\n\n/**\n * Symbol-keyed on purpose. THAT is what keeps the declaration out of a prompt: `Object.keys` and\n * `JSON.stringify` both ignore symbol keys, so a tool serialised on its way to the model carries\n * none of it. A string key would also risk colliding with a property the tool already has.\n *\n * Exported because the `@public` `WithBlastRadius<T>` below uses it as a COMPUTED\n * KEY. A computed key is part of the type it keys, so the emitted declaration\n * names this const — and a name the declaration file does not carry is a broken\n * reference (#335). `Symbol.for` keeps it a registry symbol, so an exported\n * binding does not weaken the property-hiding this comment describes: the value\n * was always retrievable by any code that knows the string.\n *\n * @public\n */\nexport const DECLARED: unique symbol = Symbol.for(\"@theokit/sdk.blastRadius\") as typeof DECLARED;\n\n/**\n * A tool that may carry a blast-radius declaration under {@link DECLARED}.\n *\n * The property is OPTIONAL in the type, so a plain tool is assignable to it and the type alone\n * never proves a declaration was made. `describeAction` is what tells the two apart at runtime.\n *\n * @public\n */\nexport type WithBlastRadius<T> = T & { readonly [DECLARED]?: DeclaredAction };\n\n/**\n * Declare what a tool reaches, for the approval layer rather than for the model.\n *\n * This MUTATES `tool` — it defines a symbol-keyed property on the object it was given and hands\n * the same reference back, so every existing reference to that tool sees the declaration too.\n * Calling it again on the same tool replaces the previous declaration; the property is\n * `configurable`, so re-declaring never throws.\n *\n * The declaration is invisible to `Object.keys` and `JSON.stringify` because the key is a symbol,\n * which is what keeps it out of anything serialised into a prompt.\n *\n * @returns the same tool, with its action declared. The tool is not otherwise altered — the model\n * must see exactly what it saw before.\n * @public\n */\nexport function withBlastRadius<T extends object>(\n tool: T,\n action: DeclaredAction,\n): WithBlastRadius<T> {\n return Object.defineProperty(tool, DECLARED, {\n value: action,\n // `enumerable: false` is defensive and NOT load-bearing — checked, not assumed. Flipping it to\n // true leaves every case green, because the symbol key already excludes this from `Object.keys`\n // and `JSON.stringify`. It stays because a future string-keyed variant would need it, and the\n // next reader should not have to discover that the flag has no test behind it.\n enumerable: false,\n configurable: true,\n }) as WithBlastRadius<T>;\n}\n\n/**\n * Read back the action a tool declared, if any.\n *\n * This is how an approval layer obtains the `action` for `evaluateBlastRadius`. An `undefined`\n * result means nobody has reviewed this tool's reach, which is a different fact from a tool that\n * declared a narrow scope — decide what to do with the unreviewed case explicitly rather than\n * treating it as harmless.\n *\n * @returns the declared action, or `undefined` when the tool never declared one — NOT an empty\n * action. \"Never declared\" and \"declared as reaching nothing\" are different facts, and collapsing\n * them is how an unreviewed tool passes as harmless.\n * @public\n */\nexport function describeAction(tool: object): DeclaredAction | undefined {\n return (tool as { [DECLARED]?: DeclaredAction })[DECLARED];\n}\n","/**\n * `toShareGptTrajectory` — opt-in BatchResult → ShareGPT converter (ADR D139).\n *\n * Pure transformation. Returns `null` for failed results so callers can\n * filter via `.map(toShareGptTrajectory).filter(Boolean)`. Tool calls and\n * tool results are preserved when an SDKMessage trace is provided; otherwise\n * a minimal `human → gpt` trajectory is emitted from the final text.\n *\n * @public\n */\n\nimport type { BatchResult } from \"./types/batch.js\";\nimport type { SDKMessage, TextBlock, ToolUseBlock } from \"./types/messages.js\";\nimport type { ShareGptMessage, ShareGptTrajectory } from \"./types/trajectory.js\";\n\n/**\n * Convert a successful `BatchResult` to ShareGPT-format trajectory.\n *\n * Behavior:\n * - `result.ok === false` → returns `null` (EC-11).\n * - First entry is always `{from: \"human\", value: result.prompt}`.\n * - When `options.messages` is supplied, each SDKMessage maps to one or\n * more ShareGPT entries (assistant text → gpt, tool_use → gpt + tool).\n * - Without `options.messages`, fall back to a single `{from: \"gpt\"}`\n * entry carrying `result.result.result` (the final text) when present.\n * - Malformed message entries are silently skipped (EC-F / EC-14).\n *\n * @public\n */\nexport function toShareGptTrajectory(\n result: BatchResult,\n options?: { messages?: SDKMessage[]; model?: string },\n): ShareGptTrajectory | null {\n if (!result.ok) return null;\n const conversations = buildConversations(result, options?.messages);\n const trajectory: ShareGptTrajectory = {\n conversations,\n metadata: {\n timestamp: new Date().toISOString(),\n durationMs: result.durationMs,\n promptIndex: result.index,\n ...(options?.model !== undefined ? { model: options.model } : {}),\n },\n completed: true,\n };\n const usage = extractUsage(result.result);\n if (usage !== undefined) trajectory.usage = usage;\n return trajectory;\n}\n\nfunction buildConversations(\n result: Extract<BatchResult, { ok: true }>,\n messages: SDKMessage[] | undefined,\n): ShareGptMessage[] {\n const conversations: ShareGptMessage[] = [{ from: \"human\", value: result.prompt }];\n if (Array.isArray(messages) && messages.length > 0) {\n for (const m of messages) {\n for (const entry of mapSdkMessage(m)) conversations.push(entry);\n }\n return conversations;\n }\n // Fall-back: minimal {gpt} entry with final text (EC-12).\n const finalText = typeof result.result.result === \"string\" ? result.result.result : \"\";\n conversations.push({ from: \"gpt\", value: finalText });\n return conversations;\n}\n\nfunction extractUsage(\n runResult: unknown,\n): { inputTokens: number; outputTokens: number } | undefined {\n const usage = (runResult as { usage?: { inputTokens?: unknown; outputTokens?: unknown } })?.usage;\n if (usage === undefined) return undefined;\n if (typeof usage.inputTokens !== \"number\" || typeof usage.outputTokens !== \"number\") {\n return undefined;\n }\n return { inputTokens: usage.inputTokens, outputTokens: usage.outputTokens };\n}\n\n/**\n * Map one SDKMessage to zero or more ShareGPT entries. Tool-use blocks\n * inside an assistant message split into a `gpt` entry with `tool_calls`\n * plus, when paired with a `tool_call.completed` event, a `tool` entry\n * carrying the result.\n *\n * Malformed shapes (missing `message.content`, non-array content) yield\n * an empty list — caller skips silently (EC-F).\n *\n * @internal\n */\nfunction mapSdkMessage(m: SDKMessage): ShareGptMessage[] {\n if (m === null || typeof m !== \"object\") return [];\n switch (m.type) {\n case \"assistant\":\n return mapAssistant(m);\n case \"tool_call\":\n return mapToolCall(m);\n case \"thinking\":\n case \"system\":\n case \"user\":\n case \"status\":\n case \"task\":\n case \"request\":\n case \"object_delta\":\n return [];\n default: {\n // Exhaustive sentinel — unreachable on stable SDKMessage union.\n const _exhaustive: never = m;\n void _exhaustive;\n return [];\n }\n }\n}\n\nfunction mapAssistant(m: Extract<SDKMessage, { type: \"assistant\" }>): ShareGptMessage[] {\n const content = m.message?.content;\n if (!Array.isArray(content)) return [];\n const textParts: string[] = [];\n const toolCalls: NonNullable<ShareGptMessage[\"tool_calls\"]> = [];\n for (const block of content) {\n appendBlock(block, textParts, toolCalls);\n }\n const entry: ShareGptMessage = { from: \"gpt\", value: textParts.join(\"\") };\n if (toolCalls.length > 0) entry.tool_calls = toolCalls;\n return [entry];\n}\n\nfunction appendBlock(\n block: unknown,\n textParts: string[],\n toolCalls: NonNullable<ShareGptMessage[\"tool_calls\"]>,\n): void {\n if (block === null || typeof block !== \"object\") return;\n const text = block as TextBlock;\n if (text.type === \"text\" && typeof text.text === \"string\") {\n textParts.push(text.text);\n return;\n }\n const tu = block as ToolUseBlock;\n if (tu.type !== \"tool_use\") return;\n const args =\n tu.input !== null && typeof tu.input === \"object\" ? (tu.input as Record<string, unknown>) : {};\n toolCalls.push({ name: tu.name, arguments: args });\n}\n\nfunction mapToolCall(m: Extract<SDKMessage, { type: \"tool_call\" }>): ShareGptMessage[] {\n // Only emit when the tool call completed — running/error are interim states.\n if (m.status !== \"completed\") return [];\n const value =\n typeof m.result === \"string\" ? m.result : m.result === undefined ? \"\" : safeStringify(m.result);\n return [{ from: \"tool\", value }];\n}\n\nfunction safeStringify(v: unknown): string {\n try {\n return JSON.stringify(v);\n } catch {\n return String(v);\n }\n}\n","/**\n * Decide what a project directory is allowed to switch on.\n *\n * A product that reads a repository has to answer this before it builds anything: are that\n * repository's hooks honoured, are its MCP servers started, do its instructions enter the persona?\n * The stakes are not configuration-shaped. A hook is arbitrary command execution on every tool\n * call, and an MCP server is an external process SPAWNED while the agent is built — before any\n * per-tool approval exists to refuse it. A product that gets this wrong grants local execution on\n * first build, in a directory the user only meant to open.\n *\n * ## What this is, and what it deliberately is not\n *\n * The arithmetic is small: pick a level, derive one boolean per capability. The value is the\n * INVARIANT — untrusted means EVERY declared capability is off, and `allows` is built FROM the\n * declared list, so a product that adds a ninth capability cannot forget to gate it. That failure\n * is invisible when it happens: the new capability simply works in a directory where it should not,\n * and nothing reports anything.\n *\n * It does NOT decide what \"trusted\" means. Where the record lives, what the environment variable is\n * called, whether a legacy alias is still honoured — all of that is the consumer's, because all of\n * it is that product's vocabulary. The framework owns the shape of the answer and the guarantee\n * that the answer covers everything declared.\n *\n * ## Why `source` is reported\n *\n * \"Trusted because the operator recorded this directory\" and \"trusted because a blanket environment\n * switch is on\" are different facts. A surface that only shows `trusted` cannot warn about the\n * second, which is the one that stays on across every directory the process ever opens.\n *\n * @public\n */\n\n/**\n * Whether a project directory may switch anything on.\n *\n * There is no middle level on purpose: `untrusted` means every declared capability is off, not\n * \"some are off\". A product that wants a partial grant expresses it by declaring fewer capabilities\n * for that call, not by inventing a third level here.\n *\n * @public\n */\nexport type TrustLevel = \"trusted\" | \"untrusted\";\n\n/** Where the decision came from. @public */\nexport type TrustSource = \"env\" | \"store\" | \"default\";\n\n/**\n * What the decision is made from: the capability vocabulary, a way to read the operator's record,\n * and an optional blanket override.\n *\n * `capabilities` is load-bearing rather than descriptive — the returned `allows` is built from\n * exactly this list, so a capability missing from it is a capability nothing gates.\n *\n * @public\n */\nexport interface TrustPostureInput<K extends string> {\n /**\n * Every capability a repository could switch on. `allows` is built from exactly this list — the\n * guarantee that nothing is left ungated.\n */\n readonly capabilities: readonly K[];\n /**\n * Whether the operator has recorded this directory as trusted. Called at most once, and not at\n * all when `envOverride` already granted trust — it may touch the filesystem.\n */\n readonly isTrusted: () => boolean;\n /**\n * A blanket override from the consumer's own environment vocabulary. `true` grants trust;\n * `false` and `undefined` both mean \"the operator did not switch it on\" — NOT \"switched it off\",\n * because an unset variable must not override a trusted store.\n */\n readonly envOverride?: boolean;\n}\n\n/**\n * The decision: the level, where it came from, and one boolean per declared capability.\n *\n * `allows` has exactly the keys of the `capabilities` list it was built from, so reading a\n * capability the caller never declared is a type error rather than a silent `undefined` that a\n * consumer would read as \"not allowed\".\n *\n * @public\n */\nexport interface TrustPosture<K extends string> {\n readonly level: TrustLevel;\n readonly source: TrustSource;\n /** One entry per declared capability. Every value is `false` when the level is untrusted. */\n readonly allows: Readonly<Record<K, boolean>>;\n}\n\n/**\n * Decide what a project directory is allowed to switch on.\n *\n * Precedence: `envOverride === true` grants trust and SHORT-CIRCUITS — `isTrusted` is not called at\n * all, which matters because it may touch the filesystem. Otherwise `isTrusted()` is called exactly\n * once and its answer decides. `envOverride === false` is not a denial: it falls through to the\n * store like `undefined` does, so an unset or explicitly-off environment switch can never revoke a\n * directory the operator recorded as trusted.\n *\n * Every entry of `allows` is `false` whenever the level is untrusted, and the entries are generated\n * from `capabilities` rather than supplied per capability — that is what makes \"nothing was left\n * ungated\" a property of the call instead of a habit of the caller.\n *\n * @public\n */\nexport function resolveTrustPosture<K extends string>(\n input: TrustPostureInput<K>,\n): TrustPosture<K> {\n const source: TrustSource =\n input.envOverride === true ? \"env\" : input.isTrusted() ? \"store\" : \"default\";\n const level: TrustLevel = source === \"default\" ? \"untrusted\" : \"trusted\";\n const granted = level === \"trusted\";\n\n // Built from the declared list rather than from anything the caller passes per capability: that\n // is what makes \"nothing is ungated\" a property of the type instead of a habit.\n const allows = Object.fromEntries(input.capabilities.map((key) => [key, granted])) as Record<\n K,\n boolean\n >;\n\n return { level, source, allows };\n}\n","/**\n * Record what a build actually wired, as opposed to what configuration asked for.\n *\n * A product that reads a project directory decides, while building, which of that directory's\n * entities it will honour: MCP servers, skills, hook events, commands. When a trust posture withholds\n * them, the build simply proceeds with fewer — and every surface that later asks \"what is loaded?\"\n * sees an empty list. Empty because nothing was configured and empty because everything was withheld\n * are the same emptiness to the reader, and only one of them is something they can act on.\n *\n * ## Why this is not a re-read\n *\n * The obvious implementation of any \"what is loaded?\" listing is to read the configuration again.\n * That is the defect this exists to prevent: a re-read cannot detect a disagreement between what\n * config asked for and what the build did, because it IS the config. The two disagree exactly when\n * something suppressed an entity, which is the case worth reporting.\n *\n * So this function is pure and parameterized. It performs no I/O, which is what makes \"no second\n * read\" checkable rather than promised — the caller passes the values it handed to the builder, at\n * the moment it handed them over, and what comes back is an observation of that moment.\n *\n * ## What is generic here, and what is not\n *\n * The RULE is generic: for each capability, active is the request when allowed and empty when not,\n * and suppression is only claimed when something was actually removed. The VOCABULARY is not —\n * which capabilities exist and what the entities are called belong to the product, and arrive as\n * data.\n *\n * @public\n */\n\nimport { TheokitAgentError } from \"./errors.js\";\n\n/** Raised when a recorded capability has no entry in the gate. @public */\nexport class UngatedCapabilityError extends TheokitAgentError {\n override readonly name = \"UngatedCapabilityError\";\n}\n\n/** What one capability asked for, and what it got. @public */\nexport interface WiredEntity {\n /** The names actually handed to the builder. Empty when the capability was withheld. */\n readonly active: readonly string[];\n /**\n * The names configuration ASKED for. Equal to `active` when nothing was withheld; the difference\n * is exactly what the reader cannot otherwise see.\n */\n readonly requested: readonly string[];\n /**\n * True only when the gate is what emptied `active`.\n *\n * Deliberately false for a withheld capability that requested nothing: an untrusted directory with\n * no skills and a trusted one with no skills are the same emptiness, and a flag that fires when\n * nothing happened teaches the reader to ignore it.\n */\n readonly suppressedByTrust: boolean;\n}\n\n/**\n * The two halves of the observation: the gate that was applied, and what was handed to the builder.\n *\n * `requested` drives the shape of the record — the result has exactly its keys — while `posture`\n * only has to contain a gate for each of them. A posture that gates MORE than `requested` covers is\n * fine and normal; a posture that gates FEWER is refused, see `recordWiring`.\n *\n * Pass the values at the moment they go to the builder. Re-deriving them from configuration\n * afterwards would defeat the point: config is what was asked for, and the disagreement with what\n * was wired is the only thing this records.\n *\n * @public\n */\nexport interface WiringRecordInput<K extends string> {\n /**\n * The gate. Typically the output of `resolveTrustPosture`, which is what makes the name\n * `suppressedByTrust` accurate rather than decorative — a posture is the only thing in this\n * package that withholds a capability.\n *\n * It may gate MORE than `requested` covers: a posture also gates things that are not lists of\n * names, like durable memory. Those are not entities and do not appear in the record.\n */\n readonly posture: { readonly allows: Readonly<Record<string, boolean>> };\n /** Per capability, the entity names the build was given. Drives which keys the record has. */\n readonly requested: Readonly<Record<K, readonly string[]>>;\n}\n\n/**\n * Record what a build actually wired, per capability.\n *\n * For each key of `requested`: `active` is a copy of the requested names when the posture allows\n * that capability and an empty array when it does not, `requested` is always a copy of what was\n * asked for, and `suppressedByTrust` is true only when the gate emptied a NON-EMPTY request. A\n * withheld capability that requested nothing reports `false`, because a flag that fires when\n * nothing happened is a flag readers learn to ignore.\n *\n * Pure and synchronous — it performs no I/O, which is what makes \"this is not a second read of the\n * configuration\" checkable rather than promised.\n *\n * @returns one entry per key of `requested`, each a snapshot rather than a view of the caller's\n * arrays — the record is read long after the build, and aliasing would make it answer with what\n * the process holds now instead of with what was wired.\n * @throws UngatedCapabilityError when a key of `requested` has no entry in `posture.allows`. Absent\n * is not read as denied: reporting a capability nobody gates as suppressed would send the reader\n * looking for a trust setting that does not exist.\n * @public\n */\nexport function recordWiring<K extends string>(\n input: WiringRecordInput<K>,\n): Readonly<Record<K, WiredEntity>> {\n const record = {} as Record<K, WiredEntity>;\n for (const [capability, requested] of Object.entries(input.requested) as [\n K,\n readonly string[],\n ][]) {\n const allowed = input.posture.allows[capability];\n if (allowed === undefined) {\n // Fail loudly rather than defaulting. Reading an absent gate as \"not allowed\" would report a\n // capability nobody gates as SUPPRESSED — a plausible answer, and wrong in the direction the\n // reader cannot check: they would go looking for a trust setting that does not exist.\n throw new UngatedCapabilityError(\n `capability \\`${capability}\\` was recorded as wired but the posture does not gate it; ` +\n `gated capabilities are: ${Object.keys(input.posture.allows).join(\", \") || \"(none)\"}`,\n );\n }\n record[capability] = {\n // Copied, not aliased. See the @returns note.\n active: allowed ? [...requested] : [],\n requested: [...requested],\n suppressedByTrust: !allowed && requested.length > 0,\n };\n }\n return record;\n}\n"]}
|
|
1
|
+
{"version":3,"sources":["../src/agent-factory.ts","../src/approval-policy.ts","../src/blast-radius.ts","../src/internal/budget/calendar-window.ts","../src/internal/budget/ledger.ts","../src/internal/budget/registry.ts","../src/internal/budget/enforcement.ts","../src/internal/budget/normalize-usage.ts","../src/budget.ts","../src/built-in-processors.ts","../src/create-skill.ts","../src/credential-presence.ts","../src/define-provider.ts","../src/define-skill-read-tool.ts","../src/env-reachability.ts","../src/event-bus.ts","../src/goal-loop.ts","../src/internal/budget/tracker/budget-tracker-counter.ts","../src/internal/plugins/types.ts","../src/internal/runtime/memory-glue/memory-provider-noop.ts","../src/internal/runtime/validation/effective-tools.ts","../src/job-queue.ts","../src/layer-fold.ts","../src/internal/memory/dreaming/phases.ts","../src/internal/memory/dreaming/run.ts","../src/internal/memory/sdk-memory-peer-loader.ts","../src/memory.ts","../src/memory-adapter-helpers.ts","../src/migrate.ts","../src/permission-engine.ts","../src/permission-plugin.ts","../src/project-env.ts","../src/reap-plan.ts","../src/schema-normalizer.ts","../src/security.ts","../src/security-floor.ts","../src/session-guard.ts","../src/session-messages.ts","../src/session-scope.ts","../src/squad.ts","../src/task.ts","../src/internal/catalog/fixtures.ts","../src/internal/catalog/local-models.ts","../src/theokit.ts","../src/tool-blast-radius.ts","../src/trajectory-helpers.ts","../src/trust-posture.ts","../src/wiring-record.ts"],"names":["Agent","withCwdMutex","list","ConfigurationError","BudgetExceededError","diag","estimateTokens","CHARS_PER_TOKEN","createHash","registerBuiltins","listProviders","parseModelId","z","toJsonSchema","fn","randomUUID","TheokitAgentError","kept","resolveMemoryRoot","readFactsFromMarkdown","appendDiaryEntry","join","mkdir","replaceFileAtomic","MEMORY_EMBEDDING_ADAPTERS","MemoryAdapterError","migrateSqliteToLance","redactSecrets","addPattern","readSessionMessages","resolveSessionDir","FsSessionStore","Workflow","agentStep","configure","submit","get","cancel","subscribe","DEFAULT_AGENTIC_MODEL_ID","mapOllamaTransportError","readErrorResponseBody","mapOllamaHttpError","getCatalogCapabilities","discoverProviderPlugins","getProviderProfile","resolveApiKey","AuthenticationError","shouldUseFixtureMode","isFixtureApiKey","httpRequest"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCA,SAAS,mBAAmB,MAAA,EAA6C;AACvE,EAAA,OAAO;AAAA,IACL,UAAA,EAAY,CAAC,OAAA,EAAS,SAAA,KAAcA,uBAAA,CAAM,OAAO,iBAAA,CAAkB,MAAA,EAAQ,SAAA,EAAW,OAAO,CAAC,CAAA;AAAA,IAC9F,WAAA,EAAa,CAAC,OAAA,EAAS,SAAA,KACrBA,uBAAA,CAAM,WAAA,CAAY,OAAA,EAAS,iBAAA,CAAkB,MAAA,EAAQ,SAAA,EAAW,OAAO,CAAC;AAAA,GAC5E;AACF;AASA,SAAS,iBAAA,CACP,MAAA,EACA,SAAA,EACA,OAAA,EACc;AACd,EAAA,MAAM,CAAA,GAAI,aAAa,EAAC;AACxB,EAAA,MAAM,MAAA,GAAgC,EAAE,GAAG,MAAA,EAAQ,GAAG,CAAA,EAAE;AACxD,EAAA,MAAM,KAAA,GAAQ,cAAA,CAAe,MAAA,CAAO,KAAA,EAAO,EAAE,KAAK,CAAA;AAClD,EAAA,IAAI,KAAA,KAAU,MAAA,EAAW,MAAA,CAAO,KAAA,GAAQ,KAAA;AACxC,EAAA,MAAM,MAAA,GAAS,eAAA,CAAgB,MAAA,CAAO,MAAA,EAAQ,EAAE,MAAM,CAAA;AACtD,EAAA,IAAI,MAAA,KAAW,MAAA,EAAW,MAAA,CAAO,MAAA,GAAS,MAAA;AAC1C,EAAA,MAAM,KAAA,GAAQ,cAAA,CAAe,MAAA,CAAO,KAAA,EAAO,EAAE,KAAK,CAAA;AAClD,EAAA,IAAI,KAAA,KAAU,MAAA,EAAW,MAAA,CAAO,KAAA,GAAQ,KAAA;AACxC,EAAA,MAAA,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.js\";\n\n/**\n * Handle returned by {@link createAgentFactory}. See ADR D23 for merge\n * semantics.\n *\n * @public\n */\nexport interface AgentFactory {\n /**\n * Create a fresh agent for this session. Equivalent to `Agent.create(merged)`\n * where `merged` is `common` ⊕ `overrides` ⊕ `{ agentId }`.\n */\n forSession(agentId: string, overrides?: Partial<AgentOptions>): Promise<SDKAgent>;\n /**\n * Resume an existing agent for this session, or create one if the ID is\n * unknown. Equivalent to `Agent.getOrCreate(agentId, merged)`.\n */\n getOrCreate(agentId: string, overrides?: Partial<AgentOptions>): Promise<SDKAgent>;\n}\n\n/**\n * Capture a common {@link AgentOptions} prefix and produce per-session agents\n * with focused overrides. Useful for chat-bot patterns where most config is\n * shared across users/sessions.\n *\n * Merge rules (ADR D23):\n * - Top-level shallow merge with `overrides` winning.\n * - Deep merge for `local`, `memory`, `cloud` (configuration objects with\n * non-conflicting flat keys).\n * - Total replace for `mcpServers`, `agents`, `tools`, `providers`,\n * `plugins`, `skills`, `context` (collection-shaped).\n * - The function-level `agentId` always wins over both `common.agentId` and\n * `overrides.agentId`.\n *\n * The factory holds `common` by reference — mutating it after construction\n * leaks to subsequent `forSession` calls (documented caveat).\n *\n * @public\n */\nfunction createAgentFactory(common: Partial<AgentOptions>): AgentFactory {\n return {\n forSession: (agentId, overrides) => Agent.create(mergeAgentOptions(common, overrides, agentId)),\n getOrCreate: (agentId, overrides) =>\n Agent.getOrCreate(agentId, mergeAgentOptions(common, overrides, agentId)),\n };\n}\n\n/**\n * Merge factory `common` config with per-session `overrides`, forcing the\n * function-level `agentId`. Deep-merges the 3 configuration-shaped fields\n * (`local`, `memory`, `cloud`); replaces collection-shaped fields.\n *\n * @internal\n */\nfunction mergeAgentOptions(\n common: Partial<AgentOptions>,\n overrides: Partial<AgentOptions> | undefined,\n agentId: string,\n): AgentOptions {\n const o = overrides ?? {};\n const merged: Partial<AgentOptions> = { ...common, ...o };\n const local = deepMergeLocal(common.local, o.local);\n if (local !== undefined) merged.local = local;\n const memory = deepMergeMemory(common.memory, o.memory);\n if (memory !== undefined) merged.memory = memory;\n const cloud = deepMergeCloud(common.cloud, o.cloud);\n if (cloud !== undefined) merged.cloud = cloud;\n merged.agentId = agentId;\n return merged as AgentOptions;\n}\n\nfunction deepMergeLocal(\n base: AgentOptions[\"local\"],\n top: AgentOptions[\"local\"],\n): AgentOptions[\"local\"] | undefined {\n if (base === undefined && top === undefined) return undefined;\n return { ...(base ?? {}), ...(top ?? {}) };\n}\n\nfunction deepMergeMemory(\n base: AgentOptions[\"memory\"],\n top: AgentOptions[\"memory\"],\n): AgentOptions[\"memory\"] | undefined {\n if (base === undefined && top === undefined) return undefined;\n return {\n ...(base ?? {}),\n ...(top ?? {}),\n enabled: top?.enabled ?? base?.enabled ?? false,\n };\n}\n\nfunction deepMergeCloud(\n base: AgentOptions[\"cloud\"],\n top: AgentOptions[\"cloud\"],\n): AgentOptions[\"cloud\"] | undefined {\n if (base === undefined && top === undefined) return undefined;\n return { ...(base ?? {}), ...(top ?? {}) };\n}\n\n/** SE36 — `AgentFactory.create` replaces `createAgentFactory` (ADR 0015). Merges with the `AgentFactory` interface. @public */\n// biome-ignore lint/suspicious/noUnsafeDeclarationMerging: SE36 namespace class merges with the `AgentFactory` instance interface (ADR 0015) — intentional; `create()` returns the interface type, `new` is blocked by the private ctor.\nexport class AgentFactory {\n private constructor() {}\n static create(common: Partial<AgentOptions>): AgentFactory {\n return createAgentFactory(common);\n }\n}\n","/**\n * Decide whether a tool call proceeds, and say WHY — as a typed signal rather than a tool result.\n *\n * When a veto is delivered as an ordinary tool result, the MODEL reads it as output: it sees a\n * string, concludes the tool failed for some reason, and retries or works around it. A denial, an\n * error, and a tool that legitimately returned the word \"denied\" become indistinguishable to\n * everything downstream — including the surface that should be telling the user what happened.\n *\n * ## What is generic, and what is not\n *\n * The RULE is a precedence: an explicit per-tool decision outranks the mode, a convenience mode does\n * not overturn an explicit refusal, and anything undecided falls to the mode. The VOCABULARY is not\n * — which tools exist belongs to the product and arrives as data. Nothing here names one.\n *\n * Deliberately separate from the blast-radius policy: that one answers \"what does this action\n * reach\", this one answers \"who said yes\". Keeping them apart is what lets a product gate on reach\n * without re-implementing the mode ladder, and compose both where it needs to.\n *\n * @public\n */\n\n/** What the operator chose for everything not decided per tool. @public */\nexport type ApprovalMode = \"ask\" | \"never-ask\" | \"refuse-all\";\n\n/**\n * The three answers a policy can give: proceed, put the call in front of a human, or stop it.\n *\n * `ask` is not a softer `deny`. A surface with no way to reach a human must treat it as a refusal,\n * because treating it as permission is how an unattended run approves everything it was meant to\n * pause on.\n *\n * @public\n */\nexport type ApprovalOutcome = \"allow\" | \"ask\" | \"deny\";\n\n/**\n * Which rule produced the outcome.\n *\n * The `explicitly-` pair means a per-tool list decided it; the `mode-` triple means no list named\n * the tool and the operator's mode decided instead. Worth rendering alongside the outcome: \"you\n * denied this tool\" and \"your mode refuses everything\" send the operator to different settings.\n *\n * @public\n */\nexport type ApprovalReason =\n | \"explicitly-allowed\"\n | \"explicitly-denied\"\n | \"mode-ask\"\n | \"mode-never-ask\"\n | \"mode-refuse-all\";\n\n/**\n * One tool call to decide on, plus the operator's configuration.\n *\n * `tool` is matched against `denied` and `allowed` by exact string equality — there is no pattern\n * or prefix rule. Both lists default to empty, so with neither supplied every call is decided by\n * `mode` alone.\n *\n * @public\n */\nexport interface ApprovalInput {\n readonly tool: string;\n readonly mode: ApprovalMode;\n /** Tools the operator allowed once and for all. */\n readonly allowed?: readonly string[];\n /** Tools the operator refused. Outranks `allowed` and every mode. */\n readonly denied?: readonly string[];\n}\n\n/**\n * The answer, the rule that produced it, and the tool it was about.\n *\n * @public\n */\nexport interface ApprovalDecision {\n readonly outcome: ApprovalOutcome;\n readonly reason: ApprovalReason;\n /** The tool the decision was about, so a surface names it without re-deriving it. */\n readonly tool: string;\n}\n\nconst BY_MODE: Readonly<\n Record<ApprovalMode, { outcome: ApprovalOutcome; reason: ApprovalReason }>\n> = {\n ask: { outcome: \"ask\", reason: \"mode-ask\" },\n \"never-ask\": { outcome: \"allow\", reason: \"mode-never-ask\" },\n \"refuse-all\": { outcome: \"deny\", reason: \"mode-refuse-all\" },\n};\n\n/**\n * Decide one tool call against the operator's lists and mode.\n *\n * The precedence is fixed and each step short-circuits: `denied` is consulted first, then\n * `allowed`, then `mode`. A tool named in BOTH lists is therefore denied — a contradictory config\n * is read restrictively, because the usual cause is an allow-entry that outlived the denial meant\n * to replace it.\n *\n * This answers only who said yes. What the call REACHES is a separate question with a separate\n * policy — `evaluateBlastRadius` — and neither consults the other, so a product that wants both\n * gates calls both and combines the outcomes itself.\n *\n * @returns the outcome, why it was reached, and the tool it was about.\n * @public\n */\nexport function decideApproval(input: ApprovalInput): ApprovalDecision {\n const { tool } = input;\n\n // Denial first, and it outranks everything. A contradictory config — a tool in both lists — is a\n // product bug, and the safe reading is the restrictive one: silently taking the permissive side is\n // how a stale allow-entry outlives the denial that was meant to replace it.\n if ((input.denied ?? []).includes(tool)) {\n return { outcome: \"deny\", reason: \"explicitly-denied\", tool };\n }\n if ((input.allowed ?? []).includes(tool)) {\n return { outcome: \"allow\", reason: \"explicitly-allowed\", tool };\n }\n\n const fromMode = BY_MODE[input.mode];\n return { outcome: fromMode.outcome, reason: fromMode.reason, tool };\n}\n","/**\n * Decide an action by what it REACHES and whether it can be undone — not by its name.\n *\n * A sandbox answers \"which files may this process touch\", and that is a different question from the\n * one that decides whether an action is safe. A tool that drops a production database touches no\n * file the sandbox cares about; a tool that lists pods reaches an entire cluster while writing\n * nothing. Confinement covers the disk, not the reach.\n *\n * With nothing better available, every product gates on the tool's NAME: an allowlist of strings\n * that says nothing about what the tool does, drifts the moment one is renamed, and cannot be\n * reasoned about by anyone who did not write it. A guard each product re-implements is a guard some\n * product forgets.\n *\n * ## What is generic here, and what is not\n *\n * The RULE is: an action declares the scope it reaches and whether it is reversible, and a policy\n * decides from those two facts plus what the operator granted. The VOCABULARY is not — which scopes\n * exist (\"cluster:prod\", \"billing-account\", \"the laptop\") belongs to the product and arrives as\n * data. Nothing in this module names a scope, the same way the security floor names no sandbox mode\n * and the trust posture names no capability.\n *\n * ## Why the reason is part of the answer\n *\n * \"The sandbox stopped this\" and \"you never granted reach to that scope\" are different facts with\n * different fixes, and an operator told the wrong one widens the wrong thing. So a decision carries\n * WHY — the same reason a trust posture reports its `source` and a wiring record distinguishes\n * withheld-by-trust from never-configured.\n *\n * @public\n */\n\n/** What an action reaches, and whether it can be taken back. @public */\nexport interface DeclaredAction {\n /**\n * The product's name for what this action reaches. An empty string is treated as UNDECLARED and\n * refused: a tool that forgot to declare is not a tool that reaches nothing.\n */\n readonly scope: string;\n /**\n * Whether the action can be undone. Reversible actions inside a granted scope proceed;\n * irreversible ones ask, because granting reach is not granting destruction.\n */\n readonly reversible: boolean;\n}\n\n/**\n * The action to decide on, plus what the operator granted.\n *\n * `granted` is matched against `action.scope` by exact string equality: there is no prefix or\n * wildcard rule, so granting `cluster:prod` does not grant `cluster:prod:kube-system`. A product\n * that wants hierarchical scopes expands them itself before calling.\n *\n * `irreversibleAllowed` defaults to empty, so an irreversible action inside a granted scope asks\n * for approval unless its scope was pre-approved for destruction as well.\n *\n * @public\n */\nexport interface BlastRadiusInput {\n readonly action: DeclaredAction;\n /** Scopes the operator granted reach to. Empty grants nothing — never everything. */\n readonly granted: readonly string[];\n /** Scopes where the operator pre-approved irreversible actions, so an unattended run can work. */\n readonly irreversibleAllowed?: readonly string[];\n}\n\n/**\n * What the policy decided.\n *\n * `require-approval` means a human has to say yes before the action runs; a caller with no way to\n * ask must treat it as a refusal. `refuse` is not appealable through this policy at all — the\n * operator has to grant the scope first, which is deliberately a configuration change rather than\n * a prompt.\n *\n * @public\n */\nexport type BlastRadiusOutcome = \"allow\" | \"require-approval\" | \"refuse\";\n\n/** Why the decision came out that way. Rendered to the operator and read by an audit. @public */\nexport type BlastRadiusReason =\n | \"within-granted-scope\"\n | \"irreversible\"\n | \"scope-not-granted\"\n | \"scope-undeclared\";\n\n/**\n * The outcome, the rule that produced it, and the scope it was decided about.\n *\n * `scope` echoes what the action declared, so it is the empty string when the reason is\n * `scope-undeclared` — the decision names what it saw rather than substituting a placeholder.\n *\n * @public\n */\nexport interface BlastRadiusDecision {\n readonly outcome: BlastRadiusOutcome;\n readonly reason: BlastRadiusReason;\n /** The scope the decision was made about, so a surface can name it without re-deriving it. */\n readonly scope: string;\n}\n\n/**\n * Decide one declared action against the scopes the operator granted.\n *\n * Four checks, in this order, each short-circuiting: an empty `scope` is refused as undeclared\n * before any comparison happens; a scope absent from `granted` is refused; an irreversible action\n * whose scope is not in `irreversibleAllowed` escalates to approval; anything left is allowed.\n *\n * Refusal outranking escalation is a decision, not an accident. Asking a human to approve a scope\n * the operator never granted trains them to approve by reflex, which is how an approval prompt\n * stops being a control.\n *\n * This decides reach only. Whether the operator permitted the tool at all is `decideApproval`, and\n * the two are independent.\n *\n * @returns the outcome with the reason and the scope it was decided on.\n * @public\n */\nexport function evaluateBlastRadius(input: BlastRadiusInput): BlastRadiusDecision {\n const { scope, reversible } = input.action;\n\n // Undeclared first: a tool that forgot to declare must not fall through to a scope comparison\n // against `\"\"`, which any product using an empty-string scope would accidentally satisfy.\n if (scope.length === 0) {\n return { outcome: \"refuse\", reason: \"scope-undeclared\", scope };\n }\n\n // Refusal outranks approval, deliberately. Asking a human to approve something the operator never\n // granted reach for teaches them to approve by reflex, which is how an approval prompt stops\n // being a control.\n if (!input.granted.includes(scope)) {\n return { outcome: \"refuse\", reason: \"scope-not-granted\", scope };\n }\n\n if (!reversible && !(input.irreversibleAllowed ?? []).includes(scope)) {\n return { outcome: \"require-approval\", reason: \"irreversible\", scope };\n }\n\n return { outcome: \"allow\", reason: \"within-granted-scope\", scope };\n}\n","/**\n * UTC-aligned calendar window helpers (ADR D382).\n *\n * - `1h` — relative (now - 1 hour).\n * - `1d` — UTC midnight (current UTC day).\n * - `1w` — UTC monday 00:00:00 (current UTC week, Monday is week start).\n * - `30d` — relative 30 days.\n * - `365d` — relative 365 days.\n *\n * `1d` and `1w` are calendar-aligned because users expect \"1 USD per day\"\n * = \"since midnight UTC\", not a rolling 24h.\n * `30d`/`365d` are relative because nobody expects \"since the 1st\".\n *\n * @internal\n */\n\nimport type { BudgetWindow } from \"../../types/budget.js\";\n\nexport function startOfDayUtc(now: Date = new Date()): Date {\n return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), now.getUTCDate()));\n}\n\nexport function startOfWeekUtc(now: Date = new Date()): Date {\n // ISO 8601 week starts on Monday. getUTCDay() returns 0 (Sun) .. 6 (Sat).\n const dayOfWeek = now.getUTCDay();\n const daysSinceMonday = (dayOfWeek + 6) % 7; // Mon=0, Sun=6\n const start = startOfDayUtc(now);\n start.setUTCDate(start.getUTCDate() - daysSinceMonday);\n return start;\n}\n\nconst MS_PER_HOUR = 60 * 60 * 1000;\nconst MS_PER_DAY = 24 * MS_PER_HOUR;\n\n/** Returns the inclusive start timestamp (ms) for the given window relative to `now`. */\nexport function windowStartMs(window: BudgetWindow, now: Date = new Date()): number {\n switch (window) {\n case \"1h\":\n return now.getTime() - MS_PER_HOUR;\n case \"1d\":\n return startOfDayUtc(now).getTime();\n case \"1w\":\n return startOfWeekUtc(now).getTime();\n case \"30d\":\n return now.getTime() - 30 * MS_PER_DAY;\n case \"365d\":\n return now.getTime() - 365 * MS_PER_DAY;\n default: {\n const _exhaustive: never = window;\n throw new Error(`unreachable window: ${_exhaustive as string}`);\n }\n }\n}\n","/**\n * In-process Budget ledger (ADR D385).\n *\n * Singleton mutex-protected. Stores per-budget ChargeLog[] arrays;\n * `spentIn(window)` filters by timestamp.\n *\n * EC-6: GC eviction runs INSIDE the same mutex as charge — no race.\n * EC-9: charge() is called inside the same critical section as preflight\n * check by Budget enforcement.\n *\n * Persistence cross-restart: deferred to v0.2 (JsonFile pattern).\n *\n * @internal\n */\n\nimport type { BudgetWindow } from \"../../types/budget.js\";\nimport { withCwdMutex } from \"../persistence/cwd-mutex.js\";\nimport { windowStartMs } from \"./calendar-window.js\";\n\ninterface ChargeLog {\n timestamp: number;\n amountUsd: number;\n}\n\nconst MS_PER_YEAR = 365 * 24 * 60 * 60 * 1000;\nconst GC_INTERVAL_MS = 5 * 60 * 1000; // 5 minutes\nconst GC_LOGS_THRESHOLD = 10_000;\n\ninterface LedgerState {\n readonly logs: Map<string, ChargeLog[]>;\n lastGcAt: number;\n}\n\nlet state: LedgerState = {\n logs: new Map(),\n lastGcAt: Date.now(),\n};\n\nconst MUTEX_KEY = \"budget-ledger\";\n\nfunction shouldGc(now: number): boolean {\n if (now - state.lastGcAt < GC_INTERVAL_MS) return false;\n let totalLogs = 0;\n for (const arr of state.logs.values()) totalLogs += arr.length;\n return totalLogs > GC_LOGS_THRESHOLD;\n}\n\nfunction gcOlderThanOneYear(now: number): void {\n const cutoff = now - MS_PER_YEAR;\n for (const [name, arr] of state.logs.entries()) {\n const kept = arr.filter((l) => l.timestamp >= cutoff);\n if (kept.length === 0) state.logs.delete(name);\n else state.logs.set(name, kept);\n }\n state.lastGcAt = now;\n}\n\n/** Charge a budget. Idempotent across concurrent calls via withCwdMutex. */\nexport async function charge(name: string, amountUsd: number): Promise<void> {\n if (amountUsd <= 0) return;\n await withCwdMutex(MUTEX_KEY, async () => {\n const now = Date.now();\n const list = state.logs.get(name) ?? [];\n list.push({ timestamp: now, amountUsd });\n state.logs.set(name, list);\n if (shouldGc(now)) gcOlderThanOneYear(now);\n });\n}\n\n/** Return total spend in the given window for `name`. Snapshot read (no mutex needed). */\nexport function spentIn(name: string, window: BudgetWindow, now: Date = new Date()): number {\n const arr = state.logs.get(name);\n if (arr === undefined) return 0;\n const sinceMs = windowStartMs(window, now);\n let total = 0;\n for (const log of arr) {\n if (log.timestamp >= sinceMs) total += log.amountUsd;\n }\n return total;\n}\n\n/** Diagnostic — total logs across all budgets. */\nexport function __getLogCountForTests(name?: string): number {\n if (name !== undefined) return state.logs.get(name)?.length ?? 0;\n let total = 0;\n for (const arr of state.logs.values()) total += arr.length;\n return total;\n}\n\nexport function __resetLedgerForTests(): void {\n state = { logs: new Map(), lastGcAt: Date.now() };\n}\n\n/** Force GC manually (tests only). */\nexport async function __evictNowForTests(): Promise<void> {\n await withCwdMutex(MUTEX_KEY, async () => {\n gcOlderThanOneYear(Date.now());\n });\n}\n\n/** Force-insert a log at a specific timestamp (tests only). */\nexport function __injectLogForTests(name: string, timestamp: number, amountUsd: number): void {\n const list = state.logs.get(name) ?? [];\n list.push({ timestamp, amountUsd });\n state.logs.set(name, list);\n}\n","/**\n * Internal Budget registry — keeps live `BudgetOptions` per name.\n * Singleton; no persistence (D385).\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport type {\n BudgetHandle,\n BudgetMode,\n BudgetOptions,\n BudgetSnapshot,\n BudgetWindow,\n} from \"../../types/budget.js\";\nimport { spentIn } from \"./ledger.js\";\n\nconst NAME_GRAMMAR = /^[a-z0-9][a-z0-9_-]*$/;\n\nconst registry = new Map<string, BudgetOptions>();\n\nexport function __resetRegistryForTests(): void {\n registry.clear();\n}\n\nexport function validateBudgetName(name: string): void {\n if (typeof name !== \"string\" || name.length === 0) {\n throw new ConfigurationError(\"Budget name must be a non-empty string\", {\n code: \"invalid_budget_name\",\n });\n }\n if (!NAME_GRAMMAR.test(name)) {\n throw new ConfigurationError(\n `Budget name \"${name}\" must match ^[a-z0-9][a-z0-9_-]*$ (lowercase + dash/underscore, start alphanumeric)`,\n { code: \"invalid_budget_name\" },\n );\n }\n}\n\n/**\n * Refuse a `BudgetScope` this version does not implement.\n *\n * `BudgetScope` declares `\"agent\" | \"call\" | \"process\"` and `scope` is REQUIRED, so every caller must\n * pick from a union two-thirds of which is unbuilt. Measured 2026-09-02: nothing outside this file\n * reads `scope` at all — `buildHandle` copies it onto the handle and the tracker never consults it —\n * so `scope: \"agent\"` was ACCEPTED and silently ignored. A caller asking for per-agent accounting got\n * process-wide accounting and no signal of any kind.\n *\n * That is the failure `rules/error-handling.md` § 2 exists to prevent, and it is worse than the\n * unbuilt feature: a limit believed to be per-agent, applied globally, is a cost control that reports\n * the wrong number. Refusing is honest; narrowing the union to `\"process\"` would be honest too and is\n * a breaking change to a published type, so it belongs to a major rather than to this fix.\n *\n * @internal\n */\nfunction assertImplementedScope(scope: BudgetOptions[\"scope\"]): void {\n if (scope === \"process\") return;\n throw new ConfigurationError(\n `Budget scope \"${scope}\" is declared but not implemented — only \"process\" is honoured. ` +\n \"A budget created with it would have been accounted process-wide with no warning.\",\n { code: \"unimplemented_budget_scope\" },\n );\n}\n\nexport function createBudget(opts: BudgetOptions): BudgetHandle {\n // EC-7: name validation\n validateBudgetName(opts.name);\n assertImplementedScope(opts.scope);\n if (registry.has(opts.name)) {\n // EC-16: duplicate throws (vs Task.submit idempotent return)\n throw new ConfigurationError(`Budget \"${opts.name}\" already exists`, {\n code: \"invalid_budget_name\",\n });\n }\n registry.set(opts.name, opts);\n return buildHandle(opts);\n}\n\nexport function getBudget(name: string): BudgetHandle | undefined {\n const opts = registry.get(name);\n if (opts === undefined) return undefined;\n return buildHandle(opts);\n}\n\nexport function listBudgets(): readonly BudgetHandle[] {\n return [...registry.values()].map(buildHandle);\n}\n\nexport function deleteBudget(name: string): boolean {\n return registry.delete(name);\n}\n\nexport function snapshotAll(): readonly BudgetSnapshot[] {\n const result: BudgetSnapshot[] = [];\n for (const opts of registry.values()) {\n for (const lim of opts.limits) {\n const spent = spentIn(opts.name, lim.window);\n result.push({\n name: opts.name,\n window: lim.window,\n spentUsd: spent,\n limitUsd: lim.limitUsd,\n ratio: lim.limitUsd > 0 ? spent / lim.limitUsd : 0,\n });\n }\n }\n return result;\n}\n\nexport function getBudgetOptionsRaw(name: string): BudgetOptions | undefined {\n return registry.get(name);\n}\n\nexport function defaultMode(opts: BudgetOptions): BudgetMode {\n return opts.mode ?? \"warn\";\n}\n\nfunction buildHandle(opts: BudgetOptions): BudgetHandle {\n return {\n name: opts.name,\n mode: defaultMode(opts),\n scope: opts.scope,\n limits: opts.limits,\n spentIn: (window: BudgetWindow) => spentIn(opts.name, window),\n remainingIn: (window: BudgetWindow) => {\n const lim = opts.limits.find((l) => l.window === window);\n if (lim === undefined) return Number.POSITIVE_INFINITY;\n return Math.max(0, lim.limitUsd - spentIn(opts.name, window));\n },\n };\n}\n","/**\n * Budget enforcement (ADRs D383, D386, EC-7/8/9).\n *\n * - `preflightCheck(name, estimatedUsd)` — in `block` mode, throw\n * `BudgetExceededError` before the LLM call if any limit would be\n * exceeded (EC-9 — the caller invokes it inside the mutex section).\n * - `chargeAndCheckThresholds(name, actualUsd)` — apply the charge to the\n * ledger + invoke onThreshold/onExceed callbacks isolated in\n * try/catch (EC-8).\n *\n * @internal\n */\n\nimport { BudgetExceededError } from \"../../errors.js\";\nimport type { BudgetMode, BudgetOptions } from \"../../types/budget.js\";\nimport { diag } from \"../diagnostics.js\";\nimport { charge, spentIn } from \"./ledger.js\";\nimport { defaultMode, getBudgetOptionsRaw } from \"./registry.js\";\n\nconst THRESHOLDS = [0.8, 0.95] as const;\ntype Threshold = (typeof THRESHOLDS)[number];\n\n/**\n * Throws BudgetExceededError if `mode === \"block\"` and any limit\n * would be exceeded. No-op for audit/warn modes (post-charge checks\n * handle those).\n *\n * Caller invokes this BEFORE the LLM call.\n */\nexport function preflightCheck(name: string, estimatedUsd: number): void {\n const opts = getBudgetOptionsRaw(name);\n if (opts === undefined) return; // EC-20: budget deleted; charge becomes no-op\n if (defaultMode(opts) !== \"block\") return;\n for (const lim of opts.limits) {\n const currentSpent = spentIn(opts.name, lim.window);\n if (currentSpent + estimatedUsd > lim.limitUsd) {\n throw new BudgetExceededError({\n budgetName: opts.name,\n window: lim.window,\n spentUsd: currentSpent + estimatedUsd,\n limitUsd: lim.limitUsd,\n mode: \"block\",\n });\n }\n }\n}\n\n/**\n * Charge the budget + dispatch threshold/exceed callbacks (EC-8 isolated).\n *\n * - In `audit` mode: charge only, no callbacks.\n * - In `warn` mode: charge + onThreshold (80/95) + onExceed (100). No throw.\n * - In `block` mode: charge + onThreshold + onExceed. No throw post-call\n * (preflightCheck already prevented exceed for the upcoming call;\n * this protects against simultaneous-call races where multiple sends\n * each pass preflight independently — last one to charge may still\n * tip a limit. We document the case rather than retroactively throw).\n */\nexport async function chargeAndCheckThresholds(name: string, actualUsd: number): Promise<void> {\n const opts = getBudgetOptionsRaw(name);\n if (opts === undefined) {\n // EC-20: budget deleted during in-flight call. Charge is silent no-op.\n diag(\n `[budget] charge for deleted budget \"${name}\" is a no-op (was the budget removed during in-flight send?)\\n`,\n );\n return;\n }\n const mode = defaultMode(opts);\n\n await charge(opts.name, actualUsd);\n\n if (mode === \"audit\") return;\n await dispatchCallbacksFor(opts, mode);\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: 3-mode × 3-threshold dispatch table inherently branchy; pulling out helpers loses local context.\nasync function dispatchCallbacksFor(opts: BudgetOptions, mode: BudgetMode): Promise<void> {\n for (const lim of opts.limits) {\n const spent = spentIn(opts.name, lim.window);\n if (lim.limitUsd <= 0) {\n if (spent > 0) await dispatchExceed(opts, lim.window, spent, lim.limitUsd, mode);\n continue;\n }\n const ratio = spent / lim.limitUsd;\n if (ratio >= 1) {\n await dispatchExceed(opts, lim.window, spent, lim.limitUsd, mode);\n } else {\n // Iterate descending so the HIGHEST matched threshold fires (0.95 not 0.8)\n for (const t of [...THRESHOLDS].reverse() as Threshold[]) {\n if (ratio >= t) {\n await dispatchThreshold(opts, lim.window, spent, lim.limitUsd, t);\n break;\n }\n }\n }\n }\n}\n\nasync function dispatchThreshold(\n opts: BudgetOptions,\n window: BudgetOptions[\"limits\"][number][\"window\"],\n spentUsd: number,\n limitUsd: number,\n threshold: Threshold,\n): Promise<void> {\n if (opts.onThreshold === undefined) return;\n try {\n await opts.onThreshold({\n budgetName: opts.name,\n window,\n threshold,\n spentUsd,\n limitUsd,\n });\n } catch (err) {\n // EC-8: callback throw isolated\n const msg = err instanceof Error ? err.message : String(err);\n diag(`[budget] onThreshold callback threw: ${msg}\\n`);\n }\n}\n\nasync function dispatchExceed(\n opts: BudgetOptions,\n window: BudgetOptions[\"limits\"][number][\"window\"],\n spentUsd: number,\n limitUsd: number,\n mode: BudgetMode,\n): Promise<void> {\n if (opts.onExceed === undefined) {\n if (mode === \"warn\") {\n diag(\n `[budget] \"${opts.name}\" exceeded ${window} limit: $${spentUsd.toFixed(4)} > $${limitUsd.toFixed(4)}\\n`,\n );\n }\n return;\n }\n try {\n await opts.onExceed({\n budgetName: opts.name,\n window,\n spentUsd,\n limitUsd,\n mode,\n });\n } catch (err) {\n const msg = err instanceof Error ? err.message : String(err);\n diag(`[budget] onExceed callback threw: ${msg}\\n`);\n }\n}\n","/**\n * normalizeUsage — convert provider-shaped raw `usage` object to\n * canonical `TokenUsage`. Ports Hermes Agent's `normalize_usage`\n * (reference/peer-agent/agent/usage_pricing.py:672-742).\n *\n * Handles 3 API shapes:\n * - Anthropic Messages: 4 explicit buckets (input/output/cache_read/cache_creation).\n * - OpenAI Chat Completions: prompt_tokens INCLUDES cache; subtract cached_tokens.\n * - OpenAI Responses (Codex): input_tokens INCLUDES cache; same subtraction.\n *\n * Edge cases:\n * - a peer#10266 — OpenAI-compat proxies (OpenRouter, a peer vendor AI Gateway,\n * a peer) routing Claude expose Anthropic-style top-level fields\n * (cache_read_input_tokens / cache_creation_input_tokens). Both\n * locations are checked with top-level fallback.\n * - Null/undefined fields → 0 via `int()` coerce.\n * - String token counts → parsed via int.\n * - Negative values → clamped to 0 (defensive against proxy bugs).\n *\n * @internal\n */\n\nimport type { TokenUsage } from \"../../types/usage.js\";\n\nexport type ApiMode = \"anthropic_messages\" | \"openai_chat_completions\" | \"openai_responses\";\n\nfunction int(v: unknown): number {\n if (typeof v === \"number\") return Number.isFinite(v) ? Math.max(0, Math.trunc(v)) : 0;\n if (typeof v === \"string\") {\n const n = Number.parseInt(v, 10);\n return Number.isFinite(n) ? Math.max(0, n) : 0;\n }\n return 0;\n}\n\nfunction buildTotal(buckets: {\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens: number;\n cacheWriteTokens: number;\n}): number {\n // total = visible input + cache buckets + output (reasoning counted via output)\n return (\n buckets.inputTokens + buckets.outputTokens + buckets.cacheReadTokens + buckets.cacheWriteTokens\n );\n}\n\nfunction omitUndefined(usage: {\n inputTokens: number;\n outputTokens: number;\n cacheReadTokens: number;\n cacheWriteTokens: number;\n reasoningTokens: number;\n totalTokens: number;\n}): TokenUsage {\n return {\n inputTokens: usage.inputTokens,\n outputTokens: usage.outputTokens,\n ...(usage.cacheReadTokens > 0 ? { cacheReadTokens: usage.cacheReadTokens } : {}),\n ...(usage.cacheWriteTokens > 0 ? { cacheWriteTokens: usage.cacheWriteTokens } : {}),\n ...(usage.reasoningTokens > 0 ? { reasoningTokens: usage.reasoningTokens } : {}),\n totalTokens: usage.totalTokens,\n };\n}\n\n/**\n * Guess which usage shape a provider reports, from its name alone.\n *\n * Matching is case-insensitive and exact — `\"anthropic\"`, `\"claude\"` and `\"bedrock_anthropic\"`\n * give `\"anthropic_messages\"`; `\"openai-codex\"` and `\"codex\"` give `\"openai_responses\"`. Every\n * other name, including ones this SDK has never seen, falls through to\n * `\"openai_chat_completions\"`. There is no unknown result, so a wrong guess is silent: it is\n * read as a Chat Completions payload, whose fields are absent, and the tokens come back as 0.\n *\n * The default is right for the OpenAI-compatible majority (openai, openrouter, deepseek, and the\n * compat endpoints of google, ollama and lmstudio). When it is not, pass `apiMode` to\n * `normalizeUsage` explicitly instead of relying on the name.\n */\nexport function inferApiMode(provider: string): ApiMode {\n const p = provider.toLowerCase();\n if (p === \"anthropic\" || p === \"claude\" || p === \"bedrock_anthropic\") {\n return \"anthropic_messages\";\n }\n if (p === \"openai-codex\" || p === \"codex\") return \"openai_responses\";\n // openai, openrouter, deepseek, google (compat), ollama (compat), lmstudio (compat), etc\n return \"openai_chat_completions\";\n}\n\ninterface RawRecord {\n [k: string]: unknown;\n}\n\n/**\n * Convert a provider's raw `usage` object into the SDK's canonical `TokenUsage`.\n *\n * Never throws and never reports failure. `null`, `undefined` and any non-object argument return\n * all-zero usage, which is indistinguishable from a real response that used no tokens — so this\n * is not the place to detect a malformed payload.\n *\n * `opts.apiMode` selects the reader; when omitted it is derived from `opts.provider` via\n * `inferApiMode`, whose fallback is Chat Completions. Pass it explicitly for any provider whose\n * name does not identify its wire shape.\n *\n * The shapes differ in one way that matters: Anthropic reports cache tokens in buckets separate\n * from `input_tokens`, while both OpenAI shapes report a prompt total that already includes\n * them. For the OpenAI readers the cache buckets are subtracted, so `inputTokens` is always the\n * uncached portion and `inputTokens + cacheReadTokens + cacheWriteTokens` reconstructs the\n * provider's prompt total. The subtraction is floored at 0, so a payload whose cache counts\n * exceed its prompt total yields 0 rather than a negative.\n *\n * Every field is coerced: numbers are truncated toward zero, numeric strings are parsed, negative\n * and non-finite values become 0, and anything else becomes 0.\n *\n * `totalTokens` is computed here as input + output + both cache buckets; a `total_tokens` the\n * provider sent is ignored. Reasoning tokens are reported separately but are NOT added again —\n * providers already count them inside output. `cacheReadTokens`, `cacheWriteTokens` and\n * `reasoningTokens` are omitted from the result when they are 0, so absent means zero, not\n * unknown.\n *\n * Chat Completions also accepts Anthropic-style top-level `cache_read_input_tokens` /\n * `cache_creation_input_tokens`, which OpenAI-compatible proxies emit when they route Claude.\n * The nested `prompt_tokens_details` values win; the top-level fields are consulted only when\n * those are 0 or missing.\n */\nexport function normalizeUsage(\n rawUsage: unknown,\n opts: { provider: string; apiMode?: ApiMode },\n): TokenUsage {\n if (rawUsage === null || rawUsage === undefined) {\n return { inputTokens: 0, outputTokens: 0, totalTokens: 0 };\n }\n if (typeof rawUsage !== \"object\") {\n return { inputTokens: 0, outputTokens: 0, totalTokens: 0 };\n }\n const raw = rawUsage as RawRecord;\n const mode = opts.apiMode ?? inferApiMode(opts.provider);\n\n if (mode === \"anthropic_messages\") return normalizeAnthropic(raw);\n if (mode === \"openai_responses\") return normalizeOpenAIResponses(raw);\n return normalizeOpenAIChat(raw);\n}\n\nfunction normalizeAnthropic(raw: RawRecord): TokenUsage {\n const inputTokens = int(raw.input_tokens);\n const outputTokens = int(raw.output_tokens);\n const cacheReadTokens = int(raw.cache_read_input_tokens);\n const cacheWriteTokens = int(raw.cache_creation_input_tokens);\n const usage = {\n inputTokens,\n outputTokens,\n cacheReadTokens,\n cacheWriteTokens,\n reasoningTokens: 0,\n totalTokens: buildTotal({ inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens }),\n };\n return omitUndefined(usage);\n}\n\nfunction normalizeOpenAIResponses(raw: RawRecord): TokenUsage {\n const inputTotal = int(raw.input_tokens);\n const outputTokens = int(raw.output_tokens);\n const inputDetails = (raw.input_tokens_details as RawRecord | undefined) ?? {};\n const outputDetails = (raw.output_tokens_details as RawRecord | undefined) ?? {};\n const cacheReadTokens = int(inputDetails.cached_tokens);\n const cacheWriteTokens = int(inputDetails.cache_creation_tokens);\n const reasoningTokens = int(outputDetails.reasoning_tokens);\n const inputTokens = Math.max(0, inputTotal - cacheReadTokens - cacheWriteTokens);\n const usage = {\n inputTokens,\n outputTokens,\n cacheReadTokens,\n cacheWriteTokens,\n reasoningTokens,\n totalTokens: buildTotal({ inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens }),\n };\n return omitUndefined(usage);\n}\n\nfunction normalizeOpenAIChat(raw: RawRecord): TokenUsage {\n const promptTotal = int(raw.prompt_tokens);\n const outputTokens = int(raw.completion_tokens);\n const promptDetails = (raw.prompt_tokens_details as RawRecord | undefined) ?? {};\n const completionDetails = (raw.completion_tokens_details as RawRecord | undefined) ?? {};\n\n // a peer#10266 fallback — proxies expose Anthropic-style top-level fields when routing Claude\n const cacheReadTokens = int(promptDetails.cached_tokens) || int(raw.cache_read_input_tokens);\n const cacheWriteTokens =\n int(promptDetails.cache_write_tokens) || int(raw.cache_creation_input_tokens);\n\n const reasoningTokens = int(completionDetails.reasoning_tokens);\n const inputTokens = Math.max(0, promptTotal - cacheReadTokens - cacheWriteTokens);\n const usage = {\n inputTokens,\n outputTokens,\n cacheReadTokens,\n cacheWriteTokens,\n reasoningTokens,\n totalTokens: buildTotal({ inputTokens, outputTokens, cacheReadTokens, cacheWriteTokens }),\n };\n return omitUndefined(usage);\n}\n","/**\n * `Budget` — token cost enforcement primitive (Adoption Roadmap #1\n * post-Tasks, ADRs D375-D388).\n *\n * Static facade delegating to the in-process registry + ledger.\n * 3 modes: `audit` (log-only), `warn` (callbacks + log), `block`\n * (preflight throw before LLM call).\n *\n * @public\n *\n * @deprecated since SDK 2.0 (iter 18+) — import this facade from\n * `@theokit/sdk-budget` instead. The sources backing this facade have\n * been physically extracted to `@theokit/sdk-budget/internal/` per\n * ADR-008. The sdk-core copies are retained for the v1.x sync API\n * contract; consumers MUST migrate before sdk-core v3.0.\n *\n * Migration:\n *\n * ```ts\n * // Before (sdk-core, deprecated):\n * import { Budget, computeCost } from \"@theokit/sdk\";\n *\n * // After (sdk-budget, authoritative):\n * import {\n * chargeAndCheckThresholds,\n * createBudget,\n * computeUsdCost, // replaces computeCost\n * createUsdBudgetTracker,\n * } from \"@theokit/sdk-budget\";\n * ```\n */\n\nimport { computeCost } from \"./internal/budget/compute-cost.js\";\nimport { chargeAndCheckThresholds, preflightCheck } from \"./internal/budget/enforcement.js\";\nimport { inferApiMode, normalizeUsage } from \"./internal/budget/normalize-usage.js\";\nimport { getPricingEntry } from \"./internal/budget/pricing-registry.js\";\nimport {\n createBudget,\n deleteBudget,\n getBudget,\n listBudgets,\n snapshotAll,\n} from \"./internal/budget/registry.js\";\nimport { UsageAccumulator } from \"./internal/budget/usage-accumulator.js\";\nimport type { BudgetHandle, BudgetOptions, BudgetSnapshot } from \"./types/budget.js\";\n\n// Re-exports for caller-side composition until auto-wire-up in v0.2 (T4.2 deferred).\nexport {\n chargeAndCheckThresholds,\n computeCost,\n getPricingEntry,\n inferApiMode,\n normalizeUsage,\n preflightCheck,\n UsageAccumulator,\n};\n\nexport class Budget {\n // D375 — static class with private constructor.\n private constructor() {\n throw new Error(\"Budget is static; do not instantiate\");\n }\n\n /**\n * Create a budget. `name` must match `^[a-z0-9][a-z0-9_-]*$` (EC-7).\n * Throws `ConfigurationError` if name is invalid OR already exists\n * (EC-16: duplicate surface caller bug).\n *\n * `limits` is stacked (D384) — ANY exceeded triggers enforcement.\n * Empty `limits[]` is valid: pure tracking, no thresholds/exceed\n * callbacks fire (EC-19).\n *\n * Default `mode` is `\"warn\"` (D383). For emergency stop, use\n * `mode: \"block\", limits: [{ window: \"1d\", limitUsd: 0 }]` (EC-18).\n */\n static create(options: BudgetOptions): BudgetHandle {\n return createBudget(options);\n }\n\n /** Returns the handle for an active budget, or `undefined`. */\n static get(name: string): BudgetHandle | undefined {\n return getBudget(name);\n }\n\n /** Returns all active budgets. */\n static list(): readonly BudgetHandle[] {\n return listBudgets();\n }\n\n /**\n * Deletes a budget from the registry. Returns `true` if it existed.\n * In-flight `agent.send` calls referencing the name treat the\n * subsequent charge as a silent no-op + stderr warn (EC-20).\n */\n static delete(name: string): boolean {\n return deleteBudget(name);\n }\n\n /**\n * Returns per-window spend snapshot for all active budgets. Each\n * entry has `{ name, window, spentUsd, limitUsd, ratio }`.\n */\n static snapshot(): readonly BudgetSnapshot[] {\n return snapshotAll();\n }\n}\n","/**\n * SE25 — deterministic, no-LLM guardrail processors built on the SE24\n * {@link Processor} seam. Cheap and churn-free (no provider/model deltas), so\n * they are safe to own in-core — unlike the LLM-classifier processors, which are\n * delegated (see the guardrails ADR). All are OPT-IN: add them to\n * `AgentOptions.inputProcessors` / `outputProcessors`.\n *\n * @public\n */\n\n/**\n * Approximate token count from string length. This is an ESTIMATE\n * (≈ UTF-16-code-units / 4, NOT Unicode code points, NOT an exact per-model\n * tokenizer count) — good enough for a coarse cap, and dependency-free.\n *\n * Re-exported rather than reimplemented: the ratio lives in `compaction.ts`, which is where the\n * heuristic is load-bearing. The name and the behaviour here are unchanged.\n */\nimport { CHARS_PER_TOKEN, estimateTokens } from \"./compaction.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport type { Processor, ProcessorControls } from \"./types/processors.js\";\n\nexport { CHARS_PER_TOKEN, estimateTokens };\n\n/** Options for {@link createUnicodeNormalizer}. @public */\nexport interface UnicodeNormalizerOptions {\n /** Remove C0 + C1 control chars + DEL (keeps tab / newline / carriage-return). Default `false`. */\n stripControlChars?: boolean;\n /** Collapse runs of intra-line whitespace to one space, 3+ blank lines to one, and trim. Default `false`. Uses legacy `\\s`; Unicode-only whitespace (U+00A0 NBSP, U+FEFF BOM, U+2000–U+200A) is NOT collapsed. */\n collapseWhitespace?: boolean;\n}\n\n// C0 controls (U+0000–U+001F) + DEL (U+007F) + C1 controls (U+0080–U+009F),\n// EXCLUDING tab (U+0009), line feed (U+000A), and carriage return (U+000D) so\n// line structure survives. C1 is included (matching a peer framework's Cc-category strip)\n// since C1 controls are invisible noise / prompt-injection vectors in LLM input.\n// biome-ignore lint/suspicious/noControlCharactersInRegex: intentional — this processor's whole job is to strip control characters (written with \\u escapes, no literal control char in source).\nconst CONTROL_CHARS = /[\\u0000-\\u0008\\u000B\\u000C\\u000E-\\u001F\\u007F-\\u009F]/g;\n\n/**\n * SE25 — an input processor that normalizes user text: Unicode NFC (so\n * canonically-equivalent sequences compare equal) plus optional control-char\n * stripping and whitespace collapsing. Pure + deterministic; no LLM. Mirrors\n * a peer framework's `UnicodeNormalizer`.\n *\n * @public\n */\nexport function createUnicodeNormalizer(opts: UnicodeNormalizerOptions = {}): Processor {\n const stripControlChars = opts.stripControlChars ?? false;\n const collapseWhitespace = opts.collapseWhitespace ?? false;\n return {\n id: \"unicode-normalizer\",\n processInput(ctx) {\n let s = ctx.message.normalize(\"NFC\");\n if (stripControlChars) s = s.replace(CONTROL_CHARS, \"\");\n if (collapseWhitespace) {\n s = s\n .replace(/[^\\S\\n]+/g, \" \") // runs of intra-line whitespace -> one space\n .replace(/ *\\n */g, \"\\n\") // drop spaces hugging a newline\n .replace(/\\n{3,}/g, \"\\n\\n\") // 3+ blank lines -> one blank line\n .trim();\n }\n return s;\n },\n };\n}\n\n/** Options for {@link createTokenLimiter}. @public */\nexport interface TokenLimiterOptions {\n /** Positive integer token budget (estimate — see {@link estimateTokens}). */\n limit: number;\n /** Over the limit: `\"truncate\"` (default, cut to fit) or `\"block\"` (abort with a tripwire). */\n strategy?: \"truncate\" | \"block\";\n}\n\n/**\n * SE25 — a processor that caps text to a token budget. Placed in\n * `inputProcessors` it limits the prompt; in `outputProcessors` it limits the\n * response. Uses a char-based estimate (no tokenizer dep). `truncate` cuts to\n * fit; `block` aborts (tripwire). Mirrors a peer framework's `TokenLimiterProcessor`.\n *\n * @public\n */\nexport function createTokenLimiter(opts: TokenLimiterOptions): Processor {\n if (!Number.isInteger(opts.limit) || opts.limit <= 0) {\n throw new ConfigurationError(\"createTokenLimiter: `limit` must be a positive integer.\", {\n code: \"invalid_processor_options\",\n });\n }\n const limit = opts.limit;\n const strategy = opts.strategy ?? \"truncate\";\n const cap = (text: string, controls: Pick<ProcessorControls, \"abort\">): string => {\n const estimated = estimateTokens(text);\n if (estimated <= limit) return text;\n if (strategy === \"block\") {\n controls.abort(`exceeds token limit ${limit} (~${estimated} estimated)`);\n }\n // Truncate on CODE POINTS (not UTF-16 code units) so a cut never splits a\n // surrogate pair into a lone surrogate (invalid UTF-8 → rejected by LLM APIs).\n return [...text].slice(0, limit * CHARS_PER_TOKEN).join(\"\");\n };\n return {\n id: \"token-limiter\",\n processInput: (ctx) => cap(ctx.message, ctx),\n processOutput: (ctx) => cap(ctx.text, ctx),\n };\n}\n\n/** SE36 — `TokenLimiter.create` replaces `createTokenLimiter` (ADR 0015). @public *\n * `TokenLimiter.create` returns a **`Processor`**, not a `TokenLimiter`. The class is\n * the namespace; the processor is the product.\n */\nexport class TokenLimiter {\n private constructor() {}\n static create(opts: TokenLimiterOptions): Processor {\n return createTokenLimiter(opts);\n }\n}\n/** SE36 — `UnicodeNormalizer.create` replaces `createUnicodeNormalizer` (ADR 0015). @public *\n * `UnicodeNormalizer.create` returns a **`Processor`**, not a `UnicodeNormalizer`. The\n * class is the namespace; the processor is the product.\n */\nexport class UnicodeNormalizer {\n private constructor() {}\n static create(opts: UnicodeNormalizerOptions = {}): Processor {\n return createUnicodeNormalizer(opts);\n }\n}\n","/**\n * M22 — `createSkill`: define a skill in TypeScript, without a `SKILL.md` file on disk.\n *\n * An inline skill is usable ALONGSIDE filesystem skills (`AgentOptions.skills.inline`), and points\n * an agent at code-defined capabilities without a `.theokit/skills/<name>/SKILL.md`. Like file\n * skills, its `name` + `description` surface in the `<skills>` system-prompt block; its\n * `instructions` (the body) travel on the object for the consumer (the SDK injects name+description,\n * not bodies — inline and file skills are symmetric there). Inline skills override file skills on a\n * name conflict (mirrors the subagents-loader precedent).\n */\n\nimport { ConfigurationError } from \"./errors.js\";\nimport type { Skill as SkillShape } from \"./internal/runtime/skills/discover-skills.js\";\n\n/** A code-defined skill (from {@link createSkill}) — a {@link Skill} plus its inline body. */\nexport interface InlineSkill extends SkillShape {\n /** The skill body/instructions (inline skills carry it here instead of a SKILL.md file). */\n instructions: string;\n /**\n * SE21 — supporting documents bundled with the skill (filename → content),\n * mirroring a filesystem skill's `references/` directory. Surfaced to the app\n * via `agent.skills.get(name)`; not injected into the model prompt.\n */\n references?: Record<string, string>;\n}\n\n/** Spec accepted by {@link createSkill}. */\nexport interface CreateSkillSpec {\n name: string;\n description: string;\n instructions: string;\n category?: string;\n dependencies?: string[];\n /** SE21 — supporting documents (filename → content), like a filesystem skill's `references/`. */\n references?: Record<string, string>;\n}\n\n/**\n * Build an {@link InlineSkill} from a code spec. Fails fast on an empty `name`/`description`\n * (error-handling.md). The synthetic `source` (`inline://<name>`) marks it as file-less.\n */\nfunction createSkill(spec: CreateSkillSpec): InlineSkill {\n if (!spec.name) {\n throw new ConfigurationError(\"createSkill: `name` is required.\", {\n code: \"invalid_skill_spec\",\n });\n }\n if (!spec.description) {\n throw new ConfigurationError(\"createSkill: `description` is required.\", {\n code: \"invalid_skill_spec\",\n });\n }\n return {\n name: spec.name,\n description: spec.description,\n source: `inline://${spec.name}`,\n instructions: spec.instructions,\n ...(spec.category !== undefined ? { category: spec.category } : {}),\n ...(spec.dependencies !== undefined ? { dependencies: spec.dependencies } : {}),\n ...(spec.references !== undefined ? { references: spec.references } : {}),\n };\n}\n\n/** SE36 — `Skill.create` replaces `createSkill` (ADR 0015). @public *\n * `Skill.create` returns an **`InlineSkill`**, not a `Skill`. The class is the namespace;\n * the inline skill descriptor is the product.\n */\nexport class Skill {\n private constructor() {}\n static create(spec: CreateSkillSpec): InlineSkill {\n return createSkill(spec);\n }\n}\n","/**\n * Report whether a credential resolved — never what it is.\n *\n * Every agent product grows a \"why can't I use this model?\" surface: a doctor command, a status\n * panel, a startup diagnostic. Each needs to know whether a credential resolved, and each is one\n * careless line from printing it. The line is careless precisely because it is convenient — the\n * value is right there, and whoever is debugging a routing problem wants to see it.\n *\n * So presence-only is the DEFAULT here rather than each consumer's discipline. Discipline is what\n * every product has until the day it does not, and a leaked key is not a defect anyone can withdraw.\n *\n * ## Why a fingerprint and not a prefix\n *\n * A report has to be actionable: two people asking \"is it the same key?\" need something to compare.\n * The convenient answer — the first eight characters — is still the secret, and it is enough to\n * identify a key in a breach corpus. A hash is not.\n *\n * @public\n */\n\nimport { createHash } from \"node:crypto\";\n\n/**\n * One provider's credential lookup, as the product resolved it.\n *\n * `value` is the secret itself. It is hashed and dropped inside `describeCredential` — it never\n * reaches the report, and nothing here stores it.\n *\n * @public\n */\nexport interface CredentialInput {\n /** The product's name for the provider. This module never knows one of its own. */\n readonly provider: string;\n /** The resolved secret, or `undefined`/empty when nothing resolved. */\n readonly value: string | undefined;\n /** Where it came from, in the product's vocabulary — `env`, `file`, `keychain`, `oauth`. */\n readonly source: string;\n}\n\n/**\n * A presence-only view of one credential, safe to print, log, or attach to a support bundle.\n *\n * `fingerprint` is the first eight hex characters of the SHA-256 of the trimmed secret: enough for\n * two people to agree they are holding the same key, and not a substring of it. It is absent\n * whenever `present` is false.\n *\n * @public\n */\nexport interface CredentialReport {\n readonly provider: string;\n readonly present: boolean;\n readonly source: string;\n /** Eight hex characters of a hash. Absent when no credential resolved. Never a prefix. */\n readonly fingerprint?: string;\n}\n\n/**\n * Turn a resolved credential into something you can show a user.\n *\n * The value is trimmed before the emptiness test, so `undefined`, `\"\"` and whitespace all report\n * `present: false` with no fingerprint. That matters because an environment variable that expanded\n * to nothing arrives as an empty string, and calling that \"present\" sends whoever is debugging to\n * hunt for a routing bug instead of a missing secret.\n *\n * @returns a report safe to log, render and attach to a support bundle.\n * @public\n */\nexport function describeCredential(input: CredentialInput): CredentialReport {\n // Trimmed before the emptiness test: an unset variable read through a shell expansion arrives as\n // `\"\"` or whitespace, and reporting that as present claims a working credential where there is\n // none — the same shape B-118 measured with an npm token resolving to empty.\n const secret = (input.value ?? \"\").trim();\n if (secret.length === 0) {\n return { provider: input.provider, present: false, source: input.source };\n }\n\n return {\n provider: input.provider,\n present: true,\n source: input.source,\n fingerprint: createHash(\"sha256\").update(secret).digest(\"hex\").slice(0, 8),\n };\n}\n","import { parseModelId } from \"./internal/llm/model-identifier.js\";\nimport type { Plugin } from \"./internal/plugins/types.js\";\nimport { registerBuiltins } from \"./internal/providers/builtin/index.js\";\nimport { listProviders } from \"./internal/providers/registry.js\";\nimport type { ProviderProfile } from \"./internal/providers/types.js\";\n\n/**\n * Options for {@link defineProvider}.\n *\n * @public\n */\nexport interface DefineProviderOptions {\n /** Plugin version surfaced in diagnostics. Default `\"1.0.0\"`. */\n version?: string;\n}\n\n/**\n * Canonical factory for a custom LLM provider, mirroring {@link Tool.create} and\n * {@link definePlugin} (Inviolable Rule 9 — every agentic capability ships as a\n * factory function).\n *\n * A {@link ProviderProfile} is data-only: it declares the provider name, the\n * HTTP dialect (`apiMode`), auth, base URL and fallback models. The transport\n * is selected from `apiMode` by the router, so any OpenAI-/Anthropic-compatible\n * endpoint (Groq, Together, Fireworks, a private gateway) is expressible as a\n * profile with no new code.\n *\n * Reached through {@link Provider.create}, which is the exported façade — this function\n * itself is internal. The docblock used to show `defineProvider(...)` as the call to write,\n * and it is not exported from any entry point, so following it produced\n * `TypeError: defineProvider is not a function`.\n *\n * One door rather than two, deliberately: `Provider` already owns `create`, `builtins` and\n * `forModel`, and a second exported way to build the same plugin would be a choice nobody\n * needs to make.\n *\n * Pass the result to `Agent.create({ plugins: [...] })` and route to it with\n * the `provider/model` id prefix or `providers.routes`:\n *\n * ```ts\n * const groq = Provider.create({\n * name: \"groq\",\n * apiMode: \"chat_completions\",\n * authType: \"api_key\",\n * envVars: [\"GROQ_API_KEY\"],\n * baseUrl: \"https://api.groq.com/openai/v1\",\n * fallbackModels: [\"groq/llama-3.1-8b-instant\"],\n * });\n * const agent = await Agent.create({\n * model: { id: \"groq/llama-3.1-8b-instant\" },\n * plugins: [groq],\n * });\n * ```\n *\n * @public\n */\nfunction defineProvider(profile: ProviderProfile, opts?: DefineProviderOptions): Plugin {\n return {\n name: profile.name,\n version: opts?.version ?? \"1.0.0\",\n kind: \"model-provider\",\n profile,\n };\n}\n\n/** SE36 — uniform namespace API. `Provider.create` replaces `defineProvider` (ADR 0015). @public */\nexport class Provider {\n private constructor() {}\n static create(profile: ProviderProfile, opts?: DefineProviderOptions): Plugin {\n return defineProvider(profile, opts);\n }\n\n /**\n * Every first-party builtin provider (anthropic, openai, openrouter, gemini, ollama, the ChatGPT/Codex\n * `openai-chatgpt`, …) as model-provider plugins, ready to hand to `Agent.create({ plugins })` or any\n * runtime that consumes model-provider plugins (e.g. the `theokit` agent server / `@theokit/agents`, whose\n * own model resolution does NOT share this registry). Enables a consumer to route to ANY SDK builtin —\n * including one added later in a single SDK file — with ZERO provider-specific code: just\n * `.plugins(Provider.builtins())` once, then pick a `provider/model` id. @public\n */\n static builtins(): Plugin[] {\n registerBuiltins();\n return listProviders().map((profile) => defineProvider(profile));\n }\n\n /**\n * The builtin serving `modelId`, or `undefined` when none does.\n *\n * The grammar of a model id — `provider/model` — now has **one** owner. M94: the consumer\n * redid it by hand with `modelId.slice(0, modelId.indexOf('/'))`, which on an id **without a slash** returns the\n * id minus its last character (`claude-opus-5` -> `claude-opus-`): it matches no provider and the\n * caller fell through to the default, without distinguishing that from a hit. A non-routable model was\n * indistinguishable from the happy path.\n *\n * Returns `undefined` instead of throwing: the caller decides whether absence is an error, and only they\n * know whether the model came from an explicit `--model` (an error) or from the default (normal).\n *\n * @public\n */\n static forModel(modelId: string): Plugin | undefined {\n // Delegates to `parseModelId`, the grammar's canonical owner — M94's DoD asked for\n // exactly that (\"reusing the SDK's own id parser so the grammar has ONE\n // owner\") and the first version redid `indexOf`/`slice` inline, reinventing the owner right next to it.\n //\n // Adversarial review measured the cost: 7 of 8 divergences. `lm-studio/qwen3` resolves to the\n // real `lmstudio` builtin via the parser and to NOTHING via the slice — and since the consumer now\n // throwing when there is no provider, a custom command that worked before M94 would start\n // fails. `Anthropic/...`, ` openai/...`, `llama.cpp/...` likewise. And the inverse: `openai/` (empty name) the\n // the parser rejects and the slice used to accept.\n const { provider } = parseModelId(modelId);\n if (provider === undefined) return undefined;\n return Provider.builtins().find((p) => p.name === provider);\n }\n}\n","/**\n * SE23 — `defineSkillReadTool`: an OPT-IN factory that gives the MODEL on-demand\n * access to a skill's full body + references via a `skill_read` tool.\n *\n * TheoKit discloses skills eagerly through the `<skills>` system-prompt block\n * (name + description only). This factory is the LAZY read path: the consumer\n * explicitly adds the returned {@link CustomTool} to `tools`, and when the model\n * calls it with a skill name, it gets that skill's `instructions` (+ SE21\n * `references`). The SDK NEVER auto-injects it — bring-your-own-tools stays\n * intact (sibling of `defineSubAgent` / `workflowAsTool`). See ADR 0007.\n *\n * import { Agent, createSkill, defineSkillReadTool } from \"@theokit/sdk\";\n *\n * const skills = [createSkill({ name: \"release\", description: \"…\", instructions: \"…\" })];\n * const agent = await Agent.create({\n * model: { id: \"openai/gpt-4o-mini\" },\n * skills: { inline: skills },\n * tools: [defineSkillReadTool(skills)],\n * });\n *\n * @public\n */\n\nimport { z } from \"zod\";\nimport type { InlineSkill } from \"./create-skill.js\";\nimport { ConfigurationError } from \"./errors.js\";\nimport { toJsonSchema } from \"./internal/zod-to-json-schema.js\";\nimport type { CustomTool } from \"./types/agent.js\";\n\nconst SkillReadInputSchema = z.object({\n name: z.string().min(1, \"skill_read: `name` is required.\"),\n});\n\n/**\n * Render a skill's body (+ references) into a single model-facing string.\n * `skill.name` is expected to be a short identifier-like token (no newlines /\n * Markdown headings) — the consumer controls both the names and the tool, so\n * this is a formatting assumption, not a trust boundary.\n */\nfunction renderSkill(skill: InlineSkill): string {\n const parts = [`# Skill: ${skill.name}`, \"\", skill.instructions];\n const refs = skill.references;\n if (refs !== undefined && Object.keys(refs).length > 0) {\n parts.push(\"\", \"## References\");\n for (const [file, content] of Object.entries(refs)) {\n parts.push(\"\", `### ${file}`, content);\n }\n }\n return parts.join(\"\\n\");\n}\n\n/**\n * SE23 — build an OPT-IN `skill_read` {@link CustomTool} over the given inline\n * skills. When the model calls it with `{ name }`, the handler returns that\n * skill's body + references. An UNKNOWN (but well-formed) name returns a typed\n * \"not found\" string the model can act on — NOT a throw that kills the run.\n * Malformed input (missing `name`) fails at the trust boundary via the schema.\n *\n * The consumer controls exposure by choosing which skills to pass; the SDK\n * never auto-injects this tool.\n *\n * @public\n */\nfunction defineSkillReadTool(skills: ReadonlyArray<InlineSkill>): CustomTool {\n // Fail fast on duplicate names (Rule 8): a shadowed skill would be silently\n // unreachable and the \"not found\" list would show the name twice. Names are\n // addressed by exact, case-sensitive match — the same identity the <skills>\n // block uses — so a collision is a construction-time error, not a runtime one.\n const seen = new Set<string>();\n for (const skill of skills) {\n if (seen.has(skill.name)) {\n throw new ConfigurationError(`defineSkillReadTool: duplicate skill name \"${skill.name}\".`, {\n code: \"duplicate_skill_name\",\n });\n }\n seen.add(skill.name);\n }\n return {\n name: \"skill_read\",\n description:\n \"Read a skill's full instructions (and any bundled reference documents) by its name. \" +\n \"Use this to load the body of a skill listed in the <skills> block before acting on it.\",\n inputSchema: toJsonSchema(SkillReadInputSchema),\n handler: (input: Record<string, unknown>): string => {\n const { name } = SkillReadInputSchema.parse(input);\n const skill = skills.find((s) => s.name === name);\n if (skill === undefined) {\n const available = skills.map((s) => s.name).join(\", \");\n return `Skill \"${name}\" not found. Available skills: ${available.length > 0 ? available : \"(none)\"}.`;\n }\n return renderSkill(skill);\n },\n };\n}\n\n/** SE36 — `SkillReadTool.create` replaces `defineSkillReadTool` (ADR 0015). @public *\n * `SkillReadTool.create` returns a **`CustomTool`** — a skill-reading tool, not a\n * `SkillReadTool` instance.\n */\nexport class SkillReadTool {\n private constructor() {}\n static create(skills: ReadonlyArray<InlineSkill>): CustomTool {\n return defineSkillReadTool(skills);\n }\n}\n","/**\n * Audit whether every configuration key can be set from the environment, or says why not.\n *\n * A key settable only by editing a file cannot be set in CI, in a container, or for a single\n * invocation. That is usually an oversight rather than a decision, and it is invisible — nothing\n * fails, the key simply has no environment path, and nobody notices until someone needs one.\n *\n * The opposite failure rots more quietly. An opt-out written for a key that has since gained an\n * environment path, or for a key that no longer exists, still reads as a considered decision while\n * exempting nothing. Both questions are answered by one call so a consumer cannot check the gap and\n * forget the rot: they fail for opposite reasons, and a suite that asks only one looks complete.\n *\n * ## Why the framework owns the rule and not the keys\n *\n * A framework cannot enumerate a consumer's configuration keys, and should not try. Which keys exist\n * is that product's vocabulary — the same reason the security floor takes its permissiveness order\n * as data and the trust posture takes its capability list. So the consumer ranges over its own keys\n * with this, rather than registering them here.\n *\n * That is a narrower claim than \"reachability is checked in the framework\", and it is the honest\n * one: the failure still surfaces in the consumer's own suite. What the consumer no longer writes is\n * the detector, which is where the subtlety lives — the stale-opt-out half is the part everyone\n * forgets.\n *\n * @public\n */\n\n/** A key deliberately left off the environment, with the reason and what would reverse it. @public */\nexport interface EnvOptOut {\n readonly key: string;\n /** Why an environment variable is the wrong shape for this key. */\n readonly reason: string;\n /** What would make this opt-out obsolete. An opt-out with no exit is a permanent excuse. */\n readonly exitCriterion: string;\n}\n\n/**\n * The three lists the audit compares: every key the product declares, the subset an environment\n * variable can set, and the documented exemptions.\n *\n * All three are matched by exact string equality, and `reachable` and `optOuts` are read as subsets\n * of `keys` — an entry in either that is not in `keys` is what makes an opt-out stale, and an entry\n * in `reachable` that is not in `keys` is simply ignored.\n *\n * @public\n */\nexport interface EnvReachabilityInput {\n /** Every configuration key the product declares. */\n readonly keys: readonly string[];\n /** The subset that an environment variable can set. */\n readonly reachable: readonly string[];\n /** Documented exemptions for keys that deliberately have no environment path. */\n readonly optOuts: readonly EnvOptOut[];\n}\n\n/**\n * The two failures, reported separately because they have opposite fixes.\n *\n * A key in `unreachable` needs either an environment path or a documented opt-out. A key in\n * `staleOptOuts` needs its opt-out DELETED — it exempts nothing, either because the key gained an\n * environment path or because the key no longer exists. Both lists empty is the passing state.\n *\n * @public\n */\nexport interface EnvReachabilityAudit {\n /** Keys with neither an environment path nor a documented opt-out. */\n readonly unreachable: readonly string[];\n /** Opt-outs that exempt nothing: the key gained an environment path, or no longer exists. */\n readonly staleOptOuts: readonly string[];\n}\n\n/**\n * Answer both halves of the reachability question in one call.\n *\n * A key counts as covered when it is in `reachable` OR carries an opt-out, so an opt-out silences\n * the gap it was written for and nothing else. Assert on both returned lists: a suite that checks\n * only `unreachable` still passes while the opt-outs rot, which is the half everyone forgets.\n *\n * This performs no I/O and reads no environment. The caller supplies its own key vocabulary,\n * because a framework cannot enumerate a consumer's configuration keys.\n *\n * @returns both axes, in the order the caller declared them — a stable order so a failure message\n * does not change between runs for reasons unrelated to the code.\n * @public\n */\nexport function auditEnvReachability(input: EnvReachabilityInput): EnvReachabilityAudit {\n const reachable = new Set(input.reachable);\n const exempt = new Set(input.optOuts.map((o) => o.key));\n const declared = new Set(input.keys);\n\n return {\n unreachable: input.keys.filter((k) => !reachable.has(k) && !exempt.has(k)),\n staleOptOuts: input.optOuts\n .filter((o) => !declared.has(o.key) || reachable.has(o.key))\n .map((o) => o.key),\n };\n}\n","/**\n * `EventBus` — typed EventEmitter wrapper.\n *\n * Provides type-safe publish/subscribe with automatic unsubscribe cleanup.\n * Each handler is try-caught (EC-2) so one failing handler cannot break others.\n */\n\nimport { diag } from \"./internal/diagnostics.js\";\n\ntype EventHandler<T> = (payload: T) => void;\n\n/**\n * A typed publish/subscribe bus, parameterised by a map of event name to payload type.\n *\n * `publish` is SYNCHRONOUS: handlers run in subscription order before it returns, so a slow handler\n * blocks the publisher. Each handler is invoked inside its own try/catch, so one that throws cannot\n * stop the others — the error is written to the diagnostics channel and counted on\n * `handlerErrorCount`. Assert on that counter in tests; a subscriber failing on every event is\n * otherwise invisible.\n *\n * `subscribe` returns the unsubscribe function, which is the only way to detach a handler — there\n * is no `off` taking the handler back. Handlers are held in a `Set` per event, so subscribing the\n * same function reference twice registers it once.\n *\n * Payload objects are passed by reference to every handler; nothing here copies them, so a handler\n * that mutates a payload mutates it for the handlers after it.\n */\nexport class EventBus<Events extends Record<string, unknown>> {\n private handlers = new Map<keyof Events, Set<EventHandler<never>>>();\n // M3 #64 — a swallowed handler error used to vanish without a trace (fail-loud\n // violation). We now log it AND expose an observable count so ops/tests can see\n // that a subscriber is silently failing, without breaking the EC-2 contract.\n #handlerErrorCount = 0;\n\n /** M3 #64 — number of handler invocations that threw (and were logged). */\n get handlerErrorCount(): number {\n return this.#handlerErrorCount;\n }\n\n /**\n * Subscribe to an event. Returns an unsubscribe function.\n */\n subscribe<K extends keyof Events>(event: K, handler: EventHandler<Events[K]>): () => void {\n if (!this.handlers.has(event)) {\n this.handlers.set(event, new Set());\n }\n const set = this.handlers.get(event)!;\n set.add(handler as EventHandler<never>);\n return () => {\n set.delete(handler as EventHandler<never>);\n };\n }\n\n /**\n * Publish an event to all subscribers. EC-2: try-catch per handler.\n */\n publish<K extends keyof Events>(event: K, payload: Events[K]): void {\n const set = this.handlers.get(event);\n if (!set) return;\n for (const handler of set) {\n try {\n (handler as EventHandler<Events[K]>)(payload);\n } catch (cause) {\n // EC-2: an error in one handler MUST NOT break the others — but M3 #64\n // makes it fail-loud: log with the event key + message and count it,\n // instead of the pre-M3 empty catch that discarded it without a trace.\n this.#handlerErrorCount += 1;\n const message = cause instanceof Error ? cause.message : String(cause);\n // theokit#147 — through the interceptable channel, not straight at the terminal: a TUI\n // host installs a diagnostics sink precisely so a stray write cannot corrupt its frame.\n diag(`[theokit-sdk] event-bus: handler for \"${String(event)}\" threw: ${message}\\n`);\n }\n }\n }\n\n /**\n * Subscribe to an event for a single firing. Returns an unsubscribe function.\n */\n once<K extends keyof Events>(event: K, handler: EventHandler<Events[K]>): () => void {\n const wrapped: EventHandler<Events[K]> = (payload) => {\n unsub();\n handler(payload);\n };\n const unsub = this.subscribe(event, wrapped);\n return unsub;\n }\n}\n","/**\n * M56 (agent-builder goal transparency) — PUBLIC goal-loop driver for CUSTOM agent surfaces.\n *\n * `LocalAgent.runUntil` binds the goal loop to a registered local agent. Surfaces that route turns\n * through their OWN transport (e.g. a TUI store facade, so every goal turn renders in the same\n * timeline as a manual turn) need the SAME loop over a minimal `send → wait` shape. This export\n * gives them exactly that: the canonical `runUntilImpl` (judge + continuation + token budget +\n * Codex states) with the default judge wired from the DI registry.\n *\n * @public\n */\n\nimport type { JudgeContext, JudgeOptions } from \"./internal/judge/judge-call.js\";\nimport type { RunUntilDeps } from \"./internal/runtime/lifecycle/run-until.js\";\nimport type { SDKAgent } from \"./types/agent.js\";\n\n/**\n * Stable marker on the FIRST LINE of every goal-continuation prompt. Surfaces detect it to render the\n * turn collapsed, exclude it from backtrack windows, and skip it in compaction preservation.\n */\nexport { GOAL_CONTINUATION_MARKER } from \"./internal/runtime/lifecycle/goal-marker.js\";\n\nimport type { GoalEvent, GoalOptions, GoalResult } from \"./types/goal-events.js\";\n\n/** The minimal surface the goal loop drives — anything that can send a prompt and wait for it. */\nexport interface GoalLoopAgent {\n send(prompt: string): Promise<{\n wait(): Promise<{ result?: string; usage?: { totalTokens?: number } }>;\n }>;\n}\n\n/**\n * Run the goal-driven loop (`send → judge → continuation`) over ANY `send → wait` surface.\n * Identical semantics to `Agent.runUntil` (ADRs D115-D121 + M55 token budget / states).\n * `depsOverride` is a test seam for injecting a fake judge.\n */\nexport function runGoalLoop(\n agent: GoalLoopAgent,\n goal: string,\n options?: GoalOptions,\n depsOverride?: RunUntilDeps,\n): AsyncGenerator<GoalEvent, GoalResult, void> {\n async function* wrap(): AsyncGenerator<GoalEvent, GoalResult, void> {\n const { runUntilImpl } = await import(\"./internal/runtime/lifecycle/run-until.js\");\n const deps: RunUntilDeps =\n depsOverride ??\n (await (async () => {\n const { judgeCallImpl } = await import(\"./internal/judge/judge-call.js\");\n const { getAgentFacade } = await import(\n \"./internal/runtime/registry/agent-factory-registry.js\"\n );\n const create = getAgentFacade().create;\n return {\n judge: (ctx: JudgeContext, opts?: JudgeOptions) => judgeCallImpl(ctx, opts, { create }),\n };\n })());\n // runUntilImpl only touches `agent.send(...)` → `run.wait()` — the SDKAgent cast is safe for\n // any GoalLoopAgent (structural subset).\n return yield* runUntilImpl(agent as unknown as SDKAgent, goal, options, deps);\n }\n return wrap();\n}\n","/**\n * Reference `BudgetTracker` impl — pure token + iteration counter\n * (SDK 2.0 Phase 2 / T2.1 — ADR D1 reference implementation).\n *\n * Counts tokens per type (input/output) + iteration count. Enforces\n * optional `maxTokens` / `maxIterations` ceilings via `check()`.\n *\n * Does NOT compute USD cost — leaves that to richer impls in\n * `@theokit/sdk-budget` (post-Phase-2). This file is intentionally\n * minimal so consumers can:\n * - use it as-is for simple guard-rails;\n * - read it as a worked example before authoring a custom tracker;\n * - rely on it as a fallback before sdk-budget ships.\n *\n * @public — surface-level reference impl.\n */\n\nimport type {\n BudgetCheck,\n BudgetTotal,\n BudgetTracker,\n BudgetUsageEvent,\n} from \"./budget-tracker.js\";\n\n/** Options for `createCounterBudgetTracker`. */\nexport interface CounterBudgetTrackerOptions {\n /** Hard ceiling on total tokens (input + output). When reached, `check()` returns `allowed: false`. */\n readonly maxTokens?: number;\n /** Hard ceiling on iterations counted by `nextIteration()`. */\n readonly maxIterations?: number;\n}\n\n/**\n * Build a fresh tracker. The returned object is independent — call\n * `createCounterBudgetTracker()` per Agent instance.\n *\n * The tracker exposes the `BudgetTracker` contract PLUS a `nextIteration()`\n * helper for impls that want explicit iteration counting (the agent loop\n * calls it once per turn). Without `nextIteration()` calls, the iteration\n * cap is never reached.\n */\nexport function createCounterBudgetTracker(\n options: CounterBudgetTrackerOptions = {},\n): BudgetTracker & { nextIteration(): void } {\n let totalTokens = 0;\n let iterations = 0;\n const maxTokens = options.maxTokens;\n const maxIterations = options.maxIterations;\n\n return {\n track(event: BudgetUsageEvent): void {\n // `track()` MUST be synchronous and non-throwing per the contract.\n // Invalid events (negative tokens) are silently clamped.\n const t = Number.isFinite(event.tokens) && event.tokens > 0 ? event.tokens : 0;\n totalTokens += t;\n },\n\n check(): BudgetCheck {\n if (maxTokens !== undefined && totalTokens >= maxTokens) {\n return {\n allowed: false,\n reason: \"token_limit\",\n detail: `${totalTokens} >= maxTokens ${maxTokens}`,\n };\n }\n if (maxIterations !== undefined && iterations >= maxIterations) {\n return {\n allowed: false,\n reason: \"iteration_limit\",\n detail: `${iterations} >= maxIterations ${maxIterations}`,\n };\n }\n return { allowed: true };\n },\n\n getTotal(): BudgetTotal {\n return { tokens: totalTokens, iterations };\n },\n\n nextIteration(): void {\n iterations += 1;\n },\n };\n}\n","/**\n * Plugin contract — RUNTIME value + type re-exports (T1.1, ADRs D97-D101).\n *\n * SE45/SE46 — the pure `Plugin` *type* and its type companions now live in\n * `types/plugin.ts` (above the DIP boundary, because `Plugin` is public\n * contract). This module keeps the RUNTIME value (`definePlugin` /\n * `Plugin.create`) and re-exports the types so every existing\n * `../plugins/types.js` importer (and the `index.ts` barrel) resolves the same\n * names unchanged.\n *\n * @public\n */\n\nimport type { Plugin as PluginType } from \"../../types/plugin.js\";\n\nexport type {\n CommandHandler,\n CommandOptions,\n HookHandler,\n HookName,\n LlmCallContext,\n // #335 — this used to be omitted here, with the note that it \"stays reachable as\n // the `createProvider` field type on the `Plugin` union, which IS re-exported\".\n // That inference was false, and it is what shipped a broken declaration: the DTS\n // rollup emits an exported type's BODY and treeshakes away a non-exported type\n // that body merely NAMES. Reachable-as-a-field-type is not reachable-as-a-\n // declaration. The published `.d.ts` said `createProvider: MemoryProviderFactory`\n // with no such type in the file — invisible under `skipLibCheck`, and an\n // `error`-typed graph for any consumer running type-aware lint.\n //\n // The original reason for the omission (re-exporting a decl that carries the\n // internal-visibility JSDoc tag leaves a dangling re-export once `stripInternal`\n // deletes it) no longer applies: the tag came off `types/plugin.ts`, because a\n // type named by a public signature is public. That tag is matched as TEXT, so\n // its literal spelling is deliberately absent from this comment too.\n MemoryProviderFactory,\n PluginContext,\n PluginHookDisposer,\n PostAssistantReplyContext,\n PostToolCallContext,\n PreToolCallContext,\n PreToolCallDecision,\n PreUserSendContext,\n PreUserSendResult,\n SessionLifecycleContext,\n ToolCallSummary,\n ToolContext,\n ToolResultTransformContext,\n TransformContext,\n} from \"../../types/plugin.js\";\n\n// Re-establish the declaration merge locally: `Plugin` is BOTH the discriminated\n// union *type* (aliased from ./types/plugin.js) AND the runtime const-companion\n// (`Plugin.create`) declared below. Keeping both bindings under the one exported\n// name `Plugin` preserves the public value+type surface byte-for-byte.\nexport type Plugin = PluginType;\n\n/**\n * Identity helper for plugin authors. TS-only convenience — preserves\n * inferred type without forcing manual `Plugin` annotation.\n *\n * @public\n */\nexport function definePlugin<P extends Plugin>(p: P): P {\n return p;\n}\n\n/** SE36 — `Plugin.create` replaces `definePlugin` (ADR 0015). Const-companion (the `Plugin` type alias blocks a class of the same name); `create` is the generic `definePlugin`. @public */\nexport const Plugin = { create: definePlugin };\n","/**\n * Reference `MemoryProvider` impl — no-op fallback (SDK 2.0 Phase 1 /\n * T1.2 reference implementation, mirrors `createCounterBudgetTracker`).\n *\n * Every method is a degenerate identity:\n * - `init()` returns a handle wrapping a no-op `MemoryAdapter`.\n * - `buildTools()` returns `[]` (no memory tools surfaced to the LLM).\n * - `runActivePass()` returns `{ facts: [] }` (no recall fires).\n * - `dispose()` is a no-op.\n *\n * Why ship this:\n * - Default safety net before `@theokit/sdk-memory` is installed.\n * - Worked reference for authors of custom providers.\n * - Enables `Agent.create({ memoryProvider: createNoopMemoryProvider() })`\n * unit tests without pulling memory infrastructure.\n *\n * NOT a substitute for the existing `Memory` class — the legacy class\n * stays authoritative until the subsystem fully ports to providers\n * (Phase 1 / T1.6).\n *\n * @public — surface-level reference impl.\n */\n\nimport type {\n MemoryAdapter,\n MemoryAdapterCapabilities,\n MemoryContext,\n MemoryFact,\n MemoryId,\n MemoryTurnMessage,\n} from \"../../../types/memory-adapter.js\";\nimport type {\n ActiveMemoryPassArgs,\n ActiveMemoryPassResult,\n MemoryProvider,\n MemoryProviderHandle,\n MemoryProviderInitOptions,\n} from \"./memory-provider.js\";\n\n/** Adapter-id used by the no-op MemoryAdapter — namespaced to avoid collision. */\nconst NOOP_ADAPTER_ID = \"noop\";\n\n/** All-false capabilities — every optional feature gated off. */\nconst NOOP_CAPABILITIES: MemoryAdapterCapabilities = {\n history: false,\n sessions: false,\n tenancy: false,\n reasoning: false,\n toolSchemas: false,\n prefetch: false,\n};\n\n/** Build the no-op MemoryAdapter satisfying the public contract. */\nfunction createNoopMemoryAdapter(): MemoryAdapter {\n return {\n id: NOOP_ADAPTER_ID,\n capabilities: NOOP_CAPABILITIES,\n isAvailable(): boolean {\n return true;\n },\n async write(_content: string | MemoryTurnMessage[], _ctx: MemoryContext): Promise<MemoryId> {\n // Return a deterministic noop id with the adapter-id prefix so\n // `extractRawId` cross-adapter safety check still works.\n return `${NOOP_ADAPTER_ID}:noop` as MemoryId;\n },\n async recall(_query: string, _ctx: MemoryContext, _k?: number): Promise<MemoryFact[]> {\n return [];\n },\n async delete(_id: MemoryId): Promise<void> {\n return;\n },\n };\n}\n\n/**\n * Build a fresh no-op MemoryProvider. The returned object is independent —\n * call `createNoopMemoryProvider()` per Agent instance. `init()` is\n * idempotent: subsequent calls return a NEW handle (no per-agent cache —\n * the no-op has no state worth caching).\n */\nexport function createNoopMemoryProvider(): MemoryProvider {\n return {\n async init(_opts: MemoryProviderInitOptions): Promise<MemoryProviderHandle> {\n return {\n adapter: createNoopMemoryAdapter(),\n };\n },\n buildTools(_handle: MemoryProviderHandle): readonly never[] {\n return [];\n },\n async runActivePass(\n _handle: MemoryProviderHandle,\n _args: ActiveMemoryPassArgs,\n ): Promise<ActiveMemoryPassResult> {\n return { facts: [] };\n },\n recordSessionSummary(): void {\n // No-op: the no-op provider doesn't persist anything. Defining the\n // method (vs leaving it undefined) is intentional — when consumers\n // wire the no-op explicitly, they OPT INTO the port path for the\n // session-summary write site too. Future rich impls override this\n // with real disk writes.\n return;\n },\n dispose(_handle: MemoryProviderHandle): void {\n return;\n },\n };\n}\n\n/** SE36 — `NoopMemoryProvider.create` replaces `createNoopMemoryProvider` (ADR 0015). @public */\nexport class NoopMemoryProvider {\n private constructor() {}\n static create(): MemoryProvider {\n return createNoopMemoryProvider();\n }\n}\n","/**\n * #583 — what tool names an agent built from these options will actually offer the model.\n *\n * ## The gap this closes\n *\n * `Agent.describe()` was the only reflection surface, and it builds its catalog as\n * `(agent.options.tools ?? [])` — literally the array the caller passed. The SDK's own builtins were\n * never in it. So the two states that matter most were indistinguishable:\n *\n * Agent.create({ tools: [] }) describe().tools = [] (holds a shell)\n * the same, withheldBuiltinTools: [\"shell\"] describe().tools = [] (holds nothing)\n *\n * A consumer trying to confirm that a role declared read-only really is one had no instrument. What\n * they had to do instead — measured, in a real session — was ask the agent to enumerate its own\n * catalog: needs a credential, needs the network, and returns the list the MODEL decided to write\n * rather than the one the runtime holds. The same session recorded a subagent answering *\"I can't\n * run shell commands in this environment\"* while its catalog listed `shell`. An attempt measures the\n * model's disposition; the catalog measures its authority.\n *\n * ## Why it takes options rather than an agent id\n *\n * The asked-for shape, and it is the right one: synchronous, credential-free, and answerable BEFORE\n * the agent runs — so a test can compare what it declared against what the runtime will declare.\n * `describe()` needs a registered agent and answers too late for that.\n *\n * ## Why it does not return a bare array\n *\n * Because a bare array reads as complete, and completeness is exactly what this cannot promise: MCP\n * tools need a live connection, plugin tools and the reasoning `think` tool are assembled per run.\n * Returning `string[]` would rebuild the defect one function over. `unresolved` names the sources\n * that were configured and could not be enumerated — and is EMPTY when none were, which is when the\n * list is genuinely the whole catalog.\n *\n * @public\n */\n\nimport type { AgentOptions, BuiltinToolName } from \"../../../types/agent.js\";\n\n/** The builtins this SDK registers, and the option that governs each. */\nconst ALWAYS_REGISTERED: readonly BuiltinToolName[] = [\"shell\"];\nconst MEMORY_BUILTINS: readonly BuiltinToolName[] = [\"memory_search\", \"memory_get\"];\n\n/** A tool source that is configured but cannot be enumerated without running the agent. */\nexport type UnresolvedToolSource = \"mcp\" | \"plugins\" | \"reasoning\";\n\n/** The result of {@link effectiveToolNames}. */\nexport interface EffectiveToolCatalog {\n /**\n * Every tool name resolvable from the options alone: the builtins still registered after\n * withholding, plus the names of the custom tools declared.\n */\n readonly names: readonly string[];\n /**\n * Sources that ARE configured and could not be enumerated here. Empty means `names` is the\n * complete catalog — which is the only condition under which it may be read as one.\n */\n readonly unresolved: readonly UnresolvedToolSource[];\n}\n\n/**\n * The tool names an agent created with `options` will offer the model, as far as the options can say.\n *\n * Pure and synchronous: no credential, no network, no registration. Intended for a test that asserts\n * a role is as narrow as it claims.\n *\n * ```ts\n * const { names, unresolved } = effectiveToolNames({ tools: [], withheldBuiltinTools: [\"shell\"] });\n * expect(names).toEqual([]); // and `shell` is genuinely gone\n * expect(unresolved).toEqual([]); // nothing else could contribute, so [] is the whole catalog\n * ```\n */\nexport function effectiveToolNames(options: AgentOptions): EffectiveToolCatalog {\n return { names: resolvableNames(options), unresolved: unresolvableSources(options) };\n}\n\n/**\n * The names the options DO determine: builtins surviving the withholding, plus declared custom tools.\n */\nfunction resolvableNames(options: AgentOptions): readonly string[] {\n const withheld = new Set<BuiltinToolName>(options.withheldBuiltinTools ?? []);\n // Memory builtins are registered only when memory is on. Reporting them unconditionally would\n // overstate the catalog; omitting them when it IS on would understate it. Both are this defect.\n const builtins = [\n ...ALWAYS_REGISTERED,\n ...(options.memory?.enabled === true ? MEMORY_BUILTINS : []),\n ];\n return [\n ...builtins.filter((builtin) => !withheld.has(builtin)),\n ...(options.tools ?? []).map((tool) => tool.name),\n ];\n}\n\n/**\n * The sources that ARE configured and cannot be enumerated without running the agent.\n *\n * Split from the names deliberately: this half is the honesty of the answer, and folding it into the\n * same function is what let the caller's complexity ceiling object to the pair rather than to either.\n */\nfunction unresolvableSources(options: AgentOptions): readonly UnresolvedToolSource[] {\n const unresolved: UnresolvedToolSource[] = [];\n if (options.mcpServers !== undefined && Object.keys(options.mcpServers).length > 0) {\n unresolved.push(\"mcp\");\n }\n if (hasPlugins(options.plugins)) unresolved.push(\"plugins\");\n if (options.reasoning === true) unresolved.push(\"reasoning\");\n return unresolved;\n}\n\n/**\n * `plugins` is a union — a settings object or an array of registered plugins — and both shapes can be\n * present-but-empty, which contributes nothing and must not be reported as unresolved.\n */\nfunction hasPlugins(plugins: AgentOptions[\"plugins\"]): boolean {\n if (plugins === undefined) return false;\n if (Array.isArray(plugins)) return plugins.length > 0;\n const enabled = (plugins as { enabled?: readonly string[] }).enabled;\n return enabled === undefined || enabled.length > 0;\n}\n","/**\n * `JobQueue` — background job queue with status tracking, cancellation, and an\n * optional concurrency bound.\n *\n * EC-1: all enqueued functions are wrapped in Promise.resolve().then() so\n * synchronous throws become rejections.\n *\n * #58: each job runs under an `AbortController` whose signal is passed to the\n * job fn, so `cancel()` actually interrupts a running job (not just a status\n * flip); an optional `maxConcurrency` bounds how many jobs run at once.\n */\n\nimport { randomUUID } from \"node:crypto\";\n\ntype JobStatus = \"pending\" | \"running\" | \"completed\" | \"failed\" | \"cancelled\";\n\ninterface Job<T> {\n id: string;\n status: JobStatus;\n result?: T;\n error?: string;\n}\n\n/** #58 — construction options. */\nexport interface JobQueueOptions {\n /**\n * Max jobs running concurrently. Omit for unbounded (previous behavior).\n * Values < 1 are clamped to 1 (an invalid bound must not deadlock).\n */\n maxConcurrency?: number;\n}\n\n/**\n * An in-process queue of background jobs with status tracking, cancellation, and an optional\n * concurrency bound.\n *\n * `enqueue` returns a job id immediately and never throws for the job's own failure: a synchronous\n * throw inside the function becomes a rejection, and a rejection becomes `status: \"failed\"` with\n * the message on `job.error`. Poll `getJob(id)` or `list()` for outcomes — there is no completion\n * event and no promise to await.\n *\n * Cancellation is COOPERATIVE. `cancel` aborts the `AbortSignal` handed to the job function and\n * flips the status, but a function that ignores the signal keeps running to completion; its result\n * is then discarded, because a cancelled job never leaves the cancelled state. The concurrency slot\n * of a running job is freed at cancel time rather than when it eventually settles, so a job that\n * never settles cannot deadlock a bounded queue.\n *\n * State lives entirely in memory and grows without bound — nothing evicts finished jobs. This is a\n * queue for one process, not a durable one.\n */\nexport class JobQueue {\n private jobs = new Map<string, Job<unknown>>();\n private controllers = new Map<string, AbortController>();\n private readonly maxConcurrency: number;\n private running = 0;\n private readonly waiting: Array<() => void> = [];\n\n constructor(options: JobQueueOptions = {}) {\n this.maxConcurrency =\n options.maxConcurrency === undefined\n ? Number.POSITIVE_INFINITY\n : Math.max(1, options.maxConcurrency);\n }\n\n /**\n * Enqueue a background function. Returns the job ID immediately. The function\n * receives an `AbortSignal` that fires when the job is cancelled (#58) — a\n * cooperative job should observe it to stop early. Existing `() => Promise<T>`\n * callers are unaffected (the signal argument is simply ignored).\n */\n enqueue<T>(fn: (signal: AbortSignal) => Promise<T>): string {\n const id = randomUUID();\n const job: Job<T> = { id, status: \"pending\" };\n this.jobs.set(id, job as Job<unknown>);\n const controller = new AbortController();\n this.controllers.set(id, controller);\n\n void this.#acquire().then(() => {\n // Cancelled while waiting for a slot → never start.\n if (job.status === \"cancelled\") {\n this.#release(id);\n return;\n }\n job.status = \"running\";\n Promise.resolve()\n .then(() => fn(controller.signal))\n .then((result) => {\n if (job.status === \"cancelled\") return;\n job.result = result;\n job.status = \"completed\";\n })\n .catch((err: unknown) => {\n if (job.status === \"cancelled\") return;\n job.error = err instanceof Error ? err.message : String(err);\n job.status = \"failed\";\n })\n .finally(() => this.#release(id));\n });\n\n return id;\n }\n\n getJob(id: string): Job<unknown> | undefined {\n return this.jobs.get(id);\n }\n\n list(): Job<unknown>[] {\n return [...this.jobs.values()];\n }\n\n /**\n * Cancel a pending or running job. Returns true if cancelled. #58 — aborts the\n * job's `AbortSignal` so a cooperative running job is actually interrupted.\n */\n cancel(id: string): boolean {\n const job = this.jobs.get(id);\n if (!job) return false;\n if (job.status === \"pending\" || job.status === \"running\") {\n const wasRunning = job.status === \"running\";\n job.status = \"cancelled\";\n this.controllers.get(id)?.abort();\n // A running job holds a concurrency slot; its fn may ignore the signal and\n // never settle, so free the slot NOW rather than waiting for `.finally`\n // (which would never fire → the bounded queue would deadlock). `#release`\n // is idempotent, so the job's eventual `.finally` is a no-op. A *pending*\n // job holds no slot yet — its slot-grant self-releases when it starts.\n if (wasRunning) this.#release(id);\n return true;\n }\n return false;\n }\n\n /** Acquire a concurrency slot (resolves immediately when unbounded/free). */\n #acquire(): Promise<void> {\n if (this.running < this.maxConcurrency) {\n this.running += 1;\n return Promise.resolve();\n }\n return new Promise<void>((resolve) => {\n this.waiting.push(() => {\n this.running += 1;\n resolve();\n });\n });\n }\n\n /**\n * Release a slot + clean up the controller; start the next waiting job.\n * Idempotent — keyed on the controller's presence, so a running job that was\n * cancelled (released early) does not double-decrement when its `.finally`\n * eventually fires.\n */\n #release(id: string): void {\n if (!this.controllers.has(id)) return; // already released\n this.controllers.delete(id);\n this.running -= 1;\n const next = this.waiting.shift();\n if (next !== undefined) next();\n }\n}\n","/**\n * Fold configuration layers in a declared order — later layers win, named keys accumulate.\n *\n * Every product that reads configuration from more than one place rebuilds these two rules, and the\n * second one is not a nicety. With plain last-wins, a project file DISPLACES the user's entries for\n * a list-valued key rather than adding to them — and for a key like `hooks`, which carries arbitrary\n * command execution, that is the difference between a repository adding a hook and a repository\n * removing yours.\n *\n * The layer NAMES are the caller's, supplied as data. One product's chain is\n * defaults/user/project/profile/env/cli; `profile` is that product's idea and does not belong here.\n * That is the same test the security floor passed: a vocabulary expressible as data generalises, an\n * open-ended interface shaped by one product does not.\n *\n * @public\n */\n\nimport { TheokitAgentError } from \"./errors.js\";\n\n/** Raised when a declared layer chain is not strictly ascending. @public */\nexport class LayerOrderError extends TheokitAgentError {\n override readonly name = \"LayerOrderError\";\n}\n\n/**\n * One named layer in a precedence chain.\n *\n * `precedence` is optional and the two usages do not mix well: omit it everywhere to say \"this\n * array is already in order\", or supply it everywhere you want `verifyLayerOrdering` to check.\n * Entries without it are SKIPPED by that check rather than treated as zero, so a chain where only\n * some entries declare a number is verified only between those.\n *\n * @public\n */\nexport interface DeclaredLayer {\n readonly layer: string;\n /** Higher wins. Optional — omit it to mean \"this array is already the order\". */\n readonly precedence?: number;\n}\n\n/**\n * A declared layer together with the values it supplies.\n *\n * `foldLayers` consumes these in array order, so a later entry wins for the keys it mentions. A key\n * a layer does not mention — or mentions with `undefined` — leaves the earlier value standing;\n * there is no way for a layer to erase a key another layer set.\n *\n * @public\n */\nexport interface LayerValues extends DeclaredLayer {\n readonly values: Readonly<Record<string, unknown>>;\n}\n\n/**\n * Assert that each layer strictly outranks the one before it.\n *\n * Entries without a `precedence` are skipped rather than treated as zero: omitting it means the\n * caller is expressing order by position, and inventing a number for them would manufacture a\n * conflict out of a legitimate usage.\n *\n * @throws LayerOrderError naming both layers and both precedences — a refusal that only says \"out\n * of order\" sends the reader to compare the whole list by hand.\n * @public\n */\nexport function verifyLayerOrdering(layers: readonly DeclaredLayer[]): void {\n // Narrowed to the entries that actually declare a precedence, so the comparison below has no\n // `undefined` to reason about and the type says so.\n let previous: { layer: string; precedence: number } | undefined;\n for (const current of layers) {\n if (current.precedence === undefined) continue;\n const declared = { layer: current.layer, precedence: current.precedence };\n if (previous !== undefined && declared.precedence <= previous.precedence) {\n throw new LayerOrderError(\n `layers out of order: \\`${declared.layer}\\` (precedence ${String(declared.precedence)}) ` +\n `comes after \\`${previous.layer}\\` (precedence ${String(previous.precedence)}) but does ` +\n `not outrank it`,\n );\n }\n previous = declared;\n }\n}\n\n/**\n * Combine `entries` into one record.\n *\n * Later entries win. A value of `undefined` never overwrites — a layer that does not mention a key\n * must not erase it, because \"said nothing\" is overwhelmingly more common than \"said nothing on\n * purpose\".\n *\n * Keys in `accumulatingKeys` whose value is an array are CONCATENATED across layers instead of\n * replaced. A non-array value for such a key replaces, deliberately: a malformed config must not\n * corrupt the accumulator into a mixed list, and leaving the raw value visible lets the consumer's\n * own validation reject it with its own message.\n *\n * The accumulator is per-call and the inputs are never mutated, so folding twice yields the same\n * answer — which a consumer that folds once to display and once to apply depends on.\n *\n * @public\n */\nexport function foldLayers(\n entries: readonly LayerValues[],\n accumulatingKeys: readonly string[] = [],\n): Record<string, unknown> {\n verifyLayerOrdering(entries);\n\n const accumulated = new Map<string, unknown[]>(accumulatingKeys.map((k) => [k, []]));\n const combined: Record<string, unknown> = {};\n\n for (const { values } of entries) {\n for (const [key, value] of Object.entries(values)) {\n if (value === undefined) continue;\n const stack = accumulated.get(key);\n if (stack !== undefined && Array.isArray(value)) {\n stack.push(...(value as readonly unknown[]));\n // The copy is defensive and NOT covered by a test, because it is not observable: the\n // accumulator is per-call and nothing touches it after the fold returns. Mutating this line\n // to `combined[key] = stack` leaves every case green — checked, not assumed. It stays\n // because returning internal mutable state from a public API is a smell that costs one\n // allocation to avoid, and the next change to this function should not have to notice.\n combined[key] = [...stack];\n continue;\n }\n combined[key] = value;\n }\n }\n return combined;\n}\n","import type { EmbeddingRuntime } from \"../embedding-adapter.js\";\nimport type { MemoryFact, MemoryKind } from \"../types.js\";\n\n/**\n * Dreaming/REM phase logic.\n *\n * Three phases:\n * - **light** — drop near-duplicate facts (cosine similarity > 0.95).\n * - **REM** — cluster thematically related facts (cosine ≥ 0.75).\n * - **deep** — pick a representative bullet per cluster (longest text\n * wins) and emit consolidated markdown notes.\n *\n * @internal\n */\n\nexport interface DedupResult {\n kept: MemoryFact[];\n duplicatesRemoved: number;\n}\n\nexport interface Cluster {\n representativeText: string;\n members: ReadonlyArray<MemoryFact>;\n}\n\nexport interface ClusterResult {\n clusters: Cluster[];\n}\n\nconst DEFAULT_DEDUP_THRESHOLD = 0.95;\nconst DEFAULT_CLUSTER_THRESHOLD = 0.75;\n\n/**\n * Kinds a sweep may consolidate. ADR-14 partitions the vocabulary into three buckets and only\n * this one is a merge candidate; the rest are protected for a reason that survives the sweep\n * being non-destructive.\n *\n * `user`, `feedback` and `reference` are ATOMIC: there is nothing to merge and the loss is\n * irreversible. Two corrections a user gave on different days can read alike and are not the\n * same correction. An untyped fact is protected too — a kind that nobody declared is not a\n * licence to treat it as consolidatable.\n *\n * Why this matters even though nothing is deleted: dedup drops the near-duplicate from the\n * CLUSTERING INPUT, and the cluster's representative is what the search index returns. The\n * source file survives; the artefact the agent reads does not. That is ADR-14's third rule —\n * the invariant is about what the agent reads, not what survives on disk.\n */\n// Typed against `MemoryKind` rather than `string`, so the compiler checks these against the vocabulary\n// they mirror. They were `Set<string>` and CONSOLIDATABLE_KINDS held \"session\" — not a member of\n// `MemoryKind`, and rejected by `markdown-store.assertWritable` before any fact is written, so no\n// fact reaching this policy could ever carry it. The arm read as though sessions were consolidatable\n// while no session could exist. Adding a member to either set is now a type error unless `MemoryKind`\n// gains it deliberately.\nconst CONSOLIDATABLE_KINDS: ReadonlySet<MemoryKind> = new Set([\"project\"]);\nconst ATOMIC_KINDS: ReadonlySet<MemoryKind> = new Set([\"user\", \"feedback\", \"reference\"]);\n\n/**\n * Three levels, graded by how much the store knows about the entry. The middle one exists\n * because the first draft of this filter did not have it and broke the common case.\n *\n * - ATOMIC (`user`, `feedback`, `reference`) — never deduplicated. Two corrections given on\n * different days can read alike and are not the same correction.\n * - CONSOLIDATABLE (`project`, `session`) — near-duplicate dedup at the similarity threshold.\n * Overlapping project facts are exactly what a sweep is for.\n * - UNTYPED — EXACT duplicates only. A hand-written bullet under `## Facts` carries no kind,\n * and the store's own header invites editing those by hand, so untyped is the common case\n * rather than an edge one. Treating it as atomic would disable the sweep for most stores;\n * treating it as consolidatable would let a near-duplicate of an untyped correction be\n * dropped. Exact-match is the only claim the store can make without inferring a kind, which\n * is the rule this codebase already applies one field over.\n */\ntype DedupPolicy = \"never\" | \"exact\" | \"similar\";\n\nfunction dedupPolicy(fact: MemoryFact): DedupPolicy {\n if (fact.kind === undefined) return \"exact\";\n if (ATOMIC_KINDS.has(fact.kind)) return \"never\";\n return CONSOLIDATABLE_KINDS.has(fact.kind) ? \"similar\" : \"never\";\n}\n\n/** Whitespace and case collapsed; nothing else. Not a similarity measure — an identity one. */\nfunction normalizeForExactMatch(text: string): string {\n return text\n .trim()\n .toLowerCase()\n .replace(/\\s+/g, \" \")\n .replace(/[.!?]+$/, \"\");\n}\n\n/**\n * Light phase — drop facts whose embedding is too similar to one already kept.\n *\n * Protected kinds bypass deduplication entirely and are returned untouched, so a sweep can\n * never conflate two of them into one representative.\n *\n * \"Drop\" here means DROPPED FROM THE RETURNED LIST. Nothing on disk is deleted, by any phase of\n * this sweep, today.\n *\n * BEFORE YOU ADD PRUNING HERE, READ THIS. The security contract for this store requires a backup\n * to precede any destructive operation (SOP-06-05 step 7). That requirement is currently LATENT\n * — not satisfied, not waived — precisely because the sweep only ever adds notes and filters a\n * list. There is no backup implementation in this package, and an audit that looked for one\n * recorded its absence as having no present consequence.\n *\n * The first commit that makes this sweep delete a file from disk is the commit that makes the\n * gap real, and it is also the commit whose author will have no reason to know this line exists.\n * That is why the trigger is written beside the code that would trip it rather than in the audit\n * that found it: a gap recorded in a reviewer's file reappears as a surprise; a gap recorded\n * here stops the person adding pruning.\n */\nexport async function lightPhase(\n facts: ReadonlyArray<MemoryFact>,\n embedding: EmbeddingRuntime,\n threshold: number = DEFAULT_DEDUP_THRESHOLD,\n): Promise<DedupResult> {\n if (facts.length <= 1) return { kept: [...facts], duplicatesRemoved: 0 };\n const never = facts.filter((f) => dedupPolicy(f) === \"never\");\n const exact = facts.filter((f) => dedupPolicy(f) === \"exact\");\n const similar = facts.filter((f) => dedupPolicy(f) === \"similar\");\n\n // Exact pass: identity, not similarity. No embedding call, no threshold, no judgement.\n const seen = new Set<string>();\n const exactKept: MemoryFact[] = [];\n let removed = 0;\n for (const f of exact) {\n const key = normalizeForExactMatch(f.text);\n if (seen.has(key)) {\n removed += 1;\n continue;\n }\n seen.add(key);\n exactKept.push(f);\n }\n\n const sim =\n similar.length > 1\n ? await dedupCandidates(similar, embedding, threshold)\n : { kept: [...similar], duplicatesRemoved: 0 };\n\n // Protected facts keep their original relative position at the front: they were never in\n // the running, and putting them back through the sort would imply they had been judged.\n return {\n kept: [...never, ...exactKept, ...sim.kept],\n duplicatesRemoved: removed + sim.duplicatesRemoved,\n };\n}\n\nasync function dedupCandidates(\n facts: ReadonlyArray<MemoryFact>,\n embedding: EmbeddingRuntime,\n threshold: number,\n): Promise<DedupResult> {\n if (facts.length <= 1) return { kept: [...facts], duplicatesRemoved: 0 };\n const vectors = await embedding.embed(facts.map((f) => f.text));\n const keptIdx: number[] = [];\n const keptVecs: number[][] = [];\n for (let i = 0; i < facts.length; i++) {\n const vec = vectors[i] ?? [];\n const isDup = keptVecs.some((kept) => cosineSimilarity(vec, kept) >= threshold);\n if (isDup) continue;\n keptIdx.push(i);\n keptVecs.push(vec);\n }\n const kept = keptIdx.map((i) => facts[i] as MemoryFact);\n return { kept, duplicatesRemoved: facts.length - kept.length };\n}\n\n// T4.6 — cap facts per sweep to prevent O(N²) blowup. 500 facts →\n// 125K comparisons (acceptable). 5000 facts → 12.5M (unacceptable).\n// When facts exceed the cap, a deterministic subsample is taken so the\n// sweep is bounded. The remaining facts are carried to the next sweep.\nconst DEFAULT_MAX_FACTS_PER_SWEEP = 500;\n\n/** REM phase — single-link agglomerative clustering by cosine similarity. */\nexport async function remPhase(\n facts: ReadonlyArray<MemoryFact>,\n embedding: EmbeddingRuntime,\n threshold: number = DEFAULT_CLUSTER_THRESHOLD,\n maxFactsPerSweep: number = DEFAULT_MAX_FACTS_PER_SWEEP,\n): Promise<ClusterResult> {\n // KNOWN GAP, deliberately not closed here. Protected kinds are excluded from DEDUP — a\n // near-duplicate correction is never dropped — but they still reach CLUSTERING, and a cluster\n // carries one representative into the consolidated note.\n //\n // Filtering them out here too was tried and reverted: untyped is the common case (hand-written\n // bullets carry no kind), so excluding it disables consolidation for most stores, and it broke\n // three existing golden tests. The damage is also smaller than in the dedup case — the source\n // files survive and remain readable, so what a cluster costs is nuance in an ADDITIONAL\n // artefact rather than a lost entry.\n //\n // It becomes real damage only if recall serves notes INSTEAD of sources. That depends on what\n // the index covers, which is not settled here. Recorded rather than silently accepted.\n if (facts.length === 0) return { clusters: [] };\n // T4.6 — cap: subsample when facts exceed budget. Deterministic\n // sort by text hash so the same input always picks the same subset.\n const capped = facts.length > maxFactsPerSweep ? facts.slice(0, maxFactsPerSweep) : facts;\n const vectors = await embedding.embed(capped.map((f) => f.text));\n const clusterOfIdx = unionFindByPairs(vectors, threshold);\n const groups = bucketFactsByClusterRoot(capped, clusterOfIdx);\n return { clusters: [...groups.values()].map(buildClusterFromMembers) };\n}\n\nfunction unionFindByPairs(\n vectors: ReadonlyArray<ReadonlyArray<number>>,\n threshold: number,\n): number[] {\n const clusterOfIdx = vectors.map((_, i) => i);\n for (let i = 0; i < vectors.length; i++) {\n for (let j = i + 1; j < vectors.length; j++) {\n if (cosineSimilarity(vectors[i] ?? [], vectors[j] ?? []) >= threshold) {\n unifyClusters(clusterOfIdx, i, j);\n }\n }\n }\n return clusterOfIdx;\n}\n\nfunction bucketFactsByClusterRoot(\n facts: ReadonlyArray<MemoryFact>,\n clusterOfIdx: number[],\n): Map<number, MemoryFact[]> {\n const groups = new Map<number, MemoryFact[]>();\n for (let i = 0; i < facts.length; i++) {\n const root = findRoot(clusterOfIdx, i);\n const list = groups.get(root) ?? [];\n list.push(facts[i] as MemoryFact);\n groups.set(root, list);\n }\n return groups;\n}\n\nfunction buildClusterFromMembers(members: ReadonlyArray<MemoryFact>): Cluster {\n const sorted = [...members].sort((a, b) => b.text.length - a.text.length);\n return { representativeText: sorted[0]?.text ?? \"\", members };\n}\n\n/** Deep phase — render consolidated markdown for the dreamed note. */\nexport function deepPhase(clusters: ReadonlyArray<Cluster>, timestampMs: number): string {\n if (clusters.length === 0) return \"\";\n const isoStamp = new Date(timestampMs).toISOString();\n const lines: string[] = [`# Dreamed ${isoStamp}`, \"\"];\n for (let i = 0; i < clusters.length; i++) {\n const c = clusters[i];\n if (c === undefined) continue;\n lines.push(`## Cluster ${i + 1}: ${c.representativeText}`);\n lines.push(\"\");\n for (const member of c.members) lines.push(`- ${member.text}`);\n lines.push(\"\");\n }\n return `${lines.join(\"\\n\")}\\n`;\n}\n\nfunction cosineSimilarity(a: ReadonlyArray<number>, b: ReadonlyArray<number>): number {\n if (a.length === 0 || b.length === 0 || a.length !== b.length) return 0;\n let dot = 0;\n let aNorm = 0;\n let bNorm = 0;\n for (let i = 0; i < a.length; i++) {\n const ai = a[i] ?? 0;\n const bi = b[i] ?? 0;\n dot += ai * bi;\n aNorm += ai * ai;\n bNorm += bi * bi;\n }\n const denom = Math.sqrt(aNorm) * Math.sqrt(bNorm);\n return denom === 0 ? 0 : dot / denom;\n}\n\nfunction findRoot(parents: number[], i: number): number {\n let root = i;\n while (parents[root] !== root) {\n const next = parents[root] ?? root;\n if (next === root) break;\n root = next;\n }\n parents[i] = root;\n return root;\n}\n\nfunction unifyClusters(parents: number[], a: number, b: number): void {\n const rootA = findRoot(parents, a);\n const rootB = findRoot(parents, b);\n if (rootA !== rootB) parents[rootB] = rootA;\n}\n","import { mkdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { diag } from \"../../diagnostics.js\";\nimport { replaceFileAtomic } from \"../../persistence/atomic-write.js\";\nimport { withCwdMutex } from \"../../persistence/cwd-mutex.js\";\nimport type { EmbeddingRuntime } from \"../embedding-adapter.js\";\nimport { readFactsFromMarkdown } from \"../storage/markdown-store.js\";\nimport { type MemoryRoot, resolveMemoryRoot } from \"../storage/memory-root.js\";\nimport { appendDiaryEntry } from \"./diary.js\";\nimport { deepPhase, lightPhase, remPhase } from \"./phases.js\";\n\n/**\n * Dreaming sweep orchestrator (ADR D7 of memory-system-peer-project-parity).\n *\n * Phases:\n * 1. **light** — drop near-duplicate facts via cosine similarity.\n * 2. **REM** — cluster thematically related facts.\n * 3. **deep** — write a `notes/dreamed-<ts>.md` per sweep with consolidated\n * clusters; append a diary entry.\n *\n * All file writes go through `replaceFileAtomic` (EC-3) and the entire sweep\n * holds the per-cwd mutex so a `Remember:` append can't race it.\n *\n * @internal\n */\n\nexport interface DreamingOptions {\n cwd: string;\n /**\n * The memory root to sweep. Defaults to the project store — right for a caller with no\n * `memory.directory`, and wrong for one that has it, which is why it is passable (#463).\n */\n memoryRoot?: MemoryRoot;\n embedding: EmbeddingRuntime;\n dedupThreshold?: number;\n clusterThreshold?: number;\n /** Test hook — fixed timestamp for the run. */\n now?: () => number;\n}\n\nexport interface DreamingResult {\n status: \"ok\" | \"skipped\" | \"error\";\n factsBefore: number;\n factsAfter: number;\n duplicatesRemoved: number;\n clustersCreated: number;\n notesWritten: number;\n diaryEntryHash: string | undefined;\n}\n\nexport function runDreamingSweep(options: DreamingOptions): Promise<DreamingResult> {\n return withCwdMutex(`dream:${options.cwd}`, () => runInner(options));\n}\n\nasync function runInner(options: DreamingOptions): Promise<DreamingResult> {\n const now = options.now ?? Date.now;\n const timestampMs = now();\n try {\n const root = options.memoryRoot ?? resolveMemoryRoot(options.cwd);\n const facts = await readFactsFromMarkdown(\n options.cwd,\n options.memoryRoot ? { directory: options.memoryRoot } : undefined,\n );\n if (facts.length === 0) {\n return emptyResult(\"skipped\");\n }\n const dedup = await lightPhase(facts, options.embedding, options.dedupThreshold);\n const rem = await remPhase(dedup.kept, options.embedding, options.clusterThreshold);\n const notesWritten = await writeConsolidatedNotes(root, rem.clusters, timestampMs);\n const result: DreamingResult = {\n status: \"ok\",\n factsBefore: facts.length,\n factsAfter: dedup.kept.length,\n duplicatesRemoved: dedup.duplicatesRemoved,\n clustersCreated: rem.clusters.length,\n notesWritten,\n diaryEntryHash: undefined,\n };\n await appendDiaryEntry(root, {\n timestampMs,\n factsBefore: result.factsBefore,\n factsAfter: result.factsAfter,\n duplicatesRemoved: result.duplicatesRemoved,\n clustersCreated: result.clustersCreated,\n notesWritten: result.notesWritten,\n });\n return result;\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : String(cause);\n diag(`[theokit-sdk] dreaming sweep failed: ${message}\\n`);\n return emptyResult(\"error\");\n }\n}\n\nasync function writeConsolidatedNotes(\n root: MemoryRoot,\n clusters: ReadonlyArray<{ representativeText: string; members: ReadonlyArray<{ text: string }> }>,\n timestampMs: number,\n): Promise<number> {\n if (clusters.length === 0) return 0;\n const notesDir = join(root, \"notes\");\n await mkdir(notesDir, { recursive: true });\n const isoSlug = new Date(timestampMs).toISOString().replace(/[^\\dT]/g, \"-\");\n const file = join(notesDir, `dreamed-${isoSlug}.md`);\n const body = deepPhase(clusters, timestampMs);\n await replaceFileAtomic(file, body);\n return 1;\n}\n\nfunction emptyResult(status: \"skipped\" | \"error\"): DreamingResult {\n return {\n status,\n factsBefore: 0,\n factsAfter: 0,\n duplicatesRemoved: 0,\n clustersCreated: 0,\n notesWritten: 0,\n diaryEntryHash: undefined,\n };\n}\n","/**\n * SDK 2.0 Phase 4 (Stage 4) — Optional peer loader for\n * `@theokit/sdk-memory`.\n *\n * The Memory class public API in `src/memory.ts` keeps its surface\n * stable but routes through sdk-memory when installed. When sdk-memory\n * is NOT installed, methods fall back to sdk-core's legacy\n * `internal/memory/*` implementations — preserving v1.x back-compat.\n *\n * Pattern mirrors sdk-handoff's optional-peer dynamic import: try\n * `await import(\"@theokit/sdk-memory\")` once, cache the result (the\n * module OR `null` for \"definitively missing\"), and let the caller\n * route.\n *\n * Iter 76 (Stage 4 #1): foundation helper for the Memory class\n * delegation refactor. No behavior changes yet — this iter only\n * adds the loader; iter 77+ wires Memory class methods to use it.\n *\n * @internal\n */\n\nimport { diag } from \"../diagnostics.js\";\n/**\n * Minimal structural mirror of the sdk-memory surface this loader\n * exposes to Memory class methods. Keeps the contract pinned even\n * if sdk-memory ships additional exports.\n */\nexport interface SdkMemoryModule {\n /** Mirrors @theokit/sdk-memory's catalog Record. */\n readonly MEMORY_EMBEDDING_ADAPTERS: Readonly<\n Record<\n string,\n {\n readonly id: string;\n readonly defaultModel: string;\n readonly transport: \"local\" | \"remote\";\n // biome-ignore lint/suspicious/noExplicitAny: structural mirror — runtime carries the canonical types\n create(options: any): Promise<any>;\n }\n >\n >;\n\n /** Mirrors @theokit/sdk-memory's runDreamingSweep entrypoint. */\n runDreamingSweep(opts: {\n cwd: string;\n // biome-ignore lint/suspicious/noExplicitAny: structural mirror\n embedding: any;\n dedupThreshold?: number;\n clusterThreshold?: number;\n }): Promise<{\n status: \"ok\" | \"skipped\" | \"error\";\n factsBefore: number;\n factsAfter: number;\n duplicatesRemoved: number;\n clustersCreated: number;\n notesWritten: number;\n }>;\n\n /** Mirrors @theokit/sdk-memory's IndexManager class (static open). */\n readonly IndexManager: {\n open(opts: {\n cwd: string;\n filePath?: string;\n // biome-ignore lint/suspicious/noExplicitAny: structural mirror\n embedding?: any;\n backend?: \"sqlite-vec\" | \"lance\";\n // biome-ignore lint/suspicious/noExplicitAny: structural mirror\n }): Promise<any>;\n };\n\n /** Mirrors @theokit/sdk-memory's migrateSqliteToLance entrypoint (ADR D44). */\n migrateSqliteToLance(opts: {\n cwd: string;\n dryRun?: boolean;\n batchSize?: number;\n logger?: (msg: string) => void;\n }): Promise<{\n countSqlite: number;\n countLance: number;\n validated: boolean;\n sampleComparisons: ReadonlyArray<{ id: string; match: boolean }>;\n lancePath: string;\n committed: boolean;\n }>;\n}\n\nlet cachedAttempt: Promise<SdkMemoryModule | null> | undefined;\nlet forcedAbsentForTests = false;\n\n/**\n * One load attempt, with the two failure shapes reported differently.\n *\n * Split out of {@link tryLoadSdkMemoryPeer} so the memoisation and the loading read separately —\n * the guard, the cache and three outcomes in one closure was over the project's own complexity\n * threshold once the outcomes stopped being \"return null\" three times.\n */\nasync function loadPeer(): Promise<SdkMemoryModule | null> {\n try {\n // Dynamic specifier kept opaque so bundlers can't statically resolve sdk-memory and bake it into\n // a bundle that would require the package to exist at install time.\n const spec = \"@theokit/sdk-memory\";\n const mod = (await import(spec)) as unknown as SdkMemoryModule;\n if (hasExpectedSurface(mod)) return mod;\n // Present but the wrong shape — a version skew, or a bundler that rewrote the entry. This is NOT\n // the same as absent, and it used to report identically.\n diag(\n \"sdk-memory peer loaded but does not expose the expected surface \" +\n \"(runDreamingSweep / MEMORY_EMBEDDING_ADAPTERS / IndexManager / migrateSqliteToLance) — \" +\n \"falling back to the legacy memory path\",\n );\n return null;\n } catch (err) {\n // #174, applied here. `catch { return null; }` is what that issue removed from file-lock.ts, with\n // the cost recorded: a fallback that asserts a cause it never observed sends a consumer to\n // re-check an install that was already correct.\n //\n // Absent is expected and silent — the peer is optional and most installs do not have it.\n // Present-but-unloadable is always worth reporting: a module-format interop failure, a broken\n // native dependency, or a bundler rewrite all land here, and the SDK otherwise falls back to the\n // legacy path saying nothing at all.\n if ((err as { code?: string } | undefined)?.code !== \"ERR_MODULE_NOT_FOUND\") {\n diag(\n `sdk-memory peer is installed but failed to load — falling back to the legacy memory path: ${\n err instanceof Error ? err.message : String(err)\n }`,\n );\n }\n return null;\n }\n}\n\n/** The four surfaces this SDK routes through. Anything less is a version skew, not a peer. */\nfunction hasExpectedSurface(mod: SdkMemoryModule): boolean {\n return (\n typeof mod.runDreamingSweep === \"function\" &&\n mod.MEMORY_EMBEDDING_ADAPTERS !== undefined &&\n mod.IndexManager !== undefined &&\n typeof mod.migrateSqliteToLance === \"function\"\n );\n}\n\n/**\n * Attempt to load `@theokit/sdk-memory`. Returns the module on\n * success, `null` on definitive absence. Result is memoized so\n * repeated calls during agent runtime don't re-pay the dynamic\n * import cost.\n *\n * @internal\n */\nexport function tryLoadSdkMemoryPeer(): Promise<SdkMemoryModule | null> {\n if (forcedAbsentForTests) return Promise.resolve(null);\n if (cachedAttempt !== undefined) return cachedAttempt;\n cachedAttempt = loadPeer();\n return cachedAttempt;\n}\n\n/**\n * Test-only: reset the memoized loader state so an integration test\n * can probe both the \"peer present\" and \"peer absent\" code paths.\n *\n * @internal\n */\nexport function resetSdkMemoryPeerCacheForTests(): void {\n cachedAttempt = undefined;\n forcedAbsentForTests = false;\n}\n\n/**\n * Test-only: force the loader to behave as if sdk-memory is NOT\n * installed, even when the workspace setup makes it resolvable. Lets\n * tests exercise the legacy fallback code path inside sdk-core's\n * Memory class methods + migrate wrapper without uninstalling the\n * peer.\n *\n * Pair with `resetSdkMemoryPeerCacheForTests()` in afterEach to undo.\n *\n * @internal\n */\nexport function forceSdkMemoryPeerAbsentForTests(): void {\n cachedAttempt = undefined;\n forcedAbsentForTests = true;\n}\n","import { MEMORY_EMBEDDING_ADAPTERS } from \"./internal/memory/adapters/catalog.js\";\nimport { runDreamingSweep as runDreamingSweepInternal } from \"./internal/memory/dreaming/run.js\";\nimport { tryLoadSdkMemoryPeer } from \"./internal/memory/sdk-memory-peer-loader.js\";\nimport { type MemoryRoot, resolveMemoryRoot } from \"./internal/memory/storage/memory-root.js\";\n\n/**\n * Public handle to an open memory index. Mirrors the internal `MemoryIndex`\n * contract structurally; defined here (NOT re-exported from internal/) so\n * the public DTS surface does not pull the internal/runtime cycle that\n * trips rollup-plugin-dts.\n *\n * @public\n */\nexport interface MemoryIndexHandle {\n sync(): Promise<{\n filesScanned: number;\n filesUpdated: number;\n chunksWritten: number;\n chunksEmbedded: number;\n /**\n * Whether this backend actually walked a corpus. `false` on the Lance backend, which is a\n * vector store fed by explicit writes and has no corpus — its zero counts mean \"not applicable\",\n * not \"nothing to reindex\". Read this before treating the counts as a measurement.\n */\n supported: boolean;\n }>;\n search(\n query: string,\n options?: {\n maxResults?: number;\n minScore?: number;\n sources?: ReadonlyArray<\"memory\" | \"sessions\" | \"wiki\">;\n },\n ): Promise<\n ReadonlyArray<{\n path: string;\n startLine: number;\n endLine: number;\n score: number;\n textScore: number;\n vectorScore?: number;\n snippet: string;\n source: \"memory\" | \"sessions\" | \"wiki\";\n citation: string;\n }>\n >;\n status(): {\n backend: \"fts-only\" | \"hybrid\";\n filesIndexed: number;\n chunksIndexed: number;\n lastSyncMs?: number;\n /**\n * Whether `filesIndexed` / `chunksIndexed` were measured. `false` on the Lance backend, whose\n * store is async while `status()` is not — the zeros there are placeholders, so\n * `chunksIndexed > 0` is not a valid test for \"is the index populated\".\n */\n countsExact: boolean;\n };\n close(): Promise<void> | void;\n}\n\n/**\n * Inputs for {@link Memory.runDreamingSweep}.\n *\n * `embedding` is required and has no default: the sweep scores cosine similarity between facts, so\n * without real embeddings there is nothing to dedup or cluster on. Both thresholds are cosine\n * similarity in [0, 1] and default to `0.95` for dedup and `0.75` for clustering — dedup is the\n * stricter of the two because merging two facts that were merely related is a data loss, while\n * failing to cluster them only costs a note.\n *\n * @public\n */\nexport interface DreamingSweepOptions {\n /** Workspace cwd holding `.theokit/memory/`. */\n cwd: string;\n /**\n * Absolute path (or `~/`-prefixed) of the memory root to sweep, when the agent that wrote it set\n * `memory.directory`. Defaults to `<cwd>/.theokit/memory`.\n */\n directory?: string;\n /**\n * Embedding provider for semantic dedup + clustering. Required — dreaming\n * relies on real embeddings to score cosine similarity. Supported providers:\n * `\"openai\"`, `\"mistral\"`, `\"openrouter\"`, `\"voyage\"`, `\"deepinfra\"`,\n * `\"ollama\"` (local, ADR D183).\n */\n embedding: {\n provider: \"openai\" | \"mistral\" | \"openrouter\" | \"voyage\" | \"deepinfra\" | \"ollama\";\n model?: string;\n };\n /** Cosine-similarity threshold for the dedup phase. Default `0.95`. */\n dedupThreshold?: number;\n /** Cosine-similarity threshold for the clustering phase. Default `0.75`. */\n clusterThreshold?: number;\n}\n\n/**\n * What one dreaming sweep did.\n *\n * `status` is `\"skipped\"` when the workspace held no facts to work on and `\"error\"` when the sweep\n * failed; both come back with every counter at zero, so check `status` before reading a zero as\n * \"there was nothing to consolidate\". A failure is reported through this field rather than as a\n * rejection, which means a caller that only awaits the promise never learns the sweep did nothing.\n * `factsBefore` and `factsAfter` bracket the run, which is the pair to compare when you want to\n * know whether the sweep was worth running rather than how many operations it performed.\n *\n * @public\n */\nexport interface DreamingSweepResult {\n status: \"ok\" | \"skipped\" | \"error\";\n factsBefore: number;\n factsAfter: number;\n duplicatesRemoved: number;\n clustersCreated: number;\n notesWritten: number;\n}\n\n/**\n * Options for `Memory.openIndex`. Mirrors the internal `OpenIndexOptions`\n * but using only public types from the SDK surface.\n *\n * @public\n */\nexport interface OpenMemoryIndexOptions {\n /** Workspace cwd holding `.theokit/memory/`. */\n cwd: string;\n /** Override storage file path (SQLite) OR storage directory (Lance). */\n filePath?: string;\n /**\n * Embedding runtime — REQUIRED for `backend: \"lance\"`, optional for\n * `\"sqlite-vec\"` (when omitted, SQLite runs FTS-only without vector\n * recall).\n */\n embedding?: {\n provider: \"openai\" | \"mistral\" | \"openrouter\" | \"voyage\" | \"deepinfra\" | \"ollama\";\n model?: string;\n };\n /** Default `\"sqlite-vec\"`. Set to `\"lance\"` to opt into LanceDB (peer dep). */\n backend?: \"sqlite-vec\" | \"lance\";\n}\n\n/**\n * Memory operations that run OUTSIDE an agent turn.\n *\n * Everything here is reachable without `Agent.create({ memory: ... })`, which is the point: opening\n * an index directly is how a CLI or a maintenance job inspects or rebuilds what the agent will\n * later read, and the dreaming sweep is maintenance that no `send()` triggers.\n *\n * Both operations route through the `@theokit/sdk-memory` peer package when it is installed and\n * fall back to the in-tree implementation when it is not. The fallback is not a degraded mode —\n * behaviour and thrown errors match — so consumers do not branch on which path ran.\n *\n * @public\n */\nexport const Memory = {\n /**\n * Open a memory index. Dispatches to SQLite-vec (default, zero deps) or\n * LanceDB (opt-in via `backend: \"lance\"`, requires `@lancedb/lancedb`\n * peer dep + an embedding runtime).\n *\n * Returns a `MemoryIndex` with `sync()`, `search(query, opts?)`,\n * `status()`, and `close()`. Use this when you want a direct index\n * handle outside of `Agent.create({ memory: ... })`.\n *\n * @throws ConfigurationError({code:\"invalid_memory_backend\"}) for typos\n * like `\"lancedb\"`.\n * @throws ConfigurationError({code:\"lance_requires_embedding\"}) when\n * `backend: \"lance\"` is requested without `embedding`.\n * @throws ConfigurationError({code:\"lance_backend_unavailable\"}) when\n * `backend: \"lance\"` is requested but the peer dep is absent.\n *\n * @public\n */\n async openIndex(opts: OpenMemoryIndexOptions): Promise<MemoryIndexHandle> {\n // SDK 2.0 Phase 4 (Stage 4, iter 77): if @theokit/sdk-memory is\n // installed, route through it. Otherwise fall back to the legacy\n // internal path. Behavior + thrown errors are byte-equivalent\n // because sdk-memory's IndexManager + MEMORY_EMBEDDING_ADAPTERS\n // are hybrid copies of sdk-core's internals (iter 44-75).\n const peer = await tryLoadSdkMemoryPeer();\n const openArgs = buildIndexOpenArgs(opts, undefined);\n if (peer !== null) {\n openArgs.embedding = await resolveEmbedding(opts.embedding, peer.MEMORY_EMBEDDING_ADAPTERS);\n // biome-ignore lint/suspicious/noExplicitAny: peer is dynamically loaded — structural compat ensured by sdk-memory\n return (await peer.IndexManager.open(openArgs as any)) as MemoryIndexHandle;\n }\n // Fallback path — sdk-memory peer absent; use the internal\n // implementation (v1.x behavior preserved).\n // Lazy import to avoid pulling internal/runtime types into the public\n // DTS surface (rollup-plugin-dts trips on a pre-existing cycle in\n // types/agent.ts ↔ fork-agent.ts when reached transitively).\n const { IndexManager } = await import(\"./internal/memory/index-manager.js\");\n openArgs.embedding = await resolveEmbedding(opts.embedding, MEMORY_EMBEDDING_ADAPTERS);\n // Cast: structural-compat (internal MemoryIndex matches MemoryIndexHandle).\n // biome-ignore lint/suspicious/noExplicitAny: embedding is resolved from the same catalog — types match at runtime\n return (await IndexManager.open(openArgs as any)) as MemoryIndexHandle;\n },\n\n /**\n * Run a dreaming sweep: dedup near-duplicate facts, cluster thematically\n * related ones, and write a consolidated note + diary entry.\n *\n * @public\n */\n async runDreamingSweep(opts: DreamingSweepOptions): Promise<DreamingSweepResult> {\n // SDK 2.0 Phase 4 (Stage 4, iter 77): route through sdk-memory\n // when installed; fall back to legacy internal/ path otherwise.\n const peer = await tryLoadSdkMemoryPeer();\n const catalog = peer !== null ? peer.MEMORY_EMBEDDING_ADAPTERS : MEMORY_EMBEDDING_ADAPTERS;\n const sweepArgs = await buildDreamingSweepArgs(opts, catalog);\n const result =\n peer !== null\n ? // biome-ignore lint/suspicious/noExplicitAny: peer is dynamically loaded — structural compat ensured by sdk-memory\n await peer.runDreamingSweep(sweepArgs as any)\n : // biome-ignore lint/suspicious/noExplicitAny: legacy path accepts the same shape\n await runDreamingSweepInternal(sweepArgs as any);\n return toDreamingSweepResult(result);\n },\n};\n\n// ---------------------------------------------------------------------------\n// Internal helpers — deduplicate patterns shared across peer + legacy paths.\n// ---------------------------------------------------------------------------\n\n/** Catalog shape shared between sdk-memory peer and local MEMORY_EMBEDDING_ADAPTERS. */\ninterface EmbeddingCatalog {\n [provider: string]: { create(opts: Record<string, unknown>): Promise<unknown> } | undefined;\n}\n\n/**\n * Resolve an embedding runtime from a provider catalog. Throws the canonical\n * \"Unknown embedding provider\" error when the provider is not in the catalog.\n */\nasync function resolveEmbedding(\n embeddingOpts: { provider: string; model?: string } | undefined,\n catalog: EmbeddingCatalog,\n): Promise<unknown> {\n if (embeddingOpts === undefined) return undefined;\n const adapter = catalog[embeddingOpts.provider];\n if (adapter === undefined) {\n throw new Error(\n `Unknown embedding provider \"${embeddingOpts.provider}\". Supported: ${Object.keys(catalog).join(\", \")}.`,\n );\n }\n return adapter.create(embeddingOpts.model !== undefined ? { model: embeddingOpts.model } : {});\n}\n\ninterface IndexOpenArgs {\n cwd: string;\n filePath?: string;\n embedding?: unknown;\n backend?: \"sqlite-vec\" | \"lance\";\n}\n\n/** Build the args object for IndexManager.open from user-facing options. */\nfunction buildIndexOpenArgs(opts: OpenMemoryIndexOptions, embedding: unknown): IndexOpenArgs {\n return {\n cwd: opts.cwd,\n ...(opts.filePath !== undefined ? { filePath: opts.filePath } : {}),\n ...(embedding !== undefined ? { embedding } : {}),\n ...(opts.backend !== undefined ? { backend: opts.backend } : {}),\n };\n}\n\ninterface DreamingSweepArgs {\n cwd: string;\n /** Resolved once here so the facts, the notes and the diary all land in one place (#463). */\n memoryRoot: MemoryRoot;\n embedding: unknown;\n dedupThreshold?: number;\n clusterThreshold?: number;\n}\n\n/** Build args for runDreamingSweep from user-facing options + resolved embedding. */\nasync function buildDreamingSweepArgs(\n opts: DreamingSweepOptions,\n catalog: EmbeddingCatalog,\n): Promise<DreamingSweepArgs> {\n const runtime = await resolveEmbedding(opts.embedding, catalog);\n return {\n cwd: opts.cwd,\n memoryRoot: resolveMemoryRoot(opts.cwd, { directory: opts.directory }),\n embedding: runtime,\n ...(opts.dedupThreshold !== undefined ? { dedupThreshold: opts.dedupThreshold } : {}),\n ...(opts.clusterThreshold !== undefined ? { clusterThreshold: opts.clusterThreshold } : {}),\n };\n}\n\n/** Normalize a raw dreaming sweep result into the public DreamingSweepResult shape. */\nfunction toDreamingSweepResult(result: {\n status: string;\n factsBefore: number;\n factsAfter: number;\n duplicatesRemoved: number;\n clustersCreated: number;\n notesWritten: number;\n}): DreamingSweepResult {\n return {\n status: result.status as DreamingSweepResult[\"status\"],\n factsBefore: result.factsBefore,\n factsAfter: result.factsAfter,\n duplicatesRemoved: result.duplicatesRemoved,\n clustersCreated: result.clustersCreated,\n notesWritten: result.notesWritten,\n };\n}\n","/**\n * Runtime helpers for `MemoryAdapter` (T1.1, ADR D141).\n *\n * Kept separate from `types/memory-adapter.ts` so the types module\n * stays import-free of runtime code (dep-cruise rule\n * `types-dont-import-runtime`). Adapter authors call `mkMemoryId` to\n * construct a branded id and `extractRawId` to unwrap with cross-adapter\n * safety (EC-B).\n *\n * @public\n */\n\nimport { MemoryAdapterError } from \"./errors.js\";\nimport type { MemoryId } from \"./types/memory-adapter.js\";\n\n/**\n * Construct a branded `MemoryId` for an adapter. Embeds the adapter\n * identifier so `extractRawId` can reject ids minted by other adapters.\n *\n * @public\n */\nexport function mkMemoryId(adapterId: string, rawId: string): MemoryId {\n return `${adapterId}:${rawId}` as MemoryId;\n}\n\n/**\n * Extract the raw provider id from a `MemoryId`, enforcing that the\n * prefix matches `expectedAdapterId`. Throws `MemoryAdapterError(code:\n * \"invalid_input\")` on mismatch — prevents `mem0.delete(supermemoryId)`\n * from accidentally deleting unrelated data (EC-B).\n *\n * @public\n */\nexport function extractRawId(id: MemoryId, expectedAdapterId: string): string {\n const prefix = `${expectedAdapterId}:`;\n if (!id.startsWith(prefix)) {\n const sourcePrefix = id.split(\":\", 1)[0] ?? \"<malformed>\";\n throw new MemoryAdapterError(\n `MemoryId belongs to a different adapter (expected \"${expectedAdapterId}\", got \"${sourcePrefix}\")`,\n { adapterId: expectedAdapterId, code: \"invalid_input\" },\n );\n }\n return id.slice(prefix.length);\n}\n","// Public API for memory migration (ADR D44).\n//\n// This file is the public re-export wrapper for the internal implementation.\n// Declaring types here (rather than re-exporting from internal/) avoids a\n// known rollup-dts resolution quirk with internal/ paths.\n//\n// Iter 78 (SDK 2.0 Phase 4 Stage 4 #3): routes through\n// `@theokit/sdk-memory` when the peer is installed. Falls back to\n// the legacy `internal/memory/migrate-sqlite-to-lance.js` when the\n// peer is absent. Both paths share byte-equivalent runtime behavior\n// because sdk-memory's copy is the iter 71 source-move (atomic\n// rename commit, NFC sample compare, D70 redaction logger wrap).\n\nimport { migrateSqliteToLance as _migrateSqliteToLance } from \"./internal/memory/migrate-sqlite-to-lance.js\";\nimport { tryLoadSdkMemoryPeer } from \"./internal/memory/sdk-memory-peer-loader.js\";\n\n/**\n * Options for {@link migrateSqliteToLance}.\n *\n * @public\n */\nexport interface MigrateOptions {\n cwd: string;\n dryRun?: boolean;\n batchSize?: number;\n logger?: (msg: string) => void;\n}\n\n/**\n * Outcome of {@link migrateSqliteToLance}.\n *\n * @public\n */\nexport interface MigrateResult {\n countSqlite: number;\n countLance: number;\n validated: boolean;\n sampleComparisons: ReadonlyArray<{ id: string; match: boolean }>;\n lancePath: string;\n committed: boolean;\n}\n\n/**\n * Migrate the Memory index from SQLite to LanceDB. ADR D44.\n *\n * @public\n */\nexport async function migrateSqliteToLance(options: MigrateOptions): Promise<MigrateResult> {\n // SDK 2.0 Phase 4 Stage 4 (iter 78): peer routing.\n const peer = await tryLoadSdkMemoryPeer();\n if (peer !== null) {\n return peer.migrateSqliteToLance(options);\n }\n return _migrateSqliteToLance(options);\n}\n","/**\n * `PermissionEngine` — first-match permission rules for tool invocations.\n *\n * Evaluates a tool name (and optional arguments, #55) against an ordered list\n * of rules. First matching rule wins; when no rule matches the `defaultAction`\n * is returned. #55 — the default is now `\"ask\"` (FAIL-CLOSED): a permission\n * engine that cannot positively allow must not silently allow. Opt back into\n * the previous fail-open behavior with `{ defaultAction: \"allow\" }`.\n */\n\nexport type PermissionAction = \"allow\" | \"deny\" | \"ask\";\n\n/**\n * SE1 — a per-run permission MODE that adjusts the rule-engine verdict globally.\n * A PURE post-processor of the verdict (no tool-safety metadata needed, so it fits\n * a bring-your-own-tools runtime). Grounded in a peer project (plan agent = deny-all,\n * `dangerously-skip-permissions`) + Codex (`AskForApproval`: `OnRequest` default,\n * `Never`, `UnlessTrusted`). See {@link applyMode} for the exact table.\n *\n * - `default` — verdict as-is (rules decide; unmatched ⇒ `ask`, fail-closed).\n * - `plan` — read-only: `allow` rules pass, everything else ⇒ `deny` (mutations blocked).\n * NOTE: `plan` gates on the resolved verdict, so an engine configured with\n * `{ defaultAction: \"allow\" }` still yields `allow` for UNMATCHED calls under\n * `plan` — pair `plan` with the default fail-closed engine (`defaultAction: \"ask\"`)\n * for full read-only behavior.\n * - `acceptEdits` — auto-approve the UNMATCHED verdict, but STILL honor an explicit\n * `ask` rule (a caller gates a risky tool with an ask rule). Codex `UnlessTrusted`.\n * - `bypass` (alias `bypassPermissions`, the Anthropic-exact name) — everything ⇒\n * `allow` EXCEPT an explicit `deny` rule. Never asks. a peer project\n * `dangerously-skip-permissions` / Codex `Never` / Anthropic `bypassPermissions`.\n */\nimport type { PermissionMode } from \"./types/agent-prims.js\";\n\nexport type { PermissionMode };\n\n/**\n * SE1 — apply a {@link PermissionMode} to a rule-engine verdict. Pure.\n *\n * `explicit` is `true` when the verdict came from a rule that matched by name (and\n * args), `false` when it is the fail-closed default for an unmatched call. The flag\n * is load-bearing for `acceptEdits`, which auto-approves the unmatched default but\n * keeps honoring an explicit `ask` rule (unlike `bypass`, which allows even that).\n *\n * INVARIANT (both a peer project + Codex): an explicit `deny` is immune to EVERY\n * auto-approve mode — `bypass`/`acceptEdits` never un-deny.\n */\nexport function applyMode(\n verdict: PermissionAction,\n mode: PermissionMode,\n explicit: boolean,\n): PermissionAction {\n // (a) explicit deny is terminal under every mode — fail-closed.\n if (verdict === \"deny\") return \"deny\";\n switch (mode) {\n case \"default\":\n return verdict;\n case \"plan\":\n // read-only: only allow rules pass; ask + unmatched ⇒ deny.\n return verdict === \"allow\" ? \"allow\" : \"deny\";\n case \"acceptEdits\":\n // (b) auto-approve the unmatched default; honor an explicit ask rule.\n if (verdict === \"ask\") return explicit ? \"ask\" : \"allow\";\n return verdict; // allow stays allow\n case \"bypass\":\n case \"bypassPermissions\":\n // everything that survived the deny check ⇒ allow (never asks).\n return \"allow\";\n }\n}\n\n/**\n * #55 — an argument matcher. A rule with `args` gates on the tool's argument\n * VALUES, not just its name: an exact string, a RegExp (tested against the\n * stringified value), or a predicate. Every declared arg must match for the\n * rule to apply — so `{ tool: \"shell\", args: { command: /rm\\s+-rf/ } }` denies\n * a destructive shell call while leaving `ls` to fall through.\n */\nexport type ArgMatcher = string | RegExp | ((value: unknown) => boolean);\n\n/**\n * One entry in a {@link PermissionEngine}'s ordered rule list.\n *\n * Order is the semantics. The engine walks the list and the first rule whose `tool` matches — and\n * whose `args` matchers all pass, when it declares any — decides; nothing after it is consulted. Put\n * the narrow rules first: a catch-all `tool` RegExp placed above a specific deny makes that deny\n * unreachable, and nothing warns you.\n *\n * `args` is what lets one tool name resolve differently depending on what it is asked to do —\n * `{ tool: \"shell\", args: { command: /rm\\s+-rf/ }, action: \"deny\" }` blocks the destructive call and\n * leaves `ls` to fall through to a later rule. Every declared matcher must pass.\n *\n * **A rule that declares an argument the call did not supply does not match**, whatever form the\n * matcher takes — string, RegExp or predicate. The predicate is not invoked with `undefined`; the\n * guard runs first, for every matcher form. Evaluation continues to the next rule.\n *\n * That was not always true, and the fix is the reason this paragraph is explicit (#367). A predicate\n * used to be called anyway, so `(v) => v !== \"prod\"` returned true for a missing argument and an\n * ALLOW rule authorized a call that supplied nothing, while `(v) => v.includes(\"rm\")` threw a\n * TypeError out of the permission gate. This docblock told consumers to guard every predicate by\n * hand for months after `argMatches` stopped needing it — you do not have to.\n *\n * A rule that matches yields an EXPLICIT verdict, and that is what makes it survive a permissive\n * `PermissionMode`: `acceptEdits` auto-approves the unmatched default but still honours an explicit\n * `ask` rule, and an explicit `deny` is immune to every mode, `bypass` included.\n */\nexport interface PermissionRule {\n /** Tool name (exact string) or pattern (RegExp). */\n tool: string | RegExp;\n /**\n * #55 — optional per-argument matchers. When present, the rule matches only\n * if the tool name matches AND every declared arg predicate matches the\n * corresponding call argument. A missing/undefined arg fails its predicate\n * (the rule does not match) — never throws.\n */\n args?: Record<string, ArgMatcher>;\n /** Action to take when rule matches. */\n action: PermissionAction;\n}\n\n/** Options for {@link PermissionEngine}. */\nexport interface PermissionEngineOptions {\n /**\n * Action when no rule matches. #55 — default is now `\"ask\"` (fail-closed): a\n * permission engine that cannot positively allow must not silently allow.\n * Pass `\"allow\"` to restore the previous fail-open behavior.\n */\n readonly defaultAction?: PermissionAction;\n}\n\nfunction argMatches(matcher: ArgMatcher, value: unknown): boolean {\n // The guard comes FIRST, for every matcher form including a predicate (#367). It used to sit\n // below the function branch, so a declared predicate was invoked with `undefined` — and both\n // directions of that were wrong:\n //\n // allow rule `(v) => v !== \"prod\"` returns true for undefined, so a call that supplied NO\n // argument produced an EXPLICIT allow — a matcher written to narrow, widening.\n // deny rule `(v) => v.includes(\"rm\")` raised TypeError out of the permission gate, which\n // is not a denial but an unhandled failure on the path that decides authorization.\n //\n // A rule that declares an argument is a rule about that argument. A call that omitted it has\n // not satisfied the rule, whatever shape the matcher takes.\n if (value === undefined) return false;\n if (typeof matcher === \"function\") return matcher(value);\n if (matcher instanceof RegExp) {\n // Reset `lastIndex` so a global/sticky-flag regex (`/x/g`) does not carry\n // state across `.test()` calls — otherwise the same rule would alternate\n // verdicts on identical repeated calls (non-deterministic authorization).\n matcher.lastIndex = 0;\n return matcher.test(String(value));\n }\n return matcher === value;\n}\n\n/**\n * Ordered first-match permission rules for tool invocations — the policy object you hand to\n * `PermissionPlugin.create()` to have it enforced.\n *\n * On its own it enforces nothing. `evaluate(toolName, args, mode)` is a pure function returning\n * `\"allow\" | \"deny\" | \"ask\"`, and no part of the SDK calls it until the engine is wrapped in a plugin\n * and that plugin is registered on an agent. The plugin is where a verdict becomes behaviour: `deny`\n * blocks the tool call, `allow` passes it through, and `ask` is routed to the host's `canUseTool`\n * gate — with no gate configured, `ask` blocks. So constructing an engine and never registering it\n * is a policy that does nothing, which is the mistake worth knowing about first.\n *\n * It is fail-closed by default: a call no rule matches resolves to `\"ask\"`, not `\"allow\"`, so a tool\n * the rules never mention needs a human — or an explicit `{ defaultAction: \"allow\" }` — before it\n * runs. Keep that default if you intend to use `PermissionMode: \"plan\"` for read-only behaviour,\n * because `plan` gates on the RESOLVED verdict: an engine built with `defaultAction: \"allow\"` still\n * allows every unmatched call under `plan`.\n *\n * The rules array is stored by reference and walked afresh on every `evaluate` call. Mutating the\n * array you passed in therefore changes the policy of a live engine; build a new engine when you\n * want a policy change to be a deliberate, visible event.\n */\nexport class PermissionEngine {\n private readonly defaultAction: PermissionAction;\n\n constructor(\n private readonly rules: PermissionRule[],\n options: PermissionEngineOptions = {},\n ) {\n // #55 — fail-closed by default.\n this.defaultAction = options.defaultAction ?? \"ask\";\n }\n\n /**\n * Evaluate a tool name (and optional arguments) against the rules. First\n * match wins; falls back to the configured `defaultAction` (default `\"ask\"`,\n * fail-closed) when no rule matches. #55 — a rule with `args` gates on the\n * argument values, so the same tool name can resolve to different actions\n * depending on what it is asked to do.\n */\n evaluate(\n toolName: string,\n args?: Record<string, unknown>,\n mode: PermissionMode = \"default\",\n ): PermissionAction {\n for (const rule of this.rules) {\n const nameMatches =\n typeof rule.tool === \"string\" ? rule.tool === toolName : rule.tool.test(toolName);\n if (!nameMatches) continue;\n if (rule.args !== undefined && !this.#argsMatch(rule.args, args)) continue;\n // SE1 — a matched rule is an EXPLICIT verdict; apply the mode with explicit=true.\n return applyMode(rule.action, mode, true);\n }\n // SE1 — no rule matched: the default is NOT explicit (explicit=false), so\n // `acceptEdits` auto-approves it while still honoring explicit `ask` rules above.\n return applyMode(this.defaultAction, mode, false);\n }\n\n #argsMatch(\n matchers: Record<string, ArgMatcher>,\n args: Record<string, unknown> | undefined,\n ): boolean {\n const call = args ?? {};\n for (const [key, matcher] of Object.entries(matchers)) {\n if (!argMatches(matcher, call[key])) return false;\n }\n return true;\n }\n}\n","/**\n * M7-5 — `createPermissionPlugin`: wire a {@link PermissionEngine} into the\n * `definePlugin` `pre_tool_call` veto seam. This is the canonical exemplar that\n * gives `PermissionEngine` a real caller (it was previously exported-but-unwired):\n * on each tool call the engine's verdict maps to the veto contract —\n * `\"deny\"` -> block, `\"ask\"` -> the caller's `onAsk` resolver (or block, fail-closed),\n * `\"allow\"` -> pass.\n *\n * @public\n */\n\nimport { definePlugin } from \"./internal/plugins/index.js\";\nimport type { Plugin, PreToolCallDecision } from \"./internal/plugins/types.js\";\nimport type { PermissionEngine, PermissionMode } from \"./permission-engine.js\";\n\n/**\n * SE1 — context passed to the {@link PermissionGate}. Intentionally minimal for\n * SE1; `agentId`/`runId` (for audit logging) are a documented follow-up — they are\n * available on the raw `pre_tool_call` context and can be threaded in a later slice.\n */\nexport interface PermissionGateContext {\n /** The tool being gated. */\n readonly toolName: string;\n /** The active permission mode for this run. */\n readonly mode: PermissionMode;\n}\n\n/**\n * SE1 — the resolution of an `\"ask\"` verdict by the host gate. Fail-closed: an\n * absent gate, a throwing gate, and a `\"deny\"` decision all block. Arg rewrite\n * (`updatedInput`) is intentionally NOT supported yet — the `pre_tool_call` seam\n * is veto-only (`{ block, message }`); a future enhancement can extend it.\n */\nexport type PermissionGateDecision =\n | { readonly behavior: \"allow\" }\n | { readonly behavior: \"deny\"; readonly message?: string };\n\n/**\n * SE1 — the enriched `canUseTool` gate (the Anthropic-parity shape). Invoked ONLY\n * on an `\"ask\"` verdict, it receives the tool name, its input args, and the run\n * {@link PermissionGateContext}, and resolves to allow/deny. May be async (a real\n * gate can prompt a human — the `pre_tool_call` seam awaits it).\n */\nexport type PermissionGate = (\n toolName: string,\n input: Record<string, unknown>,\n ctx: PermissionGateContext,\n) => PermissionGateDecision | Promise<PermissionGateDecision>;\n\n/** Options for {@link createPermissionPlugin}. */\nexport interface PermissionPluginOptions {\n /** Plugin name (default `\"permission-engine\"`). */\n readonly name?: string;\n /**\n * SE1 — the per-run {@link PermissionMode}. Threaded into `engine.evaluate`, so\n * `bypass` auto-allows the ask verdict (gate never consulted), `plan` blocks\n * mutations, etc. An explicit `deny` rule is immune to every mode. Default\n * `\"default\"` (rules decide; unmatched ⇒ fail-closed ask).\n */\n readonly mode?: PermissionMode;\n /**\n * SE1 — the enriched gate for the `\"ask\"` verdict. Preferred over {@link onAsk}.\n * Absent gate on an `ask` verdict ⇒ fail-closed block.\n */\n readonly canUseTool?: PermissionGate;\n /**\n * @deprecated since SE1 — use {@link canUseTool}, which receives `(toolName,\n * input, ctx)` and returns a typed decision. Honored only when `canUseTool` is\n * absent. Returns a veto (`{block,message}`) to deny or `undefined` to allow.\n */\n readonly onAsk?: (toolName: string) => PreToolCallDecision | undefined;\n}\n\n/**\n * Resolve an `\"ask\"` verdict via the gate (fail-closed). Extracted from the\n * register handler to keep its cognitive complexity in budget. Prefers\n * `canUseTool`; falls back to the deprecated `onAsk`; blocks when neither exists.\n */\nasync function resolveAsk(\n opts: PermissionPluginOptions,\n name: string,\n args: Record<string, unknown>,\n mode: PermissionMode,\n): Promise<PreToolCallDecision | undefined> {\n if (opts.canUseTool !== undefined) {\n let decision: PermissionGateDecision;\n try {\n decision = await opts.canUseTool(name, args, { toolName: name, mode });\n } catch {\n // Fail-closed: a gate that throws must not silently allow.\n return { block: true, message: `permission gate error (fail-closed): ${name}` };\n }\n // Fail-CLOSED (allow-list): only an explicit `allow` passes. Any other value\n // — `deny`, a malformed/undefined return from a JS consumer, a wrong-cased\n // behavior — blocks, so the gate can never silently allow on a bad decision.\n return decision?.behavior === \"allow\"\n ? undefined\n : { block: true, message: decision?.message ?? `denied: ${name}` };\n }\n // Deprecated back-compat: honor onAsk (undefined = allow). Fail-closed (block)\n // only when NEITHER a gate nor onAsk was supplied.\n return opts.onAsk ? opts.onAsk(name) : { block: true, message: `requires approval: ${name}` };\n}\n\n/**\n * Build a `general` plugin that vetoes tool calls per the engine's verdict, under\n * the configured {@link PermissionMode}, resolving `ask` via the {@link canUseTool}\n * gate. Register it on an agent's plugin manager (same as the ACP permission plugin).\n */\nfunction createPermissionPlugin(\n engine: PermissionEngine,\n opts: PermissionPluginOptions = {},\n): Plugin {\n return definePlugin({\n name: opts.name ?? \"permission-engine\",\n version: \"1.0.0\",\n kind: \"general\",\n register(ctx) {\n ctx.on(\"pre_tool_call\", async (rawCtx) => {\n const { name, args, permissionMode } = rawCtx as {\n name: string;\n args: Record<string, unknown>;\n permissionMode?: PermissionMode;\n };\n // SE1 — precedence: the RUN's mode (threaded from `SendOptions`/`AgentOptions`\n // via the pre_tool_call context) wins over the plugin's construction-time\n // default. `default` when neither is set.\n const mode: PermissionMode = permissionMode ?? opts.mode ?? \"default\";\n // #55 — args gate rules on the command/args, not just the tool name.\n // SE1 — the mode adjusts the verdict (bypass/plan/acceptEdits); an explicit\n // `deny` rule is immune to every auto-approve mode.\n const action = engine.evaluate(name, args, mode);\n if (action === \"deny\") {\n return { block: true, message: `denied by permission engine: ${name}` };\n }\n if (action === \"ask\") return resolveAsk(opts, name, args, mode);\n return undefined;\n });\n },\n });\n}\n\n/** SE36 — `PermissionPlugin.create` replaces `createPermissionPlugin` (ADR 0015). @public */\nexport class PermissionPlugin {\n private constructor() {}\n static create(engine: PermissionEngine, opts: PermissionPluginOptions = {}): Plugin {\n return createPermissionPlugin(engine, opts);\n }\n}\n","/**\n * Load a project's `.env` without letting it move the credential store or switch off a trust\n * decision.\n *\n * `process.loadEnvFile()` reads the PROJECT's `.env` into `process.env`. For a provider key that is\n * exactly right and is the documented way to configure a scaffolded product. For the handful of\n * variables that decide WHERE credentials live and WHAT is trusted it is a hole: a cloned\n * repository is untrusted input, and a `.env` inside it is untrusted input the runtime is about to\n * treat as configuration.\n *\n * Concretely, without this guard a repository shipping\n *\n * ```\n * THEOKIT_AUTH_HOME=/tmp/attacker-store\n * ```\n *\n * redirects the credential store the moment the product starts in that directory — before any\n * trust prompt, because locating the store is what happens first.\n *\n * ## Why it lives here\n *\n * The scaffolding template (`create-theokit`, TUI surface) calls `process.loadEnvFile()` with no\n * guard, so every product generated from it starts exposed. One consumer found this and fixed it in\n * ~30 lines of its own. A defence each consumer has to rediscover is a defence most will not have,\n * and this one is invisible when missing: nothing fails, the store simply moves.\n *\n * ## Why the set is named\n *\n * A convention — \"anything ending in `_HOME`\", \"anything with TRUST in it\" — silently changes\n * meaning as variables are added, in the direction of accidentally sovereign or accidentally not.\n * The list is explicit so that making a variable sovereign is a deliberate act, and so a reader can\n * see the security boundary without grepping for it.\n *\n * @public\n */\n\n/**\n * Variables a project-scoped source may never set. Each either locates the credential store, names\n * the config directory that is read as configuration, or carries a trust decision.\n *\n * `THEOKIT_API_KEY` is deliberately ABSENT. A project supplying its own provider key through `.env`\n * is the documented, intended path — treating it as sovereign would break every scaffolded product\n * to defend nothing, since a key the project supplies is a key the project already has.\n *\n * @public\n */\n// `THEOKIT_DIR_NAME` was listed here until #410, described as naming the project config directory.\n// It was never read — `paths.ts` hardcoded the literal — so the entry defended a variable that\n// decided nothing, and the description told a consumer they could point the SDK's config directory\n// elsewhere. Removed rather than implemented: the one concrete use anyone had for it (pointing at\n// `.claude` to share a layout with the Claude Code CLI) is now served by `projectConfigRoots()`,\n// which reads BOTH directories with no variable involved. Implementing the knob today would add a\n// public surface whose only motivating case had already been solved a better way.\n//\n// A `//` block, not a docblock: this is history about a REMOVED entry, and as JSDoc it stranded the\n// documentation for the constant below and would have shipped in its place.\nexport const SOVEREIGN_ENV_KEYS = [\n /** Locates the SDK home — sessions, and the credential store beneath it. */\n \"THEOKIT_HOME\",\n /** Locates the credential store explicitly, independently of `THEOKIT_HOME`. */\n \"THEOKIT_AUTH_HOME\",\n /** A trust decision: which providers are honoured without further checks. */\n \"THEOKIT_TRUSTED_PROVIDERS\",\n /** Turning redaction off from a repository's `.env` would put secrets into logs. */\n \"THEOKIT_REDACT_SECRETS\",\n /** Cryptographic material for the OAuth transaction cookie. */\n \"THEOKIT_OAUTH_TX_SALT\",\n] as const;\n\n/**\n * The union of {@link SOVEREIGN_ENV_KEYS} entries — the variables a project-scoped `.env` may never\n * set.\n *\n * Derived from the array rather than written out, so adding a key in one place cannot leave the\n * type behind. Use it where a caller must name one of the protected variables and a plain `string`\n * would let a typo through silently.\n *\n * @public\n */\nexport type SovereignEnvKey = (typeof SOVEREIGN_ENV_KEYS)[number];\n\n/** The mutable shape of `process.env`, narrowed so a caller can pass a plain object in tests. */\ntype MutableEnv = Record<string, string | undefined>;\n\n/**\n * Read the project's `.env` into `env`, then restore every {@link SOVEREIGN_ENV_KEYS} entry to the\n * value it had BEFORE the load — including restoring it to absent.\n *\n * Capture-then-restore rather than filtering the file: `process.loadEnvFile` offers no hook between\n * parsing and assignment, and reimplementing dotenv parsing to filter it would be a second parser\n * to keep in step with Node's. Restoring afterwards needs no parser and cannot disagree with one.\n *\n * @param env the environment to mutate. Defaults to `process.env`.\n * @param load performs the load. Defaults to `process.loadEnvFile` when the runtime has it, and to\n * `undefined` when it does not — in which case this is a no-op rather than a startup crash.\n * @public\n */\nexport function loadProjectEnv(\n env: MutableEnv = process.env,\n load: (() => void) | undefined = typeof process.loadEnvFile === \"function\"\n ? (): void => {\n process.loadEnvFile();\n }\n : undefined,\n): void {\n if (load === undefined) return;\n\n // Captured BEFORE the load, including the absent case — `undefined` here means \"was not set\",\n // and restoring that means deleting the key rather than leaving the project's value in place.\n const sovereign = new Map<string, string | undefined>(\n SOVEREIGN_ENV_KEYS.map((key) => [key, env[key]] as const),\n );\n\n try {\n load();\n } catch {\n // No `.env` on disk is the ordinary case and `loadEnvFile` throws for it. Nothing was assigned,\n // so there is nothing to restore.\n return;\n }\n\n for (const [key, original] of sovereign) {\n if (original === undefined) delete env[key];\n else env[key] = original;\n }\n}\n","/**\n * Decide which session artifacts may be deleted — and never delete them.\n *\n * This package creates session artifacts (transcripts, locks, temp files) and cleans up only what is\n * in flight in the operation doing the cleaning: a lock it just released, a `.tmp` from a failed\n * atomic write. Nothing collects the rest, so every consumer either writes its own collector or lets\n * the directory grow without bound — and a hand-rolled collector on the path that deletes a user's\n * transcript is the worst place for each product to learn the same lessons separately.\n *\n * ## Planning is not deleting, deliberately\n *\n * A function that decided AND deleted could not be tested without a filesystem, and the case that\n * matters most — \"we could not establish whether this session is live\" — would have to be simulated\n * rather than asserted. Here the decision is pure: the plan IS the dry run, and executing it is a\n * separate act on a value someone can read first. That separation is the dry-run guarantee, rather\n * than a flag that has to be remembered.\n *\n * ## The tri-state\n *\n * `keep`, `reap`, `undetermined`. An artifact whose liveness could not be established is never\n * reaped and never quietly counted as dead. Collapsing \"could not determine\" into \"not there\" is how\n * a collector deletes a session running on another machine, or behind a mount that answered slowly.\n * The third bucket costs a branch and buys the only guarantee worth having on this path.\n *\n * @public\n */\n\nimport { TheokitAgentError } from \"./errors.js\";\n\n/** Raised when a retention policy cannot be honoured as written. @public */\nexport class RetentionPolicyError extends TheokitAgentError {\n override readonly name = \"RetentionPolicyError\";\n}\n\n/**\n * One artifact the caller is considering deleting, described well enough to decide about.\n *\n * `id` is only ever compared for equality, so any stable identity works — a path, a session id, an\n * inode. `live` is the tri-state that carries the whole safety property: `\"unknown\"` means the\n * caller could not establish liveness, and it is honoured as a third answer rather than folded into\n * `false`.\n *\n * @public\n */\nexport interface ReapableArtifact {\n readonly id: string;\n /** Epoch milliseconds. Compared against an injected `nowMs`, never against a read clock. */\n readonly lastModifiedMs: number;\n /**\n * Whether a writer still holds this artifact. `\"unknown\"` when the caller could not establish it —\n * a stale lock behind a slow mount, a PID on another host — and it is honoured as a third answer\n * rather than folded into `false`.\n */\n readonly live: boolean | \"unknown\";\n}\n\n/**\n * How long artifacts are kept and how many always survive.\n *\n * The two interact as a window plus a FLOOR, not as two independent allowances: `keepLast` rescues\n * artifacts only when the window and liveness together spared fewer than that many, and rescues\n * exactly enough to reach the count. Both are refused by `planReaping` rather than clamped when\n * they are not expressible — see its `@throws`.\n *\n * @public\n */\nexport interface RetentionPolicy {\n /** Artifacts strictly older than this are candidates. The boundary itself is kept. */\n readonly maxAgeMs: number;\n /**\n * A FLOOR on how many artifacts survive: \"you will always have your last N sessions\". When\n * liveness and the retention window already spare N or more, this changes nothing; when they\n * spare fewer, the newest of the remainder are spared until the count reaches N.\n *\n * Undetermined artifacts do NOT count toward the floor. Their liveness was never established, so\n * counting them would let a transient mount failure satisfy the floor with artifacts nobody\n * confirmed exist as sessions — and quietly delete the ones that do.\n */\n readonly keepLast: number;\n}\n\n/** Why an artifact survived. @public */\nexport type KeepReason = \"live\" | \"within-retention\" | \"keep-last\";\n\n/**\n * An artifact that survived, carrying the reason it did.\n *\n * The reason is the one that spared it FIRST, in the order liveness, then the retention window,\n * then the floor — so a live artifact inside the window reports `\"live\"`, and `\"keep-last\"` only\n * appears on artifacts that had no reason of their own.\n *\n * @public\n */\nexport interface KeptArtifact extends ReapableArtifact {\n readonly reason: KeepReason;\n}\n\n/**\n * The decision, as three disjoint buckets whose union is exactly the input.\n *\n * Nothing is deleted by producing one of these — the plan IS the dry run, and executing it is a\n * separate act on a value you can read first. Delete only what is in `reap`; `undetermined` is not\n * a smaller `reap`, it is the set nobody could decide about.\n *\n * @public\n */\nexport interface ReapPlan {\n /** Safe to delete. Everything here was decided, not defaulted. */\n readonly reap: readonly ReapableArtifact[];\n readonly keep: readonly KeptArtifact[];\n /** Liveness could not be established. Never deleted, never counted as kept. */\n readonly undetermined: readonly ReapableArtifact[];\n}\n\n/**\n * Everything `planReaping` needs: the candidates, the policy, and the current time.\n *\n * `nowMs` is a parameter rather than a clock read so the same input always produces the same plan —\n * which is what lets a caller compute a plan, show it, and execute it later against the same\n * decision instead of a freshly re-derived one.\n *\n * @public\n */\nexport interface ReapPlanInput {\n readonly artifacts: readonly ReapableArtifact[];\n readonly retention: RetentionPolicy;\n /** Injected so the plan is reproducible and testable; this module never reads a clock. */\n readonly nowMs: number;\n}\n\n/**\n * Refuse a policy that cannot be honoured as written. Nonsense is not clamped: on this path a\n * clamped window deletes data the operator meant to keep.\n *\n * @internal\n */\nfunction assertPolicy(retention: RetentionPolicy): void {\n const { maxAgeMs, keepLast } = retention;\n if (!Number.isFinite(maxAgeMs) || maxAgeMs < 0) {\n throw new RetentionPolicyError(\n `retention.maxAgeMs must be a non-negative number of milliseconds, got ${String(maxAgeMs)}`,\n );\n }\n if (!Number.isInteger(keepLast) || keepLast < 0) {\n throw new RetentionPolicyError(\n `retention.keepLast must be a non-negative integer, got ${String(keepLast)}`,\n );\n }\n}\n\n/**\n * Everything spared for a reason of its own — liveness, or the retention window. What survives this\n * pass is what the floor then has to decide about.\n *\n * @internal\n */\nfunction classifyByOwnReason(input: ReapPlanInput): {\n keep: KeptArtifact[];\n atRisk: ReapableArtifact[];\n} {\n const keep: KeptArtifact[] = [];\n const atRisk: ReapableArtifact[] = [];\n\n for (const artifact of input.artifacts) {\n if (artifact.live === \"unknown\") continue;\n // Liveness first: a session that has not written for weeks is still running, and deleting its\n // transcript underneath it loses everything it has not flushed.\n if (artifact.live === true) {\n keep.push({ ...artifact, reason: \"live\" });\n continue;\n }\n // The boundary belongs to the safe side: at exactly the window, keep. Reaping there makes a\n // 30-day retention sometimes mean 29, depending on clock granularity.\n if (input.nowMs - artifact.lastModifiedMs <= input.retention.maxAgeMs) {\n keep.push({ ...artifact, reason: \"within-retention\" });\n continue;\n }\n atRisk.push(artifact);\n }\n return { keep, atRisk };\n}\n\n/**\n * The floor. `keepLast` is a promise about how many sessions survive in total, not a bonus on top of\n * the window — the standard reading of \"keep last N\", and the one explainable in a sentence. When\n * the window already spared enough, nothing more is rescued.\n *\n * @internal\n */\nfunction applyFloor(\n kept: readonly KeptArtifact[],\n atRisk: readonly ReapableArtifact[],\n keepLast: number,\n): { rescued: KeptArtifact[]; reap: ReapableArtifact[] } {\n const shortfall = Math.max(0, keepLast - kept.length);\n const newestFirst = [...atRisk].sort((a, b) => b.lastModifiedMs - a.lastModifiedMs);\n const spared = new Set(newestFirst.slice(0, shortfall).map((a) => a.id));\n\n const rescued: KeptArtifact[] = [];\n const reap: ReapableArtifact[] = [];\n for (const artifact of atRisk) {\n if (spared.has(artifact.id)) rescued.push({ ...artifact, reason: \"keep-last\" });\n else reap.push(artifact);\n }\n return { rescued, reap };\n}\n\n/**\n * Sort artifacts into keep, reap, and undetermined — and delete nothing.\n *\n * The order of decision is liveness, then the retention window, then the floor. An artifact whose\n * `live` is `\"unknown\"` leaves at the first step and is never considered again: it is not counted\n * toward `keepLast`, so a transient mount failure cannot satisfy \"keep my last two\" with artifacts\n * nobody confirmed while the confirmed ones are deleted.\n *\n * The window boundary belongs to the safe side. An artifact exactly `maxAgeMs` old is kept, so a\n * 30-day retention never means 29 depending on clock granularity.\n *\n * @returns the three buckets. Their union is exactly the input, each artifact counted once — the\n * invariant an operator reads the totals against.\n * @throws RetentionPolicyError when `maxAgeMs` is negative or not finite, or `keepLast` is negative\n * or not an integer. Nonsense is refused rather than clamped, because a clamped window on this\n * path deletes data the operator meant to keep.\n * @public\n */\nexport function planReaping(input: ReapPlanInput): ReapPlan {\n assertPolicy(input.retention);\n\n // Undetermined artifacts are set aside before anything else and never counted toward the floor: a\n // transient mount failure must not satisfy \"keep 2\" with artifacts nobody confirmed, while the\n // confirmed ones are deleted.\n const undetermined = input.artifacts.filter((a) => a.live === \"unknown\");\n const { keep, atRisk } = classifyByOwnReason(input);\n const { rescued, reap } = applyFloor(keep, atRisk, input.retention.keepLast);\n\n return { reap, keep: [...keep, ...rescued], undetermined };\n}\n","/**\n * M23 — schema normalizer: convert a schema from any supported provider to the internal JSON Schema\n * the synthetic `output` tool uses. Zod stays the DEFAULT and the documented recommendation; this is\n * a THIN adapter with no deep coupling (ADR-0041). Supported inputs:\n *\n * - **Zod** (default) — via the SDK's native `z.toJSONSchema` path.\n * - **JSON Schema** — a plain object with `type`/`properties` (or `$schema`) → passthrough.\n * - **ArkType** — any schema exposing `.toJsonSchema()` (ArkType 2.0) → called directly.\n * - **Valibot** — via the OPTIONAL `@valibot/to-json-schema` peer (dynamic import; a clear\n * error tells the user to install it — no hard dependency).\n *\n * Parse-failure handling stays uniform: the normalized JSON Schema drives the same synthetic-tool\n * validation + M14 `errorStrategy` regardless of the source library.\n */\nimport { ConfigurationError } from \"./errors.js\";\nimport { toJsonSchema } from \"./internal/zod-to-json-schema.js\";\n\n/** The internal JSON-Schema shape the synthetic `output` tool consumes. */\nexport type NormalizedJsonSchema = Record<string, unknown>;\n\n/** A plain JSON Schema object already in the target shape. */\nfunction isJsonSchemaObject(s: unknown): s is NormalizedJsonSchema {\n if (typeof s !== \"object\" || s === null) return false;\n const o = s as Record<string, unknown>;\n if (\"$schema\" in o) return true;\n return o.type === \"object\" && typeof o.properties === \"object\" && o.properties !== null;\n}\n\n/** ArkType (and any lib) exposing its own `.toJsonSchema()`. */\nfunction hasToJsonSchemaMethod(s: unknown): s is { toJsonSchema: () => NormalizedJsonSchema } {\n return (\n typeof s === \"object\" &&\n s !== null &&\n typeof (s as { toJsonSchema?: unknown }).toJsonSchema === \"function\"\n );\n}\n\n/** A Zod schema — carries `safeParse` plus the Zod internals (`_def` v3 / `def` v4). */\nfunction isZodSchema(s: unknown): boolean {\n if (typeof s !== \"object\" || s === null) return false;\n const o = s as Record<string, unknown>;\n return typeof o.safeParse === \"function\" && (\"_def\" in o || \"def\" in o);\n}\n\n/** A Valibot schema — `{ kind: 'schema', type, ... }` (no built-in JSON-Schema method). */\nfunction isValibotSchema(s: unknown): boolean {\n if (typeof s !== \"object\" || s === null) return false;\n const o = s as Record<string, unknown>;\n return o.kind === \"schema\" && \"type\" in o && typeof o.toJsonSchema !== \"function\";\n}\n\n/**\n * Whether a failed dynamic import means \"the optional peer is not installed\".\n *\n * The structural fact first: Node reports a missing module as `err.code`, and `compaction.ts`'s\n * `isContextOverflowError` already states the rule for this repo — read the code, \"never a brittle\n * message regex\". The regex survives ONLY as a fallback, because a bundler may rewrite the error and\n * drop the code; on its own it also depended on English-locale wording that neither Node nor any\n * bundler guarantees.\n */\nfunction isMissingModuleError(err: unknown): boolean {\n if ((err as NodeJS.ErrnoException | undefined)?.code === \"ERR_MODULE_NOT_FOUND\") return true;\n return (\n err instanceof Error && /Cannot find|Cannot resolve|ERR_MODULE_NOT_FOUND/.test(err.message)\n );\n}\n\n/**\n * Valibot needs its own converter, which is an optional peer. The specifier is NON-literal so TS\n * does not try to statically resolve an uninstalled package at build time.\n */\nasync function normalizeValibotSchema(schema: unknown): Promise<NormalizedJsonSchema> {\n const specifier = \"@valibot/to-json-schema\";\n try {\n const mod = (await import(specifier)) as {\n toJsonSchema: (s: unknown) => NormalizedJsonSchema;\n };\n return mod.toJsonSchema(schema);\n } catch (err) {\n if (!isMissingModuleError(err)) throw err;\n throw new ConfigurationError(\n \"normalizeSchema: a Valibot schema requires the optional '@valibot/to-json-schema' package. \" +\n \"Install it, or use a Zod schema (the default recommendation).\",\n { code: \"valibot_converter_missing\" },\n );\n }\n}\n\n/**\n * Normalize any supported schema to the internal JSON Schema. Async because the Valibot path\n * dynamically imports its optional converter. Throws a clear, typed-message error for an unsupported\n * schema or a missing Valibot peer (error-handling.md).\n */\nexport async function normalizeSchema(schema: unknown): Promise<NormalizedJsonSchema> {\n // JSON Schema — passthrough (already the target shape).\n if (isJsonSchemaObject(schema)) return schema;\n\n if (isValibotSchema(schema)) return await normalizeValibotSchema(schema);\n\n // Zod — the default path.\n if (isZodSchema(schema)) {\n return toJsonSchema(schema as never, { unrepresentable: \"any\" }) as NormalizedJsonSchema;\n }\n\n // ArkType (or any lib exposing `.toJsonSchema()`).\n if (hasToJsonSchemaMethod(schema)) return schema.toJsonSchema();\n\n // Typed, with a stable code: `normalizeSchema` is public (re-exported from the root barrel), and a\n // bare `Error` gives a caller nothing to branch on but the sentence.\n throw new ConfigurationError(\n \"normalizeSchema: unsupported schema. Supported: Zod (default), JSON Schema, ArkType (.toJsonSchema()), \" +\n \"Valibot (with @valibot/to-json-schema).\",\n { code: \"unsupported_schema\" },\n );\n}\n","/**\n * Public security namespace (T2.1, ADR D68).\n *\n * Two entry points:\n *\n * - `Security.redact(text, opts?)` — apply the canonical redactor to\n * arbitrary text. Useful when a consumer app (or example) writes its\n * own logs / metrics / paste-share artifacts that the SDK's wired\n * sinks (error metadata, telemetry, transcript, migration) don't\n * cover.\n * - `Security.addPattern(re)` — register a custom credential pattern\n * on top of the 12 builtins (OpenAI, Anthropic, GitHub PAT classic +\n * fine, GitLab, AWS, Google, Slack, Sentry, Stripe live + restricted)\n * plus the parametric `key=value` + `Bearer <token>` matchers.\n *\n * Redaction is ON by default. Disable with `THEOKIT_REDACT_SECRETS=false`\n * (a warning is emitted on stderr so the operator knows the SDK process\n * is vulnerable). The env var is snapshotted at module init — runtime\n * mutation cannot disable it, defending against prompt injection that\n * tries to flip the flag mid-run.\n */\n\nimport { ConfigurationError } from \"./errors.js\";\nimport {\n addPattern as _addPattern,\n redactSecrets as _redactSecrets,\n} from \"./internal/security/index.js\";\n\nexport class Security {\n private constructor() {}\n\n /**\n * Redact known credential patterns from `text` and return the masked\n * string. Use this at any consumer output boundary the SDK does not\n * directly own (custom stdout loggers, app-level metrics, debug-share\n * artifacts, etc.).\n *\n * Coerces non-strings (objects via JSON.stringify, null/undefined → \"\").\n * Two-bucket masking: tokens shorter than 18 chars → `***`; longer\n * tokens preserve `prefix...suffix` for debuggability without revealing\n * the secret middle.\n *\n * @param text - The value to redact. Strings, objects, primitives all OK.\n * @param opts.codeFile - When `true`, skips the parametric `key=value`\n * matcher so file content like `.env.example` placeholders is left\n * intact. Built-in pattern matches still apply.\n *\n * @example\n * console.log(`[bot] received: ${Security.redact(userText)}`);\n * // → \"[bot] received: please remember sk-abc...xyz1\"\n */\n static redact(text: unknown, opts?: { codeFile?: boolean }): string {\n return _redactSecrets(text, opts);\n }\n\n /**\n * Register a custom redaction pattern. Additive — built-in patterns\n * (OpenAI, Anthropic, GitHub PAT, AWS, etc.) cannot be removed.\n *\n * @param re - RegExp with `/g` flag. Throws if `/g` is missing\n * (without /g, only first match is replaced and the rest\n * leaks).\n *\n * Process-global mutable state. The SDK is designed for single-tenant\n * processes (Theo PaaS user runtime, local CLI). Multi-tenant\n * deployments running multiple SDK consumers in the same Node process\n * share this list — patterns added by tenant A apply to tenant B's\n * redactions. Acceptable for v1; future isolate-aware refactor would\n * thread patterns through a context if needed.\n *\n * @example\n * Security.addPattern(/MYORG-[A-Z0-9]{32}/g);\n * // → text containing \"MYORG-AAAA...AAAA\" now masks like a builtin.\n */\n static addPattern(re: RegExp): void {\n // Validated HERE rather than in the primitive. `internal/security/redact.ts` has to stay below\n // `errors.ts` — the error hierarchy imports `redactSecrets` for the anti-leak invariant on\n // `providerError` — so it cannot import ConfigurationError without closing a cycle. This is the\n // surface a consumer touches, and it can.\n //\n // Without /g, `String.replaceAll` throws and only the first match would be masked anyway: a\n // pattern registered to redact a secret would leave every occurrence after the first in clear.\n if (!re.global) {\n throw new ConfigurationError(\n \"Security.addPattern: regex must have /g flag for replace-all semantics\",\n { code: \"invalid_redaction_pattern\" },\n );\n }\n _addPattern(re);\n }\n}\n","/**\n * Resolve a security-relevant setting across configuration layers, where a lower-trust layer may\n * TIGHTEN it and never loosen it.\n *\n * Layered configuration usually resolves last-wins, and for the keys that decide confinement — a\n * sandbox mode, an approval policy — last-wins is a hole. With plain precedence a project layer\n * outranks the user's own file, so a cloned repository can hand itself the most permissive setting\n * and the operator's global choice loses silently, at the moment the directory is opened. Nothing\n * fails; the confinement is simply gone.\n *\n * ## What is generic here, and what is not\n *\n * The RULE is generic: named layers may only move the value in the confining direction, while one\n * designated layer — the operator's explicit flag — wins in both. The VOCABULARY is not: which\n * values count as more permissive, what the layers are called, and which one is the operator's are\n * all the consumer's, and are parameters.\n *\n * That distinction is what makes this extractable when a keypress router was not. Here the\n * vocabulary is DATA — two lists and a name — so a second product supplies its own without\n * inheriting the first's words. An interface shaped by one product's states would have given the\n * second consumer something to route around.\n *\n * ## Why the override is not validated\n *\n * `override` is returned verbatim, even when it is outside `permissiveness`. Validating the\n * operator's flag is the consumer's job: it owns the vocabulary, the error message and the exit\n * code. Silently dropping an unrecognised flag would be worse than passing it through — the\n * operator would see their explicit instruction ignored with no explanation.\n *\n * A value outside the vocabulary in a RESTRICTED layer is different and IS ignored: a typo in a\n * repository's config must neither become the effective setting nor be treated as maximally\n * permissive.\n *\n * @public\n */\n\n/**\n * The vocabulary, the layer names, and the values to resolve.\n *\n * Two orders matter and they are not the same one. The UNRESTRICTED layers — every key of `layers`\n * that is neither `override` nor listed in `restricted` — are resolved last-wins in the enumeration\n * order of the `layers` object. The RESTRICTED layers are applied in the order of the `restricted`\n * array, regardless of where they sit in `layers`. Put a layer in `restricted` and its position in\n * that array is what decides when it gets to tighten.\n *\n * A layer named in `restricted` but absent from `layers`, or present with `undefined`, is skipped.\n *\n * @public\n */\nexport interface SecurityFloorInput {\n /**\n * The vocabulary, ordered from most confined to least. Index is permissiveness, so\n * `[\"read-only\", \"workspace-write\", \"danger-full-access\"]` says read-only confines the most.\n */\n readonly permissiveness: readonly string[];\n /** Layers that may only tighten — typically anything a repository or environment can supply. */\n readonly restricted: readonly string[];\n /** The layer that wins outright in both directions — the operator's explicit flag. */\n readonly override: string;\n /**\n * Values per layer. Layers absent from `restricted` are unconstrained, which is how a `user`\n * layer loosens its own `defaults`.\n */\n readonly layers: Readonly<Record<string, string | undefined>>;\n}\n\n/** Index in `order`, or -1 when the value is absent or outside the vocabulary. @internal */\nfunction permissivenessOf(order: readonly string[], value: string | undefined): number {\n if (value === undefined) return -1;\n return order.indexOf(value);\n}\n\n/**\n * The value the restricted layers must not exceed, taken from the unrestricted layers in the order\n * given. Separated because it answers a different question from the floor itself: what did the\n * operator and the defaults already settle on, before any repository or environment had a say.\n *\n * @internal\n */\nfunction baseline(input: SecurityFloorInput): string | undefined {\n const { restricted, override, layers } = input;\n let value: string | undefined;\n for (const [name, candidate] of Object.entries(layers)) {\n if (name === override || restricted.includes(name)) continue;\n if (candidate !== undefined) value = candidate;\n }\n return value;\n}\n\n/**\n * Apply the restricted layers to `start`, letting each one CONFINE and never widen.\n *\n * @internal\n */\nfunction tightenOnly(input: SecurityFloorInput, start: string | undefined): string | undefined {\n const { permissiveness, restricted, layers } = input;\n let resolved = start;\n let ceiling = permissivenessOf(permissiveness, start);\n\n for (const layer of restricted) {\n const candidate = layers[layer];\n if (candidate === undefined) continue;\n const level = permissivenessOf(permissiveness, candidate);\n // Outside the vocabulary: ignored rather than trusted. See the docblock.\n if (level < 0) continue;\n // With no ceiling yet the layer is choosing, not widening.\n if (ceiling >= 0 && level > ceiling) continue;\n resolved = candidate;\n // Assigned, never max'd: the ceiling only ever descends, so a layer that hardens binds the\n // ones after it. A mutation to `Math.max` here is invisible until a later layer offers a value\n // between the old and new ceiling — which is why that case is written out in the tests.\n ceiling = level;\n }\n return resolved;\n}\n\n/**\n * Resolve a security-relevant setting so that a lower-trust layer can only tighten it.\n *\n * Two paths. When `layers[override]` holds a value, that value is returned VERBATIM and nothing\n * else is consulted — it is not checked against `permissiveness`, because validating the operator's\n * own flag belongs to the consumer that owns the vocabulary and the error message. Otherwise a\n * baseline is taken from the unrestricted layers, and each restricted layer in turn may lower it\n * and never raise it.\n *\n * Two consequences worth knowing before wiring this up. A value in a restricted layer that is not\n * in `permissiveness` is IGNORED rather than trusted, so a typo in a repository's config leaves the\n * baseline standing instead of becoming the effective setting. And the ceiling only ever descends:\n * once one restricted layer tightens, a later one cannot return to the baseline, even though it\n * could have chosen that value had it come first.\n *\n * When no layer supplied a value at all, the answer is `undefined` — the absence is reported rather\n * than filled in with the most confined member of the vocabulary.\n *\n * @returns the resolved value, or `undefined` when no layer supplied one.\n * @public\n */\nexport function applySecurityFloor(input: SecurityFloorInput): string | undefined {\n return input.layers[input.override] ?? tightenOnly(input, baseline(input));\n}\n","/**\n * Refuse to destroy a session another process is still writing.\n *\n * Every agent product that lets a user delete or overwrite a session needs this, and the failure is\n * unrecoverable in the worst way: a transcript removed underneath a running session takes with it\n * everything that session had not flushed, and nothing errors. The user sees a successful delete.\n *\n * ## The ordering is the point\n *\n * The check runs BEFORE anything is mutated. Removing a registry entry and then refusing leaves a\n * session that can be neither opened nor deleted — worse than either outcome on its own. So this is\n * a function the caller passes through rather than a flag it may consult afterwards: the throw is\n * what stops the mutation, and there is no way to read the answer and forget to act on it.\n *\n * ## What is generic, and what is not\n *\n * The RULE is: a session declared live is not destroyable, and refusing says which one and why. The\n * VOCABULARY is not — how a product decides liveness (a pointer file, the newest transcript, a\n * lease, an active registry entry) is its own. Nothing here touches a filesystem.\n *\n * @public\n */\n\nimport { TheokitAgentError } from \"./errors.js\";\n\n/** Why the destruction was refused. @public */\nexport type LiveSessionReason = \"session-is-live\" | \"liveness-undetermined\";\n\n/**\n * Raised by `guardSessionDestruction` instead of letting a session be destroyed.\n *\n * Read `reason` rather than the message when deciding what to do: `\"session-is-live\"` is fixed by\n * closing the other session, `\"liveness-undetermined\"` is fixed by making the liveness check work\n * again, and telling a user to close a session when nothing could be read sends them to close\n * nothing. `sessionId` carries the session the refusal was about.\n *\n * @public\n */\nexport class LiveSessionError extends TheokitAgentError {\n override readonly name = \"LiveSessionError\";\n readonly sessionId: string;\n readonly reason: LiveSessionReason;\n\n constructor(sessionId: string, reason: LiveSessionReason) {\n super(\n reason === \"session-is-live\"\n ? `refusing to destroy session ${sessionId}: it is live — another process is probably still ` +\n `appending to it. Switch to another session first.`\n : `refusing to destroy session ${sessionId}: the set of live sessions could not be ` +\n `determined, so this cannot be shown to be safe. Resolve that before deleting.`,\n );\n this.sessionId = sessionId;\n this.reason = reason;\n }\n}\n\n/**\n * Throw unless `sessionId` is safe to destroy.\n *\n * @param live - the sessions the product declares live, or `undefined` when it could not tell.\n * The distinction is load-bearing: an EMPTY set is a legitimate answer (nothing is open), while\n * `undefined` refuses. A product that swallowed a read error and returned `[]` would hand this\n * guard the one input that disables it entirely, on exactly the path that destroys data.\n * @throws LiveSessionError naming the session and the reason — \"close that session\" and \"the guard\n * could not read\" have different fixes, and conflating them sends the user to close nothing.\n * @public\n */\nexport function guardSessionDestruction(\n sessionId: string,\n live: readonly string[] | undefined,\n): void {\n if (live === undefined) {\n throw new LiveSessionError(sessionId, \"liveness-undetermined\");\n }\n if (live.includes(sessionId)) {\n throw new LiveSessionError(sessionId, \"session-is-live\");\n }\n}\n","import { FsSessionStore } from \"./internal/persistence/fs-session-store.js\";\nimport { resolveSessionDir } from \"./internal/persistence/session-dir.js\";\nimport { readSessionMessages as readFromStore } from \"./internal/session/agent-session-store.js\";\nimport type { SessionMessage } from \"./types/session-message.js\";\n\n/** Which session to read, in the terms a host already has. */\nexport interface ReadSessionMessagesOptions {\n /** The session's agent id — the same id `Agent` was created or resumed with. */\n sessionId: string;\n /**\n * The working directory the session belongs to. Sessions are per-cwd, so the same\n * id under a different cwd is a different session. Defaults to `process.cwd()`.\n */\n cwd?: string;\n /**\n * Where transcripts live. Only needed when the agent was created with\n * `local.sessionDir`; otherwise the SDK's default location is used.\n */\n sessionDir?: string;\n}\n\n/**\n * Read the messages a session already contains, for a surface that needs to re-render it.\n *\n * #546 — the SDK read these records to give the model its context on resume, and a host had\n * no way to read the same thing: a resumed session showed an empty screen while the model\n * demonstrably remembered. The alternative was for the host to parse\n * `<sessionDir>/projects/<encoded-cwd>/<id>.jsonl` itself, which is a private contract —\n * both the record shape and the directory encoding are the SDK's to change.\n *\n * This is deliberately narrower than the internal reader it wraps. That one takes a\n * {@link SessionStore}, and exporting it would put that interface, its record shape and its\n * lease semantics into the public surface to serve a caller that only wants to render what\n * is already there. A host that HAS a custom store can already read from it directly.\n *\n * Parsing stays tolerant, as it is on the resume path: a malformed line costs one message,\n * not the screen. A session that was never written resolves to `[]` rather than throwing —\n * a fresh session has no history, which is not an error.\n *\n * @example\n * ```ts\n * const history = await readSessionMessages({ sessionId, cwd: projectDir });\n * for (const m of history) render(m.role, m.text);\n * ```\n */\nexport async function readSessionMessages(\n options: ReadSessionMessagesOptions,\n): Promise<SessionMessage[]> {\n const cwd = options.cwd ?? process.cwd();\n const baseDir = resolveSessionDir({ sessionDir: options.sessionDir });\n return readFromStore(new FsSessionStore({ baseDir, cwd }), options.sessionId);\n}\n","/**\n * M3 #62 — scoped session state.\n *\n * A conversation id can be namespaced by SCOPE so a consumer keeps app-durable,\n * user-durable, and ephemeral (temp) session data separated in the same store:\n *\n * - `app:` — durable state shared across users (app-level memory).\n * - `user:` — durable state for one user.\n * - `temp:` — ephemeral state a consumer prunes on logout / session end.\n *\n * The scope is a prefix on the conversation id (`\"<scope>__<id>\"`). The `__`\n * separator is path-safe (unlike `:`, which the identifier guard rejects), so a\n * host can partition sessions by scope over the native transcript store.\n *\n * @public\n */\n\n/** M3 #62 — session state scope. */\nexport type SessionScope = \"app\" | \"user\" | \"temp\";\n\n/** M3 #62 — build a scope-namespaced conversation id (`\"<scope>__<id>\"`). */\nexport function scopedConversationId(scope: SessionScope, id: string): string {\n return `${scope}__${id}`;\n}\n\n/** M3 #62 — the id prefix (`\"<scope>__\"`) used to match a scope's conversations. */\nexport function sessionScopePrefix(scope: SessionScope): string {\n return `${scope}__`;\n}\n","/**\n * `createSquad` — a sequential team of agents.\n *\n * A Squad is a thin convenience that COMPOSES `Workflow` + `agentStep` — it\n * adds NO new orchestration logic. Agents run in array order; each agent's\n * output is threaded into the next agent's prompt. For branching/parallel/\n * foreach teams use `Workflow` directly; for manager→worker delegation use\n * subagents or `@theokit/sdk-handoff`.\n *\n * Mirrors the `createAgentFactory` composition-LEGO precedent (a factory over\n * existing primitives, not a new subsystem).\n *\n * @public\n */\n\nimport { ConfigurationError } from \"./errors.js\";\nimport type { AgentDefinition, SDKAgent } from \"./types/agent.js\";\nimport type { StepResult } from \"./types/workflow.js\";\nimport { agentStep, Workflow } from \"./workflow.js\";\n\n/**\n * Options for {@link createSquad}.\n *\n * @public\n */\nexport interface SquadOptions {\n /**\n * Agents run in array order (sequential pipeline). Must be non-empty.\n *\n * M81 — accepts an `AgentDefinition` (plain data) as well as a constructed `SDKAgent`. Building a\n * team used to force the caller to materialize every member by hand first: resolve the credential,\n * assemble the options, call `Agent.create`, await. That is precisely the work this milestone moves\n * into the framework elsewhere, so leaving it here would be inconsistent — and with\n * `discoverSubagents` now public (`@theokit/sdk/subagents-loader`), the data that describes an\n * agent is reachable, which closes the loop: discover → build a team, with no manual step between.\n *\n * Mixing both forms in one list is supported on purpose: a real team usually has members from\n * different origins.\n */\n agents: ReadonlyArray<SDKAgent | AgentDefinition>;\n /**\n * Orchestration process. Only `\"sequential\"` is supported (the default).\n * `\"hierarchical\"` is accepted by the type but rejected at runtime with\n * guidance — use subagents or `@theokit/sdk-handoff` for manager→worker\n * delegation (those already cover it).\n */\n process?: \"sequential\" | \"hierarchical\";\n /** Optional squad name (surfaced on the underlying workflow). Default `\"squad\"`. */\n name?: string;\n}\n\n/**\n * Result of a {@link Squad.run}. `result` is the final (last agent's) output;\n * `steps` is the per-agent trace from the underlying workflow run.\n *\n * @public\n */\nexport interface SquadRun {\n readonly result: unknown;\n readonly status: \"running\" | \"completed\" | \"failed\" | \"suspended\" | \"cancelled\";\n readonly steps: ReadonlyArray<StepResult>;\n}\n\n/**\n * A sequential agent team produced by {@link createSquad}.\n *\n * @public\n */\nexport interface Squad {\n /** Run the team over `input`, threading each agent's output to the next. */\n run(input: unknown): Promise<SquadRun>;\n}\n\n/**\n * M81 — an `SDKAgent` is recognised by having `send`; an `AgentDefinition` is plain data.\n *\n * Structural, not `instanceof`: the definition crosses package boundaries as data (that is the whole\n * interop contract the layer relies on), so an identity check would fail exactly when two copies of\n * the SDK are loaded — the failure mode M79 measured.\n */\nfunction isBuiltAgent(m: SDKAgent | AgentDefinition): m is SDKAgent {\n return typeof (m as SDKAgent).send === \"function\";\n}\n\n/**\n * M81 — turns an `AgentDefinition` into an executable agent.\n *\n * `Agent` is imported dynamically because `squad.ts` is consumed by paths that do not want to drag the\n * whole agent in just to declare a team; the cost is only paid by callers actually passing raw data.\n */\nasync function materialize(def: AgentDefinition, index: number): Promise<SDKAgent> {\n const { Agent } = await import(\"./agent.js\");\n return Agent.create({\n // `AgentDefinition.model` admits the sentinel `'inherit'`, which is not a model id. Inheriting\n // here means \"declare nothing and let the default apply\" — forwarding the literal would create\n // an agent asking for a model literally named `inherit`.\n ...(def.model !== undefined && def.model !== \"inherit\" ? { model: def.model } : {}),\n ...(def.prompt !== undefined ? { systemPrompt: def.prompt } : {}),\n agentId: `squad-member-${String(index)}`,\n local: {},\n });\n}\n\n/**\n * Build a sequential agent team. The returned {@link Squad} composes a\n * `Workflow` of `agentStep`s under the hood — all orchestration is delegated\n * to the workflow engine.\n */\nfunction createSquad(options: SquadOptions): Squad {\n const { agents } = options;\n if (!Array.isArray(agents) || agents.length === 0) {\n throw new ConfigurationError(\"createSquad requires a non-empty `agents` array\", {\n code: \"invalid_squad\",\n });\n }\n if (options.process !== undefined && options.process !== \"sequential\") {\n throw new ConfigurationError(\n `createSquad only supports process \"sequential\"; for manager→worker delegation use subagents or @theokit/sdk-handoff`,\n { code: \"squad_process_unsupported\" },\n );\n }\n\n return {\n run: async (input: unknown): Promise<SquadRun> => {\n const run = await (await buildPipeline(agents, options.name)).run(input);\n return { result: run.output, status: run.status, steps: run.stepResults };\n },\n };\n}\n\n/**\n * Builds the sequential pipeline, materializing the members that are still raw data.\n *\n * Extracted from `run` because the cognitive-complexity gate rejected the combined function — and because\n * \"building the pipeline\" and \"running it and translating the result\" are two responsibilities that were only\n * together by proximity.\n */\nasync function buildPipeline(\n agents: ReadonlyArray<SDKAgent | AgentDefinition>,\n name: string | undefined,\n): Promise<ReturnType<ReturnType<typeof Workflow.create>[\"commit\"]>> {\n // Compose Workflow + agentStep — identity threading: each agent's prompt is the previous agent's\n // output (the run input for the first agent).\n let builder = Workflow.create({ name: name ?? \"squad\" });\n for (let i = 0; i < agents.length; i++) {\n const member = agents[i];\n if (member === undefined) continue;\n // M81 — materializes at RUN time, not at construction: `Squad.create` is synchronous and an\n // `AgentDefinition` only becomes an agent with an `await`. Deferring to here keeps construction cheap and\n // avoids requiring a resolved credential to assemble a team before the first run.\n const agent = isBuiltAgent(member) ? member : await materialize(member, i);\n // SE3 — the first agent receives the human input (no peer origin); every subsequent agent\n // receives its predecessor's output, so its turn carries `{ kind: \"peer\", from: \"agent-<i-1>\" }`.\n const opts = i > 0 ? { origin: { kind: \"peer\" as const, from: `agent-${i - 1}` } } : undefined;\n builder = builder.then(agentStep(`agent-${i}`, agent, (prev) => String(prev), opts));\n }\n return builder.commit();\n}\n\n/** SE36 — `Squad.create` replaces `createSquad` (ADR 0015). Merges with the `Squad` interface. @public */\n// biome-ignore lint/suspicious/noUnsafeDeclarationMerging: SE36 namespace class merges with the `Squad` instance interface (ADR 0015) — intentional; `create()` returns the interface type, `new` is blocked by the private ctor.\nexport class Squad {\n private constructor() {}\n static create(options: SquadOptions): Squad {\n return createSquad(options);\n }\n}\n","/**\n * `Task` — observable async work registry (Adoption Roadmap gap #2,\n * ADRs D361-D374).\n *\n * Static facade delegating to the in-process `TaskRegistry` singleton.\n * The lifecycle of any task is the 5-state machine `queued | running |\n * finished | error | cancelled` (D362). Wrapping `Agent.send` /\n * `Agent.batch` / `Workflow.run` / `Cron` fires is opt-in via the\n * `{ task: true }` option on each (D363).\n *\n * @public\n */\n\nimport {\n cancel as registryCancel,\n configure as registryConfigure,\n get as registryGet,\n list as registryList,\n submit as registrySubmit,\n subscribe as registrySubscribe,\n} from \"./internal/task/registry.js\";\nimport type {\n TaskCancelResult,\n TaskEvent,\n TaskFilter,\n TaskHandle,\n TaskKind,\n TaskStoreOptions,\n TaskSubmitOptions,\n} from \"./types/task.js\";\n\nexport interface TaskWorkContext {\n readonly signal: AbortSignal;\n emit(payload: unknown): void;\n}\n\n/**\n * The unit of work handed to {@link Task.submit}.\n *\n * It receives the context rather than raw arguments: `ctx.signal` aborts on cancel and should be\n * observed by anything long-running, and `ctx.emit(payload)` produces a `progress` event for\n * subscribers. May be synchronous — the return type allows a plain value as well as a promise.\n *\n * @public\n */\nexport type TaskWorkFn<T> = (ctx: TaskWorkContext) => Promise<T> | T;\n\n/**\n * Registry-level configuration. May only be applied BEFORE the first\n * `Task.submit` of the process — see EC-13. Subsequent calls emit a\n * single stderr line and become no-ops.\n */\nexport interface TaskConfigureOptions {\n readonly store?: TaskStoreOptions;\n readonly maxConcurrent?: number;\n readonly retentionMs?: number;\n}\n\n/**\n * Static facade over the process-wide task registry — the observability layer for asynchronous\n * work.\n *\n * Not instantiable: the constructor throws, and every operation is a static that delegates to one\n * in-process singleton. Tasks are an OPT-IN wrapper. `Agent.send`, `Agent.batch`, `Workflow.run`\n * and `Cron` fires only appear here when submitted with `{ task: true }`; work you submit yourself\n * goes through `Task.submit`.\n *\n * Two ordering constraints bite in practice. `Task.configure` must run before the first `submit` of\n * the process — a later call logs one line and is otherwise a no-op. And `Task.get` returning\n * `undefined` does not mean the id never existed: retention evicts terminal tasks, so an id can go\n * from known to unknown over time.\n *\n * @public\n */\nexport class Task {\n // D361 — static class with private constructor.\n private constructor() {\n throw new Error(\"Task is static; do not instantiate\");\n }\n\n /**\n * Configure the registry. **Must be called before the first `submit`**\n * (EC-13). Available knobs: pluggable store (D364), concurrency cap\n * (D369), and retention (D373).\n */\n static configure(opts: TaskConfigureOptions): void {\n registryConfigure(opts);\n }\n\n /**\n * Submit a unit of asynchronous work to the registry.\n *\n * The `work` function receives `{ signal, emit }` — `signal` is the\n * AbortSignal honored on cancel; `emit(payload)` produces a\n * `progress` event observable via `Task.subscribe`.\n *\n * Returns a `TaskHandle` in `state: \"queued\"`. Subsequent state\n * transitions are observable via `Task.subscribe(handle.id)` OR\n * polled via `Task.get(handle.id)`.\n *\n * **Idempotency (D367):** submitting twice with the same `id` returns\n * the existing handle without re-invoking work.\n *\n * **Grammar (D368):** user-supplied ids must match\n * `^[a-z0-9][a-z0-9_-]*$` and must not start with reserved prefixes\n * `wf-` / `b-` / `cron-`. Otherwise `InvalidTaskIdError` is thrown.\n *\n * **Pre-aborted signal (EC-4):** if `options.signal` is already\n * aborted, the task short-circuits to `cancelled` without acquiring\n * a semaphore slot and without invoking `work`.\n */\n static async submit<T>(\n kind: TaskKind,\n work: TaskWorkFn<T>,\n options: TaskSubmitOptions = {},\n ): Promise<TaskHandle> {\n return registrySubmit<T>({\n kind,\n work,\n ...(options.id !== undefined ? { id: options.id } : {}),\n ...(options.meta !== undefined ? { meta: options.meta } : {}),\n ...(options.signal !== undefined ? { signal: options.signal } : {}),\n ...(options.onRunEvent !== undefined ? { onRunEvent: options.onRunEvent } : {}),\n });\n }\n\n /** Returns matching handles, capped at `filter.limit ?? 100`. */\n static list(filter: TaskFilter = {}): Promise<TaskHandle[]> {\n return registryList(filter);\n }\n\n /** Returns a single handle by id, or `undefined` if unknown / evicted. */\n static get(id: string): Promise<TaskHandle | undefined> {\n return registryGet(id);\n }\n\n /**\n * Idempotent cancel (D365). Returns:\n * - `{ cancelled: true, alreadyTerminal: false }` — transitioned\n * queued/running task to `cancelled`.\n * - `{ cancelled: false, alreadyTerminal: true }` — task already\n * terminal.\n * - `{ cancelled: false, alreadyTerminal: false }` — task unknown.\n *\n * Never throws.\n */\n static cancel(id: string, reason?: string): Promise<TaskCancelResult> {\n return registryCancel(id, reason);\n }\n\n /**\n * Subscribe to a task's event stream. The returned `AsyncIterable<TaskEvent>`\n * starts by replaying buffered events (ring buffer cap 64, D372) and\n * then yields live events until a terminal event (finished / errored\n * / cancelled) is emitted, at which point it closes automatically.\n *\n * Calling `.return()` on the iterator (or `break` in a `for await`)\n * cleans up the subscriber callback (EC-10).\n *\n * Throws `TaskNotFoundError` if the id is unknown or has been evicted.\n */\n static subscribe(id: string): AsyncIterable<TaskEvent> {\n return registrySubscribe(id);\n }\n}\n","import type { SDKProvider } from \"../../types/providers.js\";\nimport type { SDKModel, SDKRepository, SDKUser } from \"../../types/theokit.js\";\nimport { DEFAULT_AGENTIC_MODEL_ID } from \"../runtime/config/default-model.js\";\n\n/**\n * Fixture catalog data — returned when fixture-mode is active (no\n * `THEOKIT_API_BASE_URL` set + `theo_test_*` API key).\n *\n * Shapes here must match the JSON files under `tests/golden/theokit/`\n * after `normalizeForGolden()` is applied. `createdAt` is an ISO timestamp\n * normalized to `<timestamp>` by the test helper.\n *\n * @internal\n */\n\nconst FIXTURE_TIMESTAMP = \"2024-01-01T00:00:00.000Z\";\n\n/** Fixture user identity (matches `tests/golden/theokit/me.json`). */\nexport const FIXTURE_USER: SDKUser = {\n apiKeyName: \"Contract Test Key\",\n userEmail: \"sdk-contract@example.com\",\n createdAt: FIXTURE_TIMESTAMP,\n};\n\n/** Fixture model catalog (matches `tests/golden/theokit/models.json`). */\nexport const FIXTURE_MODELS: SDKModel[] = [\n {\n id: DEFAULT_AGENTIC_MODEL_ID,\n name: \"Gemini 2.0 Flash\",\n displayName: \"Gemini 2.0 Flash\",\n parameters: [\n {\n id: \"thinking\",\n displayName: \"Thinking\",\n values: [\n { value: \"low\", displayName: \"Low\" },\n { value: \"high\", displayName: \"High\" },\n ],\n },\n ],\n variants: [\n {\n displayName: \"High thinking\",\n params: [{ id: \"thinking\", value: \"high\" }],\n isDefault: false,\n },\n ],\n },\n];\n\n/** Fixture connected repos (matches `tests/golden/theokit/repositories.json`). */\nexport const FIXTURE_REPOSITORIES: SDKRepository[] = [\n { url: \"https://github.com/usetheo/example\" },\n];\n\n/**\n * Generic JSON Schema used as `setupSchema` for fixture providers. The\n * property name is intentionally generic (`credential`) so the schema never\n * contains substrings that look like environment variable names for real\n * provider tokens — fixture output must remain secret-shaped-noise-free.\n */\nconst GENERIC_SETUP_SCHEMA = {\n type: \"object\",\n description: \"Configuration values for this provider.\",\n required: [\"credential\"],\n properties: { credential: { type: \"string\" } },\n} as const;\n\n/**\n * Fixture provider catalog. Covers chat, web_search, image, and embedding\n * capabilities. The `setupSchema` is intentionally generic JSON Schema —\n * consumers drive UI from these definitions.\n *\n * Public and secret-free by design — no tokens or API key examples.\n */\nexport const FIXTURE_PROVIDERS: SDKProvider[] = [\n {\n name: \"anthropic\",\n displayName: \"Anthropic\",\n capabilities: [\"chat\"],\n isAvailable: true,\n setupSchema: GENERIC_SETUP_SCHEMA,\n },\n {\n name: \"openai\",\n displayName: \"OpenAI\",\n capabilities: [\"chat\", \"embedding\", \"image\"],\n isAvailable: false,\n setupSchema: GENERIC_SETUP_SCHEMA,\n },\n {\n name: \"openrouter\",\n displayName: \"OpenRouter\",\n capabilities: [\"chat\"],\n isAvailable: true,\n setupSchema: GENERIC_SETUP_SCHEMA,\n },\n {\n name: \"nous\",\n displayName: \"Nous Research\",\n capabilities: [\"chat\"],\n isAvailable: true,\n setupSchema: GENERIC_SETUP_SCHEMA,\n },\n {\n name: \"fixture-search\",\n displayName: \"Fixture Search\",\n capabilities: [\"web_search\"],\n isAvailable: true,\n setupSchema: GENERIC_SETUP_SCHEMA,\n },\n];\n","/**\n * Local model discovery via OpenAI-compatible `/v1/models` endpoint\n * (T2.1, ADR D184).\n *\n * Used by `Theokit.models.list({ provider: \"ollama\" })` (and any other\n * future provider with `authType: \"none\"` exposing the OpenAI-shape\n * models endpoint — LM Studio, llama.cpp `./server`, vLLM, etc.) to\n * enumerate locally-installed models without a cloud round-trip.\n *\n * Aligned with peer-project `extensions/ollama/src/provider-models.ts` which\n * targets the same endpoint shape. Mirrors the relevant Hermes\n * `models.dev` catalog behavior for local providers.\n *\n * @internal\n */\n\nimport { ConfigurationError } from \"../../errors.js\";\nimport type { SDKModel } from \"../../types/theokit.js\";\nimport { mapOllamaHttpError, mapOllamaTransportError } from \"../error-mappers/ollama.js\";\nimport { readErrorResponseBody } from \"../http.js\";\n\ninterface OpenAiModelsResponse {\n object?: string;\n data?: Array<{ id?: string; owned_by?: string }>;\n}\n\n/**\n * Fetch and map `<baseUrl>/v1/models` → `SDKModel[]`. Throws a typed\n * `ConfigurationError` on connection failures (ECONNREFUSED → \"Run\n * `ollama serve`\"). Returns `[]` when the body is unparseable —\n * defensive choice over crashing on malformed responses from\n * non-standard local runtimes.\n */\nexport async function listLocalModelsViaOpenAiCompat(baseUrl: string): Promise<SDKModel[]> {\n const url = `${baseUrl}/v1/models`;\n let response: Response;\n try {\n response = await fetch(url, { method: \"GET\" });\n } catch (fetchErr) {\n const mapped = mapOllamaTransportError({\n providerId: \"ollama\",\n cause: fetchErr,\n endpoint: \"/v1/models\",\n });\n if (mapped !== undefined) throw mapped;\n throw new ConfigurationError(\n `Failed to reach local provider at ${baseUrl}: ${(fetchErr as Error).message}`,\n { code: \"local_provider_unreachable\" },\n );\n }\n if (!response.ok) {\n const body = await readErrorResponseBody(response);\n const mapped = mapOllamaHttpError({\n providerId: \"ollama\",\n status: response.status,\n body,\n headers: response.headers,\n endpoint: \"/v1/models\",\n });\n if (mapped !== undefined) throw mapped;\n throw new ConfigurationError(\n `Local provider at ${baseUrl} returned HTTP ${response.status} on /v1/models`,\n { code: \"local_provider_http_error\" },\n );\n }\n let parsed: OpenAiModelsResponse;\n try {\n parsed = (await response.json()) as OpenAiModelsResponse;\n } catch {\n return [];\n }\n const data = parsed.data ?? [];\n return data\n .filter(\n (entry): entry is { id: string } => typeof entry?.id === \"string\" && entry.id.length > 0,\n )\n .map((entry) => ({\n id: entry.id,\n displayName: entry.id,\n name: entry.id,\n }));\n}\n","import { AuthenticationError } from \"./errors.js\";\nimport {\n FIXTURE_MODELS,\n FIXTURE_PROVIDERS,\n FIXTURE_REPOSITORIES,\n FIXTURE_USER,\n} from \"./internal/catalog/fixtures.js\";\nimport { listLocalModelsViaOpenAiCompat } from \"./internal/catalog/local-models.js\";\nimport { resolveApiKey } from \"./internal/env.js\";\nimport { httpRequest } from \"./internal/http.js\";\nimport { MEMORY_EMBEDDING_ADAPTERS } from \"./internal/memory/adapters/catalog.js\";\nimport {\n getCatalogCapabilities,\n type ProviderCapabilities,\n} from \"./internal/providers/catalog-loader.js\";\nimport {\n discoverProviderPlugins,\n getProviderProfile,\n listProviders,\n registerBuiltins,\n} from \"./internal/providers/index.js\";\nimport { isFixtureApiKey, shouldUseFixtureMode } from \"./internal/runtime/fixtures/fixture-mode.js\";\nimport type { SDKProvider } from \"./types/providers.js\";\nimport type { SDKModel, SDKRepository, SDKUser } from \"./types/theokit.js\";\n\n/**\n * Options shared by every `Theokit.*` request.\n *\n * @public\n */\nexport interface TheokitRequestOptions {\n /** Override the `THEOKIT_API_KEY` env var for this call. */\n apiKey?: string;\n /**\n * Target a specific provider for catalog reads. When set to a provider\n * with `authType: \"none\"` (e.g. `\"ollama\"`, `\"lmstudio\"`, `\"llamacpp\"`),\n * `Theokit.models.list({ provider })` reads from the provider's local\n * `/v1/models` endpoint instead of the TheoCloud catalog. ADR D184.\n *\n * @public\n */\n provider?: string;\n}\n\n/**\n * Account-level and catalog reads. All methods accept an optional `apiKey`\n * and otherwise fall back to the `THEOKIT_API_KEY` environment variable.\n *\n * @public\n */\nexport class Theokit {\n private constructor() {\n // Static-only namespace.\n }\n\n /**\n * Return the user behind the current API key.\n *\n * @public\n */\n static me(options: TheokitRequestOptions = {}): Promise<SDKUser> {\n return executeCatalogRequest({\n apiKey: options.apiKey,\n fixture: FIXTURE_USER,\n path: \"/v1/me\",\n });\n }\n\n /**\n * Model catalog reads.\n *\n * @public\n */\n static readonly models: {\n list: (options?: TheokitRequestOptions) => Promise<SDKModel[]>;\n capabilities: (providerOrModelId: string) => ProviderCapabilities | undefined;\n } = {\n list: async (options = {}) => {\n // ADR D184: when `provider` targets an `authType: \"none\"` provider,\n // read locally instead of hitting TheoCloud. Cloud catalog path is\n // unchanged when `provider` is undefined.\n if (options.provider !== undefined) {\n const localModels = await maybeListLocalModels(options.provider);\n if (localModels !== undefined) return localModels;\n }\n return executeCatalogRequest({\n apiKey: options.apiKey,\n fixture: FIXTURE_MODELS,\n path: \"/v1/models\",\n });\n },\n capabilities: (providerOrModelId: string) => {\n registerBuiltins();\n // Extract provider name from \"provider/model\" format\n const providerId = providerOrModelId.includes(\"/\")\n ? (providerOrModelId.split(\"/\")[0] ?? providerOrModelId)\n : providerOrModelId;\n return getCatalogCapabilities(providerId);\n },\n };\n\n /**\n * Connected GitHub repositories for the calling user's team. Cloud only.\n *\n * @public\n */\n static readonly repositories: {\n list: (options?: TheokitRequestOptions) => Promise<SDKRepository[]>;\n } = {\n list: (options = {}) =>\n executeCatalogRequest({\n apiKey: options.apiKey,\n fixture: FIXTURE_REPOSITORIES,\n path: \"/v1/repositories\",\n }),\n };\n\n /**\n * Provider catalog. Lists every provider known to the platform, including\n * plugin-registered ones, with capability and availability metadata.\n *\n * @public\n */\n static readonly providers: {\n list: (options?: TheokitRequestOptions) => Promise<SDKProvider[]>;\n } = {\n list: (options = {}) =>\n executeCatalogRequest({\n apiKey: options.apiKey,\n fixture: FIXTURE_PROVIDERS,\n path: \"/v1/providers\",\n }),\n };\n\n /**\n * Local introspection of bundled SDK assets (ADR D201). Unlike the\n * cloud-catalog `providers.list()` (which hits the TheoCloud HTTP API),\n * `inspect.*` reads the SDK's own bundled registries — useful for\n * tooling (e.g. `@theokit/cli`'s `theokit inspect`) that needs to know\n * what's available WITHOUT a network round-trip.\n *\n * @public\n */\n static readonly inspect: {\n builtinProviders: () => Array<{\n readonly name: string;\n readonly apiMode: string;\n readonly authType: string;\n readonly baseUrl: string;\n readonly aliases?: ReadonlyArray<string>;\n readonly envVars: ReadonlyArray<string>;\n }>;\n embeddingAdapters: () => Array<{\n readonly id: string;\n readonly transport: string;\n readonly defaultModel: string;\n }>;\n } = {\n builtinProviders: () => {\n registerBuiltins();\n return listProviders().map((p) => ({\n name: p.name,\n apiMode: p.apiMode,\n authType: p.authType,\n baseUrl: p.baseUrl,\n ...(p.aliases !== undefined ? { aliases: p.aliases } : {}),\n envVars: p.envVars,\n }));\n },\n embeddingAdapters: () =>\n Object.entries(MEMORY_EMBEDDING_ADAPTERS).map(([id, adapter]) => ({\n id,\n transport: adapter.transport,\n defaultModel: adapter.defaultModel,\n })),\n };\n\n // NOTE: `Theokit.subscribe` is exported from `@theokit/sdk/subscription`\n // sub-path entry instead of the main `Theokit` static class to avoid\n // pulling the subscription module into the main `index.ts` DTS bundle\n // (which trips on the pre-existing `types/agent.ts ↔ fork-agent.ts` cycle\n // — same pattern as `path-safety` per ADR D425/D429 + see tsup.config.ts\n // header comment). Consumers import via:\n // `import { subscribe } from \"@theokit/sdk/subscription\"`\n // The function shape mirrors a hypothetical `Theokit.subscribe(name, input, opts)`\n // and may be promoted onto Theokit once the agent.ts cycle is broken.\n}\n\n/**\n * ADR D184: when caller passed `{ provider }` targeting a profile with\n * `authType: \"none\"`, fetch from the local provider's `/v1/models`.\n * Returns `undefined` when the provider does not exist OR has auth —\n * caller falls back to the cloud catalog path.\n */\nasync function maybeListLocalModels(providerName: string): Promise<SDKModel[] | undefined> {\n registerBuiltins();\n // M47 review F2 — this async entrypoint resolves provider profiles, so plugin discovery must run\n // here too (the sync surfaces `models.capabilities()` / `inspect.builtinProviders()` intentionally\n // remain builtins-only — they cannot await; documented limitation).\n await discoverProviderPlugins();\n const profile = getProviderProfile(providerName);\n if (profile === undefined) return undefined;\n if (profile.authType !== \"none\") return undefined;\n const baseUrl = resolveLocalProviderBaseUrl(profile.name, profile.baseUrl);\n return listLocalModelsViaOpenAiCompat(baseUrl);\n}\n\nfunction resolveLocalProviderBaseUrl(providerName: string, fallback: string): string {\n // Mirror the env override priority used in router.ts selectTransport.\n if (providerName === \"ollama\" && process.env.OLLAMA_HOST !== undefined) {\n return process.env.OLLAMA_HOST;\n }\n return fallback;\n}\n\ninterface CatalogRequest<T> {\n apiKey: string | undefined;\n fixture: T;\n path: string;\n}\n\nasync function executeCatalogRequest<T>(request: CatalogRequest<T>): Promise<T> {\n const apiKey = resolveApiKey(request.apiKey);\n if (apiKey === undefined) {\n throw new AuthenticationError(\"Missing API key\", { code: \"missing_api_key\" });\n }\n\n if (shouldUseFixtureMode(apiKey)) {\n return request.fixture;\n }\n\n // Fixture-mode is off — either an explicit base URL is set (real HTTP)\n // or a non-fixture key is being used without a backend reachable.\n if (!isFixtureApiKey(apiKey) && process.env.THEOKIT_API_BASE_URL === undefined) {\n throw new AuthenticationError(\"Invalid API key\", { code: \"authentication_error\" });\n }\n\n return httpRequest<T>(request.path, { apiKey });\n}\n","/**\n * Attach a blast-radius declaration to a tool, so the approval layer gates on what the tool DOES.\n *\n * Without this the only key available to a policy is the tool's NAME, which says nothing about the\n * action, drifts the moment a tool is renamed, and cannot be reviewed by anyone who did not write\n * it. `delete_namespace` and `list_pods` differ by a word.\n *\n * ## Why a wrapper rather than a field on the input schema\n *\n * `inputSchema` is what the MODEL sees. Blast radius is not for the model — it is for the approval\n * layer — and putting it there would leak policy into the prompt and let a model-authored argument\n * influence its own gate. The declaration rides alongside the tool instead, under a symbol so it\n * cannot collide with a tool's own properties or be serialised into a prompt by accident.\n *\n * @public\n */\n\nimport type { DeclaredAction } from \"./blast-radius.js\";\n\n/**\n * Symbol-keyed on purpose. THAT is what keeps the declaration out of a prompt: `Object.keys` and\n * `JSON.stringify` both ignore symbol keys, so a tool serialised on its way to the model carries\n * none of it. A string key would also risk colliding with a property the tool already has.\n *\n * Exported because the `@public` `WithBlastRadius<T>` below uses it as a COMPUTED\n * KEY. A computed key is part of the type it keys, so the emitted declaration\n * names this const — and a name the declaration file does not carry is a broken\n * reference (#335). `Symbol.for` keeps it a registry symbol, so an exported\n * binding does not weaken the property-hiding this comment describes: the value\n * was always retrievable by any code that knows the string.\n *\n * @public\n */\nexport const DECLARED: unique symbol = Symbol.for(\"@theokit/sdk.blastRadius\") as typeof DECLARED;\n\n/**\n * A tool that may carry a blast-radius declaration under {@link DECLARED}.\n *\n * The property is OPTIONAL in the type, so a plain tool is assignable to it and the type alone\n * never proves a declaration was made. `describeAction` is what tells the two apart at runtime.\n *\n * @public\n */\nexport type WithBlastRadius<T> = T & { readonly [DECLARED]?: DeclaredAction };\n\n/**\n * Declare what a tool reaches, for the approval layer rather than for the model.\n *\n * This MUTATES `tool` — it defines a symbol-keyed property on the object it was given and hands\n * the same reference back, so every existing reference to that tool sees the declaration too.\n * Calling it again on the same tool replaces the previous declaration; the property is\n * `configurable`, so re-declaring never throws.\n *\n * The declaration is invisible to `Object.keys` and `JSON.stringify` because the key is a symbol,\n * which is what keeps it out of anything serialised into a prompt.\n *\n * @returns the same tool, with its action declared. The tool is not otherwise altered — the model\n * must see exactly what it saw before.\n * @public\n */\nexport function withBlastRadius<T extends object>(\n tool: T,\n action: DeclaredAction,\n): WithBlastRadius<T> {\n return Object.defineProperty(tool, DECLARED, {\n value: action,\n // `enumerable: false` is defensive and NOT load-bearing — checked, not assumed. Flipping it to\n // true leaves every case green, because the symbol key already excludes this from `Object.keys`\n // and `JSON.stringify`. It stays because a future string-keyed variant would need it, and the\n // next reader should not have to discover that the flag has no test behind it.\n enumerable: false,\n configurable: true,\n }) as WithBlastRadius<T>;\n}\n\n/**\n * Read back the action a tool declared, if any.\n *\n * This is how an approval layer obtains the `action` for `evaluateBlastRadius`. An `undefined`\n * result means nobody has reviewed this tool's reach, which is a different fact from a tool that\n * declared a narrow scope — decide what to do with the unreviewed case explicitly rather than\n * treating it as harmless.\n *\n * @returns the declared action, or `undefined` when the tool never declared one — NOT an empty\n * action. \"Never declared\" and \"declared as reaching nothing\" are different facts, and collapsing\n * them is how an unreviewed tool passes as harmless.\n * @public\n */\nexport function describeAction(tool: object): DeclaredAction | undefined {\n return (tool as { [DECLARED]?: DeclaredAction })[DECLARED];\n}\n","/**\n * `toShareGptTrajectory` — opt-in BatchResult → ShareGPT converter (ADR D139).\n *\n * Pure transformation. Returns `null` for failed results so callers can\n * filter via `.map(toShareGptTrajectory).filter(Boolean)`. Tool calls and\n * tool results are preserved when an SDKMessage trace is provided; otherwise\n * a minimal `human → gpt` trajectory is emitted from the final text.\n *\n * @public\n */\n\nimport type { BatchResult } from \"./types/batch.js\";\nimport type { SDKMessage, TextBlock, ToolUseBlock } from \"./types/messages.js\";\nimport type { ShareGptMessage, ShareGptTrajectory } from \"./types/trajectory.js\";\n\n/**\n * Convert a successful `BatchResult` to ShareGPT-format trajectory.\n *\n * Behavior:\n * - `result.ok === false` → returns `null` (EC-11).\n * - First entry is always `{from: \"human\", value: result.prompt}`.\n * - When `options.messages` is supplied, each SDKMessage maps to one or\n * more ShareGPT entries (assistant text → gpt, tool_use → gpt + tool).\n * - Without `options.messages`, fall back to a single `{from: \"gpt\"}`\n * entry carrying `result.result.result` (the final text) when present.\n * - Malformed message entries are silently skipped (EC-F / EC-14).\n *\n * @public\n */\nexport function toShareGptTrajectory(\n result: BatchResult,\n options?: { messages?: SDKMessage[]; model?: string },\n): ShareGptTrajectory | null {\n if (!result.ok) return null;\n const conversations = buildConversations(result, options?.messages);\n const trajectory: ShareGptTrajectory = {\n conversations,\n metadata: {\n timestamp: new Date().toISOString(),\n durationMs: result.durationMs,\n promptIndex: result.index,\n ...(options?.model !== undefined ? { model: options.model } : {}),\n },\n completed: true,\n };\n const usage = extractUsage(result.result);\n if (usage !== undefined) trajectory.usage = usage;\n return trajectory;\n}\n\nfunction buildConversations(\n result: Extract<BatchResult, { ok: true }>,\n messages: SDKMessage[] | undefined,\n): ShareGptMessage[] {\n const conversations: ShareGptMessage[] = [{ from: \"human\", value: result.prompt }];\n if (Array.isArray(messages) && messages.length > 0) {\n for (const m of messages) {\n for (const entry of mapSdkMessage(m)) conversations.push(entry);\n }\n return conversations;\n }\n // Fall-back: minimal {gpt} entry with final text (EC-12).\n const finalText = typeof result.result.result === \"string\" ? result.result.result : \"\";\n conversations.push({ from: \"gpt\", value: finalText });\n return conversations;\n}\n\nfunction extractUsage(\n runResult: unknown,\n): { inputTokens: number; outputTokens: number } | undefined {\n const usage = (runResult as { usage?: { inputTokens?: unknown; outputTokens?: unknown } })?.usage;\n if (usage === undefined) return undefined;\n if (typeof usage.inputTokens !== \"number\" || typeof usage.outputTokens !== \"number\") {\n return undefined;\n }\n return { inputTokens: usage.inputTokens, outputTokens: usage.outputTokens };\n}\n\n/**\n * Map one SDKMessage to zero or more ShareGPT entries. Tool-use blocks\n * inside an assistant message split into a `gpt` entry with `tool_calls`\n * plus, when paired with a `tool_call.completed` event, a `tool` entry\n * carrying the result.\n *\n * Malformed shapes (missing `message.content`, non-array content) yield\n * an empty list — caller skips silently (EC-F).\n *\n * @internal\n */\nfunction mapSdkMessage(m: SDKMessage): ShareGptMessage[] {\n if (m === null || typeof m !== \"object\") return [];\n switch (m.type) {\n case \"assistant\":\n return mapAssistant(m);\n case \"tool_call\":\n return mapToolCall(m);\n case \"thinking\":\n case \"system\":\n case \"user\":\n case \"status\":\n case \"task\":\n case \"request\":\n case \"object_delta\":\n return [];\n default: {\n // Exhaustive sentinel — unreachable on stable SDKMessage union.\n const _exhaustive: never = m;\n void _exhaustive;\n return [];\n }\n }\n}\n\nfunction mapAssistant(m: Extract<SDKMessage, { type: \"assistant\" }>): ShareGptMessage[] {\n const content = m.message?.content;\n if (!Array.isArray(content)) return [];\n const textParts: string[] = [];\n const toolCalls: NonNullable<ShareGptMessage[\"tool_calls\"]> = [];\n for (const block of content) {\n appendBlock(block, textParts, toolCalls);\n }\n const entry: ShareGptMessage = { from: \"gpt\", value: textParts.join(\"\") };\n if (toolCalls.length > 0) entry.tool_calls = toolCalls;\n return [entry];\n}\n\nfunction appendBlock(\n block: unknown,\n textParts: string[],\n toolCalls: NonNullable<ShareGptMessage[\"tool_calls\"]>,\n): void {\n if (block === null || typeof block !== \"object\") return;\n const text = block as TextBlock;\n if (text.type === \"text\" && typeof text.text === \"string\") {\n textParts.push(text.text);\n return;\n }\n const tu = block as ToolUseBlock;\n if (tu.type !== \"tool_use\") return;\n const args =\n tu.input !== null && typeof tu.input === \"object\" ? (tu.input as Record<string, unknown>) : {};\n toolCalls.push({ name: tu.name, arguments: args });\n}\n\nfunction mapToolCall(m: Extract<SDKMessage, { type: \"tool_call\" }>): ShareGptMessage[] {\n // Only emit when the tool call completed — running/error are interim states.\n if (m.status !== \"completed\") return [];\n const value =\n typeof m.result === \"string\" ? m.result : m.result === undefined ? \"\" : safeStringify(m.result);\n return [{ from: \"tool\", value }];\n}\n\nfunction safeStringify(v: unknown): string {\n try {\n return JSON.stringify(v);\n } catch {\n return String(v);\n }\n}\n","/**\n * Decide what a project directory is allowed to switch on.\n *\n * A product that reads a repository has to answer this before it builds anything: are that\n * repository's hooks honoured, are its MCP servers started, do its instructions enter the persona?\n * The stakes are not configuration-shaped. A hook is arbitrary command execution on every tool\n * call, and an MCP server is an external process SPAWNED while the agent is built — before any\n * per-tool approval exists to refuse it. A product that gets this wrong grants local execution on\n * first build, in a directory the user only meant to open.\n *\n * ## What this is, and what it deliberately is not\n *\n * The arithmetic is small: pick a level, derive one boolean per capability. The value is the\n * INVARIANT — untrusted means EVERY declared capability is off, and `allows` is built FROM the\n * declared list, so a product that adds a ninth capability cannot forget to gate it. That failure\n * is invisible when it happens: the new capability simply works in a directory where it should not,\n * and nothing reports anything.\n *\n * It does NOT decide what \"trusted\" means. Where the record lives, what the environment variable is\n * called, whether a legacy alias is still honoured — all of that is the consumer's, because all of\n * it is that product's vocabulary. The framework owns the shape of the answer and the guarantee\n * that the answer covers everything declared.\n *\n * ## Why `source` is reported\n *\n * \"Trusted because the operator recorded this directory\" and \"trusted because a blanket environment\n * switch is on\" are different facts. A surface that only shows `trusted` cannot warn about the\n * second, which is the one that stays on across every directory the process ever opens.\n *\n * @public\n */\n\n/**\n * Whether a project directory may switch anything on.\n *\n * There is no middle level on purpose: `untrusted` means every declared capability is off, not\n * \"some are off\". A product that wants a partial grant expresses it by declaring fewer capabilities\n * for that call, not by inventing a third level here.\n *\n * @public\n */\nexport type TrustLevel = \"trusted\" | \"untrusted\";\n\n/** Where the decision came from. @public */\nexport type TrustSource = \"env\" | \"store\" | \"default\";\n\n/**\n * What the decision is made from: the capability vocabulary, a way to read the operator's record,\n * and an optional blanket override.\n *\n * `capabilities` is load-bearing rather than descriptive — the returned `allows` is built from\n * exactly this list, so a capability missing from it is a capability nothing gates.\n *\n * @public\n */\nexport interface TrustPostureInput<K extends string> {\n /**\n * Every capability a repository could switch on. `allows` is built from exactly this list — the\n * guarantee that nothing is left ungated.\n */\n readonly capabilities: readonly K[];\n /**\n * Whether the operator has recorded this directory as trusted. Called at most once, and not at\n * all when `envOverride` already granted trust — it may touch the filesystem.\n */\n readonly isTrusted: () => boolean;\n /**\n * A blanket override from the consumer's own environment vocabulary. `true` grants trust;\n * `false` and `undefined` both mean \"the operator did not switch it on\" — NOT \"switched it off\",\n * because an unset variable must not override a trusted store.\n */\n readonly envOverride?: boolean;\n}\n\n/**\n * The decision: the level, where it came from, and one boolean per declared capability.\n *\n * `allows` has exactly the keys of the `capabilities` list it was built from, so reading a\n * capability the caller never declared is a type error rather than a silent `undefined` that a\n * consumer would read as \"not allowed\".\n *\n * @public\n */\nexport interface TrustPosture<K extends string> {\n readonly level: TrustLevel;\n readonly source: TrustSource;\n /** One entry per declared capability. Every value is `false` when the level is untrusted. */\n readonly allows: Readonly<Record<K, boolean>>;\n}\n\n/**\n * Decide what a project directory is allowed to switch on.\n *\n * Precedence: `envOverride === true` grants trust and SHORT-CIRCUITS — `isTrusted` is not called at\n * all, which matters because it may touch the filesystem. Otherwise `isTrusted()` is called exactly\n * once and its answer decides. `envOverride === false` is not a denial: it falls through to the\n * store like `undefined` does, so an unset or explicitly-off environment switch can never revoke a\n * directory the operator recorded as trusted.\n *\n * Every entry of `allows` is `false` whenever the level is untrusted, and the entries are generated\n * from `capabilities` rather than supplied per capability — that is what makes \"nothing was left\n * ungated\" a property of the call instead of a habit of the caller.\n *\n * @public\n */\nexport function resolveTrustPosture<K extends string>(\n input: TrustPostureInput<K>,\n): TrustPosture<K> {\n const source: TrustSource =\n input.envOverride === true ? \"env\" : input.isTrusted() ? \"store\" : \"default\";\n const level: TrustLevel = source === \"default\" ? \"untrusted\" : \"trusted\";\n const granted = level === \"trusted\";\n\n // Built from the declared list rather than from anything the caller passes per capability: that\n // is what makes \"nothing is ungated\" a property of the type instead of a habit.\n const allows = Object.fromEntries(input.capabilities.map((key) => [key, granted])) as Record<\n K,\n boolean\n >;\n\n return { level, source, allows };\n}\n","/**\n * Record what a build actually wired, as opposed to what configuration asked for.\n *\n * A product that reads a project directory decides, while building, which of that directory's\n * entities it will honour: MCP servers, skills, hook events, commands. When a trust posture withholds\n * them, the build simply proceeds with fewer — and every surface that later asks \"what is loaded?\"\n * sees an empty list. Empty because nothing was configured and empty because everything was withheld\n * are the same emptiness to the reader, and only one of them is something they can act on.\n *\n * ## Why this is not a re-read\n *\n * The obvious implementation of any \"what is loaded?\" listing is to read the configuration again.\n * That is the defect this exists to prevent: a re-read cannot detect a disagreement between what\n * config asked for and what the build did, because it IS the config. The two disagree exactly when\n * something suppressed an entity, which is the case worth reporting.\n *\n * So this function is pure and parameterized. It performs no I/O, which is what makes \"no second\n * read\" checkable rather than promised — the caller passes the values it handed to the builder, at\n * the moment it handed them over, and what comes back is an observation of that moment.\n *\n * ## What is generic here, and what is not\n *\n * The RULE is generic: for each capability, active is the request when allowed and empty when not,\n * and suppression is only claimed when something was actually removed. The VOCABULARY is not —\n * which capabilities exist and what the entities are called belong to the product, and arrive as\n * data.\n *\n * @public\n */\n\nimport { TheokitAgentError } from \"./errors.js\";\n\n/** Raised when a recorded capability has no entry in the gate. @public */\nexport class UngatedCapabilityError extends TheokitAgentError {\n override readonly name = \"UngatedCapabilityError\";\n}\n\n/** What one capability asked for, and what it got. @public */\nexport interface WiredEntity {\n /** The names actually handed to the builder. Empty when the capability was withheld. */\n readonly active: readonly string[];\n /**\n * The names configuration ASKED for. Equal to `active` when nothing was withheld; the difference\n * is exactly what the reader cannot otherwise see.\n */\n readonly requested: readonly string[];\n /**\n * True only when the gate is what emptied `active`.\n *\n * Deliberately false for a withheld capability that requested nothing: an untrusted directory with\n * no skills and a trusted one with no skills are the same emptiness, and a flag that fires when\n * nothing happened teaches the reader to ignore it.\n */\n readonly suppressedByTrust: boolean;\n}\n\n/**\n * The two halves of the observation: the gate that was applied, and what was handed to the builder.\n *\n * `requested` drives the shape of the record — the result has exactly its keys — while `posture`\n * only has to contain a gate for each of them. A posture that gates MORE than `requested` covers is\n * fine and normal; a posture that gates FEWER is refused, see `recordWiring`.\n *\n * Pass the values at the moment they go to the builder. Re-deriving them from configuration\n * afterwards would defeat the point: config is what was asked for, and the disagreement with what\n * was wired is the only thing this records.\n *\n * @public\n */\nexport interface WiringRecordInput<K extends string> {\n /**\n * The gate. Typically the output of `resolveTrustPosture`, which is what makes the name\n * `suppressedByTrust` accurate rather than decorative — a posture is the only thing in this\n * package that withholds a capability.\n *\n * It may gate MORE than `requested` covers: a posture also gates things that are not lists of\n * names, like durable memory. Those are not entities and do not appear in the record.\n */\n readonly posture: { readonly allows: Readonly<Record<string, boolean>> };\n /** Per capability, the entity names the build was given. Drives which keys the record has. */\n readonly requested: Readonly<Record<K, readonly string[]>>;\n}\n\n/**\n * Record what a build actually wired, per capability.\n *\n * For each key of `requested`: `active` is a copy of the requested names when the posture allows\n * that capability and an empty array when it does not, `requested` is always a copy of what was\n * asked for, and `suppressedByTrust` is true only when the gate emptied a NON-EMPTY request. A\n * withheld capability that requested nothing reports `false`, because a flag that fires when\n * nothing happened is a flag readers learn to ignore.\n *\n * Pure and synchronous — it performs no I/O, which is what makes \"this is not a second read of the\n * configuration\" checkable rather than promised.\n *\n * @returns one entry per key of `requested`, each a snapshot rather than a view of the caller's\n * arrays — the record is read long after the build, and aliasing would make it answer with what\n * the process holds now instead of with what was wired.\n * @throws UngatedCapabilityError when a key of `requested` has no entry in `posture.allows`. Absent\n * is not read as denied: reporting a capability nobody gates as suppressed would send the reader\n * looking for a trust setting that does not exist.\n * @public\n */\nexport function recordWiring<K extends string>(\n input: WiringRecordInput<K>,\n): Readonly<Record<K, WiredEntity>> {\n const record = {} as Record<K, WiredEntity>;\n for (const [capability, requested] of Object.entries(input.requested) as [\n K,\n readonly string[],\n ][]) {\n const allowed = input.posture.allows[capability];\n if (allowed === undefined) {\n // Fail loudly rather than defaulting. Reading an absent gate as \"not allowed\" would report a\n // capability nobody gates as SUPPRESSED — a plausible answer, and wrong in the direction the\n // reader cannot check: they would go looking for a trust setting that does not exist.\n throw new UngatedCapabilityError(\n `capability \\`${capability}\\` was recorded as wired but the posture does not gate it; ` +\n `gated capabilities are: ${Object.keys(input.posture.allows).join(\", \") || \"(none)\"}`,\n );\n }\n record[capability] = {\n // Copied, not aliased. See the @returns note.\n active: allowed ? [...requested] : [],\n requested: [...requested],\n suppressedByTrust: !allowed && requested.length > 0,\n };\n }\n return record;\n}\n"]}
|