@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 CHANGED
@@ -2,8 +2,8 @@ export { CircuitBreaker } from '@theokit/sdk/retry';
2
2
  import { mkdir, readdir, readFile } from 'fs/promises';
3
3
  import { join, resolve } from 'path';
4
4
  import { Security, ConfigurationError as ConfigurationError$1 } from '@theokit/sdk';
5
- import { resolveMaxFacts, notesDir, resolveMemoryRoot, persistActiveMemoryTranscript, LanceMemoryAdapter as LanceMemoryAdapter$1, readMemoryFileBounded, ceilingReachedError } from '@theokit/sdk/internal/memory-store';
6
- export { ActiveMemoryCache, DEFAULT_MEMORY_READ_LINES, IndexManager, LanceIndex, MEMORY_INDEX_MAX_BYTES, MEMORY_INDEX_MAX_LINES, META_KEY_DIMENSION, META_KEY_MODEL, META_KEY_PROVIDER_ID, PRAGMA_STATEMENTS, SCHEMA_STATEMENTS, VALID_BACKENDS, appendDiaryEntry, appendFact, appendFactToMarkdown, asMemoryRoot, assertValidBackend, ceilingReachedError, chunkMarkdown, claudeProjectMemoryDir, collectMarkdownFiles, createVectorIndex, deepPhase, defaultIndexPath, diaryPath, discoverSessionFiles, discoverWikiFiles, dropVectorIndex, embedMissingChunks, entryHash, factsBlockRange, identityMatches, indexBudgetWarning, isLanceAvailable, lanceStoragePath, lightPhase, listFactEntries, loadSqliteVecExtension, memoryIndexRoot, memoryMdPath, memoryReadRoots, migrateLegacyJson, migrateSqliteToLance, notesDir, openLanceIndex, openMemoryDb, packVector, parseSearchOptions, persistActiveMemoryTranscript, projectMemoryDir, readAllSqliteFacts, readEmbeddingIdentity, readFacts, readFactsFromMarkdown, readLegacyEntriesIn, readMemoryEntriesIn, readMemoryFileBounded, remPhase, removeFactEntry, renderDiaryEntry, resolveMaxFacts, resolveMemoryRoot, runDreamingSweep, sessionSummaryPath, sessionsDir, unlessMissing, upsertEmbedding, vectorSearch, wikiDir, writeEmbeddingIdentity, writeSessionSummary } from '@theokit/sdk/internal/memory-store';
5
+ import { resolveMaxFacts, LanceMemoryAdapter as LanceMemoryAdapter$1, notesDir, resolveMemoryRoot, ceilingReachedError } from '@theokit/sdk/internal/memory-store';
6
+ export { ActiveMemoryCache, DEFAULT_MEMORY_READ_LINES, IndexManager, LanceIndex, MEMORY_INDEX_MAX_BYTES, MEMORY_INDEX_MAX_LINES, META_KEY_DIMENSION, META_KEY_MODEL, META_KEY_PROVIDER_ID, PRAGMA_STATEMENTS, SCHEMA_STATEMENTS, VALID_BACKENDS, appendDiaryEntry, appendFact, appendFactToMarkdown, asMemoryRoot, assertValidBackend, ceilingReachedError, chunkMarkdown, claudeProjectMemoryDir, collectMarkdownFiles, createMemoryGetTool, createMemorySearchTool, createVectorIndex, deepPhase, defaultIndexPath, diaryPath, discoverSessionFiles, discoverWikiFiles, dropVectorIndex, embedMissingChunks, entryHash, factsBlockRange, identityMatches, indexBudgetWarning, isLanceAvailable, lanceStoragePath, lightPhase, listFactEntries, loadSqliteVecExtension, memoryIndexRoot, memoryMdPath, memoryReadRoots, migrateLegacyJson, migrateSqliteToLance, notesDir, openLanceIndex, openMemoryDb, packVector, parseSearchOptions, persistActiveMemoryTranscript, projectMemoryDir, readAllSqliteFacts, readEmbeddingIdentity, readFacts, readFactsFromMarkdown, readLegacyEntriesIn, readMemoryEntriesIn, readMemoryFileBounded, remPhase, removeFactEntry, renderDiaryEntry, resolveMaxFacts, resolveMemoryRoot, runActiveMemory, runDreamingSweep, sessionSummaryPath, sessionsDir, unlessMissing, upsertEmbedding, vectorSearch, wikiDir, writeEmbeddingIdentity, writeSessionSummary } from '@theokit/sdk/internal/memory-store';
7
7
  import { replaceFileAtomic, withCwdMutex } from '@theokit/sdk/persistence';
