@theokit/sdk-memory 0.6.3 → 0.7.3

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.
Files changed (37) hide show
  1. package/CHANGELOG.md +53 -0
  2. package/dist/index.cjs +120 -387
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.d.cts +2 -2
  5. package/dist/index.d.ts +2 -2
  6. package/dist/index.d.ts.map +1 -1
  7. package/dist/index.js +6 -356
  8. package/dist/index.js.map +1 -1
  9. package/dist/internal/active-memory/active-memory.d.ts +1 -1
  10. package/dist/internal/active-memory/active-memory.d.ts.map +1 -1
  11. package/dist/internal/adapter-catalog.d.ts +2 -10
  12. package/dist/internal/adapter-catalog.d.ts.map +1 -1
  13. package/dist/internal/embedding/azure-openai-embedding.d.ts +1 -42
  14. package/dist/internal/embedding/azure-openai-embedding.d.ts.map +1 -1
  15. package/dist/internal/embedding/cohere-embedding.d.ts +1 -29
  16. package/dist/internal/embedding/cohere-embedding.d.ts.map +1 -1
  17. package/dist/internal/embedding/deepinfra-embedding.d.ts +1 -30
  18. package/dist/internal/embedding/deepinfra-embedding.d.ts.map +1 -1
  19. package/dist/internal/embedding/gemini-embedding.d.ts +1 -26
  20. package/dist/internal/embedding/gemini-embedding.d.ts.map +1 -1
  21. package/dist/internal/embedding/jina-embedding.d.ts +1 -21
  22. package/dist/internal/embedding/jina-embedding.d.ts.map +1 -1
  23. package/dist/internal/embedding/mistral-embedding.d.ts +1 -23
  24. package/dist/internal/embedding/mistral-embedding.d.ts.map +1 -1
  25. package/dist/internal/embedding/ollama-embedding.d.ts +1 -61
  26. package/dist/internal/embedding/ollama-embedding.d.ts.map +1 -1
  27. package/dist/internal/embedding/openai-embedding.d.ts +1 -33
  28. package/dist/internal/embedding/openai-embedding.d.ts.map +1 -1
  29. package/dist/internal/embedding/openrouter-embedding.d.ts +1 -29
  30. package/dist/internal/embedding/openrouter-embedding.d.ts.map +1 -1
  31. package/dist/internal/embedding/voyage-embedding.d.ts +1 -24
  32. package/dist/internal/embedding/voyage-embedding.d.ts.map +1 -1
  33. package/dist/internal/store/markdown-store.d.ts +1 -1
  34. package/dist/internal/store/markdown-store.d.ts.map +1 -1
  35. package/package.json +3 -3
  36. package/dist/internal/circuit-breaker.d.ts +0 -53
  37. package/dist/internal/circuit-breaker.d.ts.map +0 -1
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/in-memory-provider.ts","../src/internal/store/markdown-store.ts","../src/internal/active-memory/active-memory.ts","../src/internal/circuit-breaker.ts","../src/internal/embedding/azure-openai-embedding.ts","../src/internal/embedding/cohere-embedding.ts","../src/internal/embedding/deepinfra-embedding.ts","../src/internal/embedding/gemini-embedding.ts","../src/internal/embedding/jina-embedding.ts","../src/internal/embedding/mistral-embedding.ts","../src/internal/embedding/ollama-embedding.ts","../src/internal/embedding/openai-embedding.ts","../src/internal/embedding/openrouter-embedding.ts","../src/internal/embedding/voyage-embedding.ts","../src/internal/adapter-catalog.ts","../src/internal/memory-types.ts","../src/internal/adapter-http-error.ts","../src/internal/categorized-memory.ts","../src/internal/index/lance-memory-adapter.ts","../src/internal/index/sqlite-vec-loader.ts","../src/internal/tools.ts"],"names":["ceilingReachedError","ConfigurationError","Security","sessionsDir","join","readdir","readFile","resolveMaxFacts","mkdir","replaceFileAtomic","notesDir","resolveMemoryRoot","finalized","persistActiveMemoryTranscript","createOpenAiCompatibleRuntime","DIMENSION_BY_MODEL","resolvePath","sanitizeIdentifier","safePathJoin","AuthenticationError","RateLimitError","NetworkError","UnknownAgentError","withCwdMutex","SharedLanceMemoryAdapter","readMemoryFileBounded"],"mappings":";;;;;;;;;;;;AA8CA,IAAM,UAAA,GAAa,cAAA;AAwBnB,IAAM,gBAAA,GAAmB,wEAAA;AAqBzB,IAAM,cAAA,0BAAwB,4BAA4B,CAAA;AAE1D,SAAS,iBAAA,GAA+C;AACtD,EAAA,OAAO;AAAA,IACL,OAAA,EAAS,KAAA;AAAA,IACT,QAAA,EAAU,KAAA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,OAAO,CAAC,MAAM,CAAA;AACrC,EAAA,IAAI,MAAA,KAAW,UAAA,EAAY,OAAO,CAAC,UAAU,CAAA;AAC7C,EAAA,OAAO,MAAA;AACT;AAEA,SAAS,eAAA,CACP,MACA,aAAA,EACiD;AACjD,EAAA,IAAI,IAAA,CAAK,WAAW,CAAA,EAAG,OAAO,EAAE,IAAA,EAAM,EAAC,EAAG,SAAA,EAAW,KAAA,EAAM;AAC3D,EAAA,MAAM,OAA0B,EAAC;AACjC,EAAA,IAAI,YAAA,GAAe,CAAA;AACnB,EAAA,KAAA,MAAW,OAAO,IAAA,EAAM;AACtB,IAAA,MAAM,aAAa,GAAA,CAAI,OAAA,CAAQ,UAAU,GAAA,CAAI,QAAA,EAAU,UAAU,CAAA,CAAA,GAAK,EAAA;AACtE,IAAA,IAAI,IAAA,CAAK,MAAA,GAAS,CAAA,IAAK,YAAA,GAAe,aAAa,aAAA,EAAe;AAChE,MAAA,OAAO,EAAE,IAAA,EAAM,IAAA,EAAM,SAAA,EAAW,IAAA,EAAK;AAAA,IACvC;AACA,IAAA,IAAA,CAAK,KAAK,GAAG,CAAA;AACb,IAAA,YAAA,IAAgB,UAAA;AAAA,EAClB;AACA,EAAA,OAAO,EAAE,IAAA,EAAM,IAAA,EAAM,SAAA,EAAW,KAAA,EAAM;AACxC;AAEA,SAAS,YAAA,CAAa,MAAc,SAAA,EAA4B;AAC9D,EAAA,MAAM,iBAAiB,IAAA,CAAK,QAAA,CAAS,GAAG,CAAA,GAAI,IAAA,GAAO,GAAG,IAAI,CAAA,CAAA,CAAA;AAC1D,EAAA,OAAO,SAAA,KAAc,IAAA,IAAQ,SAAA,CAAU,UAAA,CAAW,cAAc,CAAA;AAClE","file":"index.cjs","sourcesContent":["/**\n * `createInMemoryMarkdownProvider` — first concrete `MemoryProvider`\n * impl shipped in `@theokit/sdk-memory` (SDK 2.0 Phase 1 / T1.6).\n *\n * Goal: prove the contract works end-to-end with a real (non-no-op)\n * impl WITHOUT pulling LanceDB / embedding / circuit-breaker infrastructure.\n * That richer impl lands in subsequent iters.\n *\n * Semantics:\n * - Stores recalled facts in a per-agent in-process Map.\n * - `runActivePass()` returns the facts plus a `systemPromptAdditions`\n * string that joins fact contents with newlines (so the LLM sees\n * them in the system slot).\n * - `buildTools()` surfaces a `memory_remember(content)` tool the LLM\n * can call to persist a fact mid-conversation.\n * - `recordSessionSummary()` writes a markdown summary to\n * `${cwd}/.theokit/memory/sessions/${runId}.md` (real disk write\n * via `@theokit/sdk/persistence` per ADR-008).\n * - `dispose()` clears the handle's per-agent map (releases memory).\n *\n * @public\n */\n\nimport { mkdir, readdir, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type {\n ActiveMemoryPassArgs,\n ActiveMemoryPassResult,\n CustomTool,\n MemoryAdapter,\n MemoryAdapterCapabilities,\n MemoryContext,\n MemoryFact,\n MemoryId,\n MemoryProvider,\n MemoryProviderHandle,\n MemoryProviderInitOptions,\n MemoryTurnMessage,\n RecordSessionSummaryArgs,\n SDKAgent,\n} from \"@theokit/sdk\";\nimport { ConfigurationError, Security } from \"@theokit/sdk\";\nimport { ceilingReachedError, resolveMaxFacts } from \"@theokit/sdk/internal/memory-store\";\nimport { replaceFileAtomic } from \"@theokit/sdk/persistence\";\n\n/** Adapter id prefix — namespaces minted MemoryIds so cross-adapter delete is safe (EC-B). */\nconst ADAPTER_ID = \"in-memory-md\";\n\n/**\n * Options for {@link createInMemoryMarkdownProvider}.\n *\n * @public\n */\nexport interface InMemoryMarkdownProviderOptions {\n /**\n * The most facts one handle may hold. Default: no ceiling.\n *\n * Each handle counts only its own facts, so two agents on one provider each get the full\n * ceiling.\n *\n * At the ceiling a new fact is refused on both write paths: the adapter's `write` rejects with a\n * `ConfigurationError` whose code is `memory_ceiling_reached`, and the `memory_remember` tool\n * replies `{ ok: false, code, error }`. Nothing is stored either way, and `delete(id)` frees a\n * slot. A value that is not a positive integer throws `invalid_memory_ceiling` when the provider\n * is created.\n */\n maxFacts?: number;\n}\n\n/** How the in-memory store tells a caller to make room under its ceiling. */\nconst IN_MEMORY_REMEDY = \"merge or delete facts with the adapter's delete(id), or raise maxFacts\";\n\n/** Per-agent state holder. Stored on the handle via the opaque symbol slot. */\ninterface InMemoryHandleState {\n readonly facts: Map<string, MemoryFact>;\n /** The declared ceiling, validated when the provider was created; absent means none. */\n readonly maxFacts: number | undefined;\n readonly counter: { next: number };\n /**\n * Workspace cwd captured at `init()` time. Used by `runActivePass()`\n * to read previously-written session summaries from disk for recall\n * (iter 34 — closes the \"write but never read\" gap from iter 33).\n */\n readonly cwd: string;\n /**\n * `sessions: true` capability is set when cwd is available (always),\n * so future Stage 3 work can mark this provider as the canonical\n * sessions-recall path (vs. the no-op default).\n */\n}\n\nconst INTERNAL_STATE = Symbol(\"sdk-memory.in-memory.state\");\n\nfunction buildCapabilities(): MemoryAdapterCapabilities {\n return {\n history: false,\n sessions: false,\n tenancy: false,\n reasoning: false,\n toolSchemas: false,\n prefetch: false,\n };\n}\n\n/**\n * Refuse a new fact at the handle's ceiling. Called synchronously right before each `facts.set`,\n * with no `await` between the check and the set, so two racing writes cannot both pass: the event\n * loop runs each synchronous block to completion.\n */\nfunction admitNewFact(state: InMemoryHandleState): void {\n if (state.maxFacts !== undefined && state.facts.size >= state.maxFacts) {\n throw ceilingReachedError(\n \"the in-memory store\",\n state.facts.size,\n state.maxFacts,\n IN_MEMORY_REMEDY,\n );\n }\n}\n\nfunction isCeilingRefusal(cause: unknown): cause is ConfigurationError {\n return cause instanceof ConfigurationError && cause.code === \"memory_ceiling_reached\";\n}\n\nfunction buildAdapter(state: InMemoryHandleState): MemoryAdapter {\n return {\n id: ADAPTER_ID,\n capabilities: buildCapabilities(),\n isAvailable(): boolean {\n return true;\n },\n async write(content: string | MemoryTurnMessage[], _ctx: MemoryContext): Promise<MemoryId> {\n const text = typeof content === \"string\" ? content : content.map((m) => m.content).join(\"\\n\");\n // Iter 43: redact secrets before persisting. Same posture as\n // memory_remember tool handler — secret-containing payloads\n // submitted to MemoryAdapter.write directly should never\n // surface verbatim in subsequent recall.\n const safeText = Security.redact(text);\n admitNewFact(state);\n const id = `${ADAPTER_ID}:${state.counter.next++}` as MemoryId;\n state.facts.set(id, {\n id,\n content: safeText,\n createdAt: new Date().toISOString(),\n });\n return id;\n },\n async recall(_query: string, _ctx: MemoryContext, k?: number): Promise<MemoryFact[]> {\n // Naive recall — return everything (cap at k). Real impls in\n // subsequent iters add semantic similarity via embeddings.\n const all = Array.from(state.facts.values());\n const limit = k !== undefined && k >= 0 ? k : all.length;\n return all.slice(0, limit);\n },\n async delete(id: MemoryId): Promise<void> {\n if (!String(id).startsWith(`${ADAPTER_ID}:`)) {\n throw new Error(\n `MemoryAdapter.delete: id \"${String(id)}\" was not minted by adapter \"${ADAPTER_ID}\"`,\n );\n }\n state.facts.delete(id);\n },\n };\n}\n\n/** Truncate session-summary text fields to bound disk size. */\nconst MAX_SUMMARY_TURN_CHARS = 2000;\n\nfunction truncate(text: string): string {\n if (text.length <= MAX_SUMMARY_TURN_CHARS) return text;\n return `${text.slice(0, MAX_SUMMARY_TURN_CHARS)}…`;\n}\n\n/**\n * Sanitize a runId for use as a filename. Strip path separators +\n * traversal patterns; keep `[a-zA-Z0-9_-]`; cap at 128 chars.\n * Mirrors sdk-core's legacy `writeSessionSummary` sanitizer so the\n * file-path semantics are identical across paths.\n */\nfunction sanitizeRunId(runId: string): string {\n return runId.replace(/[^a-zA-Z0-9_-]/g, \"_\").slice(0, 128);\n}\n\n/** Render the session-summary markdown body. */\nfunction renderSessionSummaryMarkdown(args: RecordSessionSummaryArgs): string {\n const iso = new Date(args.at).toISOString();\n // Iter 42: redact secrets from User + Assistant text via the public\n // `Security.redact()` API (sdk-core's ADR D68 canonical redactor —\n // 12 built-in patterns: OpenAI, Anthropic, GitHub PAT, AWS, etc.).\n // Mirrors sdk-core's legacy writeSessionSummary behavior so the\n // disk artefact never leaks API keys typed by the user.\n const safeUser = Security.redact(truncate(args.userText));\n const safeAssistant = Security.redact(truncate(args.assistantText));\n return [\n \"---\",\n `runId: ${args.runId}`,\n `agentId: ${args.agentId}`,\n `at: ${iso}`,\n `status: ${args.status}`,\n \"---\",\n \"\",\n \"## User\",\n \"\",\n safeUser,\n \"\",\n \"## Assistant\",\n \"\",\n safeAssistant,\n \"\",\n ].join(\"\\n\");\n}\n\n/**\n * Extract `agentId:` value from a session-summary YAML frontmatter.\n * Returns undefined when the file is malformed or has no agentId.\n *\n * The frontmatter shape is:\n * ---\n * runId: ...\n * agentId: ...\n * ...\n * ---\n *\n * Parsing is intentionally simple (regex line-match) — full YAML parse\n * is overkill for the 5-field frontmatter we emit. A malformed file\n * shows up as undefined → falls out of the optional agentId filter.\n */\nfunction extractAgentIdFromFrontmatter(content: string): string | undefined {\n // Match `agentId: <value>` within the leading frontmatter block.\n const match = content.match(/^agentId:\\s*(.+)$/m);\n if (match === null || match[1] === undefined) return undefined;\n return match[1].trim();\n}\n\n/**\n * Read previously-written session summaries from disk + substring-\n * match against the user message. Best-effort: errors degrade to\n * empty recall (no throw — matches the non-throwing-on-hot-path\n * contract).\n *\n * Iter 34: this is the SUBSTRING-match version. Future iters can\n * upgrade to embedding-based semantic similarity (LanceDB ANN)\n * without changing the public surface.\n *\n * Cap: returns at most 5 hits to bound the systemPromptAdditions size.\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: session recall has branching on multiple storage modes\nasync function recallSessionSummaries(\n cwd: string,\n userMessage: string,\n agentIdFilter?: string,\n): Promise<ReadonlyArray<MemoryFact>> {\n const RECALL_CAP = 5;\n const sessionsDir = join(cwd, \".theokit\", \"memory\", \"sessions\");\n let files: string[];\n try {\n files = await readdir(sessionsDir);\n } catch {\n return [];\n }\n const query = userMessage.toLowerCase().trim();\n if (query.length === 0) return [];\n const hits: MemoryFact[] = [];\n for (const file of files) {\n if (!file.endsWith(\".md\")) continue;\n if (hits.length >= RECALL_CAP) break;\n const filePath = join(sessionsDir, file);\n let content: string;\n try {\n content = await readFile(filePath, \"utf-8\");\n } catch {\n continue;\n }\n // Iter 36: agentId scope filter. When set, skip summaries whose\n // frontmatter `agentId:` field doesn't match. Prevents cross-agent\n // data leakage in multi-agent setups.\n if (agentIdFilter !== undefined) {\n const fileAgentId = extractAgentIdFromFrontmatter(content);\n if (fileAgentId !== agentIdFilter) continue;\n }\n if (content.toLowerCase().includes(query)) {\n // Extract a short snippet — the User section (first 200 chars).\n const userIdx = content.indexOf(\"## User\");\n const snippet =\n userIdx >= 0 ? content.slice(userIdx, userIdx + 200).replace(/\\s+/g, \" \") : file;\n const id = `${ADAPTER_ID}:session:${file}` as MemoryId;\n hits.push({\n id,\n content: snippet,\n score: 0.5, // substring-match has no real score; placeholder\n });\n }\n }\n return hits;\n}\n\n/**\n * Build the LLM-facing `memory_search` tool (iter 35). The LLM calls\n * this when the user asks about something it might have learned in a\n * previous session. Queries the disk-backed sessions corpus via the\n * same `recallSessionSummaries` helper used by `runActivePass`.\n */\nfunction buildMemorySearchTool(state: InMemoryHandleState): CustomTool {\n return {\n name: \"memory_search\",\n description:\n \"Search past session summaries for content related to a query. Use when the user asks about something they mentioned in a previous conversation. Returns up to 5 short snippets.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: {\n type: \"string\",\n description: \"What to search for (a topic, fact, or keyword).\",\n },\n },\n required: [\"query\"],\n additionalProperties: false,\n },\n handler: async (input: Record<string, unknown>): Promise<string> => {\n const query = typeof input.query === \"string\" ? input.query : \"\";\n if (query.length === 0) {\n return JSON.stringify({ ok: false, results: [], error: \"empty query\" });\n }\n const hits = await recallSessionSummaries(state.cwd, query);\n return JSON.stringify({\n ok: true,\n count: hits.length,\n results: hits.map((h) => ({ id: String(h.id), snippet: h.content })),\n });\n },\n };\n}\n\nfunction buildMemoryRememberTool(state: InMemoryHandleState): CustomTool {\n return {\n name: \"memory_remember\",\n description:\n \"Persist a short fact about the user/conversation to memory so it can be recalled in future turns. Pass a single concise sentence as `content`.\",\n inputSchema: {\n type: \"object\",\n properties: {\n content: { type: \"string\", description: \"The fact to remember (one sentence).\" },\n },\n required: [\"content\"],\n additionalProperties: false,\n },\n handler: async (input: Record<string, unknown>): Promise<string> => {\n const content = typeof input.content === \"string\" ? input.content : \"\";\n if (content.length === 0) {\n return JSON.stringify({ ok: false, error: \"empty content\" });\n }\n // Iter 43: redact secrets from the LLM-supplied content BEFORE\n // storing in the Map. The LLM may quote a key from the user\n // verbatim (e.g., \"user said their key is sk-proj-...\"); without\n // this, that secret would persist + leak into systemPromptAdditions\n // on subsequent runActivePass calls. Mirrors the iter 42\n // recordSessionSummary redaction posture.\n const safeContent = Security.redact(content);\n try {\n admitNewFact(state);\n } catch (cause) {\n // Only the ceiling is a reply the model can act on; anything else is a defect and rises.\n if (!isCeilingRefusal(cause)) throw cause;\n return JSON.stringify({ ok: false, code: cause.code, error: cause.message });\n }\n const id = `${ADAPTER_ID}:${state.counter.next++}` as MemoryId;\n state.facts.set(id, {\n id,\n content: safeContent,\n createdAt: new Date().toISOString(),\n });\n return JSON.stringify({ ok: true, id });\n },\n };\n}\n\n/**\n * Build a fresh `MemoryProvider` whose facts live in-process. The\n * returned provider is independent — call `createInMemoryMarkdownProvider()`\n * per agent OR share across agents (each `init()` gets its own state).\n *\n * Iter 33: `recordSessionSummary()` writes session-summary markdown\n * files to disk under `${cwd}/.theokit/memory/sessions/`.\n * Iter 34: `runActivePass()` reads back those summaries + substring-\n * matches against the user message for genuine cross-session recall.\n *\n * Future LanceDB-backed impl will replace the substring match with\n * semantic-similarity ANN over embedding vectors.\n */\nexport function createInMemoryMarkdownProvider(\n options: InMemoryMarkdownProviderOptions = {},\n): MemoryProvider {\n const maxFacts = resolveMaxFacts(options.maxFacts);\n return {\n async init(opts: MemoryProviderInitOptions): Promise<MemoryProviderHandle> {\n const state: InMemoryHandleState = {\n facts: new Map(),\n maxFacts,\n counter: { next: 0 },\n cwd: opts.cwd,\n };\n const adapter = buildAdapter(state);\n return {\n adapter,\n [INTERNAL_STATE]: state,\n };\n },\n buildTools(handle: MemoryProviderHandle, _agent: SDKAgent): ReadonlyArray<CustomTool> {\n const state = handle[INTERNAL_STATE] as InMemoryHandleState | undefined;\n if (state === undefined) return [];\n return [buildMemoryRememberTool(state), buildMemorySearchTool(state)];\n },\n async runActivePass(\n handle: MemoryProviderHandle,\n args: ActiveMemoryPassArgs,\n ): Promise<ActiveMemoryPassResult> {\n const state = handle[INTERNAL_STATE] as InMemoryHandleState | undefined;\n if (state === undefined) return { facts: [] };\n // (1) In-process facts (from memory_remember tool calls this turn).\n const inProcessFacts = Array.from(state.facts.values());\n // (2) Persisted session-summary recall — iter 34. Read previously-\n // written summaries from disk + substring-match against the user\n // message. Best-effort: read errors degrade to empty recall.\n //\n // Iter 36: scope the disk recall to args.agentId so a session\n // summary written by agent-A never bleeds into agent-B's recall.\n // This is the multi-agent privacy invariant.\n const persistedHits = await recallSessionSummaries(state.cwd, args.userMessage, args.agentId);\n const allFacts = [...inProcessFacts, ...persistedHits];\n if (allFacts.length === 0) return { facts: [] };\n const systemPromptAdditions = [\n \"Known facts about the user/session (recall):\",\n ...allFacts.map((f) => `- ${f.content}`),\n ].join(\"\\n\");\n return { facts: allFacts, systemPromptAdditions };\n },\n sync(_handle: MemoryProviderHandle): void {\n // No-op for the in-memory impl — facts are written synchronously to\n // the Map at handler-call time; nothing to re-index post-run. Future\n // LanceDB-backed impl will fire IndexManager.sync() here.\n return;\n },\n async recordSessionSummary(args: RecordSessionSummaryArgs): Promise<void> {\n // Real filesystem write via `@theokit/sdk/persistence`'s\n // `replaceFileAtomic`. ADR-008 sub-path resolution guarantees the\n // same process-level write lock as sdk-core's legacy\n // `writeSessionSummary`. Future LanceDB-backed impl additionally\n // triggers IndexManager re-sync after the write.\n if (args.status !== \"finished\") return;\n const sessionsPath = join(args.cwd, \".theokit\", \"memory\", \"sessions\");\n const filePath = join(sessionsPath, `${sanitizeRunId(args.runId)}.md`);\n await mkdir(sessionsPath, { recursive: true });\n const body = renderSessionSummaryMarkdown(args);\n await replaceFileAtomic(filePath, body);\n },\n dispose(handle: MemoryProviderHandle): void {\n const state = handle[INTERNAL_STATE] as InMemoryHandleState | undefined;\n if (state === undefined) return;\n state.facts.clear();\n },\n };\n}\n","import { readdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { notesDir, resolveMemoryRoot } from \"@theokit/sdk/internal/memory-store\";\n\n/**\n * Markdown-first memory storage — re-exported from `@theokit/sdk`, not reimplemented here.\n *\n * This file used to be a full copy (iter 56, Stage 3 source-move #13). The copy went stale: `#389`\n * moved the layout from bullets under `MEMORY.md ## Facts` to a file per memory, and the\n * Claude Code compatibility work added two more read roots — both landed in the SDK's copy and\n * neither in this one. Because `Memory.runDreamingSweep` routes through this package whenever it is\n * installed, **the copy that ran was not the copy anyone had updated**: installing\n * `@theokit/sdk-memory` made every memory the SDK had written unreadable, reported as\n * `factsBefore: 0` — a number that reads exactly like an empty store (#430).\n *\n * theokit#160 fixed the identical shape for the embedding runtime, in this same package pair, by\n * importing one implementation instead of syncing two. Same remedy here. Re-syncing the copy would\n * have fixed today's divergence and left tomorrow's free to happen.\n *\n * The re-exported signatures are supersets of what this package used to expose — the added\n * parameters are optional — so nothing that called them before has to change.\n *\n * @internal\n */\nexport {\n appendFact,\n appendFactToMarkdown,\n asMemoryRoot,\n ceilingReachedError,\n claudeProjectMemoryDir,\n collectMarkdownFiles,\n type DiscoveredFile,\n defaultIndexPath,\n indexBudgetWarning,\n lanceStoragePath,\n MEMORY_INDEX_MAX_BYTES,\n MEMORY_INDEX_MAX_LINES,\n type MemoryLocationConfig,\n type MemoryRoot,\n memoryIndexRoot,\n memoryMdPath,\n memoryReadRoots,\n notesDir,\n projectMemoryDir,\n readAllSqliteFacts,\n readFacts,\n readFactsFromMarkdown,\n resolveMaxFacts,\n resolveMemoryRoot,\n type SqliteFactRow,\n} from \"@theokit/sdk/internal/memory-store\";\n\n/** One note discovered under `notes/`: its file name without the `.md` suffix, and its absolute path. */\nexport interface NoteFile {\n slug: string;\n path: string;\n}\n\n/**\n * List the `.md` files directly under `notes/`. Returns `[]` when the directory does not exist, so\n * a workspace that has never written a note is not an error. Does not recurse into sub-directories.\n *\n * Stays here rather than moving to the shared store: notes are this package's concept, and only\n * this package reads them.\n */\nexport async function listNotes(cwd: string): Promise<NoteFile[]> {\n let entries: string[] = [];\n try {\n entries = await readdir(notesDir(resolveMemoryRoot(cwd)));\n } catch {\n return [];\n }\n return entries\n .filter((name) => name.endsWith(\".md\"))\n .map((name) => ({\n slug: name.replace(/\\.md$/, \"\"),\n path: join(notesDir(resolveMemoryRoot(cwd)), name),\n }));\n}\n","/**\n * Active Memory blocking recall (ADR D6 of memory-system-peer-project-parity).\n *\n * Runs BEFORE `agent.send()` assembles the system prompt. Issues a direct\n * call to `IndexManager.search` with the user message (and optional recent\n * turns per `queryMode`).\n *\n * Returns a `summary` string capped at `maxSummaryChars` (default 220 to\n * match peer-project's `DEFAULT_MAX_SUMMARY_CHARS`) which the system-prompt\n * pipeline prepends as a `<active-memory>` block (priority 5).\n *\n * Iter 75 (Stage 3 source-move #38, FINAL move): hybrid copy from\n * sdk-core's `internal/memory/active-memory.ts`. sdk-core retains its\n * copy as the v1.x runtime that `Memory` class delegates to;\n * sdk-memory ships the canonical copy that future Stage 4 port-based\n * composition will consume.\n *\n * **CLOSES the Stage 3 source-move stage in sdk-memory.** Every\n * memory-related concept under sdk-core's internal/memory/ is now\n * canonical in @theokit/sdk-memory (38 source files moved across\n * iter 44-75; 2 inlined adapters added: adapter-http-error iter 73\n * + adapter-catalog renamed iter 74).\n *\n * **Cross-package telemetry contract:** `OTelSpan` and `TelemetryHandle`\n * are now imported from `@theokit/sdk`, which exports them since #295.\n * This file previously inlined structural mirrors of both, with a note\n * that they MUST be replaced once sdk-core made them public — and by\n * the time anyone looked, the mirrors had drifted: they narrowed\n * `setAttributes` to reject the `undefined` values the canonical type\n * accepts, and declared `end()` without its `endTime` parameter. That\n * is how a structural mirror fails: quietly, with both sides compiling.\n *\n * The 2 constant strings (`memory.recall` span name +\n * `theokit_memory_recall_duration_ms` histogram name) are still inlined\n * below, because sdk-core's `span-names.ts` remains private. They are\n * values rather than types, so exporting them is a separate decision\n * with a real bundle cost — unlike these two, which erase at build time.\n *\n * @internal\n */\n\nimport type { OTelSpan, TelemetryHandle } from \"@theokit/sdk\";\n\nimport type { CircuitBreaker } from \"../circuit-breaker.js\";\nimport type { MemorySearchHit } from \"../index/index-manager-contract.js\";\nimport type { MemoryIndex } from \"../index/memory-index.js\";\nimport { resolveMemoryRoot } from \"../store/markdown-store.js\";\nimport { persistActiveMemoryTranscript } from \"../store/transcript-store.js\";\nimport type { ActiveMemoryCache, TenantContext } from \"./active-memory-cache.js\";\n// T4.1 / D438 — `ActiveMemoryResult` and its helpers moved to `./active-memory-types.ts`\n// so `./active-memory-cache.ts` can reach them without cycling back here (cycle #10).\n// Re-exported below for back-compat with in-tree consumers.\nimport type {\n ActiveMemoryQueryMode,\n ActiveMemoryResult,\n ActiveMemoryStatus,\n} from \"./active-memory-types.js\";\n\nexport type { ActiveMemoryQueryMode, ActiveMemoryResult, ActiveMemoryStatus };\n\n// Iter 75 inlined constants — sdk-core's telemetry/span-names.ts is\n// not public. These two are the only ones this file uses.\nconst SPAN_MEMORY_RECALL = \"memory.recall\";\nconst HISTOGRAM_MEMORY_RECALL_DURATION_MS = \"theokit_memory_recall_duration_ms\";\n\n// #295 — the canonical types, not a copy of them.\n//\n// Iter 75 inlined structural mirrors here because sdk-core's telemetry/tracer.ts\n// was not public, with a note that they MUST be replaced once it was. They had\n// already drifted by the time anyone checked: the mirror narrowed `setAttributes`\n// to reject the `undefined` values the canonical type accepts, and declared\n// `end()` without the `endTime` parameter. Neither broke a build — a structural\n// mirror fails by being quietly wrong, not by being loudly missing.\n//\n// `@theokit/sdk` is already a peerDependency of this package, and both types are\n// erased at build time, so this costs nothing at runtime.\n\n/**\n * Tuning for one recall attempt. Recall is off unless `enabled` is exactly\n * `true`, so an options object that omits it disables recall rather than\n * enabling it with defaults.\n */\nexport interface ActiveMemoryOptions {\n /** Whether active recall is enabled. Default `false`. */\n enabled?: boolean;\n /** Query construction strategy. Default `\"recent\"`. */\n queryMode?: ActiveMemoryQueryMode;\n /** Hard timeout in ms. Default `15000`. */\n timeoutMs?: number;\n /** Max chars in the summary. Default `220`. */\n maxSummaryChars?: number;\n /** Number of recent user turns to include in `queryMode === \"recent\"`. Default `2`. */\n recentUserTurns?: number;\n}\n\n/**\n * Everything {@link runActiveMemory} needs for one attempt. Only `userText`,\n * `priorMessages`, `index` and `options` are required; the rest add breaker,\n * cache, transcript persistence and telemetry, each of which is inert when\n * omitted.\n *\n * `index` is accepted as `undefined` on purpose — an agent with memory\n * configured but no index open is a normal state, and it produces a `skipped`\n * result rather than an error.\n */\nexport interface RunActiveMemoryArgs {\n userText: string;\n priorMessages: ReadonlyArray<{ role: \"user\" | \"assistant\"; text: string }>;\n index: MemoryIndex | undefined;\n options: ActiveMemoryOptions;\n /** Per-agent circuit breaker (Phase 8). */\n breaker?: CircuitBreaker;\n /** Per-agent result cache (Phase 8). */\n cache?: ActiveMemoryCache;\n /** Workspace root for transcript persistence. */\n cwd?: string;\n /** When true, write transcript JSON under .theokit/memory/transcripts/active-memory/. */\n persistTranscripts?: boolean;\n /** Stable key the breaker + cache key by (default `default`). */\n agentKey?: string;\n /** Run id for transcript file naming. */\n runId?: string;\n /**\n * T0.1 — optional telemetry handle. When provided AND telemetry is enabled,\n * `memory.recall` span is emitted with `{ userId, namespace, scope, queryMode,\n * hits, status }` attrs and `theokit_memory_recall_duration_ms` histogram is\n * recorded with the same dimension keys.\n */\n telemetry?: TelemetryHandle;\n /** User id surfaced as a memory.recall span attr for cross-tenant tracing. */\n userId?: string;\n /** Memory namespace (e.g. `default`, `<orgId>`) for span/histogram dimensions. */\n namespace?: string;\n /** Memory scope (`session` / `user` / `global`) for span/histogram dimensions. */\n scope?: string;\n}\n\nconst DEFAULTS: Required<Omit<ActiveMemoryOptions, \"enabled\">> = {\n queryMode: \"recent\",\n timeoutMs: 15000,\n maxSummaryChars: 220,\n recentUserTurns: 2,\n};\n\n/**\n * Run one blocking recall before the system prompt is assembled, and report what\n * happened. Never throws for a recall failure: a search that times out or\n * rejects comes back as a `timeout` or `error` status with no summary, and the\n * agent run continues without memory.\n *\n * The order of the short-circuits decides what a caller sees. Recall disabled or\n * no index gives `skipped` with no search. An open circuit breaker gives\n * `skipped` too. A cache hit returns the earlier result as-is, which means it\n * also returns that result's `status` and `durationMs` — a cached `no-recall`\n * looks exactly like a fresh one. An empty query gives `no-recall`.\n *\n * Only a real search reaches the breaker: `timeout` records a timeout, `ok` and\n * `no-recall` record a success, and `error` records neither, so a provider that\n * keeps throwing will not trip the breaker.\n *\n * `timeoutMs` bounds how long this waits, not how long the search runs — the\n * underlying `index.search` is left running when the timer wins. The search asks\n * the index for at most 5 hits regardless of options.\n *\n * Cache entries are keyed by tenant as well as by query text, so two callers\n * with the same question and different `userId` / `namespace` / `scope` never\n * share an entry.\n */\nexport async function runActiveMemory(args: RunActiveMemoryArgs): Promise<ActiveMemoryResult> {\n const started = Date.now();\n // T0.1 — `memory.recall` span emitted around the entire body so skipped /\n // cached / no-recall paths still surface in telemetry with the correct status.\n const span = startMemoryRecallSpan(args);\n try {\n if (args.options.enabled !== true || args.index === undefined) {\n return endRecallSpan(span, args, {\n summary: undefined,\n durationMs: 0,\n status: \"skipped\",\n hits: [],\n });\n }\n const cfg = { ...DEFAULTS, ...args.options };\n const breakerKey = args.agentKey ?? \"default\";\n if (args.breaker?.shouldSkip(breakerKey) === true) {\n return endRecallSpan(span, args, {\n summary: undefined,\n durationMs: 0,\n status: \"skipped\",\n hits: [],\n });\n }\n // #56 (GAP-B) — key the cache read by tenant identity so two callers with\n // the same query text but different identity never share a cache entry.\n const tenantCtx: TenantContext = {\n namespace: args.namespace,\n userId: args.userId,\n scope: args.scope,\n };\n const cached = args.cache?.get(args.userText, cfg.queryMode, tenantCtx);\n if (cached !== undefined) return endRecallSpan(span, args, cached);\n\n const query = buildQuery(args.userText, args.priorMessages, cfg.queryMode, cfg.recentUserTurns);\n if (query.trim().length === 0) {\n const finalized = await finalize(args, cfg.queryMode, {\n summary: undefined,\n durationMs: Date.now() - started,\n status: \"no-recall\",\n hits: [],\n });\n return endRecallSpan(span, args, finalized);\n }\n const result = await searchOnce(args, cfg, query, started);\n notifyBreaker(args.breaker, breakerKey, result.status);\n const finalized = await finalize(args, cfg.queryMode, result);\n return endRecallSpan(span, args, finalized);\n } catch (cause) {\n span.recordException(cause);\n span.setStatus({ code: 2, message: cause instanceof Error ? cause.message : String(cause) });\n span.end();\n throw cause;\n }\n}\n\nfunction startMemoryRecallSpan(args: RunActiveMemoryArgs): OTelSpan {\n const telemetry: TelemetryHandle | undefined = args.telemetry;\n if (telemetry === undefined) {\n // No-op span identical to the runtime no-op when telemetry is disabled.\n return {\n setAttribute: () => {},\n setAttributes: () => {},\n addEvent: () => {},\n setStatus: () => {},\n recordException: () => {},\n end: () => {},\n spanContext: () => ({ traceId: \"0\".repeat(32), spanId: \"0\".repeat(16) }),\n isRecording: () => false,\n };\n }\n return telemetry.startSpan(SPAN_MEMORY_RECALL, {\n queryMode: args.options.queryMode ?? \"recent\",\n ...(args.userId !== undefined ? { userId: args.userId } : {}),\n ...(args.namespace !== undefined ? { namespace: args.namespace } : {}),\n ...(args.scope !== undefined ? { scope: args.scope } : {}),\n });\n}\n\nfunction endRecallSpan(\n span: OTelSpan,\n args: RunActiveMemoryArgs,\n result: ActiveMemoryResult,\n): ActiveMemoryResult {\n span.setAttributes({\n hits: result.hits.length,\n status: result.status,\n durationMs: result.durationMs,\n });\n span.end();\n args.telemetry?.recordHistogram(HISTOGRAM_MEMORY_RECALL_DURATION_MS, result.durationMs, {\n status: result.status,\n ...(args.userId !== undefined ? { userId: args.userId } : {}),\n ...(args.namespace !== undefined ? { namespace: args.namespace } : {}),\n ...(args.scope !== undefined ? { scope: args.scope } : {}),\n });\n return result;\n}\n\ninterface ResolvedConfig {\n queryMode: ActiveMemoryQueryMode;\n timeoutMs: number;\n maxSummaryChars: number;\n recentUserTurns: number;\n}\n\nasync function searchOnce(\n args: RunActiveMemoryArgs,\n cfg: ResolvedConfig,\n query: string,\n started: number,\n): Promise<ActiveMemoryResult> {\n if (args.index === undefined) {\n return { summary: undefined, durationMs: 0, status: \"skipped\", hits: [] };\n }\n try {\n const hits = await withTimeout(args.index.search(query, { maxResults: 5 }), cfg.timeoutMs);\n if (hits === \"timeout\") {\n return { summary: undefined, durationMs: Date.now() - started, status: \"timeout\", hits: [] };\n }\n if (hits.length === 0) {\n return {\n summary: undefined,\n durationMs: Date.now() - started,\n status: \"no-recall\",\n hits: [],\n };\n }\n const summary = formatSummary(hits, cfg.maxSummaryChars);\n return { summary, durationMs: Date.now() - started, status: \"ok\", hits };\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : String(cause);\n process.stderr.write(`[theokit-sdk] active-memory recall failed: ${message}\\n`);\n return { summary: undefined, durationMs: Date.now() - started, status: \"error\", hits: [] };\n }\n}\n\nfunction notifyBreaker(\n breaker: CircuitBreaker | undefined,\n key: string,\n status: ActiveMemoryStatus,\n): void {\n if (breaker === undefined) return;\n if (status === \"timeout\") breaker.recordTimeout(key);\n else if (status === \"ok\" || status === \"no-recall\") breaker.recordSuccess(key);\n}\n\nasync function finalize(\n args: RunActiveMemoryArgs,\n queryMode: ActiveMemoryQueryMode,\n result: ActiveMemoryResult,\n): Promise<ActiveMemoryResult> {\n // #56 (GAP-B) — key the cache write by tenant identity (mirrors the get side).\n const tenantCtx: TenantContext = {\n namespace: args.namespace,\n userId: args.userId,\n scope: args.scope,\n };\n args.cache?.set(args.userText, queryMode, result, tenantCtx);\n if (args.persistTranscripts === true && args.cwd !== undefined) {\n await persistActiveMemoryTranscript(resolveMemoryRoot(args.cwd), {\n runId: args.runId ?? `run-${Date.now()}`,\n startedAtMs: Date.now() - result.durationMs,\n userText: args.userText,\n queryMode,\n status: result.status,\n durationMs: result.durationMs,\n summary: result.summary,\n hits: result.hits.map((h) => ({\n path: h.path,\n startLine: h.startLine,\n endLine: h.endLine,\n score: h.score,\n snippet: h.snippet,\n })),\n });\n }\n return result;\n}\n\nfunction buildQuery(\n userText: string,\n priorMessages: ReadonlyArray<{ role: \"user\" | \"assistant\"; text: string }>,\n queryMode: ActiveMemoryQueryMode,\n recentUserTurns: number,\n): string {\n if (queryMode === \"message\") return userText;\n if (queryMode === \"full\") {\n const allUserTurns = priorMessages.filter((m) => m.role === \"user\").map((m) => m.text);\n return [...allUserTurns, userText].join(\"\\n\");\n }\n // recent\n const recent = priorMessages\n .filter((m) => m.role === \"user\")\n .slice(-recentUserTurns)\n .map((m) => m.text);\n return [...recent, userText].join(\"\\n\");\n}\n\nfunction formatSummary(hits: ReadonlyArray<MemorySearchHit>, maxChars: number): string {\n const lines = hits.map((h) => `- ${h.citation}: ${h.snippet}`);\n let summary = lines.join(\"\\n\");\n if (summary.length > maxChars) summary = `${summary.slice(0, maxChars - 1)}…`;\n return summary;\n}\n\nasync function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T | \"timeout\"> {\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<\"timeout\">((resolve) => {\n timer = setTimeout(() => resolve(\"timeout\"), timeoutMs);\n });\n try {\n const winner = await Promise.race([promise, timeout]);\n return winner;\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n}\n","/**\n * Consecutive-timeout circuit breaker for Active Memory recall.\n *\n * Mirrors peer-project's `circuitBreakerMaxTimeouts` + `circuitBreakerCooldownMs`\n * config: after N consecutive timeouts the breaker trips and `shouldSkip`\n * returns `true` until `cooldownMs` has elapsed. A successful recall resets\n * the counter immediately.\n *\n * Per-key isolation so two agents in the same process don't share a counter.\n *\n * @internal\n */\n\nexport interface CircuitBreakerOptions {\n maxTimeouts?: number;\n cooldownMs?: number;\n /** Injectable clock for tests. */\n now?: () => number;\n}\n\ninterface KeyState {\n consecutiveTimeouts: number;\n cooldownUntilMs: number;\n}\n\nconst DEFAULT_MAX_TIMEOUTS = 3;\nconst DEFAULT_COOLDOWN_MS = 60_000;\n\n/**\n * Stops calling a recall path that keeps timing out.\n *\n * After `maxTimeouts` consecutive timeouts on a key (default 3) the breaker\n * opens and {@link CircuitBreaker.shouldSkip} reports `true` until `cooldownMs`\n * has elapsed (default 60s). The first `shouldSkip` after the cooldown closes\n * the breaker and resets the counter, so it re-opens only after another full run\n * of timeouts.\n *\n * It counts timeouts, not failures. An error recorded by neither\n * `recordTimeout` nor `recordSuccess` leaves the counter where it was, so a call\n * path that throws rather than hanging will never trip it.\n *\n * State is per key and held in this instance, which is what keeps two agents in\n * one process from sharing a counter. Construct one per agent and pass a stable\n * key.\n */\nexport class CircuitBreaker {\n private readonly states = new Map<string, KeyState>();\n\n constructor(private readonly opts: CircuitBreakerOptions = {}) {}\n\n /** @returns true when the breaker is open and the call should be skipped. */\n shouldSkip(key: string): boolean {\n const state = this.states.get(key);\n if (state === undefined) return false;\n if (state.cooldownUntilMs === 0) return false;\n if (this.now() < state.cooldownUntilMs) return true;\n // Cooldown elapsed — close the breaker.\n state.cooldownUntilMs = 0;\n state.consecutiveTimeouts = 0;\n return false;\n }\n\n recordSuccess(key: string): void {\n const state = this.states.get(key);\n if (state === undefined) return;\n state.consecutiveTimeouts = 0;\n state.cooldownUntilMs = 0;\n }\n\n recordTimeout(key: string): void {\n const state = this.states.get(key) ?? { consecutiveTimeouts: 0, cooldownUntilMs: 0 };\n state.consecutiveTimeouts += 1;\n if (state.consecutiveTimeouts >= (this.opts.maxTimeouts ?? DEFAULT_MAX_TIMEOUTS)) {\n state.cooldownUntilMs = this.now() + (this.opts.cooldownMs ?? DEFAULT_COOLDOWN_MS);\n }\n this.states.set(key, state);\n }\n\n /** @internal — tests inspect counter state. */\n inspect(key: string): Readonly<KeyState> {\n return this.states.get(key) ?? { consecutiveTimeouts: 0, cooldownUntilMs: 0 };\n }\n\n private now(): number {\n return this.opts.now?.() ?? Date.now();\n }\n}\n","import type { MemoryEmbeddingProviderAdapter } from \"./embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n// Iter 74 rollup-plugin-dts workaround: see openai-embedding.ts header.\n\n/**\n * Azure OpenAI embedding adapter.\n *\n * Azure addresses the DEPLOYMENT in the path rather than the model in the body:\n * `https://{resource}.openai.azure.com/openai/deployments/{deployment}/embeddings?api-version=...`.\n * `{model}` in `embeddingsPath` is substituted by `createOpenAiCompatibleRuntime`, so `model` here\n * names the Azure deployment.\n *\n * `AZURE_OPENAI_ENDPOINT` supplies the resource URL (without the `/openai/...` suffix);\n * `AZURE_OPENAI_API_KEY` the credential.\n *\n * theokit#128 (catalog parity): sdk-core gained this adapter in T4.10 and the peer never mirrored\n * it, so a `sdk-memory` user asking for `azure-openai` was rejected by a provider the SDK's own\n * `Theokit.inspect.embeddingAdapters()` advertised.\n *\n * @internal\n */\n\nexport const DEFAULT_AZURE_OPENAI_EMBEDDING_MODEL = \"text-embedding-3-small\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"text-embedding-3-small\": 1536,\n \"text-embedding-3-large\": 3072,\n \"text-embedding-ada-002\": 1536,\n};\n\n/**\n * Azure OpenAI embeddings. Same models as the OpenAI adapter, addressed the\n * Azure way, and the one adapter whose configuration is not just \"set a key\".\n *\n * Two things differ from every other adapter here. `model` names your Azure\n * DEPLOYMENT, not an OpenAI model id — it is substituted into the path\n * (`/openai/deployments/{model}/embeddings`) rather than sent in the body. And\n * `AZURE_OPENAI_ENDPOINT` must be set to your resource URL, without the\n * `/openai/...` suffix; the built-in default is a placeholder that resolves\n * nowhere, so leaving it unset fails at the network rather than at\n * configuration.\n *\n * Authentication uses the `api-key` header, which is what an Azure resource key\n * expects; Entra ID bearer tokens are not supported by this adapter. Reads\n * `AZURE_OPENAI_API_KEY`. The API version is pinned to `2024-02-01`.\n *\n * The deployment name still has to appear in the dimension table\n * (`text-embedding-3-small`, `-3-large`, `ada-002`), so a deployment named\n * anything else is refused with `embedding_unknown_model` — pass `model` as the\n * matching id and point the base URL at the right deployment, or add the name to\n * the table.\n */\nexport const azureOpenAiMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"azure-openai\",\n defaultModel: DEFAULT_AZURE_OPENAI_EMBEDDING_MODEL,\n transport: \"remote\" as const,\n authProviderId: \"azure-openai\",\n autoSelectPriority: 25,\n create: (options: Parameters<typeof createOpenAiCompatibleRuntime>[1]) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"azure-openai\",\n defaultBaseUrl: \"https://your-resource.openai.azure.com\",\n apiKeyEnv: \"AZURE_OPENAI_API_KEY\",\n baseUrlEnv: \"AZURE_OPENAI_ENDPOINT\",\n defaultModel: DEFAULT_AZURE_OPENAI_EMBEDDING_MODEL,\n embeddingsPath: \"/openai/deployments/{model}/embeddings?api-version=2024-02-01\",\n dimensionByModel: DIMENSION_BY_MODEL,\n // theokit#159 — Azure is NOT OpenAI on the wire, despite the name. It authenticates an API\n // key with the `api-key` header (`Authorization: Bearer` is for Entra ID tokens, not for\n // AZURE_OPENAI_API_KEY), and the deployment already rides in the path, so `model` has no\n // place in the body. Sending the OpenAI shape meant every request was rejected.\n dialect: {\n authHeaders: (apiKey: string) => ({ \"api-key\": apiKey }),\n body: (_model: string, inputs: ReadonlyArray<string>) => ({ input: inputs }),\n },\n },\n options,\n ),\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"./embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n// Iter 74 rollup-plugin-dts workaround: see openai-embedding.ts header.\n\n/**\n * Cohere embedding adapter — `POST /v2/embed` at `https://api.cohere.com`. Despite living beside\n * the OpenAI-compatible adapters, this endpoint is NOT OpenAI-shaped in either direction; the\n * `dialect` below is what makes it work.\n *\n * Honors `COHERE_API_KEY`.\n *\n * theokit#128 (catalog parity): mirrors sdk-core's T4.10 adapter, which the peer never picked up.\n *\n * @internal\n */\n\nexport const DEFAULT_COHERE_EMBEDDING_MODEL = \"embed-english-v3.0\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"embed-english-v3.0\": 1024,\n \"embed-multilingual-v3.0\": 1024,\n \"embed-english-light-v3.0\": 384,\n \"embed-multilingual-light-v3.0\": 384,\n};\n\n/**\n * Cohere embeddings. Priority 30, so it is auto-selected ahead of OpenAI when\n * both keys are present.\n *\n * Cohere does not speak the OpenAI wire, and this adapter supplies a dialect for\n * it: the request names its payload `texts`, the response returns\n * `{embeddings: {float: [...]}}`, and `input_type` is sent as\n * `search_document`. That last choice matters — Cohere's v3 models embed\n * documents and queries into different spaces, and this runtime always embeds as\n * a document, including the query side of a search. Expect somewhat weaker\n * retrieval than a Cohere-native setup that embeds queries as `search_query`.\n *\n * Reads `COHERE_API_KEY`; no base-URL environment override is declared. The\n * light models are 384 dimensions and the others 1024.\n */\nexport const cohereMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"cohere\",\n defaultModel: DEFAULT_COHERE_EMBEDDING_MODEL,\n transport: \"remote\" as const,\n authProviderId: \"cohere\",\n autoSelectPriority: 30,\n create: (options: Parameters<typeof createOpenAiCompatibleRuntime>[1]) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"cohere\",\n defaultBaseUrl: \"https://api.cohere.com\",\n apiKeyEnv: \"COHERE_API_KEY\",\n defaultModel: DEFAULT_COHERE_EMBEDDING_MODEL,\n embeddingsPath: \"/v2/embed\",\n dimensionByModel: DIMENSION_BY_MODEL,\n // theokit#159 — `/v2/embed` diverges in BOTH directions: it names the payload `texts`, requires\n // `input_type`, and answers `{embeddings:{float:[[...]]}}` rather than `{data:[{embedding}]}`.\n // `search_document` is the right default here because this runtime embeds material for\n // storage; a query-side embedder would use `search_query`.\n dialect: {\n body: (model: string, inputs: ReadonlyArray<string>) => ({\n model,\n texts: [...inputs],\n input_type: \"search_document\",\n embedding_types: [\"float\"],\n }),\n vectors: (json: unknown) =>\n (json as { embeddings?: { float?: number[][] } }).embeddings?.float,\n },\n },\n options,\n ),\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"./embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n// Iter 74 rollup-plugin-dts workaround: see openai-embedding.ts header.\n\n/**\n * DeepInfra embedding adapter — hosts open-source embedding models\n * (BGE, E5, Jina, etc.) at pay-per-token. OpenAI-compatible REST at\n * `POST /v1/openai/embeddings` (note the `/openai` segment; not the\n * canonical `/v1/embeddings`). The `embeddingsPath` override on\n * `OpenAiCompatibleConfig` REPLACES the default suffix (EC-2).\n *\n * Honors `DEEPINFRA_API_KEY` and `DEEPINFRA_API_BASE_URL`.\n *\n * Iter 74 (Stage 3 source-move #33): hybrid copy from sdk-core's\n * `internal/memory/adapters/deepinfra-embedding.ts`.\n *\n * @internal\n */\n\nexport const DEFAULT_DEEPINFRA_EMBEDDING_MODEL = \"BAAI/bge-large-en-v1.5\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"BAAI/bge-large-en-v1.5\": 1024,\n \"BAAI/bge-base-en-v1.5\": 768,\n \"BAAI/bge-small-en-v1.5\": 384,\n \"BAAI/bge-m3\": 1024,\n \"intfloat/e5-large-v2\": 1024,\n \"intfloat/e5-base-v2\": 768,\n \"intfloat/multilingual-e5-large\": 1024,\n \"sentence-transformers/all-MiniLM-L6-v2\": 384,\n \"thenlper/gte-large\": 1024,\n \"thenlper/gte-base\": 768,\n};\n\n/**\n * Open-weight embedding models (BGE, E5, GTE, MiniLM) hosted by DeepInfra.\n * Reach for it when you want a specific open model — particularly a multilingual\n * one — behind a hosted API rather than running it yourself.\n *\n * Its endpoint is `/v1/openai/embeddings`, not the canonical `/v1/embeddings`;\n * the wire format is otherwise OpenAI-shaped. Reads `DEEPINFRA_API_KEY` and\n * honours `DEEPINFRA_API_BASE_URL`. Priority 13.\n *\n * Dimensions vary sharply across the ten models it knows (384 to 1024), and\n * switching between them invalidates an existing vector index — the index drops\n * every vector and re-embeds on the next sync.\n */\nexport const deepinfraMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"deepinfra\",\n defaultModel: DEFAULT_DEEPINFRA_EMBEDDING_MODEL,\n transport: \"remote\" as const,\n authProviderId: \"deepinfra\",\n autoSelectPriority: 13,\n create: (options: Parameters<typeof createOpenAiCompatibleRuntime>[1]) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"deepinfra\",\n defaultBaseUrl: \"https://api.deepinfra.com\",\n apiKeyEnv: \"DEEPINFRA_API_KEY\",\n baseUrlEnv: \"DEEPINFRA_API_BASE_URL\",\n defaultModel: DEFAULT_DEEPINFRA_EMBEDDING_MODEL,\n dimensionByModel: DIMENSION_BY_MODEL,\n embeddingsPath: \"/v1/openai/embeddings\",\n },\n options,\n ),\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"./embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n// Iter 74 rollup-plugin-dts workaround: see openai-embedding.ts header.\n\n/**\n * Google Gemini embedding adapter — the OpenAI-compatible surface at\n * `https://generativelanguage.googleapis.com/v1/embeddings`.\n *\n * Gemini's NATIVE embedding endpoint has a different shape\n * (`POST /v1beta/models/{model}:embedContent`); this adapter deliberately targets the\n * OpenAI-compatible one so it composes with the shared runtime.\n *\n * Honors `GEMINI_API_KEY`.\n *\n * theokit#128 (catalog parity): mirrors sdk-core's T4.10 adapter, which the peer never picked up.\n *\n * @internal\n */\n\nexport const DEFAULT_GEMINI_EMBEDDING_MODEL = \"text-embedding-004\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"text-embedding-004\": 768,\n \"embedding-001\": 768,\n};\n\n/**\n * Google Gemini embeddings through Google's OpenAI-compatible surface at\n * `/v1beta/openai/embeddings`. Gemini's native embedding endpoint\n * (`/v1beta/models/{model}:embedContent`) has a different shape and is\n * deliberately not used, so this composes with the shared runtime like the rest.\n *\n * Both known models are 768 dimensions. Reads `GEMINI_API_KEY`; no base-URL\n * environment override is declared. Priority 30.\n */\nexport const geminiMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"gemini\",\n defaultModel: DEFAULT_GEMINI_EMBEDDING_MODEL,\n transport: \"remote\" as const,\n authProviderId: \"gemini\",\n autoSelectPriority: 30,\n create: (options: Parameters<typeof createOpenAiCompatibleRuntime>[1]) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"gemini\",\n defaultBaseUrl: \"https://generativelanguage.googleapis.com\",\n apiKeyEnv: \"GEMINI_API_KEY\",\n defaultModel: DEFAULT_GEMINI_EMBEDDING_MODEL,\n // theokit#159 — the compat surface is under `/v1beta/openai/`, not the default\n // `/v1/embeddings`; the previous path 404'd on every call.\n embeddingsPath: \"/v1beta/openai/embeddings\",\n dimensionByModel: DIMENSION_BY_MODEL,\n },\n options,\n ),\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"./embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n// Iter 74 rollup-plugin-dts workaround: see openai-embedding.ts header.\n\n/**\n * Jina AI embedding adapter — OpenAI-compatible at `https://api.jina.ai/v1/embeddings`.\n *\n * Honors `JINA_API_KEY`.\n *\n * theokit#128 (catalog parity): mirrors sdk-core's T4.10 adapter, which the peer never picked up.\n *\n * @internal\n */\n\nexport const DEFAULT_JINA_EMBEDDING_MODEL = \"jina-embeddings-v3\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"jina-embeddings-v3\": 1024,\n \"jina-embeddings-v2-base-en\": 768,\n \"jina-embeddings-v2-small-en\": 512,\n};\n\n/**\n * Jina AI embeddings, over the standard OpenAI wire. Highest auto-select\n * priority in the catalog (35), so it wins over OpenAI when both keys are\n * present.\n *\n * Default `jina-embeddings-v3` at 1024 dimensions; the v2 models are 768 and\n * 512. Reads `JINA_API_KEY`. No base-URL environment override is declared —\n * point it elsewhere by passing `baseUrl` to `create`.\n */\nexport const jinaMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"jina\",\n defaultModel: DEFAULT_JINA_EMBEDDING_MODEL,\n transport: \"remote\" as const,\n authProviderId: \"jina\",\n autoSelectPriority: 35,\n create: (options: Parameters<typeof createOpenAiCompatibleRuntime>[1]) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"jina\",\n defaultBaseUrl: \"https://api.jina.ai\",\n apiKeyEnv: \"JINA_API_KEY\",\n defaultModel: DEFAULT_JINA_EMBEDDING_MODEL,\n dimensionByModel: DIMENSION_BY_MODEL,\n },\n options,\n ),\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"./embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n// Iter 74 rollup-plugin-dts workaround: see openai-embedding.ts header.\n\n/**\n * Mistral embedding adapter — OpenAI-compatible REST surface\n * (`POST /v1/embeddings` against `https://api.mistral.ai`). Default model\n * `mistral-embed` (1024 dims).\n *\n * Mirrors `reference/peer-project/extensions/mistral/memory-embedding-adapter.ts`.\n *\n * Iter 74 (Stage 3 source-move #32): hybrid copy from sdk-core's\n * `internal/memory/adapters/mistral-embedding.ts`.\n *\n * @internal\n */\n\nexport const DEFAULT_MISTRAL_EMBEDDING_MODEL = \"mistral-embed\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"mistral-embed\": 1024,\n};\n\n/**\n * Mistral embeddings, over the standard OpenAI wire. One model only,\n * `mistral-embed` at 1024 dimensions; any other id is refused with\n * `embedding_unknown_model`.\n *\n * Reads `MISTRAL_API_KEY` and honours `MISTRAL_API_BASE_URL`. Priority 18, just\n * below OpenAI.\n */\nexport const mistralMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"mistral\",\n defaultModel: DEFAULT_MISTRAL_EMBEDDING_MODEL,\n transport: \"remote\" as const,\n authProviderId: \"mistral\",\n autoSelectPriority: 18,\n create: (options: Parameters<typeof createOpenAiCompatibleRuntime>[1]) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"mistral\",\n defaultBaseUrl: \"https://api.mistral.ai\",\n apiKeyEnv: \"MISTRAL_API_KEY\",\n baseUrlEnv: \"MISTRAL_API_BASE_URL\",\n defaultModel: DEFAULT_MISTRAL_EMBEDDING_MODEL,\n dimensionByModel: DIMENSION_BY_MODEL,\n },\n options,\n ),\n};\n","/**\n * Ollama embedding adapter (T3.1, ADR D183).\n *\n * Targets Ollama's OpenAI-compatible `/v1/embeddings` endpoint and reuses\n * the shared `createOpenAiCompatibleRuntime` factory. The differentiating\n * bits:\n *\n * - `authType: \"none\"` — Ollama local ignores `Authorization`. Sentinel\n * `\"ollama-local\"` is passed as apiKey to satisfy the factory contract\n * (mirrors peer-project `OLLAMA_DEFAULT_API_KEY = \"ollama-local\"`).\n * - `OLLAMA_HOST` overrides the default `http://localhost:11434`.\n * - `OLLAMA_API_KEY` (optional) overrides the sentinel for Ollama Cloud\n * or reverse-proxy auth setups.\n * - Default model: `nomic-embed-text` (768 dim, ~274MB). User can opt\n * into `all-minilm` (384 dim, ~45MB) or any other locally-installed\n * embedding model.\n *\n * EC-B MUST FIX (edge-case review 2026-05-21): empty text is rejected\n * upstream in the shared factory (`classifyEntry` short-circuits to a\n * zero vector). That behavior is acceptable here because the zero\n * vector is identical for any empty input — downstream similarity\n * calcs ignore zero-norm vectors via the existing `cosineSimilarity`\n * guard. No additional fail-fast needed.\n *\n * EC-A MUST FIX (edge-case review 2026-05-21): dimension is locked\n * by the `DIMENSION_BY_MODEL` table; an unknown model id throws\n * `ConfigurationError(code: \"embedding_unknown_model\")` per the\n * factory's EC-4 contract. Future model versions with different\n * dimensions are added to the table here without breaking changes.\n *\n * Iter 74 (Stage 3 source-move #36): hybrid copy from sdk-core's\n * `internal/memory/adapters/ollama-embedding.ts`. The only\n * `transport: \"local\"` adapter in the cluster — enables 100%-local\n * RAG with no remote API key.\n *\n * @internal\n */\n\nimport type { MemoryEmbeddingProviderAdapter } from \"./embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n// Iter 74 rollup-plugin-dts workaround: see openai-embedding.ts header.\n\n/**\n * Model used when the caller names none: `nomic-embed-text`, 768 dimensions,\n * roughly 274MB to pull. `all-minilm` is the smaller alternative at 384\n * dimensions and roughly 45MB.\n */\nexport const DEFAULT_OLLAMA_EMBEDDING_MODEL = \"nomic-embed-text\";\n\n/** Sentinel forwarded as Bearer token; Ollama local ignores Authorization. */\nconst OLLAMA_LOCAL_SENTINEL_KEY = \"ollama-local\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n // Nomic — local default, recommended quality/size balance.\n \"nomic-embed-text\": 768,\n \"nomic-embed-text:latest\": 768,\n // Sentence-transformers MiniLM — smaller, faster, lower quality.\n \"all-minilm\": 384,\n \"all-minilm:latest\": 384,\n // BGE family.\n \"bge-large\": 1024,\n \"bge-large:latest\": 1024,\n \"bge-m3\": 1024,\n \"bge-m3:latest\": 1024,\n // mxbai-embed-large.\n \"mxbai-embed-large\": 1024,\n \"mxbai-embed-large:latest\": 1024,\n};\n\n/**\n * Embeddings from a local Ollama instance — the only adapter in the catalog with\n * `transport: \"local\"`, and the one to choose when the corpus must not leave the\n * machine or when there is no API key to spend.\n *\n * It needs an Ollama server reachable at `OLLAMA_HOST` (default\n * `http://localhost:11434`) with the chosen embedding model already pulled;\n * nothing here starts a server or downloads a model, so a missing model surfaces\n * as an HTTP error from Ollama rather than a configuration error.\n *\n * No credential is required: a sentinel key is sent and local Ollama ignores it.\n * Set `OLLAMA_API_KEY` for Ollama Cloud or an authenticating reverse proxy.\n *\n * Auto-select priority is 10, the lowest in the catalog, so a configured remote\n * provider wins over it. Request it explicitly to prefer local.\n */\nexport const ollamaMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"ollama\",\n defaultModel: DEFAULT_OLLAMA_EMBEDDING_MODEL,\n transport: \"local\" as const,\n authProviderId: \"ollama\",\n // Lower than remote providers — chosen only when explicitly requested\n // OR when no remote provider key is configured (local-first developer).\n autoSelectPriority: 10,\n create: (options: Parameters<typeof createOpenAiCompatibleRuntime>[1]) => {\n // Honor OLLAMA_API_KEY (Ollama Cloud / reverse-proxy auth), else use\n // sentinel that local Ollama silently ignores. This mirrors\n // `sentinelForNoAuth` in router.ts and peer-project's `resolveSyntheticAuth`.\n const apiKey = options.apiKey ?? process.env.OLLAMA_API_KEY ?? OLLAMA_LOCAL_SENTINEL_KEY;\n return createOpenAiCompatibleRuntime(\n {\n id: \"ollama\",\n defaultBaseUrl: \"http://localhost:11434\",\n apiKeyEnv: \"OLLAMA_API_KEY\",\n baseUrlEnv: \"OLLAMA_HOST\",\n defaultModel: DEFAULT_OLLAMA_EMBEDDING_MODEL,\n dimensionByModel: DIMENSION_BY_MODEL,\n },\n { ...options, apiKey },\n );\n },\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"./embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n// **Iter 74 rollup-plugin-dts workaround:** importing\n// `MemoryEmbeddingProviderAdapter` from sibling `./embedding-adapter.js`\n// fails dts emit because no public type reaches it transitively yet\n// (same iter 48/53/55/66/67/69/72 class). Fix: drop the explicit\n// type annotation on the exported adapter; TS infers the structural\n// shape from the literal, and the catalog (iter 37 / this same iter)\n// pin assignability against the canonical interface via its own\n// `Record<string, MemoryEmbeddingProviderAdapter>` constraint.\n\n/**\n * OpenAI embedding adapter (ADR D3) — built on the shared OpenAI-compatible\n * factory. Native fetch only.\n *\n * Iter 74 (Stage 3 source-move #31): hybrid copy from sdk-core's\n * `internal/memory/adapters/openai-embedding.ts`. Composes iter 45's\n * `MemoryEmbeddingProviderAdapter` + iter 73's\n * `createOpenAiCompatibleRuntime`.\n *\n * @internal\n */\n\nexport const DEFAULT_OPENAI_EMBEDDING_MODEL = \"text-embedding-3-small\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"text-embedding-3-small\": 1536,\n \"text-embedding-3-large\": 3072,\n \"text-embedding-ada-002\": 1536,\n};\n\n/**\n * OpenAI embeddings — `text-embedding-3-small` (1536), `text-embedding-3-large` (3072) and\n * `text-embedding-ada-002` (1536).\n *\n * It is NOT selected for you. The provider is whatever the caller names in\n * `embedding: { provider }`; omit that and no embedding runtime is built at all. Its\n * `autoSelectPriority` of `20` is metadata no code path reads today, and it is not the highest\n * value in the catalog either — `jina` is 35, `cohere` and `gemini` are 30, `azure-openai` is 25.\n * The 3072-wide `text-embedding-3-large` is reachable through `azure-openai` and, as\n * `openai/text-embedding-3-large`, through `openrouter` as well.\n *\n * Reads `OPENAI_API_KEY`; `OPENAI_API_BASE_URL` redirects it at a compatible\n * gateway. `create` rejects with an `AuthenticationError`\n * (`embedding_missing_api_key`) when no key is found, and with a\n * `ConfigurationError` (`embedding_unknown_model`) for a model outside\n * `text-embedding-3-small`, `text-embedding-3-large` and\n * `text-embedding-ada-002` — the dimension has to be known before any vector\n * table is created, so an unlisted model is refused rather than probed.\n */\nexport const openAiMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"openai\",\n defaultModel: DEFAULT_OPENAI_EMBEDDING_MODEL,\n transport: \"remote\" as const,\n authProviderId: \"openai\",\n autoSelectPriority: 20,\n create: (options: Parameters<typeof createOpenAiCompatibleRuntime>[1]) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"openai\",\n defaultBaseUrl: \"https://api.openai.com\",\n apiKeyEnv: \"OPENAI_API_KEY\",\n baseUrlEnv: \"OPENAI_API_BASE_URL\",\n defaultModel: DEFAULT_OPENAI_EMBEDDING_MODEL,\n dimensionByModel: DIMENSION_BY_MODEL,\n },\n options,\n ),\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"./embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n// Iter 74 rollup-plugin-dts workaround: see openai-embedding.ts header.\n\n/**\n * OpenRouter embedding adapter — routes through OpenRouter's\n * `POST /api/v1/embeddings` endpoint (OpenAI-compatible request/response\n * shape). The provider id strings follow OpenRouter's catalog\n * (e.g. `\"openai/text-embedding-3-small\"`, `\"mistralai/mistral-embed\"`).\n *\n * Honors `OPENROUTER_API_KEY` and `OPENROUTER_API_BASE_URL`. Default base\n * URL is `https://openrouter.ai/api`.\n *\n * Iter 74 (Stage 3 source-move #35): hybrid copy from sdk-core's\n * `internal/memory/adapters/openrouter-embedding.ts`.\n *\n * @internal\n */\n\nexport const DEFAULT_OPENROUTER_EMBEDDING_MODEL = \"openai/text-embedding-3-small\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"openai/text-embedding-3-small\": 1536,\n \"openai/text-embedding-3-large\": 3072,\n \"openai/text-embedding-ada-002\": 1536,\n \"mistralai/mistral-embed\": 1024,\n};\n\n/**\n * Embeddings routed through OpenRouter, which lets one key reach several\n * upstream providers. Use it when you want to switch provider without changing\n * credentials; use the provider's own adapter when you want its full model\n * range, since only the four ids in this adapter's dimension table are\n * accepted.\n *\n * Model ids carry the upstream prefix, for example\n * `openai/text-embedding-3-small` or `mistralai/mistral-embed`. The endpoint is\n * `/v1/embeddings` under the base `https://openrouter.ai/api`. Reads\n * `OPENROUTER_API_KEY` and honours `OPENROUTER_API_BASE_URL`. Priority 15.\n */\nexport const openRouterMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"openrouter\",\n defaultModel: DEFAULT_OPENROUTER_EMBEDDING_MODEL,\n transport: \"remote\" as const,\n authProviderId: \"openrouter\",\n autoSelectPriority: 15,\n create: (options: Parameters<typeof createOpenAiCompatibleRuntime>[1]) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"openrouter\",\n defaultBaseUrl: \"https://openrouter.ai/api\",\n apiKeyEnv: \"OPENROUTER_API_KEY\",\n baseUrlEnv: \"OPENROUTER_API_BASE_URL\",\n defaultModel: DEFAULT_OPENROUTER_EMBEDDING_MODEL,\n dimensionByModel: DIMENSION_BY_MODEL,\n },\n options,\n ),\n};\n","import type { MemoryEmbeddingProviderAdapter } from \"./embedding-adapter.js\";\nimport { createOpenAiCompatibleRuntime } from \"./openai-compatible.js\";\n\n// Iter 74 rollup-plugin-dts workaround: see openai-embedding.ts header.\n\n/**\n * Voyage AI embedding adapter — `POST /v1/embeddings` at\n * `https://api.voyageai.com` with the OpenAI-compatible `{ model, input }`\n * request shape. Free tier (200M tokens/month) covers most SDK use.\n *\n * Honors `VOYAGE_API_KEY` and `VOYAGE_API_BASE_URL`.\n *\n * Iter 74 (Stage 3 source-move #34): hybrid copy from sdk-core's\n * `internal/memory/adapters/voyage-embedding.ts`.\n *\n * @internal\n */\n\nexport const DEFAULT_VOYAGE_EMBEDDING_MODEL = \"voyage-3-lite\";\n\nconst DIMENSION_BY_MODEL: Record<string, number> = {\n \"voyage-3-lite\": 512,\n \"voyage-3\": 1024,\n \"voyage-3-large\": 1024,\n \"voyage-code-3\": 1024,\n \"voyage-multilingual-2\": 1024,\n};\n\n/**\n * Voyage AI embeddings, over the standard OpenAI wire. Default model\n * `voyage-3-lite` at 512 dimensions — the narrowest in the catalog, which makes\n * the index smaller and the search cheaper at some cost in quality; `voyage-3`\n * and `voyage-3-large` are 1024, and `voyage-code-3` is the one to pick for\n * source code.\n *\n * Reads `VOYAGE_API_KEY` and honours `VOYAGE_API_BASE_URL`. Priority 14.\n */\nexport const voyageMemoryEmbeddingProviderAdapter: MemoryEmbeddingProviderAdapter = {\n id: \"voyage\",\n defaultModel: DEFAULT_VOYAGE_EMBEDDING_MODEL,\n transport: \"remote\" as const,\n authProviderId: \"voyage\",\n autoSelectPriority: 14,\n create: (options: Parameters<typeof createOpenAiCompatibleRuntime>[1]) =>\n createOpenAiCompatibleRuntime(\n {\n id: \"voyage\",\n defaultBaseUrl: \"https://api.voyageai.com\",\n apiKeyEnv: \"VOYAGE_API_KEY\",\n baseUrlEnv: \"VOYAGE_API_BASE_URL\",\n defaultModel: DEFAULT_VOYAGE_EMBEDDING_MODEL,\n dimensionByModel: DIMENSION_BY_MODEL,\n },\n options,\n ),\n};\n","import { azureOpenAiMemoryEmbeddingProviderAdapter } from \"./embedding/azure-openai-embedding.js\";\nimport { cohereMemoryEmbeddingProviderAdapter } from \"./embedding/cohere-embedding.js\";\nimport { deepinfraMemoryEmbeddingProviderAdapter } from \"./embedding/deepinfra-embedding.js\";\nimport { geminiMemoryEmbeddingProviderAdapter } from \"./embedding/gemini-embedding.js\";\nimport { jinaMemoryEmbeddingProviderAdapter } from \"./embedding/jina-embedding.js\";\nimport { mistralMemoryEmbeddingProviderAdapter } from \"./embedding/mistral-embedding.js\";\nimport { ollamaMemoryEmbeddingProviderAdapter } from \"./embedding/ollama-embedding.js\";\nimport { openAiMemoryEmbeddingProviderAdapter } from \"./embedding/openai-embedding.js\";\nimport { openRouterMemoryEmbeddingProviderAdapter } from \"./embedding/openrouter-embedding.js\";\nimport { voyageMemoryEmbeddingProviderAdapter } from \"./embedding/voyage-embedding.js\";\n\n// Iter 74 rollup-plugin-dts workaround: see openai-embedding.ts header.\n// Catalog value type is inferred from the literal record; canonical\n// assignability is checked at consumer call sites that destructure into\n// the canonical `MemoryEmbeddingProviderAdapter` shape.\n\n/**\n * Memory embedding adapter catalog, indexed by provider id.\n *\n * Only adapters with full, tested implementations are exposed. The\n * `openrouter` provider proxies through OpenRouter to whichever embedding\n * model the caller selects via `model` (e.g.\n * `\"openai/text-embedding-3-small\"`, `\"mistralai/mistral-embed\"`).\n *\n * Locked by ADR D11: `openai`, `mistral`, `openrouter`, `voyage`, `deepinfra`\n * ship in v1.0. ADR D183: `ollama` added — first `transport: \"local\"`\n * adapter, enables 100%-local RAG (no remote API key needed).\n * `lmstudio`, `google`, `bedrock` are deferred to v1.1.\n *\n * Iter 74 (Stage 3 source-move #37): hybrid copy from sdk-core's\n * `internal/memory/adapters/catalog.ts`. Filename renamed to\n * `adapter-catalog.ts` in sdk-memory to disambiguate from the broader\n * \"catalog\" notion at the package barrel level.\n *\n * **This catalog must serve every provider sdk-core ADVERTISES** (theokit#128). When the peer is\n * installed it REPLACES core's catalog in the routing path (`sdk/src/memory.ts`), while the public\n * `Theokit.inspect.embeddingAdapters()` keeps listing core's — so any id core has and this one\n * lacks is a provider the SDK promises and then rejects. That is what happened to `azure-openai`,\n * `cohere`, `jina` and `gemini` for the two months between core's T4.10 and the parity fix.\n * The invariant is enforced by `@theokit/sdk-peer-integration-tests` (`peer-parity.test.ts`).\n *\n * **CLOSES the embedding-adapter cluster in sdk-memory.** The provider adapters + the shared\n * OpenAI-compatible runtime + the inlined HTTP error mapper are canonical here:\n * - iter 45: embedding-adapter (types)\n * - iter 46: embedding-cache (LRU) — REMOVED by theokit#160: the shared runtime owns caching now\n * - iter 73: openai-compatible (shared factory) + adapter-http-error\n * (inlined mapper)\n * - iter 74: openai-embedding + mistral-embedding + deepinfra-embedding\n * + voyage-embedding + openrouter-embedding + ollama-embedding +\n * adapter-catalog (THIS)\n * - theokit#128: azure-openai + cohere + jina + gemini (parity with core's T4.10)\n *\n * @internal\n */\nexport const MEMORY_EMBEDDING_ADAPTERS = {\n openai: openAiMemoryEmbeddingProviderAdapter,\n mistral: mistralMemoryEmbeddingProviderAdapter,\n openrouter: openRouterMemoryEmbeddingProviderAdapter,\n voyage: voyageMemoryEmbeddingProviderAdapter,\n deepinfra: deepinfraMemoryEmbeddingProviderAdapter,\n ollama: ollamaMemoryEmbeddingProviderAdapter,\n // theokit#128 — mirrors sdk-core's T4.10 additions, which the peer had drifted behind.\n \"azure-openai\": azureOpenAiMemoryEmbeddingProviderAdapter,\n cohere: cohereMemoryEmbeddingProviderAdapter,\n jina: jinaMemoryEmbeddingProviderAdapter,\n gemini: geminiMemoryEmbeddingProviderAdapter,\n};\n","/**\n * Public memory types (used by runtime + storage + migration + future index).\n *\n * Leaf module — depends only on `node:path` + the public\n * `@theokit/sdk/path-safety` re-exports (`safePathJoin`,\n * `sanitizeIdentifier`) + `@theokit/sdk`'s `Security` for the\n * canonical `redactSecrets` 12-pattern list (ADR D68).\n *\n * Iter 52 (Stage 3 source-move #9): hybrid copy from sdk-core's\n * `internal/memory/types.ts`. sdk-core retains its copy for v1.x\n * back-compat; sdk-memory ships the canonical copy that future\n * `storage/*`, `migration`, and `tools` moves will target as siblings.\n *\n * **Sub-path-import contract:** sdk-core copy imports\n * `safePathJoin`/`sanitizeIdentifier` from `../security/path-guard.js`\n * (internal path); sdk-memory copy imports them from\n * `@theokit/sdk/path-safety` (public sub-path stable per this\n * iter — sanitizeIdentifier was promoted to the public surface to\n * unblock this move). Same runtime, same grammar.\n *\n * @internal\n */\nimport { resolve as resolvePath } from \"node:path\";\n\nimport { Security } from \"@theokit/sdk\";\nimport { safePathJoin, sanitizeIdentifier } from \"@theokit/sdk/path-safety\";\n\n/**\n * Per-agent memory configuration. `enabled` gates the configuration-aware\n * accessors (`readFacts`, `appendFact`) — with it `false` they resolve without\n * touching disk, while the lower-level markdown functions ignore it.\n *\n * `namespace`, `scope` and `userId` are only consulted for the legacy JSON path\n * (see {@link legacyMemoryJsonPath}); the markdown store keeps one `MEMORY.md`\n * per workspace and does not partition by them. They are treated as\n * user-supplied and sanitised before they reach a path. `storePath` is treated\n * as trusted and resolved as given.\n */\nexport interface MemoryConfig {\n enabled: boolean;\n namespace?: string;\n userId?: string;\n scope?: \"agent\" | \"user\" | \"team\";\n storePath?: string;\n}\n\n/**\n * One remembered statement. `text` is what gets written, embedded and searched;\n * it passes through secret redaction on the way to disk, so what is stored may\n * differ from what was passed in.\n */\nexport interface MemoryFact {\n text: string;\n /**\n * Optional taxonomy bucket (M4-3). Backward-compatible — flat-store facts\n * omit it; the categorized store (`createCategorizedMemory`) always sets it.\n */\n category?: string;\n}\n\n/**\n * Canonical credential-redaction primitive (ADR D68).\n *\n * sdk-core's copy re-exports `redactSecrets` directly from\n * `../security/index.js` (internal path). sdk-core's PUBLIC surface\n * (`@theokit/sdk`) doesn't expose a bare `redactSecrets` symbol —\n * it ships `Security.redact()` instead (T2.1, by design — the\n * namespace also carries `Security.addPattern()`). sdk-memory's\n * canonical `redactSecrets` re-export wraps `Security.redact` 1-to-1\n * so consumers continue to see the same symbol name without sdk-memory\n * having to import sdk-core's internal subpath. Same 12-pattern\n * list, same two-bucket mask shape, same disable-via-env behavior.\n */\nexport function redactSecrets(text: unknown, opts?: { codeFile?: boolean }): string {\n return Security.redact(text, opts);\n}\n\n/**\n * Resolve the legacy JSON memory path used pre-ADR-D8 (kept for migration\n * helpers + tests). Centralized here so `migration.ts` and the legacy-aware\n * `runtime/memory-store.ts` don't duplicate the path logic (jscpd cleanup).\n */\nexport function legacyMemoryJsonPath(cwd: string, config: MemoryConfig): string {\n // ADRs D79-D81: storePath is programmatic (trusted); namespace/scope/userId\n // are user-shaped and pass sanitizeIdentifier. EC-7 (edge-case review):\n // realistic userIds (UUIDs, hash IDs, \"default\") pass; \"user@example.com\"\n // and similar need to be normalized by the caller before passing.\n if (config.storePath !== undefined) {\n return resolvePath(cwd, config.storePath);\n }\n const namespace = sanitizeIdentifier(config.namespace ?? \"default\");\n const scope = sanitizeIdentifier(config.scope ?? \"agent\", { maxLen: 16 });\n const userId = sanitizeIdentifier(config.userId ?? \"default\");\n return safePathJoin(cwd, \".theokit\", \"memory\", namespace, `${scope}-${userId}.json`);\n}\n\n/**\n * A semantically meaningful slice of a markdown memory file, produced by\n * `chunkMarkdown`. Each chunk carries stable line numbers + a content hash\n * used downstream by the embedding cache.\n *\n * Mirrors peer-project's `MemoryChunk` shape\n * (`reference/peer-project/packages/memory-host-sdk/src/host/engine-storage.ts`).\n *\n * @internal\n */\nexport interface MemoryChunk {\n /** 1-indexed starting line in the source file. */\n startLine: number;\n /** 1-indexed ending line (inclusive). */\n endLine: number;\n /** Slice of markdown source text. */\n text: string;\n /** sha256 of `text`; stable across runs for identical inputs. */\n hash: string;\n /** Optional nearest heading text (without the `#` markers). */\n heading?: string;\n}\n\n/**\n * Result of `reader.readFile`. Contains the bounded slice plus truncation\n * + provenance info.\n *\n * Mirrors peer-project's `MemoryReadResult` shape.\n *\n * @internal\n */\nexport interface MemoryReadResult {\n path: string;\n /** Requested starting line (1-indexed, defaults to 1). */\n from: number;\n /** Number of lines actually returned (may be less than `lines` near EOF). */\n linesReturned: number;\n /** Total lines in the file (after the read). */\n totalLines: number;\n /** True when content remains after the returned slice, i.e. `remainingLines > 0`. */\n truncated: boolean;\n /** Lines past the returned slice that remain in the file. */\n remainingLines: number;\n /** Slice text (joined with `\\n`). */\n text: string;\n}\n\n/**\n * Lightweight reference to a markdown file in the memory corpus.\n *\n * Mirrors peer-project's `MemoryFileEntry`.\n *\n * @internal\n */\nexport interface MemoryFileEntry {\n /** Absolute path on disk. */\n path: string;\n /** Path relative to the memory root (e.g. \"MEMORY.md\", \"notes/foo.md\"). */\n relPath: string;\n /** ms-since-epoch mtime. */\n mtime: number;\n /** sha256 of the file content; recomputed on each read. */\n hash: string;\n}\n","/**\n * OpenAI-compatible HTTP error mapper (ADR D67) — sdk-memory inlined copy.\n *\n * Translates OpenAI-shaped API error responses (covers OpenAI, OpenRouter,\n * DeepSeek, Together, Mistral, Voyage, DeepInfra, etc.) into typed\n * `TheokitAgentError` subclasses with full `ErrorMetadata`.\n *\n * Body inspection: looks at `body.error.code` / `body.error.type` to detect\n * `context_too_long`, `content_filtered`, `model_unavailable` semantics.\n * Falls back to status-based mapping when body doesn't expose `.error`\n * (e.g., HTML server error page, DeepInfra's `{message: \"...\"}` shape).\n *\n * Never throws — caller is already in an error path.\n *\n * Iter 73 (Stage 3 source-move #30): inlined adaptation of sdk-core's\n * `internal/errors/mappers/openai-compatible.ts` + `shared.ts`. sdk-core's\n * mapper is internal — not part of the public errors surface — so sdk-memory\n * carries its own minimal copy here. Behavior MUST stay byte-equivalent\n * with sdk-core's so consumers consuming hits via either package surface\n * see identical error shape.\n *\n * The 4 helpers (`parseRetryAfter`, `truncateRaw`, `buildErrorMetadata`,\n * `mapOpenAICompatibleError`) are intentionally co-located in this single\n * file so all 8 embedding adapter moves (catalog + 7 providers) share one\n * import target.\n *\n * @internal\n */\n\nimport {\n AuthenticationError,\n ConfigurationError,\n type ErrorCode,\n type ErrorMetadata,\n NetworkError,\n RateLimitError,\n type TheokitAgentError,\n UnknownAgentError,\n} from \"@theokit/sdk/errors\";\n\nimport { redactSecrets } from \"./memory-types.js\";\n\nconst RAW_MAX_BYTES = 2048;\nconst PROVIDER_DETAIL_MAX_CHARS = 512;\n// OpenRouter answers a model it does not serve with HTTP 404 and a numeric `error.code`,\n// so only the message tells it apart from a 404 for a wrong path.\nconst MISSING_MODEL_MESSAGE = /no endpoints found/i;\n\n/**\n * Parse `retry-after` header in numeric-seconds form. HTTP-date form\n * (RFC 7231) returns `undefined` to avoid NaN propagation downstream.\n */\nexport function parseRetryAfter(headers: Headers | undefined): number | undefined {\n if (headers === undefined) return undefined;\n const raw = headers.get(\"retry-after\");\n if (raw === null) return undefined;\n const n = Number(raw);\n if (Number.isFinite(n) && n >= 0) return Math.ceil(n);\n return undefined;\n}\n\n/**\n * Truncate raw response body to ~2KB and redact known credential\n * patterns so it can ride inside `ErrorMetadata.raw` without\n * ballooning logs OR leaking tokens. Returns `undefined` for\n * null/undefined input.\n */\nexport function truncateRaw(body: unknown): unknown {\n if (body === null || body === undefined) return undefined;\n const s = typeof body === \"string\" ? body : JSON.stringify(body);\n // Redact before the cut so a key straddling the limit cannot slip past the patterns.\n const redacted = redactSecrets(s);\n return redacted.length <= RAW_MAX_BYTES ? redacted : `${redacted.slice(0, RAW_MAX_BYTES)}…`;\n}\n\n/**\n * Build an `ErrorMetadata` object with all optional fields included\n * conditionally (no `undefined` keys in the output).\n */\nexport function buildErrorMetadata(args: {\n provider: string;\n endpoint: string;\n code: ErrorCode;\n status: number;\n headers: Headers | undefined;\n body: unknown;\n}): ErrorMetadata {\n const retryAfter = parseRetryAfter(args.headers);\n const raw = truncateRaw(args.body);\n return {\n provider: args.provider,\n endpoint: args.endpoint,\n code: args.code,\n statusCode: args.status,\n ...(retryAfter !== undefined ? { retryAfter } : {}),\n ...(raw !== undefined ? { raw } : {}),\n };\n}\n\ninterface MapOpenAiErrorArgs {\n providerId: string;\n status: number;\n body: unknown;\n headers: Headers | undefined;\n endpoint: string;\n}\n\n/**\n * Turn a failed OpenAI-shaped HTTP response into the typed error the SDK throws.\n * Builds the error, it does not throw it.\n *\n * The HTTP status picks the class: 401 and 403 give an `AuthenticationError`,\n * 429 a `RateLimitError`, 400 a `ConfigurationError`, 408 and 5xx a\n * `NetworkError`, and anything else an `UnknownAgentError`.\n *\n * The `code` on the metadata is finer than the class and is read from\n * `body.error.code` (or `.type`) first, so a 400 that names a context-window\n * problem carries `context_too_long` rather than `invalid_request`. A body code\n * naming an exhausted quota, and HTTP 402, both map to `quota_exceeded` — note\n * that a 402 keeps that code while still producing an `UnknownAgentError`,\n * because no status branch claims it.\n *\n * The raw body rides along on the metadata, truncated to about 2KB and passed\n * through secret redaction, so it is safe to log.\n */\nexport function mapOpenAICompatibleError(args: MapOpenAiErrorArgs): TheokitAgentError {\n const { providerId, status, body, headers, endpoint } = args;\n const code = mapOpenAiStatusToCode(status, body);\n const message = formatMessage(providerId, status, code);\n const metadata = buildErrorMetadata({\n provider: providerId,\n endpoint,\n code,\n status,\n headers,\n body,\n });\n\n if (status === 401 || status === 403) {\n return new AuthenticationError(message, { code: `${providerId}_auth_failed`, metadata });\n }\n if (status === 429) {\n return new RateLimitError(message, { code: `${providerId}_rate_limit`, metadata });\n }\n if (status === 404 && code === \"model_unavailable\") {\n // The model id lives only in the provider's text, so this case carries it.\n const detailed = formatMessage(providerId, status, code, boundedProviderDetail(body));\n return new ConfigurationError(detailed, {\n code: `${providerId}_model_unavailable`,\n metadata,\n });\n }\n if (status === 400) {\n // A 400 is fixed by changing the request, and only the provider's text says what to change.\n const detailed = formatMessage(providerId, status, code, boundedProviderDetail(body));\n return new ConfigurationError(detailed, { code: `${providerId}_${code}`, metadata });\n }\n if (status === 408) {\n return new NetworkError(message, { code: `${providerId}_timeout`, metadata });\n }\n if (status >= 500 && status < 600) {\n return new NetworkError(message, { code: `${providerId}_server_error`, metadata });\n }\n return new UnknownAgentError(message, { code: `${providerId}_unknown`, metadata });\n}\n\nfunction extractOpenAiErrorMessage(body: unknown): string | undefined {\n if (body === null || typeof body !== \"object\") return undefined;\n const err = (body as { error?: { message?: unknown } }).error;\n if (err === undefined || err === null) return undefined;\n return typeof err.message === \"string\" ? err.message : undefined;\n}\n\n// Redaction runs before the cut so a key cut short cannot slip past the credential patterns.\nfunction boundedProviderDetail(body: unknown): string | undefined {\n const raw = extractOpenAiErrorMessage(body);\n if (raw === undefined || raw.trim() === \"\") return undefined;\n const redacted = redactSecrets(raw);\n return redacted.length <= PROVIDER_DETAIL_MAX_CHARS\n ? redacted\n : `${redacted.slice(0, PROVIDER_DETAIL_MAX_CHARS)}…`;\n}\n\nfunction extractOpenAiErrorCode(body: unknown): string | undefined {\n if (body === null || typeof body !== \"object\") return undefined;\n const err = (body as { error?: { code?: unknown; type?: unknown } }).error;\n if (err === undefined || err === null) return undefined;\n if (typeof err.code === \"string\") return err.code;\n if (typeof err.type === \"string\") return err.type;\n return undefined;\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: explicit branch table is clearer than splitting\nfunction mapOpenAiStatusToCode(status: number, body: unknown): ErrorCode {\n const rawCode = extractOpenAiErrorCode(body)?.toLowerCase() ?? \"\";\n\n if (\n rawCode.includes(\"context_length\") ||\n rawCode.includes(\"context_window\") ||\n rawCode.includes(\"too_many_tokens\") ||\n rawCode.includes(\"max_tokens\")\n ) {\n return \"context_too_long\";\n }\n if (\n rawCode.includes(\"content_filter\") ||\n rawCode.includes(\"content_policy\") ||\n rawCode.includes(\"safety\")\n ) {\n return \"content_filtered\";\n }\n if (\n rawCode.includes(\"model_not_found\") ||\n rawCode.includes(\"model_unavailable\") ||\n rawCode.includes(\"invalid_model\")\n ) {\n return \"model_unavailable\";\n }\n // T3.7 — 402 / Insufficient credits / insufficient_quota body code flow\n // to canonical `quota_exceeded` (ADR-spec'd in ErrorCode union).\n if (\n status === 402 ||\n rawCode.includes(\"insufficient_quota\") ||\n rawCode.includes(\"quota_exceeded\")\n ) {\n return \"quota_exceeded\";\n }\n\n if (status === 404 && MISSING_MODEL_MESSAGE.test(extractOpenAiErrorMessage(body) ?? \"\")) {\n return \"model_unavailable\";\n }\n\n if (status === 401 || status === 403) return \"auth_failed\";\n if (status === 429) return \"rate_limit\";\n if (status === 408) return \"timeout\";\n if (status === 400) return \"invalid_request\";\n if (status >= 500 && status < 600) return \"server_error\";\n return \"unknown\";\n}\n\nfunction formatMessage(\n providerId: string,\n status: number,\n code: ErrorCode,\n detail?: string,\n): string {\n const base = `${providerId} API error: ${code} (HTTP ${status})`;\n return detail === undefined || detail === \"\" ? base : `${base}: ${detail}`;\n}\n","import { mkdir, readFile } from \"node:fs/promises\";\n\nimport { ConfigurationError } from \"@theokit/sdk/errors\";\nimport { safePathJoin, sanitizeIdentifier } from \"@theokit/sdk/path-safety\";\nimport { replaceFileAtomic, withCwdMutex } from \"@theokit/sdk/persistence\";\n\nimport { type MemoryFact, redactSecrets } from \"./memory-types.js\";\n\n/**\n * A fact stored under a typed category. Unlike the flat {@link MemoryFact}, the\n * `category` is always present in the categorized store's read shape.\n *\n * @public\n */\nexport interface CategorizedFact extends MemoryFact {\n category: string;\n}\n\n/**\n * Options for {@link createCategorizedMemory}.\n *\n * @public\n */\nexport interface CreateCategorizedMemoryOptions {\n /** Directory holding one markdown file per category (`<root>/<category>.md`). */\n root: string;\n /**\n * The closed category taxonomy. This list IS the schema: an `add`/`list`\n * with a category not in it is rejected. Must be non-empty, unique, each\n * sanitizable to a distinct filename.\n */\n categories: readonly string[];\n}\n\n/**\n * A typed, category-partitioned markdown memory store.\n *\n * @public\n */\nexport interface CategorizedMemory {\n /** The declared (frozen) category taxonomy. */\n readonly categories: readonly string[];\n /**\n * Append a fact under `category` (validated against the taxonomy). The text\n * is secret-redacted before persistence. Concurrent adds to the same category\n * are serialized (no lost update). Throws `ConfigurationError(unknown_category)`\n * for an undeclared category (before any I/O).\n */\n add(category: string, text: string): Promise<void>;\n /**\n * Read facts for one category (or every category when omitted). Never throws —\n * a missing/unreadable category file yields no facts.\n */\n list(category?: string): Promise<CategorizedFact[]>;\n}\n\nconst FACTS_HEADING = \"## Facts\";\n\n/**\n * Create a typed categorized memory store over the closed `categories`\n * taxonomy. Composes the shipped `safePathJoin`/`sanitizeIdentifier` path\n * guard, `redactSecrets`, and the atomic `replaceFileAtomic` + `withCwdMutex`\n * persistence primitives — zero new dependencies.\n *\n * @public\n */\nexport function createCategorizedMemory(\n options: CreateCategorizedMemoryOptions,\n): CategorizedMemory {\n const { root, categories } = options;\n validateCategories(categories);\n const allowed = new Set(categories);\n\n function assertKnown(category: string): void {\n if (!allowed.has(category)) {\n throw new ConfigurationError(\n `createCategorizedMemory: unknown category ${JSON.stringify(category)} (declared: ${categories.join(\", \")})`,\n { code: \"unknown_category\" },\n );\n }\n }\n\n function categoryPath(category: string): string {\n return safePathJoin(root, `${sanitizeIdentifier(category)}.md`);\n }\n\n async function add(category: string, text: string): Promise<void> {\n assertKnown(category);\n // Redact secrets, THEN encode newlines/backslashes so a multiline fact (or\n // one containing a `- ` / `## ` line) stays a single bullet and round-trips\n // faithfully — `list` decodes it back. Without this, the `## Facts` bullet\n // parse would split or truncate the fact (silent data loss).\n const encoded = encodeFact(redactSecrets(text));\n const sane = sanitizeIdentifier(category);\n await withCwdMutex(`catmem:${root}:${sane}`, async () => {\n const path = safePathJoin(root, `${sane}.md`);\n const raw = (await readFileOrEmpty(path)) || header(category);\n await mkdir(root, { recursive: true });\n await replaceFileAtomic(path, appendBullet(raw, encoded));\n });\n }\n\n async function list(category?: string): Promise<CategorizedFact[]> {\n if (category !== undefined) {\n assertKnown(category);\n return readCategory(categoryPath(category), category);\n }\n const out: CategorizedFact[] = [];\n for (const c of categories) {\n out.push(...(await readCategory(categoryPath(c), c)));\n }\n return out;\n }\n\n return { categories: [...categories], add, list };\n}\n\nfunction validateCategories(categories: readonly string[]): void {\n if (categories.length === 0) {\n throw new ConfigurationError(\"createCategorizedMemory: categories must be non-empty\", {\n code: \"invalid_categories\",\n });\n }\n if (new Set(categories).size !== categories.length) {\n throw new ConfigurationError(\"createCategorizedMemory: categories must be unique\", {\n code: \"invalid_categories\",\n });\n }\n const sanitized = categories.map((c) => trySanitize(c));\n if (new Set(sanitized).size !== categories.length) {\n throw new ConfigurationError(\n \"createCategorizedMemory: categories must map to distinct filenames after sanitization\",\n { code: \"invalid_categories\" },\n );\n }\n}\n\nfunction trySanitize(category: string): string {\n try {\n return sanitizeIdentifier(category);\n } catch (cause) {\n throw new ConfigurationError(\n `createCategorizedMemory: category ${JSON.stringify(category)} is not a valid identifier`,\n { code: \"invalid_categories\", cause },\n );\n }\n}\n\nfunction header(category: string): string {\n return `---\\ncategory: ${category}\\n---\\n\\n${FACTS_HEADING}\\n`;\n}\n\nasync function readFileOrEmpty(path: string): Promise<string> {\n try {\n return await readFile(path, \"utf8\");\n } catch {\n return \"\";\n }\n}\n\nasync function readCategory(path: string, category: string): Promise<CategorizedFact[]> {\n const raw = await readFileOrEmpty(path);\n return parseFactBullets(raw).map((text) => ({ text: decodeFact(text), category }));\n}\n\n/**\n * Encode a fact for single-bullet storage: escape `\\` first, then `\\r`/`\\n`, so\n * the text occupies exactly one `- ` line (no split, no `## ` heading injection).\n * Pure + reversible by {@link decodeFact}.\n */\nfunction encodeFact(text: string): string {\n return text.replace(/\\\\/g, \"\\\\\\\\\").replace(/\\r/g, \"\\\\r\").replace(/\\n/g, \"\\\\n\");\n}\n\n/**\n * Reverse {@link encodeFact}. A single left-to-right pass over each `\\<char>`\n * escape: `\\n`→newline, `\\r`→CR, and any other escaped char (notably `\\\\`)→the\n * literal char. Non-overlapping matching makes this exact for encoded input.\n */\nfunction decodeFact(text: string): string {\n return text.replace(/\\\\(.)/g, (_match, char: string) =>\n char === \"n\" ? \"\\n\" : char === \"r\" ? \"\\r\" : char,\n );\n}\n\n/** Parse `- text` bullets under the `## Facts` heading. Pure. */\nfunction parseFactBullets(raw: string): string[] {\n const idx = raw.indexOf(FACTS_HEADING);\n if (idx === -1) return [];\n const tail = raw.slice(idx + FACTS_HEADING.length);\n const nextHeading = tail.search(/\\n#{1,2}\\s/);\n const block = nextHeading === -1 ? tail : tail.slice(0, nextHeading);\n return block\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line.startsWith(\"- \"))\n .map((line) => line.slice(2).trim());\n}\n\n/** Append a `- text` bullet under the `## Facts` heading. Pure. */\nfunction appendBullet(raw: string, text: string): string {\n const bullet = `- ${text}`;\n const idx = raw.indexOf(FACTS_HEADING);\n if (idx === -1) {\n const sep = raw.endsWith(\"\\n\") ? \"\" : \"\\n\";\n return `${raw}${sep}${FACTS_HEADING}\\n\\n${bullet}\\n`;\n }\n const after = idx + FACTS_HEADING.length;\n const nextHeading = raw.slice(after).search(/\\n#{1,2}\\s/);\n if (nextHeading === -1) {\n const trailing = raw.endsWith(\"\\n\") ? \"\" : \"\\n\";\n return `${raw}${trailing}${bullet}\\n`;\n }\n const insertAt = after + nextHeading;\n return `${raw.slice(0, insertAt)}\\n${bullet}${raw.slice(insertAt)}`;\n}\n","import {\n type LanceIndex,\n LanceMemoryAdapter as SharedLanceMemoryAdapter,\n} from \"@theokit/sdk/internal/memory-store\";\n\n/**\n * Presents a `LanceIndex` as a `MemoryIndex`, so a consumer written against the SQLite index runs\n * unchanged on `backend: \"lance\"`.\n *\n * `sync`, `search`, `status` and `close` are the SDK's adapter, inherited rather than copied\n * (#1068), so they behave the same whether or not this package is installed: `sync()` walks\n * nothing and says so with `supported: false`, `search()` blends Lance's vector score with a\n * term-overlap text score through the caller's `vectorWeight` / `textWeight`, and `status()`\n * reports zero counts with `countsExact: false`. It always queries the `default` namespace.\n *\n * The one member this class adds is {@link LanceMemoryAdapter.unwrap}. The SDK's adapter\n * deliberately has no such member; this package published one, so it stays here. An index opened\n * with `IndexManager.open({ backend: \"lance\" })` is the SDK's adapter and does not have it: to\n * write facts, open a `LanceIndex` and either use it directly or wrap it with this class.\n *\n * Requires `@lancedb/lancedb`, an optional peer dependency, loaded when the index is opened.\n */\nexport class LanceMemoryAdapter extends SharedLanceMemoryAdapter {\n readonly #lance: LanceIndex;\n\n constructor(inner: LanceIndex) {\n super(inner);\n this.#lance = inner;\n }\n\n /** The wrapped `LanceIndex`, for `addFacts`, `countFacts` and `removeFacts`. */\n unwrap(): LanceIndex {\n return this.#lance;\n }\n}\n","import type { MemoryDb } from \"@theokit/sdk/internal/memory-store\";\n\n// `isSqliteVecLoaded` has no SDK counterpart yet, so it stays here; the loader is the SDK's.\nexport { loadSqliteVecExtension } from \"@theokit/sdk/internal/memory-store\";\n\n/** Check whether sqlite-vec is loaded by running a tiny version query. */\nexport function isSqliteVecLoaded(db: MemoryDb): boolean {\n try {\n const row = db.prepare(\"SELECT vec_version() as v\").get();\n return row !== undefined && row.v !== undefined;\n } catch {\n return false;\n }\n}\n","import { resolve as resolvePath } from \"node:path\";\n\nimport { ConfigurationError } from \"@theokit/sdk/errors\";\n\nimport type { MemorySearchHit } from \"./index/index-manager-contract.js\";\nimport type { MemoryIndex } from \"./index/memory-index.js\";\nimport type { MemoryRoot } from \"./store/markdown-store.js\";\nimport { readMemoryFileBounded } from \"./store/reader.js\";\n\n/**\n * Memory tools (`memory_search` + `memory_get`) — ADR D5 of\n * memory-system-peer-project-parity. Tool schemas mirror peer-project\n * (`reference/peer-project/extensions/memory-core/src/tools.ts:228-475`).\n *\n * Each tool is exposed as a `MemoryTool` (name + description + JSON schema +\n * async execute). The agent-loop integration wires them via the existing\n * `ResolvedTool` interface in `tool-dispatch.ts`.\n *\n * Iter 64 (Stage 3 source-move #21): hybrid copy from sdk-core's\n * `internal/memory/tools.ts`. sdk-core retains its copy for v1.x\n * memory-tools back-compat; sdk-memory ships the canonical copy.\n * Dependency chain (all resolved):\n * - `@theokit/sdk/errors` for `ConfigurationError` (public)\n * - sibling `./index-manager-contract.js` for `MemorySearchHit`\n * (moved iter 47 — note: sdk-core copy imports from\n * `./index-manager.js`; sdk-memory uses the contract leaf\n * directly since the canonical type lives there)\n * - sibling `./memory-index.js` for `MemoryIndex` (moved iter 50)\n * - sibling `./markdown-store.js` for `memoryDir` (moved iter 56)\n * - sibling `./reader.js` for `readMemoryFileBounded` (moved iter 55)\n *\n * @internal\n */\n\nexport interface MemoryToolJson {\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n}\n\n/**\n * A memory tool ready to hand to the agent loop: the JSON-serialisable\n * description an LLM sees, plus the `execute` that runs it. `execute` resolves\n * to a JSON string — the tool layer does no further encoding.\n */\nexport interface MemoryTool extends MemoryToolJson {\n execute(input: Record<string, unknown>): Promise<string>;\n}\n\nconst SEARCH_DESCRIPTION =\n \"Mandatory recall step: semantically search MEMORY.md + memory/notes/*.md (and optional wiki supplements) before answering questions about prior work, decisions, dates, people, preferences, or todos. `corpus=memory` (default) restricts to indexed memory files; `corpus=wiki` restricts to read-only wiki supplements; `corpus=all` returns both. Returns ranked `{ path, startLine, endLine, score, snippet, citation }` hits.\";\n\nconst GET_DESCRIPTION =\n \"Safe exact excerpt read from MEMORY.md or memory/notes/*.md. Defaults to a bounded excerpt (200 lines). Returns `{ path, from, linesReturned, totalLines, truncated, remainingLines, text }`. Paths are resolved against the memory root — attempts to read outside `.theokit/memory/` are rejected.\";\n\nconst MEMORY_SEARCH_SCHEMA: Record<string, unknown> = {\n type: \"object\",\n required: [\"query\"],\n properties: {\n query: { type: \"string\", description: \"Natural-language query.\" },\n maxResults: { type: \"integer\", minimum: 1, maximum: 50 },\n minScore: { type: \"number\", minimum: 0, maximum: 1 },\n corpus: { type: \"string\", enum: [\"memory\", \"sessions\", \"wiki\", \"all\"] },\n },\n additionalProperties: false,\n};\n\nconst MEMORY_GET_SCHEMA: Record<string, unknown> = {\n type: \"object\",\n required: [\"path\"],\n properties: {\n path: { type: \"string\", description: \"Path relative to .theokit/memory/\" },\n from: { type: \"integer\", minimum: 1 },\n lines: { type: \"integer\", minimum: 1, maximum: 2000 },\n },\n additionalProperties: false,\n};\n\nconst DEFAULT_MAX_TOTAL_CHARS = 16384;\n\n/** Options for {@link createMemorySearchTool}. */\nexport interface MemorySearchToolOptions {\n index: MemoryIndex;\n /** Cap on the JSON response size (EC-10 of edge-case review). Default 16384. */\n maxTotalChars?: number;\n}\n\n/**\n * Build the `memory_search` tool over an index that is already open. The tool\n * never opens or syncs anything: if `index.sync()` has not run, the search runs\n * against whatever the index last recorded, and a freshly created index returns\n * no hits.\n *\n * The tool accepts `query` (required), `maxResults` (default 10), `minScore`,\n * and `corpus`, where `corpus` maps to the index's source filter: `memory`,\n * `sessions`, `wiki`, or `all` (the default, which applies no filter). An\n * unrecognised `corpus` value is treated as `all` rather than rejected.\n *\n * `execute` returns `{\"hits\": [...], \"truncated\": bool}`. Hits are dropped from\n * the tail once their estimated size would exceed `maxTotalChars`, except that\n * the first hit is always kept even when it alone exceeds the cap.\n *\n * Use this for recall by meaning across the whole corpus, and\n * {@link createMemoryGetTool} when the model already knows the file and wants\n * exact lines.\n */\nexport function createMemorySearchTool(opts: MemorySearchToolOptions): MemoryTool {\n const cap = opts.maxTotalChars ?? DEFAULT_MAX_TOTAL_CHARS;\n return {\n name: \"memory_search\",\n description: SEARCH_DESCRIPTION,\n inputSchema: MEMORY_SEARCH_SCHEMA,\n async execute(input: Record<string, unknown>): Promise<string> {\n const query = readString(input.query, \"query is required\");\n const maxResults = readNumber(input.maxResults) ?? 10;\n const minScore = readNumber(input.minScore);\n const corpus = readString(input.corpus, undefined, true);\n const sources = mapCorpusToSources(corpus);\n const searchOptions = {\n maxResults,\n ...(minScore !== undefined ? { minScore } : {}),\n ...(sources !== undefined ? { sources } : {}),\n };\n const hits = await opts.index.search(query, searchOptions);\n return JSON.stringify(capByTotalChars(hits, cap));\n },\n };\n}\n\n/** Options for {@link createMemoryGetTool}. `cwd` is the workspace root, not the memory directory. */\nexport interface MemoryGetToolOptions {\n /** The RESOLVED memory root the tool may read inside — not a cwd (#463). */\n root: MemoryRoot;\n}\n\n/**\n * Build the `memory_get` tool, which reads an exact excerpt from a file under\n * `<cwd>/.theokit/memory`. Needs no index and no embedding runtime — it is\n * plain file reading, so it works in a workspace where search is not configured.\n *\n * The tool accepts `path` (required, relative to the memory root), `from`\n * (1-indexed, default 1) and `lines` (default 200). A `path` whose resolved\n * location falls outside the memory root is rejected with a\n * `ConfigurationError` carrying the code `memory_path_escapes_root`. A path that\n * stays inside but does not exist is not caught here: the underlying read\n * rejects with the filesystem error.\n */\nexport function createMemoryGetTool(opts: MemoryGetToolOptions): MemoryTool {\n const memoryRoot = resolvePath(opts.root);\n return {\n name: \"memory_get\",\n description: GET_DESCRIPTION,\n inputSchema: MEMORY_GET_SCHEMA,\n async execute(input: Record<string, unknown>): Promise<string> {\n const relPath = readString(input.path, \"path is required\");\n const from = readNumber(input.from);\n const lines = readNumber(input.lines);\n // EC-2: enforce that the resolved path stays inside the memory root.\n const resolved = resolvePath(memoryRoot, relPath);\n if (!isPathInside(memoryRoot, resolved)) {\n throw new ConfigurationError(\n `memory_get rejected path that escapes memory root: ${relPath}`,\n { code: \"memory_path_escapes_root\" },\n );\n }\n const readArgs: { cwd: string; relPath: string; from?: number; lines?: number } = {\n cwd: memoryRoot,\n relPath,\n };\n if (from !== undefined) readArgs.from = from;\n if (lines !== undefined) readArgs.lines = lines;\n const result = await readMemoryFileBounded(readArgs);\n return JSON.stringify(result);\n },\n };\n}\n\n// ───── helpers ──────────────────────────────────────────────────────────\n\nfunction readString(value: unknown, errorIfMissing?: string, allowUndefined = false): string {\n if (typeof value === \"string\") return value;\n if (allowUndefined && (value === undefined || value === null)) return \"\";\n if (errorIfMissing !== undefined) {\n throw new ConfigurationError(errorIfMissing, { code: \"memory_tool_bad_args\" });\n }\n return \"\";\n}\n\nfunction readNumber(value: unknown): number | undefined {\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n if (typeof value === \"string\" && value.trim().length > 0) {\n const n = Number(value);\n if (Number.isFinite(n)) return n;\n }\n return undefined;\n}\n\nfunction mapCorpusToSources(\n corpus: string,\n): ReadonlyArray<\"memory\" | \"sessions\" | \"wiki\"> | undefined {\n if (corpus === \"\" || corpus === \"all\") return undefined;\n if (corpus === \"memory\") return [\"memory\"];\n if (corpus === \"wiki\") return [\"wiki\"];\n if (corpus === \"sessions\") return [\"sessions\"];\n return undefined;\n}\n\nfunction capByTotalChars(\n hits: ReadonlyArray<MemorySearchHit>,\n maxTotalChars: number,\n): { hits: MemorySearchHit[]; truncated: boolean } {\n if (hits.length === 0) return { hits: [], truncated: false };\n const kept: MemorySearchHit[] = [];\n let runningChars = 0;\n for (const hit of hits) {\n const snippetLen = hit.snippet.length + (hit.citation?.length ?? 0) + 32; // overhead estimate\n if (kept.length > 0 && runningChars + snippetLen > maxTotalChars) {\n return { hits: kept, truncated: true };\n }\n kept.push(hit);\n runningChars += snippetLen;\n }\n return { hits: kept, truncated: false };\n}\n\nfunction isPathInside(root: string, candidate: string): boolean {\n const normalizedRoot = root.endsWith(\"/\") ? root : `${root}/`;\n return candidate === root || candidate.startsWith(normalizedRoot);\n}\n"]}
1
+ {"version":3,"sources":["../src/in-memory-provider.ts","../src/internal/store/markdown-store.ts","../src/internal/active-memory/active-memory.ts","../src/internal/adapter-catalog.ts","../src/internal/memory-types.ts","../src/internal/adapter-http-error.ts","../src/internal/categorized-memory.ts","../src/internal/index/lance-memory-adapter.ts","../src/internal/index/sqlite-vec-loader.ts","../src/internal/tools.ts"],"names":["ceilingReachedError","ConfigurationError","Security","sessionsDir","join","readdir","readFile","resolveMaxFacts","mkdir","replaceFileAtomic","notesDir","resolveMemoryRoot","finalized","persistActiveMemoryTranscript","openAiMemoryEmbeddingProviderAdapter","mistralMemoryEmbeddingProviderAdapter","openRouterMemoryEmbeddingProviderAdapter","voyageMemoryEmbeddingProviderAdapter","deepinfraMemoryEmbeddingProviderAdapter","ollamaMemoryEmbeddingProviderAdapter","azureOpenAiMemoryEmbeddingProviderAdapter","cohereMemoryEmbeddingProviderAdapter","jinaMemoryEmbeddingProviderAdapter","geminiMemoryEmbeddingProviderAdapter","resolvePath","sanitizeIdentifier","safePathJoin","AuthenticationError","RateL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,CAAA;AACnB,EAAA,KAAA,MAAW,OAAO,IAAA,EAAM;AACtB,IAAA,MAAM,aAAa,GAAA,CAAI,OAAA,CAAQ,UAAU,GAAA,CAAI,QAAA,EAAU,UAAU,CAAA,CAAA,GAAK,EAAA;AACtE,IAAA,IAAI,IAAA,CAAK,MAAA,GAAS,CAAA,IAAK,YAAA,GAAe,aAAa,aAAA,EAAe;AAChE,MAAA,OAAO,EAAE,IAAA,EAAM,IAAA,EAAM,SAAA,EAAW,IAAA,EAAK;AAAA,IACvC;AACA,IAAA,IAAA,CAAK,KAAK,GAAG,CAAA;AACb,IAAA,YAAA,IAAgB,UAAA;AAAA,EAClB;AACA,EAAA,OAAO,EAAE,IAAA,EAAM,IAAA,EAAM,SAAA,EAAW,KAAA,EAAM;AACxC;AAEA,SAAS,YAAA,CAAa,MAAc,SAAA,EAA4B;AAC9D,EAAA,MAAM,iBAAiB,IAAA,CAAK,QAAA,CAAS,GAAG,CAAA,GAAI,IAAA,GAAO,GAAG,IAAI,CAAA,CAAA,CAAA;AAC1D,EAAA,OAAO,SAAA,KAAc,IAAA,IAAQ,SAAA,CAAU,UAAA,CAAW,cAAc,CAAA;AAClE","file":"index.cjs","sourcesContent":["/**\n * `createInMemoryMarkdownProvider` — first concrete `MemoryProvider`\n * impl shipped in `@theokit/sdk-memory` (SDK 2.0 Phase 1 / T1.6).\n *\n * Goal: prove the contract works end-to-end with a real (non-no-op)\n * impl WITHOUT pulling LanceDB / embedding / circuit-breaker infrastructure.\n * That richer impl lands in subsequent iters.\n *\n * Semantics:\n * - Stores recalled facts in a per-agent in-process Map.\n * - `runActivePass()` returns the facts plus a `systemPromptAdditions`\n * string that joins fact contents with newlines (so the LLM sees\n * them in the system slot).\n * - `buildTools()` surfaces a `memory_remember(content)` tool the LLM\n * can call to persist a fact mid-conversation.\n * - `recordSessionSummary()` writes a markdown summary to\n * `${cwd}/.theokit/memory/sessions/${runId}.md` (real disk write\n * via `@theokit/sdk/persistence` per ADR-008).\n * - `dispose()` clears the handle's per-agent map (releases memory).\n *\n * @public\n */\n\nimport { mkdir, readdir, readFile } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport type {\n ActiveMemoryPassArgs,\n ActiveMemoryPassResult,\n CustomTool,\n MemoryAdapter,\n MemoryAdapterCapabilities,\n MemoryContext,\n MemoryFact,\n MemoryId,\n MemoryProvider,\n MemoryProviderHandle,\n MemoryProviderInitOptions,\n MemoryTurnMessage,\n RecordSessionSummaryArgs,\n SDKAgent,\n} from \"@theokit/sdk\";\nimport { ConfigurationError, Security } from \"@theokit/sdk\";\nimport { ceilingReachedError, resolveMaxFacts } from \"@theokit/sdk/internal/memory-store\";\nimport { replaceFileAtomic } from \"@theokit/sdk/persistence\";\n\n/** Adapter id prefix — namespaces minted MemoryIds so cross-adapter delete is safe (EC-B). */\nconst ADAPTER_ID = \"in-memory-md\";\n\n/**\n * Options for {@link createInMemoryMarkdownProvider}.\n *\n * @public\n */\nexport interface InMemoryMarkdownProviderOptions {\n /**\n * The most facts one handle may hold. Default: no ceiling.\n *\n * Each handle counts only its own facts, so two agents on one provider each get the full\n * ceiling.\n *\n * At the ceiling a new fact is refused on both write paths: the adapter's `write` rejects with a\n * `ConfigurationError` whose code is `memory_ceiling_reached`, and the `memory_remember` tool\n * replies `{ ok: false, code, error }`. Nothing is stored either way, and `delete(id)` frees a\n * slot. A value that is not a positive integer throws `invalid_memory_ceiling` when the provider\n * is created.\n */\n maxFacts?: number;\n}\n\n/** How the in-memory store tells a caller to make room under its ceiling. */\nconst IN_MEMORY_REMEDY = \"merge or delete facts with the adapter's delete(id), or raise maxFacts\";\n\n/** Per-agent state holder. Stored on the handle via the opaque symbol slot. */\ninterface InMemoryHandleState {\n readonly facts: Map<string, MemoryFact>;\n /** The declared ceiling, validated when the provider was created; absent means none. */\n readonly maxFacts: number | undefined;\n readonly counter: { next: number };\n /**\n * Workspace cwd captured at `init()` time. Used by `runActivePass()`\n * to read previously-written session summaries from disk for recall\n * (iter 34 — closes the \"write but never read\" gap from iter 33).\n */\n readonly cwd: string;\n /**\n * `sessions: true` capability is set when cwd is available (always),\n * so future Stage 3 work can mark this provider as the canonical\n * sessions-recall path (vs. the no-op default).\n */\n}\n\nconst INTERNAL_STATE = Symbol(\"sdk-memory.in-memory.state\");\n\nfunction buildCapabilities(): MemoryAdapterCapabilities {\n return {\n history: false,\n sessions: false,\n tenancy: false,\n reasoning: false,\n toolSchemas: false,\n prefetch: false,\n };\n}\n\n/**\n * Refuse a new fact at the handle's ceiling. Called synchronously right before each `facts.set`,\n * with no `await` between the check and the set, so two racing writes cannot both pass: the event\n * loop runs each synchronous block to completion.\n */\nfunction admitNewFact(state: InMemoryHandleState): void {\n if (state.maxFacts !== undefined && state.facts.size >= state.maxFacts) {\n throw ceilingReachedError(\n \"the in-memory store\",\n state.facts.size,\n state.maxFacts,\n IN_MEMORY_REMEDY,\n );\n }\n}\n\nfunction isCeilingRefusal(cause: unknown): cause is ConfigurationError {\n return cause instanceof ConfigurationError && cause.code === \"memory_ceiling_reached\";\n}\n\nfunction buildAdapter(state: InMemoryHandleState): MemoryAdapter {\n return {\n id: ADAPTER_ID,\n capabilities: buildCapabilities(),\n isAvailable(): boolean {\n return true;\n },\n async write(content: string | MemoryTurnMessage[], _ctx: MemoryContext): Promise<MemoryId> {\n const text = typeof content === \"string\" ? content : content.map((m) => m.content).join(\"\\n\");\n // Iter 43: redact secrets before persisting. Same posture as\n // memory_remember tool handler — secret-containing payloads\n // submitted to MemoryAdapter.write directly should never\n // surface verbatim in subsequent recall.\n const safeText = Security.redact(text);\n admitNewFact(state);\n const id = `${ADAPTER_ID}:${state.counter.next++}` as MemoryId;\n state.facts.set(id, {\n id,\n content: safeText,\n createdAt: new Date().toISOString(),\n });\n return id;\n },\n async recall(_query: string, _ctx: MemoryContext, k?: number): Promise<MemoryFact[]> {\n // Naive recall — return everything (cap at k). Real impls in\n // subsequent iters add semantic similarity via embeddings.\n const all = Array.from(state.facts.values());\n const limit = k !== undefined && k >= 0 ? k : all.length;\n return all.slice(0, limit);\n },\n async delete(id: MemoryId): Promise<void> {\n if (!String(id).startsWith(`${ADAPTER_ID}:`)) {\n throw new Error(\n `MemoryAdapter.delete: id \"${String(id)}\" was not minted by adapter \"${ADAPTER_ID}\"`,\n );\n }\n state.facts.delete(id);\n },\n };\n}\n\n/** Truncate session-summary text fields to bound disk size. */\nconst MAX_SUMMARY_TURN_CHARS = 2000;\n\nfunction truncate(text: string): string {\n if (text.length <= MAX_SUMMARY_TURN_CHARS) return text;\n return `${text.slice(0, MAX_SUMMARY_TURN_CHARS)}…`;\n}\n\n/**\n * Sanitize a runId for use as a filename. Strip path separators +\n * traversal patterns; keep `[a-zA-Z0-9_-]`; cap at 128 chars.\n * Mirrors sdk-core's legacy `writeSessionSummary` sanitizer so the\n * file-path semantics are identical across paths.\n */\nfunction sanitizeRunId(runId: string): string {\n return runId.replace(/[^a-zA-Z0-9_-]/g, \"_\").slice(0, 128);\n}\n\n/** Render the session-summary markdown body. */\nfunction renderSessionSummaryMarkdown(args: RecordSessionSummaryArgs): string {\n const iso = new Date(args.at).toISOString();\n // Iter 42: redact secrets from User + Assistant text via the public\n // `Security.redact()` API (sdk-core's ADR D68 canonical redactor —\n // 12 built-in patterns: OpenAI, Anthropic, GitHub PAT, AWS, etc.).\n // Mirrors sdk-core's legacy writeSessionSummary behavior so the\n // disk artefact never leaks API keys typed by the user.\n const safeUser = Security.redact(truncate(args.userText));\n const safeAssistant = Security.redact(truncate(args.assistantText));\n return [\n \"---\",\n `runId: ${args.runId}`,\n `agentId: ${args.agentId}`,\n `at: ${iso}`,\n `status: ${args.status}`,\n \"---\",\n \"\",\n \"## User\",\n \"\",\n safeUser,\n \"\",\n \"## Assistant\",\n \"\",\n safeAssistant,\n \"\",\n ].join(\"\\n\");\n}\n\n/**\n * Extract `agentId:` value from a session-summary YAML frontmatter.\n * Returns undefined when the file is malformed or has no agentId.\n *\n * The frontmatter shape is:\n * ---\n * runId: ...\n * agentId: ...\n * ...\n * ---\n *\n * Parsing is intentionally simple (regex line-match) — full YAML parse\n * is overkill for the 5-field frontmatter we emit. A malformed file\n * shows up as undefined → falls out of the optional agentId filter.\n */\nfunction extractAgentIdFromFrontmatter(content: string): string | undefined {\n // Match `agentId: <value>` within the leading frontmatter block.\n const match = content.match(/^agentId:\\s*(.+)$/m);\n if (match === null || match[1] === undefined) return undefined;\n return match[1].trim();\n}\n\n/**\n * Read previously-written session summaries from disk + substring-\n * match against the user message. Best-effort: errors degrade to\n * empty recall (no throw — matches the non-throwing-on-hot-path\n * contract).\n *\n * Iter 34: this is the SUBSTRING-match version. Future iters can\n * upgrade to embedding-based semantic similarity (LanceDB ANN)\n * without changing the public surface.\n *\n * Cap: returns at most 5 hits to bound the systemPromptAdditions size.\n */\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: session recall has branching on multiple storage modes\nasync function recallSessionSummaries(\n cwd: string,\n userMessage: string,\n agentIdFilter?: string,\n): Promise<ReadonlyArray<MemoryFact>> {\n const RECALL_CAP = 5;\n const sessionsDir = join(cwd, \".theokit\", \"memory\", \"sessions\");\n let files: string[];\n try {\n files = await readdir(sessionsDir);\n } catch {\n return [];\n }\n const query = userMessage.toLowerCase().trim();\n if (query.length === 0) return [];\n const hits: MemoryFact[] = [];\n for (const file of files) {\n if (!file.endsWith(\".md\")) continue;\n if (hits.length >= RECALL_CAP) break;\n const filePath = join(sessionsDir, file);\n let content: string;\n try {\n content = await readFile(filePath, \"utf-8\");\n } catch {\n continue;\n }\n // Iter 36: agentId scope filter. When set, skip summaries whose\n // frontmatter `agentId:` field doesn't match. Prevents cross-agent\n // data leakage in multi-agent setups.\n if (agentIdFilter !== undefined) {\n const fileAgentId = extractAgentIdFromFrontmatter(content);\n if (fileAgentId !== agentIdFilter) continue;\n }\n if (content.toLowerCase().includes(query)) {\n // Extract a short snippet — the User section (first 200 chars).\n const userIdx = content.indexOf(\"## User\");\n const snippet =\n userIdx >= 0 ? content.slice(userIdx, userIdx + 200).replace(/\\s+/g, \" \") : file;\n const id = `${ADAPTER_ID}:session:${file}` as MemoryId;\n hits.push({\n id,\n content: snippet,\n score: 0.5, // substring-match has no real score; placeholder\n });\n }\n }\n return hits;\n}\n\n/**\n * Build the LLM-facing `memory_search` tool (iter 35). The LLM calls\n * this when the user asks about something it might have learned in a\n * previous session. Queries the disk-backed sessions corpus via the\n * same `recallSessionSummaries` helper used by `runActivePass`.\n */\nfunction buildMemorySearchTool(state: InMemoryHandleState): CustomTool {\n return {\n name: \"memory_search\",\n description:\n \"Search past session summaries for content related to a query. Use when the user asks about something they mentioned in a previous conversation. Returns up to 5 short snippets.\",\n inputSchema: {\n type: \"object\",\n properties: {\n query: {\n type: \"string\",\n description: \"What to search for (a topic, fact, or keyword).\",\n },\n },\n required: [\"query\"],\n additionalProperties: false,\n },\n handler: async (input: Record<string, unknown>): Promise<string> => {\n const query = typeof input.query === \"string\" ? input.query : \"\";\n if (query.length === 0) {\n return JSON.stringify({ ok: false, results: [], error: \"empty query\" });\n }\n const hits = await recallSessionSummaries(state.cwd, query);\n return JSON.stringify({\n ok: true,\n count: hits.length,\n results: hits.map((h) => ({ id: String(h.id), snippet: h.content })),\n });\n },\n };\n}\n\nfunction buildMemoryRememberTool(state: InMemoryHandleState): CustomTool {\n return {\n name: \"memory_remember\",\n description:\n \"Persist a short fact about the user/conversation to memory so it can be recalled in future turns. Pass a single concise sentence as `content`.\",\n inputSchema: {\n type: \"object\",\n properties: {\n content: { type: \"string\", description: \"The fact to remember (one sentence).\" },\n },\n required: [\"content\"],\n additionalProperties: false,\n },\n handler: async (input: Record<string, unknown>): Promise<string> => {\n const content = typeof input.content === \"string\" ? input.content : \"\";\n if (content.length === 0) {\n return JSON.stringify({ ok: false, error: \"empty content\" });\n }\n // Iter 43: redact secrets from the LLM-supplied content BEFORE\n // storing in the Map. The LLM may quote a key from the user\n // verbatim (e.g., \"user said their key is sk-proj-...\"); without\n // this, that secret would persist + leak into systemPromptAdditions\n // on subsequent runActivePass calls. Mirrors the iter 42\n // recordSessionSummary redaction posture.\n const safeContent = Security.redact(content);\n try {\n admitNewFact(state);\n } catch (cause) {\n // Only the ceiling is a reply the model can act on; anything else is a defect and rises.\n if (!isCeilingRefusal(cause)) throw cause;\n return JSON.stringify({ ok: false, code: cause.code, error: cause.message });\n }\n const id = `${ADAPTER_ID}:${state.counter.next++}` as MemoryId;\n state.facts.set(id, {\n id,\n content: safeContent,\n createdAt: new Date().toISOString(),\n });\n return JSON.stringify({ ok: true, id });\n },\n };\n}\n\n/**\n * Build a fresh `MemoryProvider` whose facts live in-process. The\n * returned provider is independent — call `createInMemoryMarkdownProvider()`\n * per agent OR share across agents (each `init()` gets its own state).\n *\n * Iter 33: `recordSessionSummary()` writes session-summary markdown\n * files to disk under `${cwd}/.theokit/memory/sessions/`.\n * Iter 34: `runActivePass()` reads back those summaries + substring-\n * matches against the user message for genuine cross-session recall.\n *\n * Future LanceDB-backed impl will replace the substring match with\n * semantic-similarity ANN over embedding vectors.\n */\nexport function createInMemoryMarkdownProvider(\n options: InMemoryMarkdownProviderOptions = {},\n): MemoryProvider {\n const maxFacts = resolveMaxFacts(options.maxFacts);\n return {\n async init(opts: MemoryProviderInitOptions): Promise<MemoryProviderHandle> {\n const state: InMemoryHandleState = {\n facts: new Map(),\n maxFacts,\n counter: { next: 0 },\n cwd: opts.cwd,\n };\n const adapter = buildAdapter(state);\n return {\n adapter,\n [INTERNAL_STATE]: state,\n };\n },\n buildTools(handle: MemoryProviderHandle, _agent: SDKAgent): ReadonlyArray<CustomTool> {\n const state = handle[INTERNAL_STATE] as InMemoryHandleState | undefined;\n if (state === undefined) return [];\n return [buildMemoryRememberTool(state), buildMemorySearchTool(state)];\n },\n async runActivePass(\n handle: MemoryProviderHandle,\n args: ActiveMemoryPassArgs,\n ): Promise<ActiveMemoryPassResult> {\n const state = handle[INTERNAL_STATE] as InMemoryHandleState | undefined;\n if (state === undefined) return { facts: [] };\n // (1) In-process facts (from memory_remember tool calls this turn).\n const inProcessFacts = Array.from(state.facts.values());\n // (2) Persisted session-summary recall — iter 34. Read previously-\n // written summaries from disk + substring-match against the user\n // message. Best-effort: read errors degrade to empty recall.\n //\n // Iter 36: scope the disk recall to args.agentId so a session\n // summary written by agent-A never bleeds into agent-B's recall.\n // This is the multi-agent privacy invariant.\n const persistedHits = await recallSessionSummaries(state.cwd, args.userMessage, args.agentId);\n const allFacts = [...inProcessFacts, ...persistedHits];\n if (allFacts.length === 0) return { facts: [] };\n const systemPromptAdditions = [\n \"Known facts about the user/session (recall):\",\n ...allFacts.map((f) => `- ${f.content}`),\n ].join(\"\\n\");\n return { facts: allFacts, systemPromptAdditions };\n },\n sync(_handle: MemoryProviderHandle): void {\n // No-op for the in-memory impl — facts are written synchronously to\n // the Map at handler-call time; nothing to re-index post-run. Future\n // LanceDB-backed impl will fire IndexManager.sync() here.\n return;\n },\n async recordSessionSummary(args: RecordSessionSummaryArgs): Promise<void> {\n // Real filesystem write via `@theokit/sdk/persistence`'s\n // `replaceFileAtomic`. ADR-008 sub-path resolution guarantees the\n // same process-level write lock as sdk-core's legacy\n // `writeSessionSummary`. Future LanceDB-backed impl additionally\n // triggers IndexManager re-sync after the write.\n if (args.status !== \"finished\") return;\n const sessionsPath = join(args.cwd, \".theokit\", \"memory\", \"sessions\");\n const filePath = join(sessionsPath, `${sanitizeRunId(args.runId)}.md`);\n await mkdir(sessionsPath, { recursive: true });\n const body = renderSessionSummaryMarkdown(args);\n await replaceFileAtomic(filePath, body);\n },\n dispose(handle: MemoryProviderHandle): void {\n const state = handle[INTERNAL_STATE] as InMemoryHandleState | undefined;\n if (state === undefined) return;\n state.facts.clear();\n },\n };\n}\n","import { readdir } from \"node:fs/promises\";\nimport { join } from \"node:path\";\n\nimport { notesDir, resolveMemoryRoot } from \"@theokit/sdk/internal/memory-store\";\n\n/**\n * Markdown-first memory storage — re-exported from `@theokit/sdk`, not reimplemented here.\n *\n * This file used to be a full copy (iter 56, Stage 3 source-move #13). The copy went stale: `#389`\n * moved the layout from bullets under `MEMORY.md ## Facts` to a file per memory, and the\n * Claude Code compatibility work added two more read roots — both landed in the SDK's copy and\n * neither in this one. Because `Memory.runDreamingSweep` routes through this package whenever it is\n * installed, **the copy that ran was not the copy anyone had updated**: installing\n * `@theokit/sdk-memory` made every memory the SDK had written unreadable, reported as\n * `factsBefore: 0` — a number that reads exactly like an empty store (#430).\n *\n * theokit#160 fixed the identical shape for the embedding runtime, in this same package pair, by\n * importing one implementation instead of syncing two. Same remedy here. Re-syncing the copy would\n * have fixed today's divergence and left tomorrow's free to happen.\n *\n * The re-exported signatures are supersets of what this package used to expose — the added\n * parameters are optional — so nothing that called them before has to change.\n *\n * @internal\n */\nexport {\n appendFact,\n appendFactToMarkdown,\n asMemoryRoot,\n ceilingReachedError,\n claudeProjectMemoryDir,\n collectMarkdownFiles,\n type DiscoveredFile,\n defaultIndexPath,\n type FactEntryInfo,\n factsBlockRange,\n indexBudgetWarning,\n lanceStoragePath,\n listFactEntries,\n MEMORY_INDEX_MAX_BYTES,\n MEMORY_INDEX_MAX_LINES,\n type MemoryLocationConfig,\n type MemoryRoot,\n memoryIndexRoot,\n memoryMdPath,\n memoryReadRoots,\n notesDir,\n projectMemoryDir,\n readAllSqliteFacts,\n readFacts,\n readFactsFromMarkdown,\n readLegacyEntriesIn,\n readMemoryEntriesIn,\n removeFactEntry,\n resolveMaxFacts,\n resolveMemoryRoot,\n type SqliteFactRow,\n unlessMissing,\n} from \"@theokit/sdk/internal/memory-store\";\n\n/** One note discovered under `notes/`: its file name without the `.md` suffix, and its absolute path. */\nexport interface NoteFile {\n slug: string;\n path: string;\n}\n\n/**\n * List the `.md` files directly under `notes/`. Returns `[]` when the directory does not exist, so\n * a workspace that has never written a note is not an error. Does not recurse into sub-directories.\n *\n * Stays here rather than moving to the shared store: notes are this package's concept, and only\n * this package reads them.\n */\nexport async function listNotes(cwd: string): Promise<NoteFile[]> {\n let entries: string[] = [];\n try {\n entries = await readdir(notesDir(resolveMemoryRoot(cwd)));\n } catch {\n return [];\n }\n return entries\n .filter((name) => name.endsWith(\".md\"))\n .map((name) => ({\n slug: name.replace(/\\.md$/, \"\"),\n path: join(notesDir(resolveMemoryRoot(cwd)), name),\n }));\n}\n","/**\n * Active Memory blocking recall (ADR D6 of memory-system-peer-project-parity).\n *\n * Runs BEFORE `agent.send()` assembles the system prompt. Issues a direct\n * call to `IndexManager.search` with the user message (and optional recent\n * turns per `queryMode`).\n *\n * Returns a `summary` string capped at `maxSummaryChars` (default 220 to\n * match peer-project's `DEFAULT_MAX_SUMMARY_CHARS`) which the system-prompt\n * pipeline prepends as a `<active-memory>` block (priority 5).\n *\n * Iter 75 (Stage 3 source-move #38, FINAL move): hybrid copy from\n * sdk-core's `internal/memory/active-memory.ts`. sdk-core retains its\n * copy as the v1.x runtime that `Memory` class delegates to;\n * sdk-memory ships the canonical copy that future Stage 4 port-based\n * composition will consume.\n *\n * **CLOSES the Stage 3 source-move stage in sdk-memory.** Every\n * memory-related concept under sdk-core's internal/memory/ is now\n * canonical in @theokit/sdk-memory (38 source files moved across\n * iter 44-75; 2 inlined adapters added: adapter-http-error iter 73\n * + adapter-catalog renamed iter 74).\n *\n * **Cross-package telemetry contract:** `OTelSpan` and `TelemetryHandle`\n * are now imported from `@theokit/sdk`, which exports them since #295.\n * This file previously inlined structural mirrors of both, with a note\n * that they MUST be replaced once sdk-core made them public — and by\n * the time anyone looked, the mirrors had drifted: they narrowed\n * `setAttributes` to reject the `undefined` values the canonical type\n * accepts, and declared `end()` without its `endTime` parameter. That\n * is how a structural mirror fails: quietly, with both sides compiling.\n *\n * The 2 constant strings (`memory.recall` span name +\n * `theokit_memory_recall_duration_ms` histogram name) are still inlined\n * below, because sdk-core's `span-names.ts` remains private. They are\n * values rather than types, so exporting them is a separate decision\n * with a real bundle cost — unlike these two, which erase at build time.\n *\n * @internal\n */\n\nimport type { OTelSpan, TelemetryHandle } from \"@theokit/sdk\";\n\nimport type { CircuitBreaker } from \"@theokit/sdk/retry\";\nimport type { MemorySearchHit } from \"../index/index-manager-contract.js\";\nimport type { MemoryIndex } from \"../index/memory-index.js\";\nimport { resolveMemoryRoot } from \"../store/markdown-store.js\";\nimport { persistActiveMemoryTranscript } from \"../store/transcript-store.js\";\nimport type { ActiveMemoryCache, TenantContext } from \"./active-memory-cache.js\";\n// T4.1 / D438 — `ActiveMemoryResult` and its helpers moved to `./active-memory-types.ts`\n// so `./active-memory-cache.ts` can reach them without cycling back here (cycle #10).\n// Re-exported below for back-compat with in-tree consumers.\nimport type {\n ActiveMemoryQueryMode,\n ActiveMemoryResult,\n ActiveMemoryStatus,\n} from \"./active-memory-types.js\";\n\nexport type { ActiveMemoryQueryMode, ActiveMemoryResult, ActiveMemoryStatus };\n\n// Iter 75 inlined constants — sdk-core's telemetry/span-names.ts is\n// not public. These two are the only ones this file uses.\nconst SPAN_MEMORY_RECALL = \"memory.recall\";\nconst HISTOGRAM_MEMORY_RECALL_DURATION_MS = \"theokit_memory_recall_duration_ms\";\n\n// #295 — the canonical types, not a copy of them.\n//\n// Iter 75 inlined structural mirrors here because sdk-core's telemetry/tracer.ts\n// was not public, with a note that they MUST be replaced once it was. They had\n// already drifted by the time anyone checked: the mirror narrowed `setAttributes`\n// to reject the `undefined` values the canonical type accepts, and declared\n// `end()` without the `endTime` parameter. Neither broke a build — a structural\n// mirror fails by being quietly wrong, not by being loudly missing.\n//\n// `@theokit/sdk` is already a peerDependency of this package, and both types are\n// erased at build time, so this costs nothing at runtime.\n\n/**\n * Tuning for one recall attempt. Recall is off unless `enabled` is exactly\n * `true`, so an options object that omits it disables recall rather than\n * enabling it with defaults.\n */\nexport interface ActiveMemoryOptions {\n /** Whether active recall is enabled. Default `false`. */\n enabled?: boolean;\n /** Query construction strategy. Default `\"recent\"`. */\n queryMode?: ActiveMemoryQueryMode;\n /** Hard timeout in ms. Default `15000`. */\n timeoutMs?: number;\n /** Max chars in the summary. Default `220`. */\n maxSummaryChars?: number;\n /** Number of recent user turns to include in `queryMode === \"recent\"`. Default `2`. */\n recentUserTurns?: number;\n}\n\n/**\n * Everything {@link runActiveMemory} needs for one attempt. Only `userText`,\n * `priorMessages`, `index` and `options` are required; the rest add breaker,\n * cache, transcript persistence and telemetry, each of which is inert when\n * omitted.\n *\n * `index` is accepted as `undefined` on purpose — an agent with memory\n * configured but no index open is a normal state, and it produces a `skipped`\n * result rather than an error.\n */\nexport interface RunActiveMemoryArgs {\n userText: string;\n priorMessages: ReadonlyArray<{ role: \"user\" | \"assistant\"; text: string }>;\n index: MemoryIndex | undefined;\n options: ActiveMemoryOptions;\n /** Per-agent circuit breaker (Phase 8). */\n breaker?: CircuitBreaker;\n /** Per-agent result cache (Phase 8). */\n cache?: ActiveMemoryCache;\n /** Workspace root for transcript persistence. */\n cwd?: string;\n /** When true, write transcript JSON under .theokit/memory/transcripts/active-memory/. */\n persistTranscripts?: boolean;\n /** Stable key the breaker + cache key by (default `default`). */\n agentKey?: string;\n /** Run id for transcript file naming. */\n runId?: string;\n /**\n * T0.1 — optional telemetry handle. When provided AND telemetry is enabled,\n * `memory.recall` span is emitted with `{ userId, namespace, scope, queryMode,\n * hits, status }` attrs and `theokit_memory_recall_duration_ms` histogram is\n * recorded with the same dimension keys.\n */\n telemetry?: TelemetryHandle;\n /** User id surfaced as a memory.recall span attr for cross-tenant tracing. */\n userId?: string;\n /** Memory namespace (e.g. `default`, `<orgId>`) for span/histogram dimensions. */\n namespace?: string;\n /** Memory scope (`session` / `user` / `global`) for span/histogram dimensions. */\n scope?: string;\n}\n\nconst DEFAULTS: Required<Omit<ActiveMemoryOptions, \"enabled\">> = {\n queryMode: \"recent\",\n timeoutMs: 15000,\n maxSummaryChars: 220,\n recentUserTurns: 2,\n};\n\n/**\n * Run one blocking recall before the system prompt is assembled, and report what\n * happened. Never throws for a recall failure: a search that times out or\n * rejects comes back as a `timeout` or `error` status with no summary, and the\n * agent run continues without memory.\n *\n * The order of the short-circuits decides what a caller sees. Recall disabled or\n * no index gives `skipped` with no search. An open circuit breaker gives\n * `skipped` too. A cache hit returns the earlier result as-is, which means it\n * also returns that result's `status` and `durationMs` — a cached `no-recall`\n * looks exactly like a fresh one. An empty query gives `no-recall`.\n *\n * Only a real search reaches the breaker: `timeout` records a timeout, `ok` and\n * `no-recall` record a success, and `error` records neither, so a provider that\n * keeps throwing will not trip the breaker.\n *\n * `timeoutMs` bounds how long this waits, not how long the search runs — the\n * underlying `index.search` is left running when the timer wins. The search asks\n * the index for at most 5 hits regardless of options.\n *\n * Cache entries are keyed by tenant as well as by query text, so two callers\n * with the same question and different `userId` / `namespace` / `scope` never\n * share an entry.\n */\nexport async function runActiveMemory(args: RunActiveMemoryArgs): Promise<ActiveMemoryResult> {\n const started = Date.now();\n // T0.1 — `memory.recall` span emitted around the entire body so skipped /\n // cached / no-recall paths still surface in telemetry with the correct status.\n const span = startMemoryRecallSpan(args);\n try {\n if (args.options.enabled !== true || args.index === undefined) {\n return endRecallSpan(span, args, {\n summary: undefined,\n durationMs: 0,\n status: \"skipped\",\n hits: [],\n });\n }\n const cfg = { ...DEFAULTS, ...args.options };\n const breakerKey = args.agentKey ?? \"default\";\n if (args.breaker?.shouldSkip(breakerKey) === true) {\n return endRecallSpan(span, args, {\n summary: undefined,\n durationMs: 0,\n status: \"skipped\",\n hits: [],\n });\n }\n // #56 (GAP-B) — key the cache read by tenant identity so two callers with\n // the same query text but different identity never share a cache entry.\n const tenantCtx: TenantContext = {\n namespace: args.namespace,\n userId: args.userId,\n scope: args.scope,\n };\n const cached = args.cache?.get(args.userText, cfg.queryMode, tenantCtx);\n if (cached !== undefined) return endRecallSpan(span, args, cached);\n\n const query = buildQuery(args.userText, args.priorMessages, cfg.queryMode, cfg.recentUserTurns);\n if (query.trim().length === 0) {\n const finalized = await finalize(args, cfg.queryMode, {\n summary: undefined,\n durationMs: Date.now() - started,\n status: \"no-recall\",\n hits: [],\n });\n return endRecallSpan(span, args, finalized);\n }\n const result = await searchOnce(args, cfg, query, started);\n notifyBreaker(args.breaker, breakerKey, result.status);\n const finalized = await finalize(args, cfg.queryMode, result);\n return endRecallSpan(span, args, finalized);\n } catch (cause) {\n span.recordException(cause);\n span.setStatus({ code: 2, message: cause instanceof Error ? cause.message : String(cause) });\n span.end();\n throw cause;\n }\n}\n\nfunction startMemoryRecallSpan(args: RunActiveMemoryArgs): OTelSpan {\n const telemetry: TelemetryHandle | undefined = args.telemetry;\n if (telemetry === undefined) {\n // No-op span identical to the runtime no-op when telemetry is disabled.\n return {\n setAttribute: () => {},\n setAttributes: () => {},\n addEvent: () => {},\n setStatus: () => {},\n recordException: () => {},\n end: () => {},\n spanContext: () => ({ traceId: \"0\".repeat(32), spanId: \"0\".repeat(16) }),\n isRecording: () => false,\n };\n }\n return telemetry.startSpan(SPAN_MEMORY_RECALL, {\n queryMode: args.options.queryMode ?? \"recent\",\n ...(args.userId !== undefined ? { userId: args.userId } : {}),\n ...(args.namespace !== undefined ? { namespace: args.namespace } : {}),\n ...(args.scope !== undefined ? { scope: args.scope } : {}),\n });\n}\n\nfunction endRecallSpan(\n span: OTelSpan,\n args: RunActiveMemoryArgs,\n result: ActiveMemoryResult,\n): ActiveMemoryResult {\n span.setAttributes({\n hits: result.hits.length,\n status: result.status,\n durationMs: result.durationMs,\n });\n span.end();\n args.telemetry?.recordHistogram(HISTOGRAM_MEMORY_RECALL_DURATION_MS, result.durationMs, {\n status: result.status,\n ...(args.userId !== undefined ? { userId: args.userId } : {}),\n ...(args.namespace !== undefined ? { namespace: args.namespace } : {}),\n ...(args.scope !== undefined ? { scope: args.scope } : {}),\n });\n return result;\n}\n\ninterface ResolvedConfig {\n queryMode: ActiveMemoryQueryMode;\n timeoutMs: number;\n maxSummaryChars: number;\n recentUserTurns: number;\n}\n\nasync function searchOnce(\n args: RunActiveMemoryArgs,\n cfg: ResolvedConfig,\n query: string,\n started: number,\n): Promise<ActiveMemoryResult> {\n if (args.index === undefined) {\n return { summary: undefined, durationMs: 0, status: \"skipped\", hits: [] };\n }\n try {\n const hits = await withTimeout(args.index.search(query, { maxResults: 5 }), cfg.timeoutMs);\n if (hits === \"timeout\") {\n return { summary: undefined, durationMs: Date.now() - started, status: \"timeout\", hits: [] };\n }\n if (hits.length === 0) {\n return {\n summary: undefined,\n durationMs: Date.now() - started,\n status: \"no-recall\",\n hits: [],\n };\n }\n const summary = formatSummary(hits, cfg.maxSummaryChars);\n return { summary, durationMs: Date.now() - started, status: \"ok\", hits };\n } catch (cause) {\n const message = cause instanceof Error ? cause.message : String(cause);\n process.stderr.write(`[theokit-sdk] active-memory recall failed: ${message}\\n`);\n return { summary: undefined, durationMs: Date.now() - started, status: \"error\", hits: [] };\n }\n}\n\nfunction notifyBreaker(\n breaker: CircuitBreaker | undefined,\n key: string,\n status: ActiveMemoryStatus,\n): void {\n if (breaker === undefined) return;\n if (status === \"timeout\") breaker.recordTimeout(key);\n else if (status === \"ok\" || status === \"no-recall\") breaker.recordSuccess(key);\n}\n\nasync function finalize(\n args: RunActiveMemoryArgs,\n queryMode: ActiveMemoryQueryMode,\n result: ActiveMemoryResult,\n): Promise<ActiveMemoryResult> {\n // #56 (GAP-B) — key the cache write by tenant identity (mirrors the get side).\n const tenantCtx: TenantContext = {\n namespace: args.namespace,\n userId: args.userId,\n scope: args.scope,\n };\n args.cache?.set(args.userText, queryMode, result, tenantCtx);\n if (args.persistTranscripts === true && args.cwd !== undefined) {\n await persistActiveMemoryTranscript(resolveMemoryRoot(args.cwd), {\n runId: args.runId ?? `run-${Date.now()}`,\n startedAtMs: Date.now() - result.durationMs,\n userText: args.userText,\n queryMode,\n status: result.status,\n durationMs: result.durationMs,\n summary: result.summary,\n hits: result.hits.map((h) => ({\n path: h.path,\n startLine: h.startLine,\n endLine: h.endLine,\n score: h.score,\n snippet: h.snippet,\n })),\n });\n }\n return result;\n}\n\nfunction buildQuery(\n userText: string,\n priorMessages: ReadonlyArray<{ role: \"user\" | \"assistant\"; text: string }>,\n queryMode: ActiveMemoryQueryMode,\n recentUserTurns: number,\n): string {\n if (queryMode === \"message\") return userText;\n if (queryMode === \"full\") {\n const allUserTurns = priorMessages.filter((m) => m.role === \"user\").map((m) => m.text);\n return [...allUserTurns, userText].join(\"\\n\");\n }\n // recent\n const recent = priorMessages\n .filter((m) => m.role === \"user\")\n .slice(-recentUserTurns)\n .map((m) => m.text);\n return [...recent, userText].join(\"\\n\");\n}\n\nfunction formatSummary(hits: ReadonlyArray<MemorySearchHit>, maxChars: number): string {\n const lines = hits.map((h) => `- ${h.citation}: ${h.snippet}`);\n let summary = lines.join(\"\\n\");\n if (summary.length > maxChars) summary = `${summary.slice(0, maxChars - 1)}…`;\n return summary;\n}\n\nasync function withTimeout<T>(promise: Promise<T>, timeoutMs: number): Promise<T | \"timeout\"> {\n let timer: NodeJS.Timeout | undefined;\n const timeout = new Promise<\"timeout\">((resolve) => {\n timer = setTimeout(() => resolve(\"timeout\"), timeoutMs);\n });\n try {\n const winner = await Promise.race([promise, timeout]);\n return winner;\n } finally {\n if (timer !== undefined) clearTimeout(timer);\n }\n}\n","import { azureOpenAiMemoryEmbeddingProviderAdapter } from \"./embedding/azure-openai-embedding.js\";\nimport { cohereMemoryEmbeddingProviderAdapter } from \"./embedding/cohere-embedding.js\";\nimport { deepinfraMemoryEmbeddingProviderAdapter } from \"./embedding/deepinfra-embedding.js\";\nimport type { MemoryEmbeddingProviderAdapter } from \"./embedding/embedding-adapter.js\";\nimport { geminiMemoryEmbeddingProviderAdapter } from \"./embedding/gemini-embedding.js\";\nimport { jinaMemoryEmbeddingProviderAdapter } from \"./embedding/jina-embedding.js\";\nimport { mistralMemoryEmbeddingProviderAdapter } from \"./embedding/mistral-embedding.js\";\nimport { ollamaMemoryEmbeddingProviderAdapter } from \"./embedding/ollama-embedding.js\";\nimport { openAiMemoryEmbeddingProviderAdapter } from \"./embedding/openai-embedding.js\";\nimport { openRouterMemoryEmbeddingProviderAdapter } from \"./embedding/openrouter-embedding.js\";\nimport { voyageMemoryEmbeddingProviderAdapter } from \"./embedding/voyage-embedding.js\";\n\n// Iter 74 rollup-plugin-dts workaround: see openai-embedding.ts header.\n// Catalog value type is inferred from the literal record; canonical\n// assignability is checked at consumer call sites that destructure into\n// the canonical `MemoryEmbeddingProviderAdapter` shape.\n\n/**\n * Memory embedding adapter catalog, indexed by provider id.\n *\n * Only adapters with full, tested implementations are exposed. The\n * `openrouter` provider proxies through OpenRouter to whichever embedding\n * model the caller selects via `model` (e.g.\n * `\"openai/text-embedding-3-small\"`, `\"mistralai/mistral-embed\"`).\n *\n * Locked by ADR D11: `openai`, `mistral`, `openrouter`, `voyage`, `deepinfra`\n * ship in v1.0. ADR D183: `ollama` added — first `transport: \"local\"`\n * adapter, enables 100%-local RAG (no remote API key needed).\n * `lmstudio`, `google`, `bedrock` are deferred to v1.1.\n *\n * Iter 74 (Stage 3 source-move #37): hybrid copy from sdk-core's\n * `internal/memory/adapters/catalog.ts`. Filename renamed to\n * `adapter-catalog.ts` in sdk-memory to disambiguate from the broader\n * \"catalog\" notion at the package barrel level.\n *\n * **This catalog must serve every provider sdk-core ADVERTISES** (theokit#128). When the peer is\n * installed it REPLACES core's catalog in the routing path (`sdk/src/memory.ts`), while the public\n * `Theokit.inspect.embeddingAdapters()` keeps listing core's — so any id core has and this one\n * lacks is a provider the SDK promises and then rejects. That is what happened to `azure-openai`,\n * `cohere`, `jina` and `gemini` for the two months between core's T4.10 and the parity fix.\n * The invariant is enforced by `@theokit/sdk-peer-integration-tests` (`peer-parity.test.ts`).\n *\n * **CLOSES the embedding-adapter cluster in sdk-memory.** The provider adapters + the shared\n * OpenAI-compatible runtime + the inlined HTTP error mapper are canonical here:\n * - iter 45: embedding-adapter (types)\n * - iter 46: embedding-cache (LRU) — REMOVED by theokit#160: the shared runtime owns caching now\n * - iter 73: openai-compatible (shared factory) + adapter-http-error\n * (inlined mapper)\n * - iter 74: openai-embedding + mistral-embedding + deepinfra-embedding\n * + voyage-embedding + openrouter-embedding + ollama-embedding +\n * adapter-catalog (THIS)\n * - theokit#128: azure-openai + cohere + jina + gemini (parity with core's T4.10)\n *\n * @internal\n */\nexport const MEMORY_EMBEDDING_ADAPTERS: {\n readonly [K in\n | \"openai\"\n | \"mistral\"\n | \"openrouter\"\n | \"voyage\"\n | \"deepinfra\"\n | \"ollama\"\n | \"azure-openai\"\n | \"cohere\"\n | \"jina\"\n | \"gemini\"]: MemoryEmbeddingProviderAdapter;\n} = {\n openai: openAiMemoryEmbeddingProviderAdapter,\n mistral: mistralMemoryEmbeddingProviderAdapter,\n openrouter: openRouterMemoryEmbeddingProviderAdapter,\n voyage: voyageMemoryEmbeddingProviderAdapter,\n deepinfra: deepinfraMemoryEmbeddingProviderAdapter,\n ollama: ollamaMemoryEmbeddingProviderAdapter,\n // theokit#128 — mirrors sdk-core's T4.10 additions, which the peer had drifted behind.\n \"azure-openai\": azureOpenAiMemoryEmbeddingProviderAdapter,\n cohere: cohereMemoryEmbeddingProviderAdapter,\n jina: jinaMemoryEmbeddingProviderAdapter,\n gemini: geminiMemoryEmbeddingProviderAdapter,\n};\n","/**\n * Public memory types (used by runtime + storage + migration + future index).\n *\n * Leaf module — depends only on `node:path` + the public\n * `@theokit/sdk/path-safety` re-exports (`safePathJoin`,\n * `sanitizeIdentifier`) + `@theokit/sdk`'s `Security` for the\n * canonical `redactSecrets` 12-pattern list (ADR D68).\n *\n * Iter 52 (Stage 3 source-move #9): hybrid copy from sdk-core's\n * `internal/memory/types.ts`. sdk-core retains its copy for v1.x\n * back-compat; sdk-memory ships the canonical copy that future\n * `storage/*`, `migration`, and `tools` moves will target as siblings.\n *\n * **Sub-path-import contract:** sdk-core copy imports\n * `safePathJoin`/`sanitizeIdentifier` from `../security/path-guard.js`\n * (internal path); sdk-memory copy imports them from\n * `@theokit/sdk/path-safety` (public sub-path stable per this\n * iter — sanitizeIdentifier was promoted to the public surface to\n * unblock this move). Same runtime, same grammar.\n *\n * @internal\n */\nimport { resolve as resolvePath } from \"node:path\";\n\nimport { Security } from \"@theokit/sdk\";\nimport { safePathJoin, sanitizeIdentifier } from \"@theokit/sdk/path-safety\";\n\n/**\n * Per-agent memory configuration. `enabled` gates the configuration-aware\n * accessors (`readFacts`, `appendFact`) — with it `false` they resolve without\n * touching disk, while the lower-level markdown functions ignore it.\n *\n * `namespace`, `scope` and `userId` are only consulted for the legacy JSON path\n * (see {@link legacyMemoryJsonPath}); the markdown store keeps one `MEMORY.md`\n * per workspace and does not partition by them. They are treated as\n * user-supplied and sanitised before they reach a path. `storePath` is treated\n * as trusted and resolved as given.\n */\nexport interface MemoryConfig {\n enabled: boolean;\n namespace?: string;\n userId?: string;\n scope?: \"agent\" | \"user\" | \"team\";\n storePath?: string;\n}\n\n/**\n * One remembered statement. `text` is what gets written, embedded and searched;\n * it passes through secret redaction on the way to disk, so what is stored may\n * differ from what was passed in.\n */\nexport interface MemoryFact {\n text: string;\n /**\n * Optional taxonomy bucket (M4-3). Backward-compatible — flat-store facts\n * omit it; the categorized store (`createCategorizedMemory`) always sets it.\n */\n category?: string;\n}\n\n/**\n * Canonical credential-redaction primitive (ADR D68).\n *\n * sdk-core's copy re-exports `redactSecrets` directly from\n * `../security/index.js` (internal path). sdk-core's PUBLIC surface\n * (`@theokit/sdk`) doesn't expose a bare `redactSecrets` symbol —\n * it ships `Security.redact()` instead (T2.1, by design — the\n * namespace also carries `Security.addPattern()`). sdk-memory's\n * canonical `redactSecrets` re-export wraps `Security.redact` 1-to-1\n * so consumers continue to see the same symbol name without sdk-memory\n * having to import sdk-core's internal subpath. Same 12-pattern\n * list, same two-bucket mask shape, same disable-via-env behavior.\n */\nexport function redactSecrets(text: unknown, opts?: { codeFile?: boolean }): string {\n return Security.redact(text, opts);\n}\n\n/**\n * Resolve the legacy JSON memory path used pre-ADR-D8 (kept for migration\n * helpers + tests). Centralized here so `migration.ts` and the legacy-aware\n * `runtime/memory-store.ts` don't duplicate the path logic (jscpd cleanup).\n */\nexport function legacyMemoryJsonPath(cwd: string, config: MemoryConfig): string {\n // ADRs D79-D81: storePath is programmatic (trusted); namespace/scope/userId\n // are user-shaped and pass sanitizeIdentifier. EC-7 (edge-case review):\n // realistic userIds (UUIDs, hash IDs, \"default\") pass; \"user@example.com\"\n // and similar need to be normalized by the caller before passing.\n if (config.storePath !== undefined) {\n return resolvePath(cwd, config.storePath);\n }\n const namespace = sanitizeIdentifier(config.namespace ?? \"default\");\n const scope = sanitizeIdentifier(config.scope ?? \"agent\", { maxLen: 16 });\n const userId = sanitizeIdentifier(config.userId ?? \"default\");\n return safePathJoin(cwd, \".theokit\", \"memory\", namespace, `${scope}-${userId}.json`);\n}\n\n/**\n * A semantically meaningful slice of a markdown memory file, produced by\n * `chunkMarkdown`. Each chunk carries stable line numbers + a content hash\n * used downstream by the embedding cache.\n *\n * Mirrors peer-project's `MemoryChunk` shape\n * (`reference/peer-project/packages/memory-host-sdk/src/host/engine-storage.ts`).\n *\n * @internal\n */\nexport interface MemoryChunk {\n /** 1-indexed starting line in the source file. */\n startLine: number;\n /** 1-indexed ending line (inclusive). */\n endLine: number;\n /** Slice of markdown source text. */\n text: string;\n /** sha256 of `text`; stable across runs for identical inputs. */\n hash: string;\n /** Optional nearest heading text (without the `#` markers). */\n heading?: string;\n}\n\n/**\n * Result of `reader.readFile`. Contains the bounded slice plus truncation\n * + provenance info.\n *\n * Mirrors peer-project's `MemoryReadResult` shape.\n *\n * @internal\n */\nexport interface MemoryReadResult {\n path: string;\n /** Requested starting line (1-indexed, defaults to 1). */\n from: number;\n /** Number of lines actually returned (may be less than `lines` near EOF). */\n linesReturned: number;\n /** Total lines in the file (after the read). */\n totalLines: number;\n /** True when content remains after the returned slice, i.e. `remainingLines > 0`. */\n truncated: boolean;\n /** Lines past the returned slice that remain in the file. */\n remainingLines: number;\n /** Slice text (joined with `\\n`). */\n text: string;\n}\n\n/**\n * Lightweight reference to a markdown file in the memory corpus.\n *\n * Mirrors peer-project's `MemoryFileEntry`.\n *\n * @internal\n */\nexport interface MemoryFileEntry {\n /** Absolute path on disk. */\n path: string;\n /** Path relative to the memory root (e.g. \"MEMORY.md\", \"notes/foo.md\"). */\n relPath: string;\n /** ms-since-epoch mtime. */\n mtime: number;\n /** sha256 of the file content; recomputed on each read. */\n hash: string;\n}\n","/**\n * OpenAI-compatible HTTP error mapper (ADR D67) — sdk-memory inlined copy.\n *\n * Translates OpenAI-shaped API error responses (covers OpenAI, OpenRouter,\n * DeepSeek, Together, Mistral, Voyage, DeepInfra, etc.) into typed\n * `TheokitAgentError` subclasses with full `ErrorMetadata`.\n *\n * Body inspection: looks at `body.error.code` / `body.error.type` to detect\n * `context_too_long`, `content_filtered`, `model_unavailable` semantics.\n * Falls back to status-based mapping when body doesn't expose `.error`\n * (e.g., HTML server error page, DeepInfra's `{message: \"...\"}` shape).\n *\n * Never throws — caller is already in an error path.\n *\n * Iter 73 (Stage 3 source-move #30): inlined adaptation of sdk-core's\n * `internal/errors/mappers/openai-compatible.ts` + `shared.ts`. sdk-core's\n * mapper is internal — not part of the public errors surface — so sdk-memory\n * carries its own minimal copy here. Behavior MUST stay byte-equivalent\n * with sdk-core's so consumers consuming hits via either package surface\n * see identical error shape.\n *\n * The 4 helpers (`parseRetryAfter`, `truncateRaw`, `buildErrorMetadata`,\n * `mapOpenAICompatibleError`) are intentionally co-located in this single\n * file so all 8 embedding adapter moves (catalog + 7 providers) share one\n * import target.\n *\n * @internal\n */\n\nimport {\n AuthenticationError,\n ConfigurationError,\n type ErrorCode,\n type ErrorMetadata,\n NetworkError,\n RateLimitError,\n type TheokitAgentError,\n UnknownAgentError,\n} from \"@theokit/sdk/errors\";\n\nimport { redactSecrets } from \"./memory-types.js\";\n\nconst RAW_MAX_BYTES = 2048;\nconst PROVIDER_DETAIL_MAX_CHARS = 512;\n// OpenRouter answers a model it does not serve with HTTP 404 and a numeric `error.code`,\n// so only the message tells it apart from a 404 for a wrong path.\nconst MISSING_MODEL_MESSAGE = /no endpoints found/i;\n\n/**\n * Parse `retry-after` header in numeric-seconds form. HTTP-date form\n * (RFC 7231) returns `undefined` to avoid NaN propagation downstream.\n */\nexport function parseRetryAfter(headers: Headers | undefined): number | undefined {\n if (headers === undefined) return undefined;\n const raw = headers.get(\"retry-after\");\n if (raw === null) return undefined;\n const n = Number(raw);\n if (Number.isFinite(n) && n >= 0) return Math.ceil(n);\n return undefined;\n}\n\n/**\n * Truncate raw response body to ~2KB and redact known credential\n * patterns so it can ride inside `ErrorMetadata.raw` without\n * ballooning logs OR leaking tokens. Returns `undefined` for\n * null/undefined input.\n */\nexport function truncateRaw(body: unknown): unknown {\n if (body === null || body === undefined) return undefined;\n const s = typeof body === \"string\" ? body : JSON.stringify(body);\n // Redact before the cut so a key straddling the limit cannot slip past the patterns.\n const redacted = redactSecrets(s);\n return redacted.length <= RAW_MAX_BYTES ? redacted : `${redacted.slice(0, RAW_MAX_BYTES)}…`;\n}\n\n/**\n * Build an `ErrorMetadata` object with all optional fields included\n * conditionally (no `undefined` keys in the output).\n */\nexport function buildErrorMetadata(args: {\n provider: string;\n endpoint: string;\n code: ErrorCode;\n status: number;\n headers: Headers | undefined;\n body: unknown;\n}): ErrorMetadata {\n const retryAfter = parseRetryAfter(args.headers);\n const raw = truncateRaw(args.body);\n return {\n provider: args.provider,\n endpoint: args.endpoint,\n code: args.code,\n statusCode: args.status,\n ...(retryAfter !== undefined ? { retryAfter } : {}),\n ...(raw !== undefined ? { raw } : {}),\n };\n}\n\ninterface MapOpenAiErrorArgs {\n providerId: string;\n status: number;\n body: unknown;\n headers: Headers | undefined;\n endpoint: string;\n}\n\n/**\n * Turn a failed OpenAI-shaped HTTP response into the typed error the SDK throws.\n * Builds the error, it does not throw it.\n *\n * The HTTP status picks the class: 401 and 403 give an `AuthenticationError`,\n * 429 a `RateLimitError`, 400 a `ConfigurationError`, 408 and 5xx a\n * `NetworkError`, and anything else an `UnknownAgentError`.\n *\n * The `code` on the metadata is finer than the class and is read from\n * `body.error.code` (or `.type`) first, so a 400 that names a context-window\n * problem carries `context_too_long` rather than `invalid_request`. A body code\n * naming an exhausted quota, and HTTP 402, both map to `quota_exceeded` — note\n * that a 402 keeps that code while still producing an `UnknownAgentError`,\n * because no status branch claims it.\n *\n * The raw body rides along on the metadata, truncated to about 2KB and passed\n * through secret redaction, so it is safe to log.\n */\nexport function mapOpenAICompatibleError(args: MapOpenAiErrorArgs): TheokitAgentError {\n const { providerId, status, body, headers, endpoint } = args;\n const code = mapOpenAiStatusToCode(status, body);\n const message = formatMessage(providerId, status, code);\n const metadata = buildErrorMetadata({\n provider: providerId,\n endpoint,\n code,\n status,\n headers,\n body,\n });\n\n if (status === 401 || status === 403) {\n return new AuthenticationError(message, { code: `${providerId}_auth_failed`, metadata });\n }\n if (status === 429) {\n return new RateLimitError(message, { code: `${providerId}_rate_limit`, metadata });\n }\n if (status === 404 && code === \"model_unavailable\") {\n // The model id lives only in the provider's text, so this case carries it.\n const detailed = formatMessage(providerId, status, code, boundedProviderDetail(body));\n return new ConfigurationError(detailed, {\n code: `${providerId}_model_unavailable`,\n metadata,\n });\n }\n if (status === 400) {\n // A 400 is fixed by changing the request, and only the provider's text says what to change.\n const detailed = formatMessage(providerId, status, code, boundedProviderDetail(body));\n return new ConfigurationError(detailed, { code: `${providerId}_${code}`, metadata });\n }\n if (status === 408) {\n return new NetworkError(message, { code: `${providerId}_timeout`, metadata });\n }\n if (status >= 500 && status < 600) {\n return new NetworkError(message, { code: `${providerId}_server_error`, metadata });\n }\n return new UnknownAgentError(message, { code: `${providerId}_unknown`, metadata });\n}\n\nfunction extractOpenAiErrorMessage(body: unknown): string | undefined {\n if (body === null || typeof body !== \"object\") return undefined;\n const err = (body as { error?: { message?: unknown } }).error;\n if (err === undefined || err === null) return undefined;\n return typeof err.message === \"string\" ? err.message : undefined;\n}\n\n// Redaction runs before the cut so a key cut short cannot slip past the credential patterns.\nfunction boundedProviderDetail(body: unknown): string | undefined {\n const raw = extractOpenAiErrorMessage(body);\n if (raw === undefined || raw.trim() === \"\") return undefined;\n const redacted = redactSecrets(raw);\n return redacted.length <= PROVIDER_DETAIL_MAX_CHARS\n ? redacted\n : `${redacted.slice(0, PROVIDER_DETAIL_MAX_CHARS)}…`;\n}\n\nfunction extractOpenAiErrorCode(body: unknown): string | undefined {\n if (body === null || typeof body !== \"object\") return undefined;\n const err = (body as { error?: { code?: unknown; type?: unknown } }).error;\n if (err === undefined || err === null) return undefined;\n if (typeof err.code === \"string\") return err.code;\n if (typeof err.type === \"string\") return err.type;\n return undefined;\n}\n\n// biome-ignore lint/complexity/noExcessiveCognitiveComplexity: explicit branch table is clearer than splitting\nfunction mapOpenAiStatusToCode(status: number, body: unknown): ErrorCode {\n const rawCode = extractOpenAiErrorCode(body)?.toLowerCase() ?? \"\";\n\n if (\n rawCode.includes(\"context_length\") ||\n rawCode.includes(\"context_window\") ||\n rawCode.includes(\"too_many_tokens\") ||\n rawCode.includes(\"max_tokens\")\n ) {\n return \"context_too_long\";\n }\n if (\n rawCode.includes(\"content_filter\") ||\n rawCode.includes(\"content_policy\") ||\n rawCode.includes(\"safety\")\n ) {\n return \"content_filtered\";\n }\n if (\n rawCode.includes(\"model_not_found\") ||\n rawCode.includes(\"model_unavailable\") ||\n rawCode.includes(\"invalid_model\")\n ) {\n return \"model_unavailable\";\n }\n // T3.7 — 402 / Insufficient credits / insufficient_quota body code flow\n // to canonical `quota_exceeded` (ADR-spec'd in ErrorCode union).\n if (\n status === 402 ||\n rawCode.includes(\"insufficient_quota\") ||\n rawCode.includes(\"quota_exceeded\")\n ) {\n return \"quota_exceeded\";\n }\n\n if (status === 404 && MISSING_MODEL_MESSAGE.test(extractOpenAiErrorMessage(body) ?? \"\")) {\n return \"model_unavailable\";\n }\n\n if (status === 401 || status === 403) return \"auth_failed\";\n if (status === 429) return \"rate_limit\";\n if (status === 408) return \"timeout\";\n if (status === 400) return \"invalid_request\";\n if (status >= 500 && status < 600) return \"server_error\";\n return \"unknown\";\n}\n\nfunction formatMessage(\n providerId: string,\n status: number,\n code: ErrorCode,\n detail?: string,\n): string {\n const base = `${providerId} API error: ${code} (HTTP ${status})`;\n return detail === undefined || detail === \"\" ? base : `${base}: ${detail}`;\n}\n","import { mkdir, readFile } from \"node:fs/promises\";\n\nimport { ConfigurationError } from \"@theokit/sdk/errors\";\nimport { safePathJoin, sanitizeIdentifier } from \"@theokit/sdk/path-safety\";\nimport { replaceFileAtomic, withCwdMutex } from \"@theokit/sdk/persistence\";\n\nimport { type MemoryFact, redactSecrets } from \"./memory-types.js\";\n\n/**\n * A fact stored under a typed category. Unlike the flat {@link MemoryFact}, the\n * `category` is always present in the categorized store's read shape.\n *\n * @public\n */\nexport interface CategorizedFact extends MemoryFact {\n category: string;\n}\n\n/**\n * Options for {@link createCategorizedMemory}.\n *\n * @public\n */\nexport interface CreateCategorizedMemoryOptions {\n /** Directory holding one markdown file per category (`<root>/<category>.md`). */\n root: string;\n /**\n * The closed category taxonomy. This list IS the schema: an `add`/`list`\n * with a category not in it is rejected. Must be non-empty, unique, each\n * sanitizable to a distinct filename.\n */\n categories: readonly string[];\n}\n\n/**\n * A typed, category-partitioned markdown memory store.\n *\n * @public\n */\nexport interface CategorizedMemory {\n /** The declared (frozen) category taxonomy. */\n readonly categories: readonly string[];\n /**\n * Append a fact under `category` (validated against the taxonomy). The text\n * is secret-redacted before persistence. Concurrent adds to the same category\n * are serialized (no lost update). Throws `ConfigurationError(unknown_category)`\n * for an undeclared category (before any I/O).\n */\n add(category: string, text: string): Promise<void>;\n /**\n * Read facts for one category (or every category when omitted). Never throws —\n * a missing/unreadable category file yields no facts.\n */\n list(category?: string): Promise<CategorizedFact[]>;\n}\n\nconst FACTS_HEADING = \"## Facts\";\n\n/**\n * Create a typed categorized memory store over the closed `categories`\n * taxonomy. Composes the shipped `safePathJoin`/`sanitizeIdentifier` path\n * guard, `redactSecrets`, and the atomic `replaceFileAtomic` + `withCwdMutex`\n * persistence primitives — zero new dependencies.\n *\n * @public\n */\nexport function createCategorizedMemory(\n options: CreateCategorizedMemoryOptions,\n): CategorizedMemory {\n const { root, categories } = options;\n validateCategories(categories);\n const allowed = new Set(categories);\n\n function assertKnown(category: string): void {\n if (!allowed.has(category)) {\n throw new ConfigurationError(\n `createCategorizedMemory: unknown category ${JSON.stringify(category)} (declared: ${categories.join(\", \")})`,\n { code: \"unknown_category\" },\n );\n }\n }\n\n function categoryPath(category: string): string {\n return safePathJoin(root, `${sanitizeIdentifier(category)}.md`);\n }\n\n async function add(category: string, text: string): Promise<void> {\n assertKnown(category);\n // Redact secrets, THEN encode newlines/backslashes so a multiline fact (or\n // one containing a `- ` / `## ` line) stays a single bullet and round-trips\n // faithfully — `list` decodes it back. Without this, the `## Facts` bullet\n // parse would split or truncate the fact (silent data loss).\n const encoded = encodeFact(redactSecrets(text));\n const sane = sanitizeIdentifier(category);\n await withCwdMutex(`catmem:${root}:${sane}`, async () => {\n const path = safePathJoin(root, `${sane}.md`);\n const raw = (await readFileOrEmpty(path)) || header(category);\n await mkdir(root, { recursive: true });\n await replaceFileAtomic(path, appendBullet(raw, encoded));\n });\n }\n\n async function list(category?: string): Promise<CategorizedFact[]> {\n if (category !== undefined) {\n assertKnown(category);\n return readCategory(categoryPath(category), category);\n }\n const out: CategorizedFact[] = [];\n for (const c of categories) {\n out.push(...(await readCategory(categoryPath(c), c)));\n }\n return out;\n }\n\n return { categories: [...categories], add, list };\n}\n\nfunction validateCategories(categories: readonly string[]): void {\n if (categories.length === 0) {\n throw new ConfigurationError(\"createCategorizedMemory: categories must be non-empty\", {\n code: \"invalid_categories\",\n });\n }\n if (new Set(categories).size !== categories.length) {\n throw new ConfigurationError(\"createCategorizedMemory: categories must be unique\", {\n code: \"invalid_categories\",\n });\n }\n const sanitized = categories.map((c) => trySanitize(c));\n if (new Set(sanitized).size !== categories.length) {\n throw new ConfigurationError(\n \"createCategorizedMemory: categories must map to distinct filenames after sanitization\",\n { code: \"invalid_categories\" },\n );\n }\n}\n\nfunction trySanitize(category: string): string {\n try {\n return sanitizeIdentifier(category);\n } catch (cause) {\n throw new ConfigurationError(\n `createCategorizedMemory: category ${JSON.stringify(category)} is not a valid identifier`,\n { code: \"invalid_categories\", cause },\n );\n }\n}\n\nfunction header(category: string): string {\n return `---\\ncategory: ${category}\\n---\\n\\n${FACTS_HEADING}\\n`;\n}\n\nasync function readFileOrEmpty(path: string): Promise<string> {\n try {\n return await readFile(path, \"utf8\");\n } catch {\n return \"\";\n }\n}\n\nasync function readCategory(path: string, category: string): Promise<CategorizedFact[]> {\n const raw = await readFileOrEmpty(path);\n return parseFactBullets(raw).map((text) => ({ text: decodeFact(text), category }));\n}\n\n/**\n * Encode a fact for single-bullet storage: escape `\\` first, then `\\r`/`\\n`, so\n * the text occupies exactly one `- ` line (no split, no `## ` heading injection).\n * Pure + reversible by {@link decodeFact}.\n */\nfunction encodeFact(text: string): string {\n return text.replace(/\\\\/g, \"\\\\\\\\\").replace(/\\r/g, \"\\\\r\").replace(/\\n/g, \"\\\\n\");\n}\n\n/**\n * Reverse {@link encodeFact}. A single left-to-right pass over each `\\<char>`\n * escape: `\\n`→newline, `\\r`→CR, and any other escaped char (notably `\\\\`)→the\n * literal char. Non-overlapping matching makes this exact for encoded input.\n */\nfunction decodeFact(text: string): string {\n return text.replace(/\\\\(.)/g, (_match, char: string) =>\n char === \"n\" ? \"\\n\" : char === \"r\" ? \"\\r\" : char,\n );\n}\n\n/** Parse `- text` bullets under the `## Facts` heading. Pure. */\nfunction parseFactBullets(raw: string): string[] {\n const idx = raw.indexOf(FACTS_HEADING);\n if (idx === -1) return [];\n const tail = raw.slice(idx + FACTS_HEADING.length);\n const nextHeading = tail.search(/\\n#{1,2}\\s/);\n const block = nextHeading === -1 ? tail : tail.slice(0, nextHeading);\n return block\n .split(\"\\n\")\n .map((line) => line.trim())\n .filter((line) => line.startsWith(\"- \"))\n .map((line) => line.slice(2).trim());\n}\n\n/** Append a `- text` bullet under the `## Facts` heading. Pure. */\nfunction appendBullet(raw: string, text: string): string {\n const bullet = `- ${text}`;\n const idx = raw.indexOf(FACTS_HEADING);\n if (idx === -1) {\n const sep = raw.endsWith(\"\\n\") ? \"\" : \"\\n\";\n return `${raw}${sep}${FACTS_HEADING}\\n\\n${bullet}\\n`;\n }\n const after = idx + FACTS_HEADING.length;\n const nextHeading = raw.slice(after).search(/\\n#{1,2}\\s/);\n if (nextHeading === -1) {\n const trailing = raw.endsWith(\"\\n\") ? \"\" : \"\\n\";\n return `${raw}${trailing}${bullet}\\n`;\n }\n const insertAt = after + nextHeading;\n return `${raw.slice(0, insertAt)}\\n${bullet}${raw.slice(insertAt)}`;\n}\n","import {\n type LanceIndex,\n LanceMemoryAdapter as SharedLanceMemoryAdapter,\n} from \"@theokit/sdk/internal/memory-store\";\n\n/**\n * Presents a `LanceIndex` as a `MemoryIndex`, so a consumer written against the SQLite index runs\n * unchanged on `backend: \"lance\"`.\n *\n * `sync`, `search`, `status` and `close` are the SDK's adapter, inherited rather than copied\n * (#1068), so they behave the same whether or not this package is installed: `sync()` walks\n * nothing and says so with `supported: false`, `search()` blends Lance's vector score with a\n * term-overlap text score through the caller's `vectorWeight` / `textWeight`, and `status()`\n * reports zero counts with `countsExact: false`. It always queries the `default` namespace.\n *\n * The one member this class adds is {@link LanceMemoryAdapter.unwrap}. The SDK's adapter\n * deliberately has no such member; this package published one, so it stays here. An index opened\n * with `IndexManager.open({ backend: \"lance\" })` is the SDK's adapter and does not have it: to\n * write facts, open a `LanceIndex` and either use it directly or wrap it with this class.\n *\n * Requires `@lancedb/lancedb`, an optional peer dependency, loaded when the index is opened.\n */\nexport class LanceMemoryAdapter extends SharedLanceMemoryAdapter {\n readonly #lance: LanceIndex;\n\n constructor(inner: LanceIndex) {\n super(inner);\n this.#lance = inner;\n }\n\n /** The wrapped `LanceIndex`, for `addFacts`, `countFacts` and `removeFacts`. */\n unwrap(): LanceIndex {\n return this.#lance;\n }\n}\n","import type { MemoryDb } from \"@theokit/sdk/internal/memory-store\";\n\n// `isSqliteVecLoaded` has no SDK counterpart yet, so it stays here; the loader is the SDK's.\nexport { loadSqliteVecExtension } from \"@theokit/sdk/internal/memory-store\";\n\n/** Check whether sqlite-vec is loaded by running a tiny version query. */\nexport function isSqliteVecLoaded(db: MemoryDb): boolean {\n try {\n const row = db.prepare(\"SELECT vec_version() as v\").get();\n return row !== undefined && row.v !== undefined;\n } catch {\n return false;\n }\n}\n","import { resolve as resolvePath } from \"node:path\";\n\nimport { ConfigurationError } from \"@theokit/sdk/errors\";\n\nimport type { MemorySearchHit } from \"./index/index-manager-contract.js\";\nimport type { MemoryIndex } from \"./index/memory-index.js\";\nimport type { MemoryRoot } from \"./store/markdown-store.js\";\nimport { readMemoryFileBounded } from \"./store/reader.js\";\n\n/**\n * Memory tools (`memory_search` + `memory_get`) — ADR D5 of\n * memory-system-peer-project-parity. Tool schemas mirror peer-project\n * (`reference/peer-project/extensions/memory-core/src/tools.ts:228-475`).\n *\n * Each tool is exposed as a `MemoryTool` (name + description + JSON schema +\n * async execute). The agent-loop integration wires them via the existing\n * `ResolvedTool` interface in `tool-dispatch.ts`.\n *\n * Iter 64 (Stage 3 source-move #21): hybrid copy from sdk-core's\n * `internal/memory/tools.ts`. sdk-core retains its copy for v1.x\n * memory-tools back-compat; sdk-memory ships the canonical copy.\n * Dependency chain (all resolved):\n * - `@theokit/sdk/errors` for `ConfigurationError` (public)\n * - sibling `./index-manager-contract.js` for `MemorySearchHit`\n * (moved iter 47 — note: sdk-core copy imports from\n * `./index-manager.js`; sdk-memory uses the contract leaf\n * directly since the canonical type lives there)\n * - sibling `./memory-index.js` for `MemoryIndex` (moved iter 50)\n * - sibling `./markdown-store.js` for `memoryDir` (moved iter 56)\n * - sibling `./reader.js` for `readMemoryFileBounded` (moved iter 55)\n *\n * @internal\n */\n\nexport interface MemoryToolJson {\n name: string;\n description: string;\n inputSchema: Record<string, unknown>;\n}\n\n/**\n * A memory tool ready to hand to the agent loop: the JSON-serialisable\n * description an LLM sees, plus the `execute` that runs it. `execute` resolves\n * to a JSON string — the tool layer does no further encoding.\n */\nexport interface MemoryTool extends MemoryToolJson {\n execute(input: Record<string, unknown>): Promise<string>;\n}\n\nconst SEARCH_DESCRIPTION =\n \"Mandatory recall step: semantically search MEMORY.md + memory/notes/*.md (and optional wiki supplements) before answering questions about prior work, decisions, dates, people, preferences, or todos. `corpus=memory` (default) restricts to indexed memory files; `corpus=wiki` restricts to read-only wiki supplements; `corpus=all` returns both. Returns ranked `{ path, startLine, endLine, score, snippet, citation }` hits.\";\n\nconst GET_DESCRIPTION =\n \"Safe exact excerpt read from MEMORY.md or memory/notes/*.md. Defaults to a bounded excerpt (200 lines). Returns `{ path, from, linesReturned, totalLines, truncated, remainingLines, text }`. Paths are resolved against the memory root — attempts to read outside `.theokit/memory/` are rejected.\";\n\nconst MEMORY_SEARCH_SCHEMA: Record<string, unknown> = {\n type: \"object\",\n required: [\"query\"],\n properties: {\n query: { type: \"string\", description: \"Natural-language query.\" },\n maxResults: { type: \"integer\", minimum: 1, maximum: 50 },\n minScore: { type: \"number\", minimum: 0, maximum: 1 },\n corpus: { type: \"string\", enum: [\"memory\", \"sessions\", \"wiki\", \"all\"] },\n },\n additionalProperties: false,\n};\n\nconst MEMORY_GET_SCHEMA: Record<string, unknown> = {\n type: \"object\",\n required: [\"path\"],\n properties: {\n path: { type: \"string\", description: \"Path relative to .theokit/memory/\" },\n from: { type: \"integer\", minimum: 1 },\n lines: { type: \"integer\", minimum: 1, maximum: 2000 },\n },\n additionalProperties: false,\n};\n\nconst DEFAULT_MAX_TOTAL_CHARS = 16384;\n\n/** Options for {@link createMemorySearchTool}. */\nexport interface MemorySearchToolOptions {\n index: MemoryIndex;\n /** Cap on the JSON response size (EC-10 of edge-case review). Default 16384. */\n maxTotalChars?: number;\n}\n\n/**\n * Build the `memory_search` tool over an index that is already open. The tool\n * never opens or syncs anything: if `index.sync()` has not run, the search runs\n * against whatever the index last recorded, and a freshly created index returns\n * no hits.\n *\n * The tool accepts `query` (required), `maxResults` (default 10), `minScore`,\n * and `corpus`, where `corpus` maps to the index's source filter: `memory`,\n * `sessions`, `wiki`, or `all` (the default, which applies no filter). An\n * unrecognised `corpus` value is treated as `all` rather than rejected.\n *\n * `execute` returns `{\"hits\": [...], \"truncated\": bool}`. Hits are dropped from\n * the tail once their estimated size would exceed `maxTotalChars`, except that\n * the first hit is always kept even when it alone exceeds the cap.\n *\n * Use this for recall by meaning across the whole corpus, and\n * {@link createMemoryGetTool} when the model already knows the file and wants\n * exact lines.\n */\nexport function createMemorySearchTool(opts: MemorySearchToolOptions): MemoryTool {\n const cap = opts.maxTotalChars ?? DEFAULT_MAX_TOTAL_CHARS;\n return {\n name: \"memory_search\",\n description: SEARCH_DESCRIPTION,\n inputSchema: MEMORY_SEARCH_SCHEMA,\n async execute(input: Record<string, unknown>): Promise<string> {\n const query = readString(input.query, \"query is required\");\n const maxResults = readNumber(input.maxResults) ?? 10;\n const minScore = readNumber(input.minScore);\n const corpus = readString(input.corpus, undefined, true);\n const sources = mapCorpusToSources(corpus);\n const searchOptions = {\n maxResults,\n ...(minScore !== undefined ? { minScore } : {}),\n ...(sources !== undefined ? { sources } : {}),\n };\n const hits = await opts.index.search(query, searchOptions);\n return JSON.stringify(capByTotalChars(hits, cap));\n },\n };\n}\n\n/** Options for {@link createMemoryGetTool}. `cwd` is the workspace root, not the memory directory. */\nexport interface MemoryGetToolOptions {\n /** The RESOLVED memory root the tool may read inside — not a cwd (#463). */\n root: MemoryRoot;\n}\n\n/**\n * Build the `memory_get` tool, which reads an exact excerpt from a file under\n * `<cwd>/.theokit/memory`. Needs no index and no embedding runtime — it is\n * plain file reading, so it works in a workspace where search is not configured.\n *\n * The tool accepts `path` (required, relative to the memory root), `from`\n * (1-indexed, default 1) and `lines` (default 200). A `path` whose resolved\n * location falls outside the memory root is rejected with a\n * `ConfigurationError` carrying the code `memory_path_escapes_root`. A path that\n * stays inside but does not exist is not caught here: the underlying read\n * rejects with the filesystem error.\n */\nexport function createMemoryGetTool(opts: MemoryGetToolOptions): MemoryTool {\n const memoryRoot = resolvePath(opts.root);\n return {\n name: \"memory_get\",\n description: GET_DESCRIPTION,\n inputSchema: MEMORY_GET_SCHEMA,\n async execute(input: Record<string, unknown>): Promise<string> {\n const relPath = readString(input.path, \"path is required\");\n const from = readNumber(input.from);\n const lines = readNumber(input.lines);\n // EC-2: enforce that the resolved path stays inside the memory root.\n const resolved = resolvePath(memoryRoot, relPath);\n if (!isPathInside(memoryRoot, resolved)) {\n throw new ConfigurationError(\n `memory_get rejected path that escapes memory root: ${relPath}`,\n { code: \"memory_path_escapes_root\" },\n );\n }\n const readArgs: { cwd: string; relPath: string; from?: number; lines?: number } = {\n cwd: memoryRoot,\n relPath,\n };\n if (from !== undefined) readArgs.from = from;\n if (lines !== undefined) readArgs.lines = lines;\n const result = await readMemoryFileBounded(readArgs);\n return JSON.stringify(result);\n },\n };\n}\n\n// ───── helpers ──────────────────────────────────────────────────────────\n\nfunction readString(value: unknown, errorIfMissing?: string, allowUndefined = false): string {\n if (typeof value === \"string\") return value;\n if (allowUndefined && (value === undefined || value === null)) return \"\";\n if (errorIfMissing !== undefined) {\n throw new ConfigurationError(errorIfMissing, { code: \"memory_tool_bad_args\" });\n }\n return \"\";\n}\n\nfunction readNumber(value: unknown): number | undefined {\n if (typeof value === \"number\" && Number.isFinite(value)) return value;\n if (typeof value === \"string\" && value.trim().length > 0) {\n const n = Number(value);\n if (Number.isFinite(n)) return n;\n }\n return undefined;\n}\n\nfunction mapCorpusToSources(\n corpus: string,\n): ReadonlyArray<\"memory\" | \"sessions\" | \"wiki\"> | undefined {\n if (corpus === \"\" || corpus === \"all\") return undefined;\n if (corpus === \"memory\") return [\"memory\"];\n if (corpus === \"wiki\") return [\"wiki\"];\n if (corpus === \"sessions\") return [\"sessions\"];\n return undefined;\n}\n\nfunction capByTotalChars(\n hits: ReadonlyArray<MemorySearchHit>,\n maxTotalChars: number,\n): { hits: MemorySearchHit[]; truncated: boolean } {\n if (hits.length === 0) return { hits: [], truncated: false };\n const kept: MemorySearchHit[] = [];\n let runningChars = 0;\n for (const hit of hits) {\n const snippetLen = hit.snippet.length + (hit.citation?.length ?? 0) + 32; // overhead estimate\n if (kept.length > 0 && runningChars + snippetLen > maxTotalChars) {\n return { hits: kept, truncated: true };\n }\n kept.push(hit);\n runningChars += snippetLen;\n }\n return { hits: kept, truncated: false };\n}\n\nfunction isPathInside(root: string, candidate: string): boolean {\n const normalizedRoot = root.endsWith(\"/\") ? root : `${root}/`;\n return candidate === root || candidate.startsWith(normalizedRoot);\n}\n"]}