@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/CHANGELOG.md CHANGED
@@ -1,5 +1,11 @@
1
1
  # Changelog — @theokit/sdk-memory
2
2
 
3
+ ## 0.7.4
4
+
5
+ ### Patch Changes
6
+
7
+ - [#1474](https://github.com/usetheokit/theokit-sdk/pull/1474) [`69282a9`](https://github.com/usetheokit/theokit-sdk/commit/69282a9e4cb1e8e5869bbc1ce16ecb014dc80bde) Thanks [@aifactory-paulohenriquevn](https://github.com/apps/aifactory-paulohenriquevn)! - `@theokit/sdk-memory` now re-exports `runActiveMemory` and the `memory_search` / `memory_get` tool factories from `@theokit/sdk` instead of carrying copies, so a fix to one reaches users of the other. The SDK's recall and tool options now accept any index that has `search`.
8
+
3
9
  ## 0.7.3
4
10
 
5
11
  ### Patch Changes
package/dist/index.cjs CHANGED
@@ -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 promises.readdir(memoryStore.notesDir(memoryStore.resolveMemoryRoot(cwd)));
268
- } catch {
269
- return [];
270
- }
271
- return entries.filter((name) => name.endsWith(".md")).map((name) => ({
272
- slug: name.replace(/\.md$/, ""),
273
- path: path.join(memoryStore.notesDir(memoryStore.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 memoryStore.persistActiveMemoryTranscript(memoryStore.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,120 +549,17 @@ 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 = path.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 = path.resolve(memoryRoot, relPath);
808
- if (!isPathInside(memoryRoot, resolved)) {
809
- throw new errors.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 memoryStore.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 errors.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 promises.readdir(memoryStore.notesDir(memoryStore.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: path.join(memoryStore.notesDir(memoryStore.resolveMemoryRoot(cwd)), name)
562
+ }));
865
563
  }
866
564
 
867
565
  Object.defineProperty(exports, "CircuitBreaker", {
@@ -952,6 +650,14 @@ Object.defineProperty(exports, "collectMarkdownFiles", {
952
650
  enumerable: true,
953
651
  get: function () { return memoryStore.collectMarkdownFiles; }
954
652
  });
653
+ Object.defineProperty(exports, "createMemoryGetTool", {
654
+ enumerable: true,
655
+ get: function () { return memoryStore.createMemoryGetTool; }
656
+ });
657
+ Object.defineProperty(exports, "createMemorySearchTool", {
658
+ enumerable: true,
659
+ get: function () { return memoryStore.createMemorySearchTool; }
660
+ });
955
661
  Object.defineProperty(exports, "createVectorIndex", {
956
662
  enumerable: true,
957
663
  get: function () { return memoryStore.createVectorIndex; }
@@ -1116,6 +822,10 @@ Object.defineProperty(exports, "resolveMemoryRoot", {
1116
822
  enumerable: true,
1117
823
  get: function () { return memoryStore.resolveMemoryRoot; }
1118
824
  });
825
+ Object.defineProperty(exports, "runActiveMemory", {
826
+ enumerable: true,
827
+ get: function () { return memoryStore.runActiveMemory; }
828
+ });
1119
829
  Object.defineProperty(exports, "runDreamingSweep", {
1120
830
  enumerable: true,
1121
831
  get: function () { return memoryStore.runDreamingSweep; }
@@ -1241,15 +951,12 @@ exports.MEMORY_EMBEDDING_ADAPTERS = MEMORY_EMBEDDING_ADAPTERS;
1241
951
  exports.buildErrorMetadata = buildErrorMetadata;
1242
952
  exports.createCategorizedMemory = createCategorizedMemory;
1243
953
  exports.createInMemoryMarkdownProvider = createInMemoryMarkdownProvider;
1244
- exports.createMemoryGetTool = createMemoryGetTool;
1245
- exports.createMemorySearchTool = createMemorySearchTool;
1246
954
  exports.isSqliteVecLoaded = isSqliteVecLoaded;
1247
955
  exports.legacyMemoryJsonPath = legacyMemoryJsonPath;
1248
956
  exports.listNotes = listNotes;
1249
957
  exports.mapOpenAICompatibleError = mapOpenAICompatibleError;
1250
958
  exports.parseRetryAfter = parseRetryAfter;
1251
959
  exports.redactSecrets = redactSecrets;
1252
- exports.runActiveMemory = runActiveMemory;
1253
960
  exports.truncateRaw = truncateRaw;
1254
961
  //# sourceMappingURL=index.cjs.map
1255
962
  //# sourceMappingURL=index.cjs.map