8
8
  import { geminiMemoryEmbeddingProviderAdapter, jinaMemoryEmbeddingProviderAdapter, cohereMemoryEmbeddingProviderAdapter, azureOpenAiMemoryEmbeddingProviderAdapter, ollamaMemoryEmbeddingProviderAdapter, deepinfraMemoryEmbeddingProviderAdapter, voyageMemoryEmbeddingProviderAdapter, openRouterMemoryEmbeddingProviderAdapter, mistralMemoryEmbeddingProviderAdapter, openAiMemoryEmbeddingProviderAdapter } from '@theokit/sdk/internal/memory-adapters';
9
9
  export { DEFAULT_AZURE_OPENAI_EMBEDDING_MODEL, DEFAULT_COHERE_EMBEDDING_MODEL, DEFAULT_DEEPINFRA_EMBEDDING_MODEL, DEFAULT_GEMINI_EMBEDDING_MODEL, DEFAULT_JINA_EMBEDDING_MODEL, DEFAULT_MISTRAL_EMBEDDING_MODEL, DEFAULT_OLLAMA_EMBEDDING_MODEL, DEFAULT_OPENAI_EMBEDDING_MODEL, DEFAULT_OPENROUTER_EMBEDDING_MODEL, DEFAULT_VOYAGE_EMBEDDING_MODEL, azureOpenAiMemoryEmbeddingProviderAdapter, cohereMemoryEmbeddingProviderAdapter, createOpenAiCompatibleRuntime, deepinfraMemoryEmbeddingProviderAdapter, geminiMemoryEmbeddingProviderAdapter, jinaMemoryEmbeddingProviderAdapter, mistralMemoryEmbeddingProviderAdapter, ollamaMemoryEmbeddingProviderAdapter, openAiMemoryEmbeddingProviderAdapter, openRouterMemoryEmbeddingProviderAdapter, voyageMemoryEmbeddingProviderAdapter } from '@theokit/sdk/internal/memory-adapters';
@@ -261,205 +261,6 @@ function createInMemoryMarkdownProvider(options = {}) {
261
261
  }
262
262
  };
263
263
  }
