@theokit/sdk-memory 0.7.3 → 0.7.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -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/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":["ConfigurationError","sessionsDir","readdir","join","finalized","resolveMemoryRoot","Security","resolvePath","safePathJoin","sanitizeIdentifier","mkdir","replaceFileAtomic","readFile","SharedLanceMemoryAdapter"],"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;AAAA,IACV,OAAA,EAAS,KAAA;AAAA,IACT,SAAA,EAAW,KAAA;AAAA,IACX,WAAA,EAAa,KAAA;AAAA,IACb,QAAA,EAAU;AAAA,GACZ;AACF;AAOA,SAAS,aAAa,KAAA,EAAkC;AACtD,EAAA,IAAI,MAAM,QAAA,KAAa,MAAA,IAAa,MAAM,KAAA,CAAM,IAAA,IAAQ,MAAM,QAAA,EAAU;AACtE,IAAA,MAAM,mBAAA;AAAA,MACJ,qBAAA;AAAA,MACA,MAAM,KAAA,CAAM,IAAA;AAAA,MACZ,KAAA,CAAM,QAAA;AAAA,MACN;AAAA,KACF;AAAA,EACF;AACF;AAEA,SAAS,iBAAiB,KAAA,EAA6C;AACrE,EAAA,OAAO,KAAA,YAAiBA,oBAAA,IAAsB,KAAA,CAAM,IAAA,KAA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I,MAAA,KAAW,MAAA,EAAQ,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.js","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"]}
1
+ {"version":3,"sources":["../src/in-memory-provider.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/store/markdown-store.ts"],"names":["ConfigurationError","sessionsDir","Security","resolvePath","safePathJoin","sanitizeIdentifier","mkdir","replaceFileAtomic","readFile","SharedLanceMemoryAdapter","readdir","join"],"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;AAAA,IACV,OAAA,EAAS,KAAA;AAAA,IACT,SAAA,EAAW,KAAA;AAAA,IACX,WAAA,EAAa,KAAA;AAAA,IACb,QAAA,EAAU;AAAA,GACZ;AACF;AAOA,SAAS,aAAa,K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AAiCC,oBAAA,CAAyB;AAAA,EACtD,MAAA;AAAA,EAET,YAAY,KAAA,EAAmB;AAC7B,IAAA,KAAA,CAAM,KAAK,CAAA;AACX,IAAA,IAAA,CAAK,MAAA,GAAS,KAAA;AAAA,EAChB;AAAA;AAAA,EAGA,MAAA,GAAqB;AACnB,IAAA,OAAO,IAAA,CAAK,MAAA;AAAA,EACd;AACF;AC5BO,SAAS,kBAAkB,EAAA,EAAuB;AACvD,EAAA,IAAI;AACF,IAAA,MAAM,GAAA,GAAM,EAAA,CAAG,OAAA,CAAQ,2BAA2B,EAAE,GAAA,EAAI;AACxD,IAAA,OAAO,GAAA,KAAQ,KAAA,CAAA,IAAa,GAAA,CAAI,CAAA,KAAM,KAAA,CAAA;AAAA,EACxC,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,KAAA;AAAA,EACT;AACF;AC4DA,eAAsB,UAAU,GAAA,EAAkC;AAChE,EAAA,IAAI,UAAoB,EAAC;AACzB,EAAA,IAAI;AACF,IAAA,OAAA,GAAU,MAAMC,OAAAA,CAAQ,QAAA,CAAS,iBAAA,CAAkB,GAAG,CAAC,CAAC,CAAA;AAAA,EAC1D,CAAA,CAAA,MAAQ;AACN,IAAA,OAAO,EAAC;AAAA,EACV;AACA,EAAA,OAAO,OAAA,CACJ,MAAA,CAAO,CAAC,IAAA,KAAS,IAAA,CAAK,QAAA,CAAS,KAAK,CAAC,CAAA,CACrC,GAAA,CAAI,CAAC,IAAA,MAAU;AAAA,IACd,IAAA,EAAM,IAAA,CAAK,OAAA,CAAQ,OAAA,EAAS,EAAE,CAAA;AAAA,IAC9B,MAAMC,IAAAA,CAAK,QAAA,CAAS,kBAAkB,GAAG,CAAC,GAAG,IAAI;AAAA,GACnD,CAAE,CAAA;AACN","file":"index.js","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 { 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 { 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"]}
@@ -1,133 +1,7 @@
1
1
  /**
2
- * Active Memory blocking recall (ADR D6 of memory-system-peer-project-parity).
3
- *
4
- * Runs BEFORE `agent.send()` assembles the system prompt. Issues a direct
5
- * call to `IndexManager.search` with the user message (and optional recent
6
- * turns per `queryMode`).
7
- *
8
- * Returns a `summary` string capped at `maxSummaryChars` (default 220 to
9
- * match peer-project's `DEFAULT_MAX_SUMMARY_CHARS`) which the system-prompt
10
- * pipeline prepends as a `<active-memory>` block (priority 5).
11
- *
12
- * Iter 75 (Stage 3 source-move #38, FINAL move): hybrid copy from
13
- * sdk-core's `internal/memory/active-memory.ts`. sdk-core retains its
14
- * copy as the v1.x runtime that `Memory` class delegates to;
15
- * sdk-memory ships the canonical copy that future Stage 4 port-based
16
- * composition will consume.
17
- *
18
- * **CLOSES the Stage 3 source-move stage in sdk-memory.** Every
19
- * memory-related concept under sdk-core's internal/memory/ is now
20
- * canonical in @theokit/sdk-memory (38 source files moved across
21
- * iter 44-75; 2 inlined adapters added: adapter-http-error iter 73
22
- * + adapter-catalog renamed iter 74).
23
- *
24
- * **Cross-package telemetry contract:** `OTelSpan` and `TelemetryHandle`
25
- * are now imported from `@theokit/sdk`, which exports them since #295.
26
- * This file previously inlined structural mirrors of both, with a note
27
- * that they MUST be replaced once sdk-core made them public — and by
28
- * the time anyone looked, the mirrors had drifted: they narrowed
29
- * `setAttributes` to reject the `undefined` values the canonical type
30
- * accepts, and declared `end()` without its `endTime` parameter. That
31
- * is how a structural mirror fails: quietly, with both sides compiling.
32
- *
33
- * The 2 constant strings (`memory.recall` span name +
34
- * `theokit_memory_recall_duration_ms` histogram name) are still inlined
35
- * below, because sdk-core's `span-names.ts` remains private. They are
36
- * values rather than types, so exporting them is a separate decision
37
- * with a real bundle cost — unlike these two, which erase at build time.
38
- *
39
- * @internal
2
+ * Active Memory blocking recall — re-exported from `@theokit/sdk`, not reimplemented here (#1069).
3
+ * The two packages carried copies with the same exported names; a fix to one did not reach users
4
+ * of the other. See `../store/transcript-store.ts` for the same method.
40
5
  */
