@theokit/sdk-memory 0.6.0 → 0.6.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (29) hide show
  1. package/CHANGELOG.md +6 -0
  2. package/dist/index.cjs +145 -501
  3. package/dist/index.cjs.map +1 -1
  4. package/dist/index.js +36 -467
  5. package/dist/index.js.map +1 -1
  6. package/dist/internal/active-memory/active-memory-cache.d.ts +1 -66
  7. package/dist/internal/active-memory/active-memory-cache.d.ts.map +1 -1
  8. package/dist/internal/active-memory/active-memory-types.d.ts +1 -54
  9. package/dist/internal/active-memory/active-memory-types.d.ts.map +1 -1
  10. package/dist/internal/adapter-http-error.d.ts.map +1 -1
  11. package/dist/internal/dreaming/dreaming-phases.d.ts +5 -53
  12. package/dist/internal/dreaming/dreaming-phases.d.ts.map +1 -1
  13. package/dist/internal/dreaming/dreaming-run.d.ts +3 -83
  14. package/dist/internal/dreaming/dreaming-run.d.ts.map +1 -1
  15. package/dist/internal/index/index-db.d.ts +1 -67
  16. package/dist/internal/index/index-db.d.ts.map +1 -1
  17. package/dist/internal/index/index-schema.d.ts +1 -29
  18. package/dist/internal/index/index-schema.d.ts.map +1 -1
  19. package/dist/internal/index/memory-index.d.ts +1 -10
  20. package/dist/internal/index/memory-index.d.ts.map +1 -1
  21. package/dist/internal/index/sqlite-vec-loader.d.ts +2 -59
  22. package/dist/internal/index/sqlite-vec-loader.d.ts.map +1 -1
  23. package/dist/internal/index/vec-index.d.ts +1 -131
  24. package/dist/internal/index/vec-index.d.ts.map +1 -1
  25. package/dist/internal/store/chunk-markdown.d.ts +1 -82
  26. package/dist/internal/store/chunk-markdown.d.ts.map +1 -1
  27. package/dist/internal/store/reader.d.ts +1 -86
  28. package/dist/internal/store/reader.d.ts.map +1 -1
  29. package/package.json +3 -3
package/dist/index.js CHANGED
@@ -1,14 +1,14 @@
1
1
  import { mkdir, readdir, readFile, stat, access, unlink } from 'fs/promises';
2
2
  import { join, resolve } from 'path';
3
3
  import { Security, ConfigurationError as ConfigurationError$1 } from '@theokit/sdk';
4
- import { resolveMaxFacts, notesDir, resolveMemoryRoot, persistActiveMemoryTranscript, readFactsFromMarkdown, appendDiaryEntry, lanceStoragePath, defaultIndexPath, projectMemoryDir, collectMarkdownFiles, readAllSqliteFacts, memoryMdPath, appendFactToMarkdown, ceilingReachedError } from '@theokit/sdk/internal/memory-store';
5
- export { MEMORY_INDEX_MAX_BYTES, MEMORY_INDEX_MAX_LINES, appendDiaryEntry, appendFact, appendFactToMarkdown, asMemoryRoot, ceilingReachedError, claudeProjectMemoryDir, collectMarkdownFiles, defaultIndexPath, diaryPath, discoverSessionFiles, discoverWikiFiles, entryHash, indexBudgetWarning, lanceStoragePath, memoryIndexRoot, memoryMdPath, memoryReadRoots, notesDir, persistActiveMemoryTranscript, projectMemoryDir, readAllSqliteFacts, readFacts, readFactsFromMarkdown, renderDiaryEntry, resolveMaxFacts, resolveMemoryRoot, sessionSummaryPath, sessionsDir, wikiDir, writeSessionSummary } from '@theokit/sdk/internal/memory-store';
6
- import { replaceFileAtomic, withCwdMutex, openSqliteResilient, sanitizeFts5Query } from '@theokit/sdk/persistence';
7
- import { createHash } from 'crypto';
4
+ import { resolveMaxFacts, notesDir, resolveMemoryRoot, persistActiveMemoryTranscript, lanceStoragePath, parseSearchOptions, defaultIndexPath, projectMemoryDir, openMemoryDb, loadSqliteVecExtension, readEmbeddingIdentity, identityMatches, dropVectorIndex, createVectorIndex, writeEmbeddingIdentity, collectMarkdownFiles, chunkMarkdown, embedMissingChunks, vectorSearch, readAllSqliteFacts, memoryMdPath, readMemoryFileBounded, appendFactToMarkdown, ceilingReachedError } from '@theokit/sdk/internal/memory-store';
5
+ export { ActiveMemoryCache, DEFAULT_MEMORY_READ_LINES, MEMORY_INDEX_MAX_BYTES, MEMORY_INDEX_MAX_LINES, META_KEY_DIMENSION, META_KEY_MODEL, META_KEY_PROVIDER_ID, PRAGMA_STATEMENTS, SCHEMA_STATEMENTS, appendDiaryEntry, appendFact, appendFactToMarkdown, asMemoryRoot, ceilingReachedError, chunkMarkdown, claudeProjectMemoryDir, collectMarkdownFiles, createVectorIndex, deepPhase, defaultIndexPath, diaryPath, discoverSessionFiles, discoverWikiFiles, dropVectorIndex, embedMissingChunks, entryHash, identityMatches, indexBudgetWarning, lanceStoragePath, lightPhase, loadSqliteVecExtension, memoryIndexRoot, memoryMdPath, memoryReadRoots, notesDir, openMemoryDb, packVector, parseSearchOptions, persistActiveMemoryTranscript, projectMemoryDir, readAllSqliteFacts, readEmbeddingIdentity, readFacts, readFactsFromMarkdown, readMemoryFileBounded, remPhase, renderDiaryEntry, resolveMaxFacts, resolveMemoryRoot, runDreamingSweep, sessionSummaryPath, sessionsDir, upsertEmbedding, vectorSearch, wikiDir, writeEmbeddingIdentity, writeSessionSummary } from '@theokit/sdk/internal/memory-store';
6
+ import { replaceFileAtomic, sanitizeFts5Query, withCwdMutex } from '@theokit/sdk/persistence';
8
7
  import { createOpenAiCompatibleRuntime } from '@theokit/sdk/internal/memory-adapters';