264
- async function listNotes(cwd) {
265
- let entries = [];
266
- try {
267
- entries = await readdir(notesDir(resolveMemoryRoot(cwd)));
268
- } catch {
269
- return [];
270
- }
271
- return entries.filter((name) => name.endsWith(".md")).map((name) => ({
272
- slug: name.replace(/\.md$/, ""),
273
- path: join(notesDir(resolveMemoryRoot(cwd)), name)
274
- }));
275
- }
276
-
277
- // src/internal/active-memory/active-memory.ts
278
- var SPAN_MEMORY_RECALL = "memory.recall";
279
- var HISTOGRAM_MEMORY_RECALL_DURATION_MS = "theokit_memory_recall_duration_ms";
280
- var DEFAULTS = {
281
- queryMode: "recent",
282
- timeoutMs: 15e3,
283
- maxSummaryChars: 220,
284
- recentUserTurns: 2
285
- };
286
- async function runActiveMemory(args) {
287
- const started = Date.now();
288
- const span = startMemoryRecallSpan(args);
289
- try {
290
- if (args.options.enabled !== true || args.index === void 0) {
291
- return endRecallSpan(span, args, {
292
- summary: void 0,
293
- durationMs: 0,
294
- status: "skipped",
295
- hits: []
296
- });
297
- }
298
- const cfg = { ...DEFAULTS, ...args.options };
299
- const breakerKey = args.agentKey ?? "default";
300
- if (args.breaker?.shouldSkip(breakerKey) === true) {
301
- return endRecallSpan(span, args, {
302
- summary: void 0,
303
- durationMs: 0,
304
- status: "skipped",
305
- hits: []
306
- });
307
- }
308
- const tenantCtx = {
309
- namespace: args.namespace,
310
- userId: args.userId,
311
- scope: args.scope
312
- };
313
- const cached = args.cache?.get(args.userText, cfg.queryMode, tenantCtx);
314
- if (cached !== void 0) return endRecallSpan(span, args, cached);
315
- const query = buildQuery(args.userText, args.priorMessages, cfg.queryMode, cfg.recentUserTurns);
316
- if (query.trim().length === 0) {
317
- const finalized2 = await finalize(args, cfg.queryMode, {
318
- summary: void 0,
319
- durationMs: Date.now() - started,
320
- status: "no-recall",
321
- hits: []
322
- });
323
- return endRecallSpan(span, args, finalized2);
324
- }
325
- const result = await searchOnce(args, cfg, query, started);
326
- notifyBreaker(args.breaker, breakerKey, result.status);
327
- const finalized = await finalize(args, cfg.queryMode, result);
328
- return endRecallSpan(span, args, finalized);
329
- } catch (cause) {
330
- span.recordException(cause);
331
- span.setStatus({ code: 2, message: cause instanceof Error ? cause.message : String(cause) });
332
- span.end();
333
- throw cause;
334
- }
335
- }
336
- function startMemoryRecallSpan(args) {
337
- const telemetry = args.telemetry;
338
- if (telemetry === void 0) {
339
- return {
340
- setAttribute: () => {
341
- },
342
- setAttributes: () => {
343
- },
344
- addEvent: () => {
345
- },
346
- setStatus: () => {
347
- },
348
- recordException: () => {
349
- },
350
- end: () => {
351
- },
352
- spanContext: () => ({ traceId: "0".repeat(32), spanId: "0".repeat(16) }),
353
- isRecording: () => false
354
- };
355
- }
356
- return telemetry.startSpan(SPAN_MEMORY_RECALL, {
357
- queryMode: args.options.queryMode ?? "recent",
358
- ...args.userId !== void 0 ? { userId: args.userId } : {},
359
- ...args.namespace !== void 0 ? { namespace: args.namespace } : {},
360
- ...args.scope !== void 0 ? { scope: args.scope } : {}
361
- });
362
- }
363
- function endRecallSpan(span, args, result) {
364
- span.setAttributes({
365
- hits: result.hits.length,
366
- status: result.status,
367
- durationMs: result.durationMs
368
- });
369
- span.end();
370
- args.telemetry?.recordHistogram(HISTOGRAM_MEMORY_RECALL_DURATION_MS, result.durationMs, {
371
- status: result.status,
372
- ...args.userId !== void 0 ? { userId: args.userId } : {},
373
- ...args.namespace !== void 0 ? { namespace: args.namespace } : {},
374
- ...args.scope !== void 0 ? { scope: args.scope } : {}
375
- });
376
- return result;
377
- }
378
- async function searchOnce(args, cfg, query, started) {
379
- if (args.index === void 0) {
380
- return { summary: void 0, durationMs: 0, status: "skipped", hits: [] };
381
- }
382
- try {
383
- const hits = await withTimeout(args.index.search(query, { maxResults: 5 }), cfg.timeoutMs);
384
- if (hits === "timeout") {
385
- return { summary: void 0, durationMs: Date.now() - started, status: "timeout", hits: [] };
386
- }
387
- if (hits.length === 0) {
388
- return {
389
- summary: void 0,
390
- durationMs: Date.now() - started,
391
- status: "no-recall",
392
- hits: []
393
- };
394
- }
395
- const summary = formatSummary(hits, cfg.maxSummaryChars);
396
- return { summary, durationMs: Date.now() - started, status: "ok", hits };
397
- } catch (cause) {
398
- const message = cause instanceof Error ? cause.message : String(cause);
399
- process.stderr.write(`[theokit-sdk] active-memory recall failed: ${message}
400
- `);
401
- return { summary: void 0, durationMs: Date.now() - started, status: "error", hits: [] };
402
- }
403
- }
404
- function notifyBreaker(breaker, key, status) {
405
- if (breaker === void 0) return;
406
- if (status === "timeout") breaker.recordTimeout(key);
407
- else if (status === "ok" || status === "no-recall") breaker.recordSuccess(key);
408
- }
409
- async function finalize(args, queryMode, result) {
410
- const tenantCtx = {
411
- namespace: args.namespace,
412
- userId: args.userId,
413
- scope: args.scope
414
- };
415
- args.cache?.set(args.userText, queryMode, result, tenantCtx);
416
- if (args.persistTranscripts === true && args.cwd !== void 0) {
417
- await persistActiveMemoryTranscript(resolveMemoryRoot(args.cwd), {
418
- runId: args.runId ?? `run-${Date.now()}`,
419
- startedAtMs: Date.now() - result.durationMs,
420
- userText: args.userText,
421
- queryMode,
422
- status: result.status,
423
- durationMs: result.durationMs,
424
- summary: result.summary,
425
- hits: result.hits.map((h) => ({
426
- path: h.path,
427
- startLine: h.startLine,
428
- endLine: h.endLine,
429
- score: h.score,
430
- snippet: h.snippet
431
- }))
432
- });
433
- }
434
- return result;
435
- }
436
- function buildQuery(userText, priorMessages, queryMode, recentUserTurns) {
437
- if (queryMode === "message") return userText;
438
- if (queryMode === "full") {
439
- const allUserTurns = priorMessages.filter((m) => m.role === "user").map((m) => m.text);
440
- return [...allUserTurns, userText].join("\n");
441
- }
442
- const recent = priorMessages.filter((m) => m.role === "user").slice(-recentUserTurns).map((m) => m.text);
443
- return [...recent, userText].join("\n");
444
- }
445
- function formatSummary(hits, maxChars) {
446
- const lines = hits.map((h) => `- ${h.citation}: ${h.snippet}`);
447
- let summary = lines.join("\n");
448
- if (summary.length > maxChars) summary = `${summary.slice(0, maxChars - 1)}\u2026`;
449
- return summary;
450
- }
451
- async function withTimeout(promise, timeoutMs) {
452
- let timer;
453
- const timeout = new Promise((resolve) => {
454
- timer = setTimeout(() => resolve("timeout"), timeoutMs);
455
- });
456
- try {
457
- const winner = await Promise.race([promise, timeout]);
458
- return winner;
459
- } finally {
460
- if (timer !== void 0) clearTimeout(timer);
461
- }
462
- }
463
264
 