41
- import type { TelemetryHandle } from "@theokit/sdk";
42
- import type { CircuitBreaker } from "@theokit/sdk/retry";
43
- import type { MemoryIndex } from "../index/memory-index.js";
44
- import type { ActiveMemoryCache } from "./active-memory-cache.js";
45
- import type { ActiveMemoryQueryMode, ActiveMemoryResult, ActiveMemoryStatus } from "./active-memory-types.js";
46
- export type { ActiveMemoryQueryMode, ActiveMemoryResult, ActiveMemoryStatus };
47
- /**
48
- * Tuning for one recall attempt. Recall is off unless `enabled` is exactly
49
- * `true`, so an options object that omits it disables recall rather than
50
- * enabling it with defaults.
51
- */
52
- export interface ActiveMemoryOptions {
53
- /** Whether active recall is enabled. Default `false`. */
54
- enabled?: boolean;
55
- /** Query construction strategy. Default `"recent"`. */
56
- queryMode?: ActiveMemoryQueryMode;
57
- /** Hard timeout in ms. Default `15000`. */
58
- timeoutMs?: number;
59
- /** Max chars in the summary. Default `220`. */
60
- maxSummaryChars?: number;
61
- /** Number of recent user turns to include in `queryMode === "recent"`. Default `2`. */
62
- recentUserTurns?: number;
63
- }
64
- /**
65
- * Everything {@link runActiveMemory} needs for one attempt. Only `userText`,
66
- * `priorMessages`, `index` and `options` are required; the rest add breaker,
67
- * cache, transcript persistence and telemetry, each of which is inert when
68
- * omitted.
69
- *
70
- * `index` is accepted as `undefined` on purpose — an agent with memory
71
- * configured but no index open is a normal state, and it produces a `skipped`
72
- * result rather than an error.
73
- */
74
- export interface RunActiveMemoryArgs {
75
- userText: string;
76
- priorMessages: ReadonlyArray<{
77
- role: "user" | "assistant";
78
- text: string;
79
- }>;
80
- index: MemoryIndex | undefined;
81
- options: ActiveMemoryOptions;
82
- /** Per-agent circuit breaker (Phase 8). */
83
- breaker?: CircuitBreaker;
84
- /** Per-agent result cache (Phase 8). */
85
- cache?: ActiveMemoryCache;
86
- /** Workspace root for transcript persistence. */
87
- cwd?: string;
88
- /** When true, write transcript JSON under .theokit/memory/transcripts/active-memory/. */
89
- persistTranscripts?: boolean;
90
- /** Stable key the breaker + cache key by (default `default`). */
91
- agentKey?: string;
92
- /** Run id for transcript file naming. */
93
- runId?: string;
94
- /**
95
- * T0.1 — optional telemetry handle. When provided AND telemetry is enabled,
96
- * `memory.recall` span is emitted with `{ userId, namespace, scope, queryMode,
97
- * hits, status }` attrs and `theokit_memory_recall_duration_ms` histogram is
98
- * recorded with the same dimension keys.
99
- */
100
- telemetry?: TelemetryHandle;
101
- /** User id surfaced as a memory.recall span attr for cross-tenant tracing. */
102
- userId?: string;
103
- /** Memory namespace (e.g. `default`, `<orgId>`) for span/histogram dimensions. */
104
- namespace?: string;
105
- /** Memory scope (`session` / `user` / `global`) for span/histogram dimensions. */
106
- scope?: string;
107
- }
108
- /**
109
- * Run one blocking recall before the system prompt is assembled, and report what
110
- * happened. Never throws for a recall failure: a search that times out or
111
- * rejects comes back as a `timeout` or `error` status with no summary, and the
112
- * agent run continues without memory.
113
- *
114
- * The order of the short-circuits decides what a caller sees. Recall disabled or
115
- * no index gives `skipped` with no search. An open circuit breaker gives
116
- * `skipped` too. A cache hit returns the earlier result as-is, which means it
117
- * also returns that result's `status` and `durationMs` — a cached `no-recall`
118
- * looks exactly like a fresh one. An empty query gives `no-recall`.
119
- *
120
- * Only a real search reaches the breaker: `timeout` records a timeout, `ok` and
121
- * `no-recall` record a success, and `error` records neither, so a provider that
122
- * keeps throwing will not trip the breaker.
123
- *
124
- * `timeoutMs` bounds how long this waits, not how long the search runs — the
125
- * underlying `index.search` is left running when the timer wins. The search asks
126
- * the index for at most 5 hits regardless of options.
127
- *
128
- * Cache entries are keyed by tenant as well as by query text, so two callers
129
- * with the same question and different `userId` / `namespace` / `scope` never
130
- * share an entry.
131
- */
132
- export declare function runActiveMemory(args: RunActiveMemoryArgs): Promise<ActiveMemoryResult>;
6
+ export { type ActiveMemoryOptions, type ActiveMemoryQueryMode, type ActiveMemoryResult, type ActiveMemoryStatus, type RunActiveMemoryArgs, runActiveMemory, } from "@theokit/sdk/internal/memory-store";
133
7
  //# sourceMappingURL=active-memory.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"active-memory.d.ts","sourceRoot":"","sources":["../../../src/internal/active-memory/active-memory.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAuCG;AAEH,OAAO,KAAK,EAAY,eAAe,EAAE,MAAM,cAAc,CAAC;AAE9D,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,oBAAoB,CAAC;AAEzD,OAAO,KAAK,EAAE,WAAW,EAAE,MAAM,0BAA0B,CAAC;AAG5D,OAAO,KAAK,EAAE,iBAAiB,EAAiB,MAAM,0BAA0B,CAAC;AAIjF,OAAO,KAAK,EACV,qBAAqB,EACrB,kBAAkB,EAClB,kBAAkB,EACnB,MAAM,0BAA0B,CAAC;AAElC,YAAY,EAAE,qBAAqB,EAAE,kBAAkB,EAAE,kBAAkB,EAAE,CAAC;AAmB9E;;;;GAIG;AACH,MAAM,WAAW,mBAAmB;IAClC,yDAAyD;IACzD,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,uDAAuD;IACvD,SAAS,CAAC,EAAE,qBAAqB,CAAC;IAClC,2CAA2C;IAC3C,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,+CAA+C;IAC/C,eAAe,CAAC,EAAE,MAAM,CAAC;IACzB,uFAAuF;IACvF,eAAe,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED;;;;;;;;;GASG;AACH,MAAM,WAAW,mBAAmB;IAClC,QAAQ,EAAE,MAAM,CAAC;IACjB,aAAa,EAAE,aAAa,CAAC;QAAE,IAAI,EAAE,MAAM,GAAG,WAAW,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAC3E,KAAK,EAAE,WAAW,GAAG,SAAS,CAAC;IAC/B,OAAO,EAAE,mBAAmB,CAAC;IAC7B,2CAA2C;IAC3C,OAAO,CAAC,EAAE,cAAc,CAAC;IACzB,wCAAwC;IACxC,KAAK,CAAC,EAAE,iBAAiB,CAAC;IAC1B,iDAAiD;IACjD,GAAG,CAAC,EAAE,MAAM,CAAC;IACb,yFAAyF;IACzF,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,iEAAiE;IACjE,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,yCAAyC;IACzC,KAAK,CAAC,EAAE,MAAM,CAAC;IACf;;;;;OAKG;IACH,SAAS,CAAC,EAAE,eAAe,CAAC;IAC5B,8EAA8E;IAC9E,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,kFAAkF;IAClF,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,kFAAkF;IAClF,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AASD;;;;;;;;;;;;;;;;;;;;;;;GAuBG;AACH,wBAAsB,eAAe,CAAC,IAAI,EAAE,mBAAmB,GAAG,OAAO,CAAC,kBAAkB,CAAC,CAsD5F"}
1
+ {"version":3,"file":"active-memory.d.ts","sourceRoot":"","sources":["../../../src/internal/active-memory/active-memory.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EACL,KAAK,mBAAmB,EACxB,KAAK,qBAAqB,EAC1B,KAAK,kBAAkB,EACvB,KAAK,kBAAkB,EACvB,KAAK,mBAAmB,EACxB,eAAe,GAChB,MAAM,oCAAoC,CAAC"}