9
8
  export { createOpenAiCompatibleRuntime } from '@theokit/sdk/internal/memory-adapters';
10
9
  import { AuthenticationError, RateLimitError, ConfigurationError, NetworkError, UnknownAgentError } from '@theokit/sdk/errors';
11
10
  import { sanitizeIdentifier, safePathJoin } from '@theokit/sdk/path-safety';
11
+ import { createHash } from 'crypto';
12
12
  import { mkdirSync, existsSync, rmSync, renameSync } from 'fs';
13
13
  import { createRequire } from 'module';
14
14
 
@@ -504,48 +504,6 @@ var CircuitBreaker = class {
504
504
  return this.opts.now?.() ?? Date.now();
505
505
  }
506
506
  };
507
- var DEFAULT_TTL_MS = 15e3;
508
- var DEFAULT_CAPACITY = 1e3;
509
- var ActiveMemoryCache = class {
510
- constructor(opts = {}) {
511
- this.opts = opts;
512
- }
513
- opts;
514
- map = /* @__PURE__ */ new Map();
515
- get(userText, queryMode, tenantCtx) {
516
- const key = cacheKey(userText, queryMode, tenantCtx);
517
- const entry = this.map.get(key);
518
- if (entry === void 0) return void 0;
519
- if (this.now() >= entry.expiresAtMs) {
520
- this.map.delete(key);
521
- return void 0;
522
- }
523
- this.map.delete(key);
524
- this.map.set(key, entry);
525
- return entry.result;
526
- }
527
- set(userText, queryMode, result, tenantCtx) {
528
- const key = cacheKey(userText, queryMode, tenantCtx);
529
- if (this.map.size >= (this.opts.capacity ?? DEFAULT_CAPACITY)) {
530
- const oldest = this.map.keys().next().value;
531
- if (oldest !== void 0) this.map.delete(oldest);
532
- }
533
- this.map.set(key, {
534
- expiresAtMs: this.now() + (this.opts.ttlMs ?? DEFAULT_TTL_MS),
535
- result
536
- });
537
- }
538
- size() {
539
- return this.map.size;
540
- }
541
- now() {
542
- return this.opts.now?.() ?? Date.now();
543
- }
544
- };
545
- function cacheKey(userText, queryMode, ctx) {
546
- const parts = [queryMode, ctx?.namespace ?? "", ctx?.userId ?? "", ctx?.scope ?? "", userText];
547
- return createHash("sha256").update(parts.join("\0")).digest("hex");
548
- }
549
507
 
550
508
  // src/internal/embedding/azure-openai-embedding.ts
551
509
  var DEFAULT_AZURE_OPENAI_EMBEDDING_MODEL = "text-embedding-3-small";