464
265
  // src/internal/adapter-catalog.ts
465
266
  var MEMORY_EMBEDDING_ADAPTERS = {
@@ -748,122 +549,19 @@ function isSqliteVecLoaded(db) {
748
549
  return false;
749
550
  }
750
551
  }
751
- var SEARCH_DESCRIPTION = "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.";
752
- var GET_DESCRIPTION = "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 \u2014 attempts to read outside `.theokit/memory/` are rejected.";
753
- var MEMORY_SEARCH_SCHEMA = {
754
- type: "object",
755
- required: ["query"],
756
- properties: {
757
- query: { type: "string", description: "Natural-language query." },
758
- maxResults: { type: "integer", minimum: 1, maximum: 50 },
759
- minScore: { type: "number", minimum: 0, maximum: 1 },
760
- corpus: { type: "string", enum: ["memory", "sessions", "wiki", "all"] }
761
- },
762
- additionalProperties: false
763
- };
764
- var MEMORY_GET_SCHEMA = {
765
- type: "object",
766
- required: ["path"],
767
- properties: {
768
- path: { type: "string", description: "Path relative to .theokit/memory/" },
769
- from: { type: "integer", minimum: 1 },
770
- lines: { type: "integer", minimum: 1, maximum: 2e3 }
771
- },
772
- additionalProperties: false
773
- };
774
- var DEFAULT_MAX_TOTAL_CHARS = 16384;
775
- function createMemorySearchTool(opts) {
776
- const cap = opts.maxTotalChars ?? DEFAULT_MAX_TOTAL_CHARS;
777
- return {
778
- name: "memory_search",
779
- description: SEARCH_DESCRIPTION,
780
- inputSchema: MEMORY_SEARCH_SCHEMA,
781
- async execute(input) {
782
- const query = readString(input.query, "query is required");
783
- const maxResults = readNumber(input.maxResults) ?? 10;
784
- const minScore = readNumber(input.minScore);
785
- const corpus = readString(input.corpus, void 0, true);
786
- const sources = mapCorpusToSources(corpus);
787
- const searchOptions = {
788
- maxResults,
789
- ...minScore !== void 0 ? { minScore } : {},
790
- ...sources !== void 0 ? { sources } : {}
791
- };
792
- const hits = await opts.index.search(query, searchOptions);
793
- return JSON.stringify(capByTotalChars(hits, cap));
794
- }
795
- };
796
- }
797
- function createMemoryGetTool(opts) {
798
- const memoryRoot = resolve(opts.root);
799
- return {
800
- name: "memory_get",
801
- description: GET_DESCRIPTION,
802
- inputSchema: MEMORY_GET_SCHEMA,
803
- async execute(input) {
804
- const relPath = readString(input.path, "path is required");
805
- const from = readNumber(input.from);
806
- const lines = readNumber(input.lines);
807
- const resolved = resolve(memoryRoot, relPath);
808
- if (!isPathInside(memoryRoot, resolved)) {
809
- throw new ConfigurationError(
810
- `memory_get rejected path that escapes memory root: ${relPath}`,
811
- { code: "memory_path_escapes_root" }
812
- );
813
- }
814
- const readArgs = {
815
- cwd: memoryRoot,
816
- relPath
817
- };
818
- if (from !== void 0) readArgs.from = from;
819
- if (lines !== void 0) readArgs.lines = lines;
820
- const result = await readMemoryFileBounded(readArgs);
821
- return JSON.stringify(result);
822
- }
823
- };
824
- }
825
- function readString(value, errorIfMissing, allowUndefined = false) {
826
- if (typeof value === "string") return value;
827
- if (allowUndefined && (value === void 0 || value === null)) return "";
828
- if (errorIfMissing !== void 0) {
829
- throw new ConfigurationError(errorIfMissing, { code: "memory_tool_bad_args" });
830
- }
831
- return "";
832
- }
833
- function readNumber(value) {
834
- if (typeof value === "number" && Number.isFinite(value)) return value;
835
- if (typeof value === "string" && value.trim().length > 0) {
836
- const n = Number(value);
837
- if (Number.isFinite(n)) return n;
838
- }
839
- return void 0;
840
- }
841
- function mapCorpusToSources(corpus) {
842
- if (corpus === "" || corpus === "all") return void 0;
843
- if (corpus === "memory") return ["memory"];
844
- if (corpus === "wiki") return ["wiki"];
845
- if (corpus === "sessions") return ["sessions"];
846
- return void 0;
847
- }
848
- function capByTotalChars(hits, maxTotalChars) {
849
- if (hits.length === 0) return { hits: [], truncated: false };
850
- const kept = [];
851
- let runningChars = 0;
852
- for (const hit of hits) {
853
- const snippetLen = hit.snippet.length + (hit.citation?.length ?? 0) + 32;
854
- if (kept.length > 0 && runningChars + snippetLen > maxTotalChars) {
855
- return { hits: kept, truncated: true };
856
- }
857
- kept.push(hit);
858
- runningChars += snippetLen;
552
+ async function listNotes(cwd) {
553
+ let entries = [];
554
+ try {
555
+ entries = await readdir(notesDir(resolveMemoryRoot(cwd)));
556
+ } catch {
557
+ return [];
859
558
  }
860
- return { hits: kept, truncated: false };
861
- }
862
- function isPathInside(root, candidate) {
863
- const normalizedRoot = root.endsWith("/") ? root : `${root}/`;
864
- return candidate === root || candidate.startsWith(normalizedRoot);
559
+ return entries.filter((name) => name.endsWith(".md")).map((name) => ({
560
+ slug: name.replace(/\.md$/, ""),
561
+ path: join(notesDir(resolveMemoryRoot(cwd)), name)
562
+ }));
865
563
  }
866
564
 
867
- export { LanceMemoryAdapter, MEMORY_EMBEDDING_ADAPTERS, buildErrorMetadata, createCategorizedMemory, createInMemoryMarkdownProvider, createMemoryGetTool, createMemorySearchTool, isSqliteVecLoaded, legacyMemoryJsonPath, listNotes, mapOpenAICompatibleError, parseRetryAfter, redactSecrets, runActiveMemory, truncateRaw };
565
+ export { LanceMemoryAdapter, MEMORY_EMBEDDING_ADAPTERS, buildErrorMetadata, createCategorizedMemory, createInMemoryMarkdownProvider, isSqliteVecLoaded, legacyMemoryJsonPath, listNotes, mapOpenAICompatibleError, parseRetryAfter, redactSecrets, truncateRaw };
868
566
  //# sourceMappingURL=index.js.map
869
567
  //# sourceMappingURL=index.js.map