@@ -885,6 +843,8 @@ function legacyMemoryJsonPath(cwd, config) {
885
843
 
886
844
  // src/internal/adapter-http-error.ts
887
845
  var RAW_MAX_BYTES = 2048;
846
+ var PROVIDER_DETAIL_MAX_CHARS = 512;
847
+ var MISSING_MODEL_MESSAGE = /no endpoints found/i;
888
848
  function parseRetryAfter(headers) {
889
849
  if (headers === void 0) return void 0;
890
850
  const raw = headers.get("retry-after");
@@ -896,8 +856,8 @@ function parseRetryAfter(headers) {
896
856
  function truncateRaw(body) {
897
857
  if (body === null || body === void 0) return void 0;
898
858
  const s = typeof body === "string" ? body : JSON.stringify(body);
899
- const truncated = s.length <= RAW_MAX_BYTES ? s : `${s.slice(0, RAW_MAX_BYTES)}\u2026`;
900
- return redactSecrets(truncated);
859
+ const redacted = redactSecrets(s);
860
+ return redacted.length <= RAW_MAX_BYTES ? redacted : `${redacted.slice(0, RAW_MAX_BYTES)}\u2026`;
901
861
  }
902
862
  function buildErrorMetadata(args) {
903
863
  const retryAfter = parseRetryAfter(args.headers);
@@ -929,8 +889,16 @@ function mapOpenAICompatibleError(args) {
929
889
  if (status === 429) {
930
890
  return new RateLimitError(message, { code: `${providerId}_rate_limit`, metadata });
931
891
  }
892
+ if (status === 404 && code === "model_unavailable") {
893
+ const detailed = formatMessage(providerId, status, code, boundedProviderDetail(body));
894
+ return new ConfigurationError(detailed, {
895
+ code: `${providerId}_model_unavailable`,
896
+ metadata
897
+ });
898
+ }
932
899
  if (status === 400) {
933
- return new ConfigurationError(message, { code: `${providerId}_${code}`, metadata });
900
+ const detailed = formatMessage(providerId, status, code, boundedProviderDetail(body));
901
+ return new ConfigurationError(detailed, { code: `${providerId}_${code}`, metadata });
934
902
  }
935
903
  if (status === 408) {
936
904
  return new NetworkError(message, { code: `${providerId}_timeout`, metadata });
@@ -940,6 +908,18 @@ function mapOpenAICompatibleError(args) {
940
908
  }
941
909
  return new UnknownAgentError(message, { code: `${providerId}_unknown`, metadata });
942
910
  }
911
+ function extractOpenAiErrorMessage(body) {
912
+ if (body === null || typeof body !== "object") return void 0;
913
+ const err = body.error;
914
+ if (err === void 0 || err === null) return void 0;
915
+ return typeof err.message === "string" ? err.message : void 0;
916
+ }
917
+ function boundedProviderDetail(body) {
918
+ const raw = extractOpenAiErrorMessage(body);
919
+ if (raw === void 0 || raw.trim() === "") return void 0;
920
+ const redacted = redactSecrets(raw);
921
+ return redacted.length <= PROVIDER_DETAIL_MAX_CHARS ? redacted : `${redacted.slice(0, PROVIDER_DETAIL_MAX_CHARS)}\u2026`;
922
+ }
943
923
  function extractOpenAiErrorCode(body) {
944
924
  if (body === null || typeof body !== "object") return void 0;
945
925
  const err = body.error;
@@ -962,6 +942,9 @@ function mapOpenAiStatusToCode(status, body) {
962
942
  if (status === 402 || rawCode.includes("insufficient_quota") || rawCode.includes("quota_exceeded")) {
963
943
  return "quota_exceeded";
964
944
  }
945
+ if (status === 404 && MISSING_MODEL_MESSAGE.test(extractOpenAiErrorMessage(body) ?? "")) {
946
+ return "model_unavailable";
947
+ }
965
948
  if (status === 401 || status === 403) return "auth_failed";
966
949
  if (status === 429) return "rate_limit";
967
950
  if (status === 408) return "timeout";
@@ -969,8 +952,9 @@ function mapOpenAiStatusToCode(status, body) {
969
952
  if (status >= 500 && status < 600) return "server_error";
970
953
  return "unknown";
971
954
  }
972
- function formatMessage(providerId, status, code) {
973
- return `${providerId} API error: ${code} (HTTP ${status})`;
955
+ function formatMessage(providerId, status, code, detail) {
956
+ const base = `${providerId} API error: ${code} (HTTP ${status})`;
957
+ return detail === void 0 || detail === "" ? base : `${base}: ${detail}`;
974
958
  }
975
959
  var FACTS_HEADING = "## Facts";
976
960
  function createCategorizedMemory(options) {
@@ -1098,298 +1082,6 @@ ${bullet}
1098
1082
  return `${raw.slice(0, insertAt)}
1099
1083
  ${bullet}${raw.slice(insertAt)}`;
1100
1084
  }
1101
-
1102
- // src/internal/dreaming/dreaming-phases.ts
1103
- var DEFAULT_DEDUP_THRESHOLD = 0.95;
1104
- var DEFAULT_CLUSTER_THRESHOLD = 0.75;
1105
- async function lightPhase(facts, embedding, threshold = DEFAULT_DEDUP_THRESHOLD) {
1106
- if (facts.length <= 1) return { kept: [...facts], duplicatesRemoved: 0 };
1107
- const vectors = await embedding.embed(facts.map((f) => f.text));
1108
- const keptIdx = [];
1109
- const keptVecs = [];
1110
- for (let i = 0; i < facts.length; i++) {
1111
- const vec = vectors[i] ?? [];
1112
- const isDup = keptVecs.some((kept2) => cosineSimilarity(vec, kept2) >= threshold);
1113
- if (isDup) continue;
1114
- keptIdx.push(i);
1115
- keptVecs.push(vec);
1116
- }
1117
- const kept = keptIdx.map((i) => facts[i]);
1118
- return { kept, duplicatesRemoved: facts.length - kept.length };
1119
- }
1120
- var DEFAULT_MAX_FACTS_PER_SWEEP = 500;
1121
- async function remPhase(facts, embedding, threshold = DEFAULT_CLUSTER_THRESHOLD, maxFactsPerSweep = DEFAULT_MAX_FACTS_PER_SWEEP) {
1122
- if (facts.length === 0) return { clusters: [], factsLeftOut: 0 };
1123
- const capped = facts.length > maxFactsPerSweep ? facts.slice(0, maxFactsPerSweep) : facts;
1124
- const vectors = await embedding.embed(capped.map((f) => f.text));
1125
- const clusterOfIdx = unionFindByPairs(vectors, threshold);
1126
- const groups = bucketFactsByClusterRoot(capped, clusterOfIdx);
1127
- return {
1128
- clusters: [...groups.values()].map(buildClusterFromMembers),
1129
- factsLeftOut: facts.length - capped.length
1130
- };
1131
- }
1132
- function unionFindByPairs(vectors, threshold) {
1133
- const clusterOfIdx = vectors.map((_, i) => i);
1134
- for (let i = 0; i < vectors.length; i++) {
1135
- for (let j = i + 1; j < vectors.length; j++) {
1136
- if (cosineSimilarity(vectors[i] ?? [], vectors[j] ?? []) >= threshold) {
1137
- unifyClusters(clusterOfIdx, i, j);
1138
- }
1139
- }
1140
- }
1141
- return clusterOfIdx;
1142
- }
1143
- function bucketFactsByClusterRoot(facts, clusterOfIdx) {
1144
- const groups = /* @__PURE__ */ new Map();
1145
- for (let i = 0; i < facts.length; i++) {
1146
- const root = findRoot(clusterOfIdx, i);
1147
- const list = groups.get(root) ?? [];
1148
- list.push(facts[i]);
1149
- groups.set(root, list);
1150
- }
1151
- return groups;
1152
- }
1153
- function buildClusterFromMembers(members) {
1154
- const sorted = [...members].sort((a, b) => b.text.length - a.text.length);
1155
- return { representativeText: sorted[0]?.text ?? "", members };
1156
- }
1157
- function deepPhase(clusters, timestampMs) {
1158
- if (clusters.length === 0) return "";
1159
- const isoStamp = new Date(timestampMs).toISOString();
1160
- const lines = [`# Dreamed ${isoStamp}`, ""];
1161
- for (let i = 0; i < clusters.length; i++) {
1162
- const c = clusters[i];
1163
- if (c === void 0) continue;
1164
- lines.push(`## Cluster ${i + 1}: ${c.representativeText}`);
1165
- lines.push("");
1166
- for (const member of c.members) lines.push(`- ${member.text}`);
1167
- lines.push("");
1168
- }
1169
- return `${lines.join("\n")}
1170
- `;
1171
- }
1172
- function cosineSimilarity(a, b) {
1173
- if (a.length === 0 || b.length === 0 || a.length !== b.length) return 0;
1174
- let dot = 0;
1175
- let aNorm = 0;
1176
- let bNorm = 0;
1177
- for (let i = 0; i < a.length; i++) {
1178
- const ai = a[i] ?? 0;
1179
- const bi = b[i] ?? 0;
1180
- dot += ai * bi;
1181
- aNorm += ai * ai;
1182
- bNorm += bi * bi;
1183
- }
1184
- const denom = Math.sqrt(aNorm) * Math.sqrt(bNorm);
1185
- return denom === 0 ? 0 : dot / denom;
1186
- }
1187
- function findRoot(parents, i) {
1188
- let root = i;
1189
- while (parents[root] !== root) {
1190
- const next = parents[root] ?? root;
1191
- if (next === root) break;
1192
- root = next;
1193
- }
1194
- parents[i] = root;
1195
- return root;
1196
- }
1197
- function unifyClusters(parents, a, b) {
1198
- const rootA = findRoot(parents, a);
1199
- const rootB = findRoot(parents, b);
1200
- if (rootA !== rootB) parents[rootB] = rootA;
1201
- }
1202
- function runDreamingSweep(options) {
1203
- return withCwdMutex(`dream:${options.cwd}`, () => runInner(options));
1204
- }
1205
- async function runInner(options) {
1206
- const now = options.now ?? Date.now;
1207
- const timestampMs = now();
1208
- try {
1209
- const facts = await readFactsFromMarkdown(options.cwd);
1210
- if (facts.length === 0) {
1211
- return emptyResult("skipped");
1212
- }
1213
- const dedup = await lightPhase(facts, options.embedding, options.dedupThreshold);
1214
- const rem = await remPhase(dedup.kept, options.embedding, options.clusterThreshold);
1215
- const notesWritten = await writeConsolidatedNotes(options.cwd, rem.clusters, timestampMs);
1216
- const result = {
1217
- status: "ok",
1218
- factsBefore: facts.length,
1219
- factsAfter: dedup.kept.length,
1220
- duplicatesRemoved: dedup.duplicatesRemoved,
1221
- clustersCreated: rem.clusters.length,
1222
- notesWritten,
1223
- diaryEntryHash: void 0,
1224
- factsLeftOut: rem.factsLeftOut
1225
- };
1226
- await appendDiaryEntry(resolveMemoryRoot(options.cwd), {
1227
- timestampMs,
1228
- factsBefore: result.factsBefore,
1229
- factsAfter: result.factsAfter,
1230
- duplicatesRemoved: result.duplicatesRemoved,
1231
- clustersCreated: result.clustersCreated,
1232
- notesWritten: result.notesWritten
1233
- });
1234
- return result;
1235
- } catch (cause) {
1236
- const message = cause instanceof Error ? cause.message : String(cause);
1237
- process.stderr.write(`[theokit-sdk] dreaming sweep failed: ${message}
1238
- `);
1239
- return emptyResult("error");
1240
- }
1241
- }
1242
- async function writeConsolidatedNotes(cwd, clusters, timestampMs) {
1243
- if (clusters.length === 0) return 0;
1244
- const notesDir3 = join(resolveMemoryRoot(cwd), "notes");
1245
- await mkdir(notesDir3, { recursive: true });
1246
- const isoSlug = new Date(timestampMs).toISOString().replace(/[^\dT]/g, "-");
1247
- const file = join(notesDir3, `dreamed-${isoSlug}.md`);
1248
- const body = deepPhase(clusters, timestampMs);
1249
- await replaceFileAtomic(file, body);
1250
- return 1;
1251
- }
1252
- function emptyResult(status) {
1253
- const result = {
1254
- status,
1255
- factsBefore: 0,
1256
- factsAfter: 0,
1257
- duplicatesRemoved: 0,
1258
- clustersCreated: 0,
1259
- notesWritten: 0,
1260
- diaryEntryHash: void 0
1261
- };
1262
- return status === "skipped" ? { ...result, factsLeftOut: 0 } : result;
1263
- }
1264
-
1265
- // src/internal/index/index-schema.ts
1266
- var SCHEMA_STATEMENTS = [
1267
- `CREATE TABLE IF NOT EXISTS files (
1268
- id INTEGER PRIMARY KEY AUTOINCREMENT,
1269
- path TEXT UNIQUE NOT NULL,
1270
- rel_path TEXT NOT NULL,
1271
- mtime INTEGER NOT NULL,
1272
- hash TEXT NOT NULL,
1273
- source TEXT NOT NULL DEFAULT 'memory'
1274
- )`,
1275
- `CREATE TABLE IF NOT EXISTS chunks (
1276
- id INTEGER PRIMARY KEY AUTOINCREMENT,
1277
- file_id INTEGER NOT NULL REFERENCES files(id) ON DELETE CASCADE,
1278
- start_line INTEGER NOT NULL,
1279
- end_line INTEGER NOT NULL,
1280
- text TEXT NOT NULL,
1281
- hash TEXT NOT NULL,
1282
- session_key TEXT
1283
- )`,
1284
- `CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5(
1285
- text,
1286
- content='chunks',
1287
- content_rowid='id'
1288
- )`,
1289
- `CREATE TRIGGER IF NOT EXISTS chunks_fts_insert AFTER INSERT ON chunks BEGIN
1290
- INSERT INTO chunks_fts(rowid, text) VALUES (new.id, new.text);
1291
- END`,
1292
- `CREATE TRIGGER IF NOT EXISTS chunks_fts_delete AFTER DELETE ON chunks BEGIN
1293
- INSERT INTO chunks_fts(chunks_fts, rowid, text) VALUES ('delete', old.id, old.text);
1294
- END`,
1295
- `CREATE TABLE IF NOT EXISTS meta (
1296
- key TEXT PRIMARY KEY,
1297
- value TEXT
1298
- )`,
1299
- `CREATE INDEX IF NOT EXISTS idx_chunks_file_id ON chunks(file_id)`
1300
- ];
1301
- var PRAGMA_STATEMENTS = [
1302
- "PRAGMA synchronous=NORMAL",
1303
- "PRAGMA foreign_keys=ON"
1304
- ];
1305
-
1306
- // src/internal/index/index-db.ts
1307
- async function openMemoryDb(opts) {
1308
- return openSqliteResilient({
1309
- filePath: opts.filePath,
1310
- label: "memory-index",
1311
- recoverCorrupt: opts.recoverCorrupt,
1312
- onOpen: (db) => {
1313
- for (const pragma of PRAGMA_STATEMENTS) db.exec(pragma);
1314
- for (const stmt of SCHEMA_STATEMENTS) db.exec(stmt);
1315
- }
1316
- });
1317
- }
1318
- var HEADING_RE = /^(#{1,6})\s+(.+?)\s*$/;
1319
- function chunkMarkdown(text, options = {}) {
1320
- const maxChars = options.maxChars ?? 800;
1321
- if (text.length === 0) return [];
1322
- const lines = text.split("\n");
1323
- const acc = { chunks: [], lines: [], start: 1, heading: void 0 };
1324
- for (let i = 0; i < lines.length; i++) {
1325
- const line = lines[i] ?? "";
1326
- const lineNumber = i + 1;
1327
- processLine(acc, line, lineNumber, maxChars);
1328
- }
1329
- flushAccumulator(acc, lines.length, maxChars);
1330
- return acc.chunks;
1331
- }
1332
- function processLine(acc, line, lineNumber, maxChars) {
1333
- const headingMatch = HEADING_RE.exec(line);
1334
- const isBlank = line.trim().length === 0;
1335
- if (headingMatch !== null && acc.lines.length > 0) {
1336
- flushAccumulator(acc, lineNumber - 1, maxChars);
1337
- }
1338
- if (headingMatch !== null) acc.heading = headingMatch[2];
1339
- acc.lines.push(line);
1340
- if (isBlank && acc.lines.length > 1) {
1341
- const joined = acc.lines.join("\n");
1342
- if (joined.trim().length > 0) flushAccumulator(acc, lineNumber, maxChars);
1343
- }
1344
- }
1345
- function flushAccumulator(acc, endLineExclusive, maxChars) {
1346
- if (acc.lines.length === 0) return;
1347
- const chunkText = acc.lines.join("\n");
1348
- if (chunkText.trim().length === 0) {
1349
- acc.lines = [];
1350
- acc.start = endLineExclusive + 1;
1351
- return;
1352
- }
1353
- if (chunkText.length > maxChars) {
1354
- pushOversizedSlices(acc.chunks, chunkText, acc.start, acc.heading, maxChars);
1355
- } else {
1356
- acc.chunks.push(buildChunk(chunkText, acc.start, endLineExclusive, acc.heading));
1357
- }
1358
- acc.lines = [];
1359
- acc.start = endLineExclusive + 1;
1360
- }
1361
- function buildChunk(text, startLine, endLine, heading) {
1362
- return {
1363
- startLine,
1364
- endLine,
1365
- text,
1366
- hash: createHash("sha256").update(text).digest("hex"),
1367
- ...heading !== void 0 ? { heading } : {}
1368
- };
1369
- }
1370
- function pushOversizedSlices(chunks, text, startLine, heading, maxChars) {
1371
- let remaining = text;
1372
- let lineCursor = startLine;
1373
- while (remaining.length > maxChars) {
1374
- const splitAt = findWordBoundarySplit(remaining, maxChars);
1375
- const slice = remaining.slice(0, splitAt);
1376
- const sliceLines = slice.split("\n").length;
1377
- chunks.push(buildChunk(slice, lineCursor, lineCursor + sliceLines - 1, heading));
1378
- remaining = remaining.slice(splitAt).replace(/^\s+/, "");
1379
- lineCursor += sliceLines - 1;
1380
- }
1381
- if (remaining.length > 0) {
1382
- const sliceLines = remaining.split("\n").length;
1383
- chunks.push(buildChunk(remaining, lineCursor, lineCursor + sliceLines - 1, heading));
1384
- }
1385
- }
1386
- function findWordBoundarySplit(text, maxChars) {
1387
- if (text.length <= maxChars) return text.length;
1388
- for (let i = maxChars; i > Math.max(0, maxChars - 200); i--) {
1389
- if (/\s/.test(text[i] ?? "x")) return i;
1390
- }
1391
- return maxChars;
1392
- }
1393
1085
  function requireLance() {
1394
1086
  try {
1395
1087
  const r = createRequire(import.meta.url);
@@ -1515,14 +1207,6 @@ function isLanceAvailable() {
1515
1207
  }
1516
1208
  }
1517
1209
 
1518
- // src/internal/index/memory-index.ts
1519
- function parseSearchOptions(options = {}) {
1520
- return {
1521
- maxResults: Math.max(1, options.maxResults ?? 10),
1522
- minScore: options.minScore ?? 0
1523
- };
1524
- }
1525
-
1526
1210
  // src/internal/index/lance-memory-adapter.ts
1527
1211
  var DEFAULT_NAMESPACE = "default";
1528
1212
  var EMPTY_SYNC_RESULT = Object.freeze({
@@ -1612,22 +1296,6 @@ async function openLanceIndex(opts) {
1612
1296
  });
1613
1297
  return new LanceMemoryAdapter(lance);
1614
1298
  }
1615
- async function loadSqliteVecExtension(db) {
1616
- try {
1617
- const mod = await import('sqlite-vec');
1618
- const loadFn = mod.load;
1619
- if (typeof loadFn !== "function") {
1620
- throw new Error("sqlite-vec module exposes no `load` export");
1621
- }
1622
- loadFn(db);
1623
- } catch (cause) {
1624
- const message = cause instanceof Error ? cause.message : String(cause);
1625
- throw new ConfigurationError(
1626
- `sqlite-vec extension unavailable. Install \`sqlite-vec\` and ensure the native binary matches your Node + OS. Cause: ${message}`,
1627
- { code: "sqlite_vec_unavailable", cause }
1628
- );
1629
- }
1630
- }
1631
1299
  function isSqliteVecLoaded(db) {
1632
1300
  try {
1633
1301
  const row = db.prepare("SELECT vec_version() as v").get();
@@ -1637,80 +1305,6 @@ function isSqliteVecLoaded(db) {
1637
1305
  }
1638
1306
  }
1639
1307
 
1640
- // src/internal/index/vec-index.ts
1641
- var META_KEY_PROVIDER_ID = "embedding.providerId";
1642
- var META_KEY_MODEL = "embedding.model";
1643
- var META_KEY_DIMENSION = "embedding.dimension";
1644
- function readEmbeddingIdentity(db) {
1645
- const get = (key) => {
1646
- const row = db.prepare("SELECT value FROM meta WHERE key = ?").get(key);
1647
- return row !== void 0 ? String(row.value) : void 0;
1648
- };
1649
- const providerId = get(META_KEY_PROVIDER_ID);
1650
- const model = get(META_KEY_MODEL);
1651
- const dimRaw = get(META_KEY_DIMENSION);
1652
- if (providerId === void 0 || model === void 0 || dimRaw === void 0) return void 0;
1653
- const dimension = Number(dimRaw);
1654
- if (!Number.isFinite(dimension) || dimension <= 0) return void 0;
1655
- return { providerId, model, dimension };
1656
- }
1657
- function writeEmbeddingIdentity(db, identity) {
1658
- const stmt = db.prepare(
1659
- "INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
1660
- );
1661
- stmt.run(META_KEY_PROVIDER_ID, identity.providerId);
1662
- stmt.run(META_KEY_MODEL, identity.model);
1663
- stmt.run(META_KEY_DIMENSION, String(identity.dimension));
1664
- }
1665
- function identityMatches(a, b) {
1666
- return a.providerId === b.providerId && a.model === b.model && a.dimension === b.dimension;
1667
- }
1668
- function dropVectorIndex(db) {
1669
- db.exec("DROP TABLE IF EXISTS embeddings");
1670
- }
1671
- function createVectorIndex(db, dimension) {
1672
- db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS embeddings USING vec0(
1673
- chunk_id INTEGER PRIMARY KEY,
1674
- vec FLOAT[${dimension}]
1675
- )`);
1676
- }
1677
- function packVector(vec) {
1678
- const f32 = new Float32Array(vec.length);
1679
- for (let i = 0; i < vec.length; i++) f32[i] = vec[i] ?? 0;
1680
- return Buffer.from(f32.buffer);
1681
- }
1682
- function upsertEmbedding(db, chunkId, vec) {
1683
- const id = BigInt(chunkId);
1684
- db.prepare("DELETE FROM embeddings WHERE chunk_id = ?").run(id);
1685
- db.prepare("INSERT INTO embeddings (chunk_id, vec) VALUES (?, ?)").run(id, packVector(vec));
1686
- }
1687
- function vectorSearch(db, query, k) {
1688
- const rows = db.prepare(
1689
- `SELECT chunk_id, distance FROM embeddings
1690
- WHERE vec MATCH ? AND k = ?
1691
- ORDER BY distance`
1692
- ).all(packVector(query), BigInt(k));
1693
- return rows.map((row) => ({ chunk_id: Number(row.chunk_id), distance: Number(row.distance) }));
1694
- }
1695
- async function embedMissingChunks(args) {
1696
- const rows = args.db.prepare(
1697
- `SELECT chunks.id as id, chunks.text as text
1698
- FROM chunks
1699
- LEFT JOIN embeddings ON embeddings.chunk_id = chunks.id
1700
- WHERE embeddings.chunk_id IS NULL`
1701
- ).all();
1702
- if (rows.length === 0) return 0;
1703
- const normalized = rows.map((row) => ({ id: Number(row.id), text: String(row.text ?? "") }));
1704
- const vectors = await args.runtime.embed(normalized.map((r) => r.text));
1705
- for (let i = 0; i < normalized.length; i++) {
1706
- const row = normalized[i];
1707
- const vector = vectors[i];
1708
- if (row === void 0 || vector === void 0) continue;
1709
- upsertEmbedding(args.db, row.id, vector);
1710
- }
1711
- return normalized.length;
1712
- }
1713
-
1714
1308
  // src/internal/index/index-manager.ts
1715
1309
  var IndexManager = class _IndexManager {
1716
1310
  constructor(memoryRoot, db, embedding) {
@@ -2138,31 +1732,6 @@ async function migrateLegacyJson(cwd, config) {
2138
1732
  function resetMigrationStateForTests() {
2139
1733
  migrationRun.clear();
2140
1734
  }
2141
- var DEFAULT_MEMORY_READ_LINES = 200;
2142
- async function readMemoryFileBounded(opts) {
2143
- const absolutePath = resolve(opts.cwd, opts.relPath);
2144
- const raw = await readFile(absolutePath, "utf8");
2145
- const allLines = raw.split("\n");
2146
- const trimmedLines = allLines.length > 0 && allLines[allLines.length - 1] === "" ? allLines.slice(0, -1) : allLines;
2147
- const totalLines = trimmedLines.length;
2148
- const requestedFrom = Math.max(1, opts.from ?? 1);
2149
- const requestedLines = Math.max(1, opts.lines ?? DEFAULT_MEMORY_READ_LINES);
2150
- const startIdx = requestedFrom - 1;
2151
- const endIdx = Math.min(totalLines, startIdx + requestedLines);
2152
- const slice = trimmedLines.slice(startIdx, endIdx);
2153
- const linesReturned = slice.length;
2154
- const remainingLines = Math.max(0, totalLines - endIdx);
2155
- const truncated = remainingLines > 0;
2156
- return {
2157
- path: opts.relPath,
2158
- from: requestedFrom,
2159
- linesReturned,
2160
- totalLines,
2161
- truncated,
2162
- remainingLines,
2163
- text: slice.join("\n")
2164
- };
2165
- }
2166
1735
  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.";
2167
1736
  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.";
2168
1737
  var MEMORY_SEARCH_SCHEMA = {
@@ -2279,6 +1848,6 @@ function isPathInside(root, candidate) {
2279
1848
  return candidate === root || candidate.startsWith(normalizedRoot);
2280
1849
  }
2281
1850
 
2282
- export { ActiveMemoryCache, CircuitBreaker, DEFAULT_AZURE_OPENAI_EMBEDDING_MODEL, DEFAULT_COHERE_EMBEDDING_MODEL, DEFAULT_DEEPINFRA_EMBEDDING_MODEL, DEFAULT_GEMINI_EMBEDDING_MODEL, DEFAULT_JINA_EMBEDDING_MODEL, DEFAULT_MEMORY_READ_LINES, DEFAULT_MISTRAL_EMBEDDING_MODEL, DEFAULT_OLLAMA_EMBEDDING_MODEL, DEFAULT_OPENAI_EMBEDDING_MODEL, DEFAULT_OPENROUTER_EMBEDDING_MODEL, DEFAULT_VOYAGE_EMBEDDING_MODEL, IndexManager, LanceIndex, LanceMemoryAdapter, MEMORY_EMBEDDING_ADAPTERS, META_KEY_DIMENSION, META_KEY_MODEL, META_KEY_PROVIDER_ID, PRAGMA_STATEMENTS, SCHEMA_STATEMENTS, VALID_BACKENDS, assertValidBackend, azureOpenAiMemoryEmbeddingProviderAdapter, buildErrorMetadata, chunkMarkdown, cohereMemoryEmbeddingProviderAdapter, createCategorizedMemory, createInMemoryMarkdownProvider, createMemoryGetTool, createMemorySearchTool, createVectorIndex, deepPhase, deepinfraMemoryEmbeddingProviderAdapter, dropVectorIndex, embedMissingChunks, geminiMemoryEmbeddingProviderAdapter, identityMatches, isLanceAvailable, isSqliteVecLoaded, jinaMemoryEmbeddingProviderAdapter, legacyMemoryJsonPath, lightPhase, listNotes, loadSqliteVecExtension, mapOpenAICompatibleError, migrateLegacyJson, migrateSqliteToLance, mistralMemoryEmbeddingProviderAdapter, ollamaMemoryEmbeddingProviderAdapter, openAiMemoryEmbeddingProviderAdapter, openLanceIndex, openMemoryDb, openRouterMemoryEmbeddingProviderAdapter, packVector, parseRetryAfter, parseSearchOptions, readEmbeddingIdentity, readMemoryFileBounded, redactSecrets, remPhase, resetMigrationStateForTests, runActiveMemory, runDreamingSweep, truncateRaw, upsertEmbedding, vectorSearch, voyageMemoryEmbeddingProviderAdapter, writeEmbeddingIdentity };
1851
+ export { CircuitBreaker, 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, IndexManager, LanceIndex, LanceMemoryAdapter, MEMORY_EMBEDDING_ADAPTERS, VALID_BACKENDS, assertValidBackend, azureOpenAiMemoryEmbeddingProviderAdapter, buildErrorMetadata, cohereMemoryEmbeddingProviderAdapter, createCategorizedMemory, createInMemoryMarkdownProvider, createMemoryGetTool, createMemorySearchTool, deepinfraMemoryEmbeddingProviderAdapter, geminiMemoryEmbeddingProviderAdapter, isLanceAvailable, isSqliteVecLoaded, jinaMemoryEmbeddingProviderAdapter, legacyMemoryJsonPath, listNotes, mapOpenAICompatibleError, migrateLegacyJson, migrateSqliteToLance, mistralMemoryEmbeddingProviderAdapter, ollamaMemoryEmbeddingProviderAdapter, openAiMemoryEmbeddingProviderAdapter, openLanceIndex, openRouterMemoryEmbeddingProviderAdapter, parseRetryAfter, redactSecrets, resetMigrationStateForTests, runActiveMemory, truncateRaw, voyageMemoryEmbeddingProviderAdapter };
2283
1852
  //# sourceMappingURL=index.js.map
2284
1853
  //# sourceMappingURL=index.js.map