@theokit/sdk-memory 0.6.0 → 0.6.2
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 +19 -0
- package/dist/index.cjs +174 -1138
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +42 -1107
- package/dist/index.js.map +1 -1
- package/dist/internal/active-memory/active-memory-cache.d.ts +1 -66
- package/dist/internal/active-memory/active-memory-cache.d.ts.map +1 -1
- package/dist/internal/active-memory/active-memory-types.d.ts +1 -54
- package/dist/internal/active-memory/active-memory-types.d.ts.map +1 -1
- package/dist/internal/adapter-http-error.d.ts.map +1 -1
- package/dist/internal/dreaming/dreaming-phases.d.ts +5 -53
- package/dist/internal/dreaming/dreaming-phases.d.ts.map +1 -1
- package/dist/internal/dreaming/dreaming-run.d.ts +3 -83
- package/dist/internal/dreaming/dreaming-run.d.ts.map +1 -1
- package/dist/internal/index/index-db.d.ts +1 -67
- package/dist/internal/index/index-db.d.ts.map +1 -1
- package/dist/internal/index/index-manager-dispatch.d.ts +1 -35
- package/dist/internal/index/index-manager-dispatch.d.ts.map +1 -1
- package/dist/internal/index/index-manager.d.ts +1 -130
- package/dist/internal/index/index-manager.d.ts.map +1 -1
- package/dist/internal/index/index-schema.d.ts +1 -29
- package/dist/internal/index/index-schema.d.ts.map +1 -1
- package/dist/internal/index/lance-index.d.ts +1 -91
- package/dist/internal/index/lance-index.d.ts.map +1 -1
- package/dist/internal/index/lance-memory-adapter.d.ts +16 -115
- package/dist/internal/index/lance-memory-adapter.d.ts.map +1 -1
- package/dist/internal/index/memory-index.d.ts +3 -12
- package/dist/internal/index/memory-index.d.ts.map +1 -1
- package/dist/internal/index/migrate-sqlite-to-lance.d.ts +1 -65
- package/dist/internal/index/migrate-sqlite-to-lance.d.ts.map +1 -1
- package/dist/internal/index/migration.d.ts +1 -35
- package/dist/internal/index/migration.d.ts.map +1 -1
- package/dist/internal/index/sqlite-vec-loader.d.ts +2 -59
- package/dist/internal/index/sqlite-vec-loader.d.ts.map +1 -1
- package/dist/internal/index/vec-index.d.ts +1 -131
- package/dist/internal/index/vec-index.d.ts.map +1 -1
- package/dist/internal/store/chunk-markdown.d.ts +1 -82
- package/dist/internal/store/chunk-markdown.d.ts.map +1 -1
- package/dist/internal/store/reader.d.ts +1 -86
- package/dist/internal/store/reader.d.ts.map +1 -1
- package/package.json +3 -3
package/dist/index.cjs
CHANGED
|
@@ -5,14 +5,10 @@ var path = require('path');
|
|
|
5
5
|
var sdk = require('@theokit/sdk');
|
|
6
6
|
var memoryStore = require('@theokit/sdk/internal/memory-store');
|
|
7
7
|
var persistence = require('@theokit/sdk/persistence');
|
|
8
|
-
var crypto = require('crypto');
|
|
9
8
|
var memoryAdapters = require('@theokit/sdk/internal/memory-adapters');
|
|
10
9
|
var errors = require('@theokit/sdk/errors');
|
|
11
10
|
var pathSafety = require('@theokit/sdk/path-safety');
|
|
12
|
-
var fs = require('fs');
|
|
13
|
-
var module$1 = require('module');
|
|
14
11
|
|
|
15
|
-
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
|
|
16
12
|
// src/in-memory-provider.ts
|
|
17
13
|
var ADAPTER_ID = "in-memory-md";
|
|
18
14
|
var IN_MEMORY_REMEDY = "merge or delete facts with the adapter's delete(id), or raise maxFacts";
|
|
@@ -505,48 +501,6 @@ var CircuitBreaker = class {
|
|
|
505
501
|
return this.opts.now?.() ?? Date.now();
|
|
506
502
|
}
|
|
507
503
|
};
|
|
508
|
-
var DEFAULT_TTL_MS = 15e3;
|
|
509
|
-
var DEFAULT_CAPACITY = 1e3;
|
|
510
|
-
var ActiveMemoryCache = class {
|
|
511
|
-
constructor(opts = {}) {
|
|
512
|
-
this.opts = opts;
|
|
513
|
-
}
|
|
514
|
-
opts;
|
|
515
|
-
map = /* @__PURE__ */ new Map();
|
|
516
|
-
get(userText, queryMode, tenantCtx) {
|
|
517
|
-
const key = cacheKey(userText, queryMode, tenantCtx);
|
|
518
|
-
const entry = this.map.get(key);
|
|
519
|
-
if (entry === void 0) return void 0;
|
|
520
|
-
if (this.now() >= entry.expiresAtMs) {
|
|
521
|
-
this.map.delete(key);
|
|
522
|
-
return void 0;
|
|
523
|
-
}
|
|
524
|
-
this.map.delete(key);
|
|
525
|
-
this.map.set(key, entry);
|
|
526
|
-
return entry.result;
|
|
527
|
-
}
|
|
528
|
-
set(userText, queryMode, result, tenantCtx) {
|
|
529
|
-
const key = cacheKey(userText, queryMode, tenantCtx);
|
|
530
|
-
if (this.map.size >= (this.opts.capacity ?? DEFAULT_CAPACITY)) {
|
|
531
|
-
const oldest = this.map.keys().next().value;
|
|
532
|
-
if (oldest !== void 0) this.map.delete(oldest);
|
|
533
|
-
}
|
|
534
|
-
this.map.set(key, {
|
|
535
|
-
expiresAtMs: this.now() + (this.opts.ttlMs ?? DEFAULT_TTL_MS),
|
|
536
|
-
result
|
|
537
|
-
});
|
|
538
|
-
}
|
|
539
|
-
size() {
|
|
540
|
-
return this.map.size;
|
|
541
|
-
}
|
|
542
|
-
now() {
|
|
543
|
-
return this.opts.now?.() ?? Date.now();
|
|
544
|
-
}
|
|
545
|
-
};
|
|
546
|
-
function cacheKey(userText, queryMode, ctx) {
|
|
547
|
-
const parts = [queryMode, ctx?.namespace ?? "", ctx?.userId ?? "", ctx?.scope ?? "", userText];
|
|
548
|
-
return crypto.createHash("sha256").update(parts.join("\0")).digest("hex");
|
|
549
|
-
}
|
|
550
504
|
|
|
551
505
|
// src/internal/embedding/azure-openai-embedding.ts
|
|
552
506
|
var DEFAULT_AZURE_OPENAI_EMBEDDING_MODEL = "text-embedding-3-small";
|
|
@@ -886,6 +840,8 @@ function legacyMemoryJsonPath(cwd, config) {
|
|
|
886
840
|
|
|
887
841
|
// src/internal/adapter-http-error.ts
|
|
888
842
|
var RAW_MAX_BYTES = 2048;
|
|
843
|
+
var PROVIDER_DETAIL_MAX_CHARS = 512;
|
|
844
|
+
var MISSING_MODEL_MESSAGE = /no endpoints found/i;
|
|
889
845
|
function parseRetryAfter(headers) {
|
|
890
846
|
if (headers === void 0) return void 0;
|
|
891
847
|
const raw = headers.get("retry-after");
|
|
@@ -897,8 +853,8 @@ function parseRetryAfter(headers) {
|
|
|
897
853
|
function truncateRaw(body) {
|
|
898
854
|
if (body === null || body === void 0) return void 0;
|
|
899
855
|
const s = typeof body === "string" ? body : JSON.stringify(body);
|
|
900
|
-
const
|
|
901
|
-
return
|
|
856
|
+
const redacted = redactSecrets(s);
|
|
857
|
+
return redacted.length <= RAW_MAX_BYTES ? redacted : `${redacted.slice(0, RAW_MAX_BYTES)}\u2026`;
|
|
902
858
|
}
|
|
903
859
|
function buildErrorMetadata(args) {
|
|
904
860
|
const retryAfter = parseRetryAfter(args.headers);
|
|
@@ -930,8 +886,16 @@ function mapOpenAICompatibleError(args) {
|
|
|
930
886
|
if (status === 429) {
|
|
931
887
|
return new errors.RateLimitError(message, { code: `${providerId}_rate_limit`, metadata });
|
|
932
888
|
}
|
|
889
|
+
if (status === 404 && code === "model_unavailable") {
|
|
890
|
+
const detailed = formatMessage(providerId, status, code, boundedProviderDetail(body));
|
|
891
|
+
return new errors.ConfigurationError(detailed, {
|
|
892
|
+
code: `${providerId}_model_unavailable`,
|
|
893
|
+
metadata
|
|
894
|
+
});
|
|
895
|
+
}
|
|
933
896
|
if (status === 400) {
|
|
934
|
-
|
|
897
|
+
const detailed = formatMessage(providerId, status, code, boundedProviderDetail(body));
|
|
898
|
+
return new errors.ConfigurationError(detailed, { code: `${providerId}_${code}`, metadata });
|
|
935
899
|
}
|
|
936
900
|
if (status === 408) {
|
|
937
901
|
return new errors.NetworkError(message, { code: `${providerId}_timeout`, metadata });
|
|
@@ -941,6 +905,18 @@ function mapOpenAICompatibleError(args) {
|
|
|
941
905
|
}
|
|
942
906
|
return new errors.UnknownAgentError(message, { code: `${providerId}_unknown`, metadata });
|
|
943
907
|
}
|
|
908
|
+
function extractOpenAiErrorMessage(body) {
|
|
909
|
+
if (body === null || typeof body !== "object") return void 0;
|
|
910
|
+
const err = body.error;
|
|
911
|
+
if (err === void 0 || err === null) return void 0;
|
|
912
|
+
return typeof err.message === "string" ? err.message : void 0;
|
|
913
|
+
}
|
|
914
|
+
function boundedProviderDetail(body) {
|
|
915
|
+
const raw = extractOpenAiErrorMessage(body);
|
|
916
|
+
if (raw === void 0 || raw.trim() === "") return void 0;
|
|
917
|
+
const redacted = redactSecrets(raw);
|
|
918
|
+
return redacted.length <= PROVIDER_DETAIL_MAX_CHARS ? redacted : `${redacted.slice(0, PROVIDER_DETAIL_MAX_CHARS)}\u2026`;
|
|
919
|
+
}
|
|
944
920
|
function extractOpenAiErrorCode(body) {
|
|
945
921
|
if (body === null || typeof body !== "object") return void 0;
|
|
946
922
|
const err = body.error;
|
|
@@ -963,6 +939,9 @@ function mapOpenAiStatusToCode(status, body) {
|
|
|
963
939
|
if (status === 402 || rawCode.includes("insufficient_quota") || rawCode.includes("quota_exceeded")) {
|
|
964
940
|
return "quota_exceeded";
|
|
965
941
|
}
|
|
942
|
+
if (status === 404 && MISSING_MODEL_MESSAGE.test(extractOpenAiErrorMessage(body) ?? "")) {
|
|
943
|
+
return "model_unavailable";
|
|
944
|
+
}
|
|
966
945
|
if (status === 401 || status === 403) return "auth_failed";
|
|
967
946
|
if (status === 429) return "rate_limit";
|
|
968
947
|
if (status === 408) return "timeout";
|
|
@@ -970,8 +949,9 @@ function mapOpenAiStatusToCode(status, body) {
|
|
|
970
949
|
if (status >= 500 && status < 600) return "server_error";
|
|
971
950
|
return "unknown";
|
|
972
951
|
}
|
|
973
|
-
function formatMessage(providerId, status, code) {
|
|
974
|
-
|
|
952
|
+
function formatMessage(providerId, status, code, detail) {
|
|
953
|
+
const base = `${providerId} API error: ${code} (HTTP ${status})`;
|
|
954
|
+
return detail === void 0 || detail === "" ? base : `${base}: ${detail}`;
|
|
975
955
|
}
|
|
976
956
|
var FACTS_HEADING = "## Facts";
|
|
977
957
|
function createCategorizedMemory(options) {
|
|
@@ -1099,536 +1079,17 @@ ${bullet}
|
|
|
1099
1079
|
return `${raw.slice(0, insertAt)}
|
|
1100
1080
|
${bullet}${raw.slice(insertAt)}`;
|
|
1101
1081
|
}
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
var DEFAULT_DEDUP_THRESHOLD = 0.95;
|
|
1105
|
-
var DEFAULT_CLUSTER_THRESHOLD = 0.75;
|
|
1106
|
-
async function lightPhase(facts, embedding, threshold = DEFAULT_DEDUP_THRESHOLD) {
|
|
1107
|
-
if (facts.length <= 1) return { kept: [...facts], duplicatesRemoved: 0 };
|
|
1108
|
-
const vectors = await embedding.embed(facts.map((f) => f.text));
|
|
1109
|
-
const keptIdx = [];
|
|
1110
|
-
const keptVecs = [];
|
|
1111
|
-
for (let i = 0; i < facts.length; i++) {
|
|
1112
|
-
const vec = vectors[i] ?? [];
|
|
1113
|
-
const isDup = keptVecs.some((kept2) => cosineSimilarity(vec, kept2) >= threshold);
|
|
1114
|
-
if (isDup) continue;
|
|
1115
|
-
keptIdx.push(i);
|
|
1116
|
-
keptVecs.push(vec);
|
|
1117
|
-
}
|
|
1118
|
-
const kept = keptIdx.map((i) => facts[i]);
|
|
1119
|
-
return { kept, duplicatesRemoved: facts.length - kept.length };
|
|
1120
|
-
}
|
|
1121
|
-
var DEFAULT_MAX_FACTS_PER_SWEEP = 500;
|
|
1122
|
-
async function remPhase(facts, embedding, threshold = DEFAULT_CLUSTER_THRESHOLD, maxFactsPerSweep = DEFAULT_MAX_FACTS_PER_SWEEP) {
|
|
1123
|
-
if (facts.length === 0) return { clusters: [], factsLeftOut: 0 };
|
|
1124
|
-
const capped = facts.length > maxFactsPerSweep ? facts.slice(0, maxFactsPerSweep) : facts;
|
|
1125
|
-
const vectors = await embedding.embed(capped.map((f) => f.text));
|
|
1126
|
-
const clusterOfIdx = unionFindByPairs(vectors, threshold);
|
|
1127
|
-
const groups = bucketFactsByClusterRoot(capped, clusterOfIdx);
|
|
1128
|
-
return {
|
|
1129
|
-
clusters: [...groups.values()].map(buildClusterFromMembers),
|
|
1130
|
-
factsLeftOut: facts.length - capped.length
|
|
1131
|
-
};
|
|
1132
|
-
}
|
|
1133
|
-
function unionFindByPairs(vectors, threshold) {
|
|
1134
|
-
const clusterOfIdx = vectors.map((_, i) => i);
|
|
1135
|
-
for (let i = 0; i < vectors.length; i++) {
|
|
1136
|
-
for (let j = i + 1; j < vectors.length; j++) {
|
|
1137
|
-
if (cosineSimilarity(vectors[i] ?? [], vectors[j] ?? []) >= threshold) {
|
|
1138
|
-
unifyClusters(clusterOfIdx, i, j);
|
|
1139
|
-
}
|
|
1140
|
-
}
|
|
1141
|
-
}
|
|
1142
|
-
return clusterOfIdx;
|
|
1143
|
-
}
|
|
1144
|
-
function bucketFactsByClusterRoot(facts, clusterOfIdx) {
|
|
1145
|
-
const groups = /* @__PURE__ */ new Map();
|
|
1146
|
-
for (let i = 0; i < facts.length; i++) {
|
|
1147
|
-
const root = findRoot(clusterOfIdx, i);
|
|
1148
|
-
const list = groups.get(root) ?? [];
|
|
1149
|
-
list.push(facts[i]);
|
|
1150
|
-
groups.set(root, list);
|
|
1151
|
-
}
|
|
1152
|
-
return groups;
|
|
1153
|
-
}
|
|
1154
|
-
function buildClusterFromMembers(members) {
|
|
1155
|
-
const sorted = [...members].sort((a, b) => b.text.length - a.text.length);
|
|
1156
|
-
return { representativeText: sorted[0]?.text ?? "", members };
|
|
1157
|
-
}
|
|
1158
|
-
function deepPhase(clusters, timestampMs) {
|
|
1159
|
-
if (clusters.length === 0) return "";
|
|
1160
|
-
const isoStamp = new Date(timestampMs).toISOString();
|
|
1161
|
-
const lines = [`# Dreamed ${isoStamp}`, ""];
|
|
1162
|
-
for (let i = 0; i < clusters.length; i++) {
|
|
1163
|
-
const c = clusters[i];
|
|
1164
|
-
if (c === void 0) continue;
|
|
1165
|
-
lines.push(`## Cluster ${i + 1}: ${c.representativeText}`);
|
|
1166
|
-
lines.push("");
|
|
1167
|
-
for (const member of c.members) lines.push(`- ${member.text}`);
|
|
1168
|
-
lines.push("");
|
|
1169
|
-
}
|
|
1170
|
-
return `${lines.join("\n")}
|
|
1171
|
-
`;
|
|
1172
|
-
}
|
|
1173
|
-
function cosineSimilarity(a, b) {
|
|
1174
|
-
if (a.length === 0 || b.length === 0 || a.length !== b.length) return 0;
|
|
1175
|
-
let dot = 0;
|
|
1176
|
-
let aNorm = 0;
|
|
1177
|
-
let bNorm = 0;
|
|
1178
|
-
for (let i = 0; i < a.length; i++) {
|
|
1179
|
-
const ai = a[i] ?? 0;
|
|
1180
|
-
const bi = b[i] ?? 0;
|
|
1181
|
-
dot += ai * bi;
|
|
1182
|
-
aNorm += ai * ai;
|
|
1183
|
-
bNorm += bi * bi;
|
|
1184
|
-
}
|
|
1185
|
-
const denom = Math.sqrt(aNorm) * Math.sqrt(bNorm);
|
|
1186
|
-
return denom === 0 ? 0 : dot / denom;
|
|
1187
|
-
}
|
|
1188
|
-
function findRoot(parents, i) {
|
|
1189
|
-
let root = i;
|
|
1190
|
-
while (parents[root] !== root) {
|
|
1191
|
-
const next = parents[root] ?? root;
|
|
1192
|
-
if (next === root) break;
|
|
1193
|
-
root = next;
|
|
1194
|
-
}
|
|
1195
|
-
parents[i] = root;
|
|
1196
|
-
return root;
|
|
1197
|
-
}
|
|
1198
|
-
function unifyClusters(parents, a, b) {
|
|
1199
|
-
const rootA = findRoot(parents, a);
|
|
1200
|
-
const rootB = findRoot(parents, b);
|
|
1201
|
-
if (rootA !== rootB) parents[rootB] = rootA;
|
|
1202
|
-
}
|
|
1203
|
-
function runDreamingSweep(options) {
|
|
1204
|
-
return persistence.withCwdMutex(`dream:${options.cwd}`, () => runInner(options));
|
|
1205
|
-
}
|
|
1206
|
-
async function runInner(options) {
|
|
1207
|
-
const now = options.now ?? Date.now;
|
|
1208
|
-
const timestampMs = now();
|
|
1209
|
-
try {
|
|
1210
|
-
const facts = await memoryStore.readFactsFromMarkdown(options.cwd);
|
|
1211
|
-
if (facts.length === 0) {
|
|
1212
|
-
return emptyResult("skipped");
|
|
1213
|
-
}
|
|
1214
|
-
const dedup = await lightPhase(facts, options.embedding, options.dedupThreshold);
|
|
1215
|
-
const rem = await remPhase(dedup.kept, options.embedding, options.clusterThreshold);
|
|
1216
|
-
const notesWritten = await writeConsolidatedNotes(options.cwd, rem.clusters, timestampMs);
|
|
1217
|
-
const result = {
|
|
1218
|
-
status: "ok",
|
|
1219
|
-
factsBefore: facts.length,
|
|
1220
|
-
factsAfter: dedup.kept.length,
|
|
1221
|
-
duplicatesRemoved: dedup.duplicatesRemoved,
|
|
1222
|
-
clustersCreated: rem.clusters.length,
|
|
1223
|
-
notesWritten,
|
|
1224
|
-
diaryEntryHash: void 0,
|
|
1225
|
-
factsLeftOut: rem.factsLeftOut
|
|
1226
|
-
};
|
|
1227
|
-
await memoryStore.appendDiaryEntry(memoryStore.resolveMemoryRoot(options.cwd), {
|
|
1228
|
-
timestampMs,
|
|
1229
|
-
factsBefore: result.factsBefore,
|
|
1230
|
-
factsAfter: result.factsAfter,
|
|
1231
|
-
duplicatesRemoved: result.duplicatesRemoved,
|
|
1232
|
-
clustersCreated: result.clustersCreated,
|
|
1233
|
-
notesWritten: result.notesWritten
|
|
1234
|
-
});
|
|
1235
|
-
return result;
|
|
1236
|
-
} catch (cause) {
|
|
1237
|
-
const message = cause instanceof Error ? cause.message : String(cause);
|
|
1238
|
-
process.stderr.write(`[theokit-sdk] dreaming sweep failed: ${message}
|
|
1239
|
-
`);
|
|
1240
|
-
return emptyResult("error");
|
|
1241
|
-
}
|
|
1242
|
-
}
|
|
1243
|
-
async function writeConsolidatedNotes(cwd, clusters, timestampMs) {
|
|
1244
|
-
if (clusters.length === 0) return 0;
|
|
1245
|
-
const notesDir3 = path.join(memoryStore.resolveMemoryRoot(cwd), "notes");
|
|
1246
|
-
await promises.mkdir(notesDir3, { recursive: true });
|
|
1247
|
-
const isoSlug = new Date(timestampMs).toISOString().replace(/[^\dT]/g, "-");
|
|
1248
|
-
const file = path.join(notesDir3, `dreamed-${isoSlug}.md`);
|
|
1249
|
-
const body = deepPhase(clusters, timestampMs);
|
|
1250
|
-
await persistence.replaceFileAtomic(file, body);
|
|
1251
|
-
return 1;
|
|
1252
|
-
}
|
|
1253
|
-
function emptyResult(status) {
|
|
1254
|
-
const result = {
|
|
1255
|
-
status,
|
|
1256
|
-
factsBefore: 0,
|
|
1257
|
-
factsAfter: 0,
|
|
1258
|
-
duplicatesRemoved: 0,
|
|
1259
|
-
clustersCreated: 0,
|
|
1260
|
-
notesWritten: 0,
|
|
1261
|
-
diaryEntryHash: void 0
|
|
1262
|
-
};
|
|
1263
|
-
return status === "skipped" ? { ...result, factsLeftOut: 0 } : result;
|
|
1264
|
-
}
|
|
1265
|
-
|
|
1266
|
-
// src/internal/index/index-schema.ts
|
|
1267
|
-
var SCHEMA_STATEMENTS = [
|
|
1268
|
-
`CREATE TABLE IF NOT EXISTS files (
|
|
1269
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1270
|
-
path TEXT UNIQUE NOT NULL,
|
|
1271
|
-
rel_path TEXT NOT NULL,
|
|
1272
|
-
mtime INTEGER NOT NULL,
|
|
1273
|
-
hash TEXT NOT NULL,
|
|
1274
|
-
source TEXT NOT NULL DEFAULT 'memory'
|
|
1275
|
-
)`,
|
|
1276
|
-
`CREATE TABLE IF NOT EXISTS chunks (
|
|
1277
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1278
|
-
file_id INTEGER NOT NULL REFERENCES files(id) ON DELETE CASCADE,
|
|
1279
|
-
start_line INTEGER NOT NULL,
|
|
1280
|
-
end_line INTEGER NOT NULL,
|
|
1281
|
-
text TEXT NOT NULL,
|
|
1282
|
-
hash TEXT NOT NULL,
|
|
1283
|
-
session_key TEXT
|
|
1284
|
-
)`,
|
|
1285
|
-
`CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5(
|
|
1286
|
-
text,
|
|
1287
|
-
content='chunks',
|
|
1288
|
-
content_rowid='id'
|
|
1289
|
-
)`,
|
|
1290
|
-
`CREATE TRIGGER IF NOT EXISTS chunks_fts_insert AFTER INSERT ON chunks BEGIN
|
|
1291
|
-
INSERT INTO chunks_fts(rowid, text) VALUES (new.id, new.text);
|
|
1292
|
-
END`,
|
|
1293
|
-
`CREATE TRIGGER IF NOT EXISTS chunks_fts_delete AFTER DELETE ON chunks BEGIN
|
|
1294
|
-
INSERT INTO chunks_fts(chunks_fts, rowid, text) VALUES ('delete', old.id, old.text);
|
|
1295
|
-
END`,
|
|
1296
|
-
`CREATE TABLE IF NOT EXISTS meta (
|
|
1297
|
-
key TEXT PRIMARY KEY,
|
|
1298
|
-
value TEXT
|
|
1299
|
-
)`,
|
|
1300
|
-
`CREATE INDEX IF NOT EXISTS idx_chunks_file_id ON chunks(file_id)`
|
|
1301
|
-
];
|
|
1302
|
-
var PRAGMA_STATEMENTS = [
|
|
1303
|
-
"PRAGMA synchronous=NORMAL",
|
|
1304
|
-
"PRAGMA foreign_keys=ON"
|
|
1305
|
-
];
|
|
1306
|
-
|
|
1307
|
-
// src/internal/index/index-db.ts
|
|
1308
|
-
async function openMemoryDb(opts) {
|
|
1309
|
-
return persistence.openSqliteResilient({
|
|
1310
|
-
filePath: opts.filePath,
|
|
1311
|
-
label: "memory-index",
|
|
1312
|
-
recoverCorrupt: opts.recoverCorrupt,
|
|
1313
|
-
onOpen: (db) => {
|
|
1314
|
-
for (const pragma of PRAGMA_STATEMENTS) db.exec(pragma);
|
|
1315
|
-
for (const stmt of SCHEMA_STATEMENTS) db.exec(stmt);
|
|
1316
|
-
}
|
|
1317
|
-
});
|
|
1318
|
-
}
|
|
1319
|
-
var HEADING_RE = /^(#{1,6})\s+(.+?)\s*$/;
|
|
1320
|
-
function chunkMarkdown(text, options = {}) {
|
|
1321
|
-
const maxChars = options.maxChars ?? 800;
|
|
1322
|
-
if (text.length === 0) return [];
|
|
1323
|
-
const lines = text.split("\n");
|
|
1324
|
-
const acc = { chunks: [], lines: [], start: 1, heading: void 0 };
|
|
1325
|
-
for (let i = 0; i < lines.length; i++) {
|
|
1326
|
-
const line = lines[i] ?? "";
|
|
1327
|
-
const lineNumber = i + 1;
|
|
1328
|
-
processLine(acc, line, lineNumber, maxChars);
|
|
1329
|
-
}
|
|
1330
|
-
flushAccumulator(acc, lines.length, maxChars);
|
|
1331
|
-
return acc.chunks;
|
|
1332
|
-
}
|
|
1333
|
-
function processLine(acc, line, lineNumber, maxChars) {
|
|
1334
|
-
const headingMatch = HEADING_RE.exec(line);
|
|
1335
|
-
const isBlank = line.trim().length === 0;
|
|
1336
|
-
if (headingMatch !== null && acc.lines.length > 0) {
|
|
1337
|
-
flushAccumulator(acc, lineNumber - 1, maxChars);
|
|
1338
|
-
}
|
|
1339
|
-
if (headingMatch !== null) acc.heading = headingMatch[2];
|
|
1340
|
-
acc.lines.push(line);
|
|
1341
|
-
if (isBlank && acc.lines.length > 1) {
|
|
1342
|
-
const joined = acc.lines.join("\n");
|
|
1343
|
-
if (joined.trim().length > 0) flushAccumulator(acc, lineNumber, maxChars);
|
|
1344
|
-
}
|
|
1345
|
-
}
|
|
1346
|
-
function flushAccumulator(acc, endLineExclusive, maxChars) {
|
|
1347
|
-
if (acc.lines.length === 0) return;
|
|
1348
|
-
const chunkText = acc.lines.join("\n");
|
|
1349
|
-
if (chunkText.trim().length === 0) {
|
|
1350
|
-
acc.lines = [];
|
|
1351
|
-
acc.start = endLineExclusive + 1;
|
|
1352
|
-
return;
|
|
1353
|
-
}
|
|
1354
|
-
if (chunkText.length > maxChars) {
|
|
1355
|
-
pushOversizedSlices(acc.chunks, chunkText, acc.start, acc.heading, maxChars);
|
|
1356
|
-
} else {
|
|
1357
|
-
acc.chunks.push(buildChunk(chunkText, acc.start, endLineExclusive, acc.heading));
|
|
1358
|
-
}
|
|
1359
|
-
acc.lines = [];
|
|
1360
|
-
acc.start = endLineExclusive + 1;
|
|
1361
|
-
}
|
|
1362
|
-
function buildChunk(text, startLine, endLine, heading) {
|
|
1363
|
-
return {
|
|
1364
|
-
startLine,
|
|
1365
|
-
endLine,
|
|
1366
|
-
text,
|
|
1367
|
-
hash: crypto.createHash("sha256").update(text).digest("hex"),
|
|
1368
|
-
...heading !== void 0 ? { heading } : {}
|
|
1369
|
-
};
|
|
1370
|
-
}
|
|
1371
|
-
function pushOversizedSlices(chunks, text, startLine, heading, maxChars) {
|
|
1372
|
-
let remaining = text;
|
|
1373
|
-
let lineCursor = startLine;
|
|
1374
|
-
while (remaining.length > maxChars) {
|
|
1375
|
-
const splitAt = findWordBoundarySplit(remaining, maxChars);
|
|
1376
|
-
const slice = remaining.slice(0, splitAt);
|
|
1377
|
-
const sliceLines = slice.split("\n").length;
|
|
1378
|
-
chunks.push(buildChunk(slice, lineCursor, lineCursor + sliceLines - 1, heading));
|
|
1379
|
-
remaining = remaining.slice(splitAt).replace(/^\s+/, "");
|
|
1380
|
-
lineCursor += sliceLines - 1;
|
|
1381
|
-
}
|
|
1382
|
-
if (remaining.length > 0) {
|
|
1383
|
-
const sliceLines = remaining.split("\n").length;
|
|
1384
|
-
chunks.push(buildChunk(remaining, lineCursor, lineCursor + sliceLines - 1, heading));
|
|
1385
|
-
}
|
|
1386
|
-
}
|
|
1387
|
-
function findWordBoundarySplit(text, maxChars) {
|
|
1388
|
-
if (text.length <= maxChars) return text.length;
|
|
1389
|
-
for (let i = maxChars; i > Math.max(0, maxChars - 200); i--) {
|
|
1390
|
-
if (/\s/.test(text[i] ?? "x")) return i;
|
|
1391
|
-
}
|
|
1392
|
-
return maxChars;
|
|
1393
|
-
}
|
|
1394
|
-
function requireLance() {
|
|
1395
|
-
try {
|
|
1396
|
-
const r = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
|
|
1397
|
-
return r("@lancedb/lancedb");
|
|
1398
|
-
} catch (cause) {
|
|
1399
|
-
throw new errors.ConfigurationError(
|
|
1400
|
-
'Lance backend selected but `@lancedb/lancedb` is not installed. Install with: `pnpm add @lancedb/lancedb`. SQLite remains available as the default (omit `backend: "lance"`).',
|
|
1401
|
-
{ code: "lance_backend_unavailable", cause }
|
|
1402
|
-
);
|
|
1403
|
-
}
|
|
1404
|
-
}
|
|
1405
|
-
var LanceIndex = class _LanceIndex {
|
|
1406
|
-
constructor(table, embedding, embeddingDim) {
|
|
1407
|
-
this.table = table;
|
|
1408
|
-
this.embedding = embedding;
|
|
1409
|
-
this.embeddingDim = embeddingDim;
|
|
1410
|
-
}
|
|
1411
|
-
table;
|
|
1412
|
-
embedding;
|
|
1413
|
-
embeddingDim;
|
|
1414
|
-
static async open(opts) {
|
|
1415
|
-
const lance = requireLance();
|
|
1416
|
-
const storagePath = opts.storagePath ?? memoryStore.lanceStoragePath(opts.memoryRoot ?? memoryStore.resolveMemoryRoot(opts.cwd));
|
|
1417
|
-
fs.mkdirSync(storagePath, { recursive: true });
|
|
1418
|
-
const conn = await lance.connect(storagePath);
|
|
1419
|
-
const dim = opts.embedding.dimension;
|
|
1420
|
-
const tableName = "facts";
|
|
1421
|
-
const existing = await conn.tableNames();
|
|
1422
|
-
let table;
|
|
1423
|
-
if (existing.includes(tableName)) {
|
|
1424
|
-
table = await conn.openTable(tableName);
|
|
1425
|
-
const schema = await table.schema();
|
|
1426
|
-
const embField = schema.fields.find((f) => f.name === "embedding");
|
|
1427
|
-
const existingDim = embField?.type?.listSize ?? embField?.type?.fixedSize;
|
|
1428
|
-
if (typeof existingDim === "number" && existingDim !== dim) {
|
|
1429
|
-
throw new errors.ConfigurationError(
|
|
1430
|
-
`Embedding dimension mismatch in Lance index: storage has ${existingDim}-dim vectors, current provider yields ${dim}-dim. Re-embed with \`migrateSqliteToLance\` after switching providers, or use a different storagePath.`,
|
|
1431
|
-
{ code: "embedding_dimension_mismatch" }
|
|
1432
|
-
);
|
|
1433
|
-
}
|
|
1434
|
-
} else {
|
|
1435
|
-
const bootstrap = {
|
|
1436
|
-
id: "__bootstrap__",
|
|
1437
|
-
text: "",
|
|
1438
|
-
source: "memory",
|
|
1439
|
-
embedding: new Array(dim).fill(0),
|
|
1440
|
-
namespace: "__bootstrap__",
|
|
1441
|
-
scope: "__bootstrap__",
|
|
1442
|
-
user_id: "__bootstrap__",
|
|
1443
|
-
timestamp: 0
|
|
1444
|
-
};
|
|
1445
|
-
table = await conn.createTable(tableName, [bootstrap]);
|
|
1446
|
-
await table.delete("namespace = '__bootstrap__'");
|
|
1447
|
-
}
|
|
1448
|
-
return new _LanceIndex(table, opts.embedding, dim);
|
|
1449
|
-
}
|
|
1450
|
-
async addFacts(facts) {
|
|
1451
|
-
if (facts.length === 0) return;
|
|
1452
|
-
const texts = facts.map((f) => f.text);
|
|
1453
|
-
const embeddings = await this.embedding.embed(texts);
|
|
1454
|
-
const rows = facts.map((f, i) => ({
|
|
1455
|
-
...f,
|
|
1456
|
-
embedding: embeddings[i] ?? new Array(this.embeddingDim).fill(0)
|
|
1457
|
-
}));
|
|
1458
|
-
await this.table.add(rows);
|
|
1459
|
-
}
|
|
1460
|
-
/**
|
|
1461
|
-
* Search facts by semantic similarity. EC-1: filters use Lance's
|
|
1462
|
-
* SQL string predicate with `'` → `''` escape — bind parameters are
|
|
1463
|
-
* not supported by Lance 0.30.
|
|
1464
|
-
*/
|
|
1465
|
-
async search(query, opts) {
|
|
1466
|
-
const [embedding] = await this.embedding.embed([query]);
|
|
1467
|
-
if (embedding === void 0) return [];
|
|
1468
|
-
const predicates = [`namespace = '${escapeSqlValue(opts.namespace)}'`];
|
|
1469
|
-
if (opts.scope !== void 0) {
|
|
1470
|
-
predicates.push(`scope = '${escapeSqlValue(opts.scope)}'`);
|
|
1471
|
-
}
|
|
1472
|
-
let q = this.table.search(embedding).where(predicates.join(" AND "));
|
|
1473
|
-
if (opts.limit !== void 0) q = q.limit(opts.limit);
|
|
1474
|
-
const results = await q.toArray();
|
|
1475
|
-
return results.filter((r) => opts.sources === void 0 || opts.sources.includes(r.source)).map((r) => ({
|
|
1476
|
-
id: r.id,
|
|
1477
|
-
text: r.text,
|
|
1478
|
-
source: r.source,
|
|
1479
|
-
namespace: r.namespace,
|
|
1480
|
-
scope: r.scope,
|
|
1481
|
-
userId: r.user_id,
|
|
1482
|
-
// Lower _distance = better match; normalize to 0..1 (1=best).
|
|
1483
|
-
score: 1 / (1 + (r._distance ?? 1))
|
|
1484
|
-
}));
|
|
1485
|
-
}
|
|
1486
|
-
async countFacts(namespace) {
|
|
1487
|
-
return this.table.countRows();
|
|
1488
|
-
}
|
|
1489
|
-
async removeFacts(ids) {
|
|
1490
|
-
if (ids.length === 0) return;
|
|
1491
|
-
const escaped = ids.map((id) => `'${id.replace(/'/g, "''")}'`).join(", ");
|
|
1492
|
-
await this.table.delete(`id IN (${escaped})`);
|
|
1493
|
-
}
|
|
1494
|
-
async close() {
|
|
1495
|
-
}
|
|
1496
|
-
};
|
|
1497
|
-
function escapeSqlValue(value) {
|
|
1498
|
-
for (let i = 0; i < value.length; i++) {
|
|
1499
|
-
const code = value.charCodeAt(i);
|
|
1500
|
-
if (code === 0 || code >= 1 && code <= 31 || code === 127) {
|
|
1501
|
-
throw new errors.ConfigurationError(
|
|
1502
|
-
`SQL filter value contains control character at position ${i} (0x${code.toString(16)}). This may indicate an injection attempt.`,
|
|
1503
|
-
{ code: "sql_injection_blocked" }
|
|
1504
|
-
);
|
|
1505
|
-
}
|
|
1506
|
-
}
|
|
1507
|
-
return value.replace(/\\/g, "\\\\").replace(/'/g, "''");
|
|
1508
|
-
}
|
|
1509
|
-
function isLanceAvailable() {
|
|
1510
|
-
try {
|
|
1511
|
-
const r = module$1.createRequire((typeof document === 'undefined' ? require('u' + 'rl').pathToFileURL(__filename).href : (_documentCurrentScript && _documentCurrentScript.tagName.toUpperCase() === 'SCRIPT' && _documentCurrentScript.src || new URL('index.cjs', document.baseURI).href)));
|
|
1512
|
-
r("@lancedb/lancedb");
|
|
1513
|
-
return true;
|
|
1514
|
-
} catch {
|
|
1515
|
-
return false;
|
|
1516
|
-
}
|
|
1517
|
-
}
|
|
1518
|
-
|
|
1519
|
-
// src/internal/index/memory-index.ts
|
|
1520
|
-
function parseSearchOptions(options = {}) {
|
|
1521
|
-
return {
|
|
1522
|
-
maxResults: Math.max(1, options.maxResults ?? 10),
|
|
1523
|
-
minScore: options.minScore ?? 0
|
|
1524
|
-
};
|
|
1525
|
-
}
|
|
1526
|
-
|
|
1527
|
-
// src/internal/index/lance-memory-adapter.ts
|
|
1528
|
-
var DEFAULT_NAMESPACE = "default";
|
|
1529
|
-
var EMPTY_SYNC_RESULT = Object.freeze({
|
|
1530
|
-
filesScanned: 0,
|
|
1531
|
-
filesUpdated: 0,
|
|
1532
|
-
chunksWritten: 0,
|
|
1533
|
-
chunksEmbedded: 0
|
|
1534
|
-
});
|
|
1535
|
-
var LanceMemoryAdapter = class {
|
|
1082
|
+
var LanceMemoryAdapter = class extends memoryStore.LanceMemoryAdapter {
|
|
1083
|
+
#lance;
|
|
1536
1084
|
constructor(inner) {
|
|
1537
|
-
|
|
1538
|
-
|
|
1539
|
-
inner;
|
|
1540
|
-
/**
|
|
1541
|
-
* No-op for Lance — see file header. Returns zero counts so callers'
|
|
1542
|
-
* existing logging (`filesScanned: X`) does not break.
|
|
1543
|
-
*/
|
|
1544
|
-
async sync() {
|
|
1545
|
-
return EMPTY_SYNC_RESULT;
|
|
1546
|
-
}
|
|
1547
|
-
// jscpd:ignore-start — search signature + early-out is idiomatic
|
|
1548
|
-
// overlap with IndexManager.search; further factoring would hurt
|
|
1549
|
-
// readability (the bodies diverge sharply right after).
|
|
1550
|
-
async search(query, options = {}) {
|
|
1551
|
-
if (query.trim().length === 0) return [];
|
|
1552
|
-
const { maxResults, minScore } = parseSearchOptions(options);
|
|
1553
|
-
const lanceHits = await this.inner.search(query, {
|
|
1554
|
-
namespace: DEFAULT_NAMESPACE,
|
|
1555
|
-
limit: maxResults * 2,
|
|
1556
|
-
...options.sources !== void 0 ? { sources: options.sources } : {}
|
|
1557
|
-
});
|
|
1558
|
-
return lanceHits.filter((h) => h.score >= minScore).slice(0, maxResults).map((h) => translateLanceHit(h));
|
|
1559
|
-
}
|
|
1560
|
-
status() {
|
|
1561
|
-
return {
|
|
1562
|
-
backend: "hybrid",
|
|
1563
|
-
filesIndexed: 0,
|
|
1564
|
-
chunksIndexed: 0
|
|
1565
|
-
};
|
|
1085
|
+
super(inner);
|
|
1086
|
+
this.#lance = inner;
|
|
1566
1087
|
}
|
|
1567
|
-
|
|
1568
|
-
await this.inner.close();
|
|
1569
|
-
}
|
|
1570
|
-
/**
|
|
1571
|
-
* Escape hatch for advanced callers (migration tool, benchmark script)
|
|
1572
|
-
* that need direct access to addFacts/countFacts/removeFacts.
|
|
1573
|
-
*/
|
|
1088
|
+
/** The wrapped `LanceIndex`, for `addFacts`, `countFacts` and `removeFacts`. */
|
|
1574
1089
|
unwrap() {
|
|
1575
|
-
return this
|
|
1090
|
+
return this.#lance;
|
|
1576
1091
|
}
|
|
1577
1092
|
};
|
|
1578
|
-
function translateLanceHit(hit) {
|
|
1579
|
-
return {
|
|
1580
|
-
path: hit.id,
|
|
1581
|
-
startLine: 0,
|
|
1582
|
-
endLine: 0,
|
|
1583
|
-
score: hit.score,
|
|
1584
|
-
textScore: 0,
|
|
1585
|
-
vectorScore: hit.score,
|
|
1586
|
-
snippet: hit.text.slice(0, 200),
|
|
1587
|
-
source: hit.source,
|
|
1588
|
-
citation: hit.id
|
|
1589
|
-
};
|
|
1590
|
-
}
|
|
1591
|
-
|
|
1592
|
-
// src/internal/index/index-manager-dispatch.ts
|
|
1593
|
-
var VALID_BACKENDS = ["sqlite-vec", "lance"];
|
|
1594
|
-
function assertValidBackend(backend) {
|
|
1595
|
-
if (!VALID_BACKENDS.includes(backend)) {
|
|
1596
|
-
throw new errors.ConfigurationError(
|
|
1597
|
-
`Invalid memory backend "${backend}". Valid values: ${VALID_BACKENDS.join(", ")}.`,
|
|
1598
|
-
{ code: "invalid_memory_backend" }
|
|
1599
|
-
);
|
|
1600
|
-
}
|
|
1601
|
-
}
|
|
1602
|
-
async function openLanceIndex(opts) {
|
|
1603
|
-
if (opts.embedding === void 0) {
|
|
1604
|
-
throw new errors.ConfigurationError(
|
|
1605
|
-
"Lance backend requires an embedding runtime. Pass `embedding: { provider, model, apiKey }` in Memory.create options (or omit `backend` to use SQLite default).",
|
|
1606
|
-
{ code: "lance_requires_embedding" }
|
|
1607
|
-
);
|
|
1608
|
-
}
|
|
1609
|
-
const lance = await LanceIndex.open({
|
|
1610
|
-
cwd: opts.cwd,
|
|
1611
|
-
embedding: opts.embedding,
|
|
1612
|
-
...opts.filePath !== void 0 ? { storagePath: opts.filePath } : {}
|
|
1613
|
-
});
|
|
1614
|
-
return new LanceMemoryAdapter(lance);
|
|
1615
|
-
}
|
|
1616
|
-
async function loadSqliteVecExtension(db) {
|
|
1617
|
-
try {
|
|
1618
|
-
const mod = await import('sqlite-vec');
|
|
1619
|
-
const loadFn = mod.load;
|
|
1620
|
-
if (typeof loadFn !== "function") {
|
|
1621
|
-
throw new Error("sqlite-vec module exposes no `load` export");
|
|
1622
|
-
}
|
|
1623
|
-
loadFn(db);
|
|
1624
|
-
} catch (cause) {
|
|
1625
|
-
const message = cause instanceof Error ? cause.message : String(cause);
|
|
1626
|
-
throw new errors.ConfigurationError(
|
|
1627
|
-
`sqlite-vec extension unavailable. Install \`sqlite-vec\` and ensure the native binary matches your Node + OS. Cause: ${message}`,
|
|
1628
|
-
{ code: "sqlite_vec_unavailable", cause }
|
|
1629
|
-
);
|
|
1630
|
-
}
|
|
1631
|
-
}
|
|
1632
1093
|
function isSqliteVecLoaded(db) {
|
|
1633
1094
|
try {
|
|
1634
1095
|
const row = db.prepare("SELECT vec_version() as v").get();
|
|
@@ -1637,533 +1098,6 @@ function isSqliteVecLoaded(db) {
|
|
|
1637
1098
|
return false;
|
|
1638
1099
|
}
|
|
1639
1100
|
}
|
|
1640
|
-
|
|
1641
|
-
// src/internal/index/vec-index.ts
|
|
1642
|
-
var META_KEY_PROVIDER_ID = "embedding.providerId";
|
|
1643
|
-
var META_KEY_MODEL = "embedding.model";
|
|
1644
|
-
var META_KEY_DIMENSION = "embedding.dimension";
|
|
1645
|
-
function readEmbeddingIdentity(db) {
|
|
1646
|
-
const get = (key) => {
|
|
1647
|
-
const row = db.prepare("SELECT value FROM meta WHERE key = ?").get(key);
|
|
1648
|
-
return row !== void 0 ? String(row.value) : void 0;
|
|
1649
|
-
};
|
|
1650
|
-
const providerId = get(META_KEY_PROVIDER_ID);
|
|
1651
|
-
const model = get(META_KEY_MODEL);
|
|
1652
|
-
const dimRaw = get(META_KEY_DIMENSION);
|
|
1653
|
-
if (providerId === void 0 || model === void 0 || dimRaw === void 0) return void 0;
|
|
1654
|
-
const dimension = Number(dimRaw);
|
|
1655
|
-
if (!Number.isFinite(dimension) || dimension <= 0) return void 0;
|
|
1656
|
-
return { providerId, model, dimension };
|
|
1657
|
-
}
|
|
1658
|
-
function writeEmbeddingIdentity(db, identity) {
|
|
1659
|
-
const stmt = db.prepare(
|
|
1660
|
-
"INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
|
|
1661
|
-
);
|
|
1662
|
-
stmt.run(META_KEY_PROVIDER_ID, identity.providerId);
|
|
1663
|
-
stmt.run(META_KEY_MODEL, identity.model);
|
|
1664
|
-
stmt.run(META_KEY_DIMENSION, String(identity.dimension));
|
|
1665
|
-
}
|
|
1666
|
-
function identityMatches(a, b) {
|
|
1667
|
-
return a.providerId === b.providerId && a.model === b.model && a.dimension === b.dimension;
|
|
1668
|
-
}
|
|
1669
|
-
function dropVectorIndex(db) {
|
|
1670
|
-
db.exec("DROP TABLE IF EXISTS embeddings");
|
|
1671
|
-
}
|
|
1672
|
-
function createVectorIndex(db, dimension) {
|
|
1673
|
-
db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS embeddings USING vec0(
|
|
1674
|
-
chunk_id INTEGER PRIMARY KEY,
|
|
1675
|
-
vec FLOAT[${dimension}]
|
|
1676
|
-
)`);
|
|
1677
|
-
}
|
|
1678
|
-
function packVector(vec) {
|
|
1679
|
-
const f32 = new Float32Array(vec.length);
|
|
1680
|
-
for (let i = 0; i < vec.length; i++) f32[i] = vec[i] ?? 0;
|
|
1681
|
-
return Buffer.from(f32.buffer);
|
|
1682
|
-
}
|
|
1683
|
-
function upsertEmbedding(db, chunkId, vec) {
|
|
1684
|
-
const id = BigInt(chunkId);
|
|
1685
|
-
db.prepare("DELETE FROM embeddings WHERE chunk_id = ?").run(id);
|
|
1686
|
-
db.prepare("INSERT INTO embeddings (chunk_id, vec) VALUES (?, ?)").run(id, packVector(vec));
|
|
1687
|
-
}
|
|
1688
|
-
function vectorSearch(db, query, k) {
|
|
1689
|
-
const rows = db.prepare(
|
|
1690
|
-
`SELECT chunk_id, distance FROM embeddings
|
|
1691
|
-
WHERE vec MATCH ? AND k = ?
|
|
1692
|
-
ORDER BY distance`
|
|
1693
|
-
).all(packVector(query), BigInt(k));
|
|
1694
|
-
return rows.map((row) => ({ chunk_id: Number(row.chunk_id), distance: Number(row.distance) }));
|
|
1695
|
-
}
|
|
1696
|
-
async function embedMissingChunks(args) {
|
|
1697
|
-
const rows = args.db.prepare(
|
|
1698
|
-
`SELECT chunks.id as id, chunks.text as text
|
|
1699
|
-
FROM chunks
|
|
1700
|
-
LEFT JOIN embeddings ON embeddings.chunk_id = chunks.id
|
|
1701
|
-
WHERE embeddings.chunk_id IS NULL`
|
|
1702
|
-
).all();
|
|
1703
|
-
if (rows.length === 0) return 0;
|
|
1704
|
-
const normalized = rows.map((row) => ({ id: Number(row.id), text: String(row.text ?? "") }));
|
|
1705
|
-
const vectors = await args.runtime.embed(normalized.map((r) => r.text));
|
|
1706
|
-
for (let i = 0; i < normalized.length; i++) {
|
|
1707
|
-
const row = normalized[i];
|
|
1708
|
-
const vector = vectors[i];
|
|
1709
|
-
if (row === void 0 || vector === void 0) continue;
|
|
1710
|
-
upsertEmbedding(args.db, row.id, vector);
|
|
1711
|
-
}
|
|
1712
|
-
return normalized.length;
|
|
1713
|
-
}
|
|
1714
|
-
|
|
1715
|
-
// src/internal/index/index-manager.ts
|
|
1716
|
-
var IndexManager = class _IndexManager {
|
|
1717
|
-
constructor(memoryRoot, db, embedding) {
|
|
1718
|
-
this.memoryRoot = memoryRoot;
|
|
1719
|
-
this.db = db;
|
|
1720
|
-
this.embedding = embedding;
|
|
1721
|
-
}
|
|
1722
|
-
memoryRoot;
|
|
1723
|
-
db;
|
|
1724
|
-
embedding;
|
|
1725
|
-
lastSyncMs;
|
|
1726
|
-
vectorReady = false;
|
|
1727
|
-
static async open(opts) {
|
|
1728
|
-
const backend = opts.backend ?? "sqlite-vec";
|
|
1729
|
-
assertValidBackend(backend);
|
|
1730
|
-
if (backend === "lance") return await openLanceIndex(opts);
|
|
1731
|
-
return await _IndexManager.openSqliteInternal(opts);
|
|
1732
|
-
}
|
|
1733
|
-
/** Internal SQLite-path open. Renamed from previous public `open`. */
|
|
1734
|
-
static async openSqliteInternal(opts) {
|
|
1735
|
-
const memoryRoot = opts.memoryRoot ?? memoryStore.resolveMemoryRoot(opts.cwd);
|
|
1736
|
-
const filePath = opts.filePath ?? memoryStore.defaultIndexPath(memoryStore.projectMemoryDir(opts.cwd));
|
|
1737
|
-
const db = await openMemoryDb({ filePath });
|
|
1738
|
-
const manager = new _IndexManager(memoryRoot, db, opts.embedding);
|
|
1739
|
-
if (opts.embedding !== void 0) await manager.initVectorBackend(opts.embedding);
|
|
1740
|
-
return manager;
|
|
1741
|
-
}
|
|
1742
|
-
async initVectorBackend(runtime) {
|
|
1743
|
-
await loadSqliteVecExtension(this.db);
|
|
1744
|
-
const currentIdentity = {
|
|
1745
|
-
providerId: runtime.id,
|
|
1746
|
-
model: runtime.model,
|
|
1747
|
-
dimension: runtime.dimension
|
|
1748
|
-
};
|
|
1749
|
-
const persisted = readEmbeddingIdentity(this.db);
|
|
1750
|
-
if (persisted !== void 0 && !identityMatches(persisted, currentIdentity)) {
|
|
1751
|
-
dropVectorIndex(this.db);
|
|
1752
|
-
}
|
|
1753
|
-
createVectorIndex(this.db, runtime.dimension);
|
|
1754
|
-
writeEmbeddingIdentity(this.db, currentIdentity);
|
|
1755
|
-
this.vectorReady = true;
|
|
1756
|
-
}
|
|
1757
|
-
/** Walk the memory corpus + (re)index changed files. */
|
|
1758
|
-
async sync() {
|
|
1759
|
-
const files = await memoryStore.collectMarkdownFiles(this.memoryRoot);
|
|
1760
|
-
let filesUpdated = 0;
|
|
1761
|
-
let chunksWritten = 0;
|
|
1762
|
-
const existingByPath = this.loadFilesIndex();
|
|
1763
|
-
for (const entry of files) {
|
|
1764
|
-
const raw = await promises.readFile(entry.absolutePath, "utf8");
|
|
1765
|
-
const hash = sha256(raw);
|
|
1766
|
-
const existing = existingByPath.get(entry.absolutePath);
|
|
1767
|
-
if (existing !== void 0 && existing.hash === hash) continue;
|
|
1768
|
-
const stats = await promises.stat(entry.absolutePath);
|
|
1769
|
-
const fileId = this.upsertFile(
|
|
1770
|
-
entry.absolutePath,
|
|
1771
|
-
entry.relPath,
|
|
1772
|
-
hash,
|
|
1773
|
-
stats.mtimeMs,
|
|
1774
|
-
entry.source
|
|
1775
|
-
);
|
|
1776
|
-
this.deleteChunksForFile(fileId);
|
|
1777
|
-
const chunks = chunkMarkdown(raw);
|
|
1778
|
-
for (const chunk of chunks) {
|
|
1779
|
-
this.insertChunk(fileId, chunk.startLine, chunk.endLine, chunk.text, chunk.hash);
|
|
1780
|
-
}
|
|
1781
|
-
filesUpdated += 1;
|
|
1782
|
-
chunksWritten += chunks.length;
|
|
1783
|
-
}
|
|
1784
|
-
let chunksEmbedded = 0;
|
|
1785
|
-
if (this.vectorReady && this.embedding !== void 0) {
|
|
1786
|
-
chunksEmbedded = await embedMissingChunks({ db: this.db, runtime: this.embedding });
|
|
1787
|
-
}
|
|
1788
|
-
this.lastSyncMs = Date.now();
|
|
1789
|
-
return { filesScanned: files.length, filesUpdated, chunksWritten, chunksEmbedded };
|
|
1790
|
-
}
|
|
1791
|
-
async search(query, options = {}) {
|
|
1792
|
-
if (query.trim().length === 0) return [];
|
|
1793
|
-
const { maxResults, minScore } = parseSearchOptions(options);
|
|
1794
|
-
const textHits = this.ftsSearch(query, maxResults * 2);
|
|
1795
|
-
const vectorHitsById = await this.vectorSearchById(query, maxResults * 2);
|
|
1796
|
-
const combined = this.combineHybridScores(textHits, vectorHitsById, options);
|
|
1797
|
-
return combined.filter((h) => h.score >= minScore).filter((h) => options.sources === void 0 || options.sources.includes(h.source)).slice(0, maxResults);
|
|
1798
|
-
}
|
|
1799
|
-
status() {
|
|
1800
|
-
const files = this.db.prepare("SELECT COUNT(*) as n FROM files").get() ?? { n: 0 };
|
|
1801
|
-
const chunks = this.db.prepare("SELECT COUNT(*) as n FROM chunks").get() ?? { n: 0 };
|
|
1802
|
-
const status = {
|
|
1803
|
-
backend: this.vectorReady ? "hybrid" : "fts-only",
|
|
1804
|
-
filesIndexed: Number(files.n ?? 0),
|
|
1805
|
-
chunksIndexed: Number(chunks.n ?? 0)
|
|
1806
|
-
};
|
|
1807
|
-
if (this.lastSyncMs !== void 0) status.lastSyncMs = this.lastSyncMs;
|
|
1808
|
-
return status;
|
|
1809
|
-
}
|
|
1810
|
-
// ───── search internals ──────────────────────────────────────────────
|
|
1811
|
-
ftsSearch(query, limit) {
|
|
1812
|
-
const sanitized = persistence.sanitizeFts5Query(query);
|
|
1813
|
-
if (sanitized.length === 0) return [];
|
|
1814
|
-
const stmt = this.db.prepare(
|
|
1815
|
-
`SELECT chunks.id as id, files.rel_path as rel_path, files.source as source,
|
|
1816
|
-
chunks.start_line as start_line, chunks.end_line as end_line,
|
|
1817
|
-
chunks.text as text, bm25(chunks_fts) as bm25_score
|
|
1818
|
-
FROM chunks_fts
|
|
1819
|
-
JOIN chunks ON chunks_fts.rowid = chunks.id
|
|
1820
|
-
JOIN files ON chunks.file_id = files.id
|
|
1821
|
-
WHERE chunks_fts MATCH ?
|
|
1822
|
-
ORDER BY bm25_score
|
|
1823
|
-
LIMIT ?`
|
|
1824
|
-
);
|
|
1825
|
-
let rows = [];
|
|
1826
|
-
try {
|
|
1827
|
-
rows = stmt.all(sanitized, limit);
|
|
1828
|
-
} catch {
|
|
1829
|
-
return [];
|
|
1830
|
-
}
|
|
1831
|
-
return rows.map((row) => {
|
|
1832
|
-
const bm25 = Number(row.bm25_score ?? 0);
|
|
1833
|
-
const textScore = bm25 < 0 ? 1 / (1 + Math.abs(bm25)) : 1 / (1 + bm25);
|
|
1834
|
-
const startLine = Number(row.start_line ?? 0);
|
|
1835
|
-
const endLine = Number(row.end_line ?? 0);
|
|
1836
|
-
const path = String(row.rel_path);
|
|
1837
|
-
return {
|
|
1838
|
-
path,
|
|
1839
|
-
startLine,
|
|
1840
|
-
endLine,
|
|
1841
|
-
score: textScore,
|
|
1842
|
-
textScore,
|
|
1843
|
-
snippet: truncateSnippet(String(row.text ?? "")),
|
|
1844
|
-
source: String(row.source),
|
|
1845
|
-
citation: `${path}:${startLine}-${endLine}`,
|
|
1846
|
-
// sneak the chunk id through for the hybrid join below
|
|
1847
|
-
// (cast away later)
|
|
1848
|
-
chunkId: Number(row.id)
|
|
1849
|
-
};
|
|
1850
|
-
});
|
|
1851
|
-
}
|
|
1852
|
-
async vectorSearchById(query, limit) {
|
|
1853
|
-
if (!this.vectorReady || this.embedding === void 0) return /* @__PURE__ */ new Map();
|
|
1854
|
-
const [queryVec] = await this.embedding.embed([query]);
|
|
1855
|
-
if (queryVec === void 0) return /* @__PURE__ */ new Map();
|
|
1856
|
-
const rows = vectorSearch(this.db, queryVec, limit);
|
|
1857
|
-
const out = /* @__PURE__ */ new Map();
|
|
1858
|
-
for (const row of rows) {
|
|
1859
|
-
const score = 1 / (1 + Math.max(0, row.distance));
|
|
1860
|
-
out.set(row.chunk_id, { vectorScore: score });
|
|
1861
|
-
}
|
|
1862
|
-
return out;
|
|
1863
|
-
}
|
|
1864
|
-
combineHybridScores(textHits, vectorHitsById, options) {
|
|
1865
|
-
const weights = resolveWeights(options);
|
|
1866
|
-
const merged = this.mergeHits(textHits, vectorHitsById);
|
|
1867
|
-
const combined = [...merged.values()].map(
|
|
1868
|
-
(hit) => blendScores(hit, vectorHitsById.get(hit.chunkId)?.vectorScore ?? 0, weights)
|
|
1869
|
-
);
|
|
1870
|
-
return combined.sort((a, b) => b.score - a.score);
|
|
1871
|
-
}
|
|
1872
|
-
mergeHits(textHits, vectorHitsById) {
|
|
1873
|
-
const merged = /* @__PURE__ */ new Map();
|
|
1874
|
-
for (const hit of textHits) merged.set(hit.chunkId, hit);
|
|
1875
|
-
const missingIds = [...vectorHitsById.keys()].filter((id) => !merged.has(id));
|
|
1876
|
-
if (missingIds.length > 0) {
|
|
1877
|
-
for (const hit of this.fetchChunksByIds(missingIds)) {
|
|
1878
|
-
merged.set(hit.chunkId, { ...hit, score: 0, textScore: 0 });
|
|
1879
|
-
}
|
|
1880
|
-
}
|
|
1881
|
-
return merged;
|
|
1882
|
-
}
|
|
1883
|
-
fetchChunksByIds(ids) {
|
|
1884
|
-
if (ids.length === 0) return [];
|
|
1885
|
-
const placeholders = ids.map(() => "?").join(",");
|
|
1886
|
-
const rows = this.db.prepare(
|
|
1887
|
-
`SELECT chunks.id as id, files.rel_path as rel_path, files.source as source,
|
|
1888
|
-
chunks.start_line as start_line, chunks.end_line as end_line,
|
|
1889
|
-
chunks.text as text
|
|
1890
|
-
FROM chunks JOIN files ON chunks.file_id = files.id
|
|
1891
|
-
WHERE chunks.id IN (${placeholders})`
|
|
1892
|
-
).all(...ids);
|
|
1893
|
-
return rows.map((row) => {
|
|
1894
|
-
const startLine = Number(row.start_line ?? 0);
|
|
1895
|
-
const endLine = Number(row.end_line ?? 0);
|
|
1896
|
-
const path = String(row.rel_path);
|
|
1897
|
-
return {
|
|
1898
|
-
chunkId: Number(row.id),
|
|
1899
|
-
path,
|
|
1900
|
-
startLine,
|
|
1901
|
-
endLine,
|
|
1902
|
-
score: 0,
|
|
1903
|
-
textScore: 0,
|
|
1904
|
-
snippet: truncateSnippet(String(row.text ?? "")),
|
|
1905
|
-
source: String(row.source),
|
|
1906
|
-
citation: `${path}:${startLine}-${endLine}`
|
|
1907
|
-
};
|
|
1908
|
-
});
|
|
1909
|
-
}
|
|
1910
|
-
// ───── persistence helpers ─────────────────────────────────────────
|
|
1911
|
-
loadFilesIndex() {
|
|
1912
|
-
const rows = this.db.prepare("SELECT id, path, hash FROM files").all();
|
|
1913
|
-
return new Map(rows.map((row) => [row.path, { id: row.id, hash: row.hash }]));
|
|
1914
|
-
}
|
|
1915
|
-
upsertFile(absPath, relPath, hash, mtimeMs, source = "memory") {
|
|
1916
|
-
const stmt = this.db.prepare(
|
|
1917
|
-
`INSERT INTO files (path, rel_path, mtime, hash, source) VALUES (?, ?, ?, ?, ?)
|
|
1918
|
-
ON CONFLICT(path) DO UPDATE SET hash = excluded.hash, mtime = excluded.mtime, source = excluded.source
|
|
1919
|
-
RETURNING id`
|
|
1920
|
-
);
|
|
1921
|
-
const row = stmt.get(absPath, relPath, Math.floor(mtimeMs), hash, source);
|
|
1922
|
-
return row.id;
|
|
1923
|
-
}
|
|
1924
|
-
deleteChunksForFile(fileId) {
|
|
1925
|
-
this.db.prepare("DELETE FROM chunks WHERE file_id = ?").run(fileId);
|
|
1926
|
-
}
|
|
1927
|
-
insertChunk(fileId, startLine, endLine, text, hash) {
|
|
1928
|
-
this.db.prepare(
|
|
1929
|
-
"INSERT INTO chunks (file_id, start_line, end_line, text, hash) VALUES (?, ?, ?, ?, ?)"
|
|
1930
|
-
).run(fileId, startLine, endLine, text, hash);
|
|
1931
|
-
}
|
|
1932
|
-
close() {
|
|
1933
|
-
this.db.close();
|
|
1934
|
-
}
|
|
1935
|
-
};
|
|
1936
|
-
function resolveWeights(options) {
|
|
1937
|
-
const vectorWeight = options.vectorWeight ?? 0.6;
|
|
1938
|
-
const textWeight = options.textWeight ?? 0.4;
|
|
1939
|
-
const total = vectorWeight + textWeight || 1;
|
|
1940
|
-
return { vectorWeight, textWeight, total };
|
|
1941
|
-
}
|
|
1942
|
-
function blendScores(hit, vectorScore, weights) {
|
|
1943
|
-
const score = (vectorScore * weights.vectorWeight + hit.textScore * weights.textWeight) / weights.total;
|
|
1944
|
-
return {
|
|
1945
|
-
path: hit.path,
|
|
1946
|
-
startLine: hit.startLine,
|
|
1947
|
-
endLine: hit.endLine,
|
|
1948
|
-
score,
|
|
1949
|
-
textScore: hit.textScore,
|
|
1950
|
-
snippet: hit.snippet,
|
|
1951
|
-
source: hit.source,
|
|
1952
|
-
citation: hit.citation,
|
|
1953
|
-
...vectorScore > 0 ? { vectorScore } : {}
|
|
1954
|
-
};
|
|
1955
|
-
}
|
|
1956
|
-
function sha256(text) {
|
|
1957
|
-
return crypto.createHash("sha256").update(text).digest("hex");
|
|
1958
|
-
}
|
|
1959
|
-
function truncateSnippet(text) {
|
|
1960
|
-
const max = 500;
|
|
1961
|
-
return text.length <= max ? text : `${text.slice(0, max)}\u2026`;
|
|
1962
|
-
}
|
|
1963
|
-
function nfcEqual(a, b) {
|
|
1964
|
-
return a.normalize("NFC") === b.normalize("NFC");
|
|
1965
|
-
}
|
|
1966
|
-
async function migrateSqliteToLance(opts) {
|
|
1967
|
-
const cwd = opts.cwd;
|
|
1968
|
-
const memoryRoot = memoryStore.resolveMemoryRoot(cwd, { directory: opts.directory });
|
|
1969
|
-
const finalPath = memoryStore.lanceStoragePath(memoryRoot);
|
|
1970
|
-
const newPath = path.join(memoryRoot, "lance-new");
|
|
1971
|
-
const rawLog = opts.logger ?? ((m) => console.log(m));
|
|
1972
|
-
const log = (m) => rawLog(redactSecrets(m));
|
|
1973
|
-
if (fs.existsSync(finalPath)) {
|
|
1974
|
-
throw new errors.ConfigurationError(
|
|
1975
|
-
`Destination already exists: ${finalPath}. Remove it manually (\`rm -rf ${finalPath}\`) and re-run.`,
|
|
1976
|
-
{ code: "migration_destination_exists" }
|
|
1977
|
-
);
|
|
1978
|
-
}
|
|
1979
|
-
if (fs.existsSync(newPath)) {
|
|
1980
|
-
log(`Removing stale ${newPath} from a previous run...`);
|
|
1981
|
-
fs.rmSync(newPath, { recursive: true, force: true });
|
|
1982
|
-
}
|
|
1983
|
-
log(`Reading SQLite facts from ${cwd}/.theokit/memory/index.sqlite ...`);
|
|
1984
|
-
const sqliteFacts = await memoryStore.readAllSqliteFacts(memoryRoot);
|
|
1985
|
-
log(`SQLite has ${sqliteFacts.length} facts.`);
|
|
1986
|
-
if (sqliteFacts.length === 0) {
|
|
1987
|
-
return {
|
|
1988
|
-
countSqlite: 0,
|
|
1989
|
-
countLance: 0,
|
|
1990
|
-
validated: true,
|
|
1991
|
-
sampleComparisons: [],
|
|
1992
|
-
lancePath: finalPath,
|
|
1993
|
-
committed: false
|
|
1994
|
-
};
|
|
1995
|
-
}
|
|
1996
|
-
const placeholderEmbedding = {
|
|
1997
|
-
id: "migration-placeholder",
|
|
1998
|
-
model: "deterministic-hash",
|
|
1999
|
-
dimension: 8,
|
|
2000
|
-
embed: async (texts) => {
|
|
2001
|
-
return texts.map((t) => {
|
|
2002
|
-
const arr = new Array(8).fill(0);
|
|
2003
|
-
for (let i = 0; i < t.length; i += 1) {
|
|
2004
|
-
arr[i % 8] += t.charCodeAt(i);
|
|
2005
|
-
}
|
|
2006
|
-
return arr.map((x) => x / 1e3);
|
|
2007
|
-
});
|
|
2008
|
-
},
|
|
2009
|
-
stats: () => ({ cacheHits: 0, cacheMisses: 0, httpCalls: 0, retries: 0 })
|
|
2010
|
-
};
|
|
2011
|
-
fs.mkdirSync(newPath, { recursive: true });
|
|
2012
|
-
log(`Writing Lance index to ${newPath} ...`);
|
|
2013
|
-
const lance = await LanceIndex.open({
|
|
2014
|
-
cwd,
|
|
2015
|
-
embedding: placeholderEmbedding,
|
|
2016
|
-
storagePath: newPath
|
|
2017
|
-
});
|
|
2018
|
-
const batchSize = opts.batchSize ?? 100;
|
|
2019
|
-
for (let i = 0; i < sqliteFacts.length; i += batchSize) {
|
|
2020
|
-
const batch = sqliteFacts.slice(i, i + batchSize).map((f) => ({
|
|
2021
|
-
id: f.id,
|
|
2022
|
-
text: f.text,
|
|
2023
|
-
source: f.source,
|
|
2024
|
-
namespace: f.namespace ?? "default",
|
|
2025
|
-
scope: f.scope ?? "agent",
|
|
2026
|
-
user_id: f.user_id ?? "default",
|
|
2027
|
-
timestamp: 0
|
|
2028
|
-
}));
|
|
2029
|
-
await lance.addFacts(batch);
|
|
2030
|
-
log(` Migrated ${Math.min(i + batchSize, sqliteFacts.length)}/${sqliteFacts.length}`);
|
|
2031
|
-
}
|
|
2032
|
-
const lanceCount = await lance.countFacts("default");
|
|
2033
|
-
log(`Lance has ${lanceCount} facts (expected ${sqliteFacts.length}).`);
|
|
2034
|
-
const sampleSize = Math.min(10, sqliteFacts.length);
|
|
2035
|
-
const sampleComparisons = [];
|
|
2036
|
-
for (let i = 0; i < sampleSize; i += 1) {
|
|
2037
|
-
const sqliteFact = sqliteFacts[Math.floor(i * sqliteFacts.length / sampleSize)];
|
|
2038
|
-
if (sqliteFact === void 0) continue;
|
|
2039
|
-
const hits = await lance.search(sqliteFact.text, {
|
|
2040
|
-
namespace: sqliteFact.namespace ?? "default",
|
|
2041
|
-
limit: 1
|
|
2042
|
-
});
|
|
2043
|
-
const hit = hits[0];
|
|
2044
|
-
const match = hit !== void 0 && nfcEqual(hit.text, sqliteFact.text);
|
|
2045
|
-
sampleComparisons.push({ id: sqliteFact.id, match });
|
|
2046
|
-
}
|
|
2047
|
-
const allMatch = sampleComparisons.every((c) => c.match);
|
|
2048
|
-
const countMatch = lanceCount === sqliteFacts.length;
|
|
2049
|
-
const validated = allMatch && countMatch;
|
|
2050
|
-
await lance.close();
|
|
2051
|
-
if (opts.dryRun === true) {
|
|
2052
|
-
log("Dry-run mode \u2014 discarding Lance staging dir.");
|
|
2053
|
-
fs.rmSync(newPath, { recursive: true, force: true });
|
|
2054
|
-
return {
|
|
2055
|
-
countSqlite: sqliteFacts.length,
|
|
2056
|
-
countLance: lanceCount,
|
|
2057
|
-
validated,
|
|
2058
|
-
sampleComparisons,
|
|
2059
|
-
lancePath: finalPath,
|
|
2060
|
-
committed: false
|
|
2061
|
-
};
|
|
2062
|
-
}
|
|
2063
|
-
if (!validated) {
|
|
2064
|
-
log("Validation FAILED \u2014 leaving SQLite intact, removing Lance staging dir.");
|
|
2065
|
-
fs.rmSync(newPath, { recursive: true, force: true });
|
|
2066
|
-
return {
|
|
2067
|
-
countSqlite: sqliteFacts.length,
|
|
2068
|
-
countLance: lanceCount,
|
|
2069
|
-
validated: false,
|
|
2070
|
-
sampleComparisons,
|
|
2071
|
-
lancePath: finalPath,
|
|
2072
|
-
committed: false
|
|
2073
|
-
};
|
|
2074
|
-
}
|
|
2075
|
-
fs.renameSync(newPath, finalPath);
|
|
2076
|
-
log(`Migration committed to ${finalPath}.`);
|
|
2077
|
-
return {
|
|
2078
|
-
countSqlite: sqliteFacts.length,
|
|
2079
|
-
countLance: lanceCount,
|
|
2080
|
-
validated: true,
|
|
2081
|
-
sampleComparisons,
|
|
2082
|
-
lancePath: finalPath,
|
|
2083
|
-
committed: true
|
|
2084
|
-
};
|
|
2085
|
-
}
|
|
2086
|
-
async function fileExists(path) {
|
|
2087
|
-
try {
|
|
2088
|
-
await promises.access(path);
|
|
2089
|
-
return true;
|
|
2090
|
-
} catch {
|
|
2091
|
-
return false;
|
|
2092
|
-
}
|
|
2093
|
-
}
|
|
2094
|
-
async function readLegacyFacts(jsonPath) {
|
|
2095
|
-
try {
|
|
2096
|
-
const raw = await promises.readFile(jsonPath, "utf8");
|
|
2097
|
-
const parsed = JSON.parse(raw);
|
|
2098
|
-
return Array.isArray(parsed.facts) ? parsed.facts : [];
|
|
2099
|
-
} catch {
|
|
2100
|
-
return void 0;
|
|
2101
|
-
}
|
|
2102
|
-
}
|
|
2103
|
-
async function writeMigratedFacts(cwd, jsonPath, facts) {
|
|
2104
|
-
try {
|
|
2105
|
-
for (const fact of facts) await memoryStore.appendFactToMarkdown(cwd, fact);
|
|
2106
|
-
await promises.unlink(jsonPath).catch(() => void 0);
|
|
2107
|
-
process.stderr.write(
|
|
2108
|
-
`[theokit-sdk] migrated ${facts.length} fact(s) from ${jsonPath} to MEMORY.md
|
|
2109
|
-
`
|
|
2110
|
-
);
|
|
2111
|
-
return { migrated: true, factCount: facts.length };
|
|
2112
|
-
} catch (cause) {
|
|
2113
|
-
const message = cause instanceof Error ? cause.message : String(cause);
|
|
2114
|
-
process.stderr.write(`[theokit-sdk] memory migration failed (readonly fs?): ${message}
|
|
2115
|
-
`);
|
|
2116
|
-
return { migrated: false, factCount: 0, reason: "readonly-fs" };
|
|
2117
|
-
}
|
|
2118
|
-
}
|
|
2119
|
-
var migrationRun = /* @__PURE__ */ new Set();
|
|
2120
|
-
async function migrateLegacyJson(cwd, config) {
|
|
2121
|
-
const key = `${cwd}::${config.namespace ?? "default"}::${config.scope ?? "agent"}::${config.userId ?? "default"}`;
|
|
2122
|
-
if (migrationRun.has(key)) return { migrated: false, factCount: 0, reason: "already-migrated" };
|
|
2123
|
-
migrationRun.add(key);
|
|
2124
|
-
const jsonPath = legacyMemoryJsonPath(cwd, config);
|
|
2125
|
-
if (!await fileExists(jsonPath)) {
|
|
2126
|
-
return { migrated: false, factCount: 0, reason: "no-legacy-json" };
|
|
2127
|
-
}
|
|
2128
|
-
if (await fileExists(memoryStore.memoryMdPath(memoryStore.resolveMemoryRoot(cwd)))) {
|
|
2129
|
-
process.stderr.write(
|
|
2130
|
-
`[theokit-sdk] memory migration skipped: both MEMORY.md and legacy JSON exist at ${jsonPath}; leaving both intact
|
|
2131
|
-
`
|
|
2132
|
-
);
|
|
2133
|
-
return { migrated: false, factCount: 0, reason: "markdown-exists" };
|
|
2134
|
-
}
|
|
2135
|
-
const facts = await readLegacyFacts(jsonPath);
|
|
2136
|
-
if (facts === void 0) return { migrated: false, factCount: 0, reason: "no-legacy-json" };
|
|
2137
|
-
return writeMigratedFacts(cwd, jsonPath, facts);
|
|
2138
|
-
}
|
|
2139
|
-
function resetMigrationStateForTests() {
|
|
2140
|
-
migrationRun.clear();
|
|
2141
|
-
}
|
|
2142
|
-
var DEFAULT_MEMORY_READ_LINES = 200;
|
|
2143
|
-
async function readMemoryFileBounded(opts) {
|
|
2144
|
-
const absolutePath = path.resolve(opts.cwd, opts.relPath);
|
|
2145
|
-
const raw = await promises.readFile(absolutePath, "utf8");
|
|
2146
|
-
const allLines = raw.split("\n");
|
|
2147
|
-
const trimmedLines = allLines.length > 0 && allLines[allLines.length - 1] === "" ? allLines.slice(0, -1) : allLines;
|
|
2148
|
-
const totalLines = trimmedLines.length;
|
|
2149
|
-
const requestedFrom = Math.max(1, opts.from ?? 1);
|
|
2150
|
-
const requestedLines = Math.max(1, opts.lines ?? DEFAULT_MEMORY_READ_LINES);
|
|
2151
|
-
const startIdx = requestedFrom - 1;
|
|
2152
|
-
const endIdx = Math.min(totalLines, startIdx + requestedLines);
|
|
2153
|
-
const slice = trimmedLines.slice(startIdx, endIdx);
|
|
2154
|
-
const linesReturned = slice.length;
|
|
2155
|
-
const remainingLines = Math.max(0, totalLines - endIdx);
|
|
2156
|
-
const truncated = remainingLines > 0;
|
|
2157
|
-
return {
|
|
2158
|
-
path: opts.relPath,
|
|
2159
|
-
from: requestedFrom,
|
|
2160
|
-
linesReturned,
|
|
2161
|
-
totalLines,
|
|
2162
|
-
truncated,
|
|
2163
|
-
remainingLines,
|
|
2164
|
-
text: slice.join("\n")
|
|
2165
|
-
};
|
|
2166
|
-
}
|
|
2167
1101
|
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.";
|
|
2168
1102
|
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.";
|
|
2169
1103
|
var MEMORY_SEARCH_SCHEMA = {
|
|
@@ -2233,7 +1167,7 @@ function createMemoryGetTool(opts) {
|
|
|
2233
1167
|
};
|
|
2234
1168
|
if (from !== void 0) readArgs.from = from;
|
|
2235
1169
|
if (lines !== void 0) readArgs.lines = lines;
|
|
2236
|
-
const result = await readMemoryFileBounded(readArgs);
|
|
1170
|
+
const result = await memoryStore.readMemoryFileBounded(readArgs);
|
|
2237
1171
|
return JSON.stringify(result);
|
|
2238
1172
|
}
|
|
2239
1173
|
};
|
|
@@ -2280,6 +1214,22 @@ function isPathInside(root, candidate) {
|
|
|
2280
1214
|
return candidate === root || candidate.startsWith(normalizedRoot);
|
|
2281
1215
|
}
|
|
2282
1216
|
|
|
1217
|
+
Object.defineProperty(exports, "ActiveMemoryCache", {
|
|
1218
|
+
enumerable: true,
|
|
1219
|
+
get: function () { return memoryStore.ActiveMemoryCache; }
|
|
1220
|
+
});
|
|
1221
|
+
Object.defineProperty(exports, "DEFAULT_MEMORY_READ_LINES", {
|
|
1222
|
+
enumerable: true,
|
|
1223
|
+
get: function () { return memoryStore.DEFAULT_MEMORY_READ_LINES; }
|
|
1224
|
+
});
|
|
1225
|
+
Object.defineProperty(exports, "IndexManager", {
|
|
1226
|
+
enumerable: true,
|
|
1227
|
+
get: function () { return memoryStore.IndexManager; }
|
|
1228
|
+
});
|
|
1229
|
+
Object.defineProperty(exports, "LanceIndex", {
|
|
1230
|
+
enumerable: true,
|
|
1231
|
+
get: function () { return memoryStore.LanceIndex; }
|
|
1232
|
+
});
|
|
2283
1233
|
Object.defineProperty(exports, "MEMORY_INDEX_MAX_BYTES", {
|
|
2284
1234
|
enumerable: true,
|
|
2285
1235
|
get: function () { return memoryStore.MEMORY_INDEX_MAX_BYTES; }
|
|
@@ -2288,6 +1238,30 @@ Object.defineProperty(exports, "MEMORY_INDEX_MAX_LINES", {
|
|
|
2288
1238
|
enumerable: true,
|
|
2289
1239
|
get: function () { return memoryStore.MEMORY_INDEX_MAX_LINES; }
|
|
2290
1240
|
});
|
|
1241
|
+
Object.defineProperty(exports, "META_KEY_DIMENSION", {
|
|
1242
|
+
enumerable: true,
|
|
1243
|
+
get: function () { return memoryStore.META_KEY_DIMENSION; }
|
|
1244
|
+
});
|
|
1245
|
+
Object.defineProperty(exports, "META_KEY_MODEL", {
|
|
1246
|
+
enumerable: true,
|
|
1247
|
+
get: function () { return memoryStore.META_KEY_MODEL; }
|
|
1248
|
+
});
|
|
1249
|
+
Object.defineProperty(exports, "META_KEY_PROVIDER_ID", {
|
|
1250
|
+
enumerable: true,
|
|
1251
|
+
get: function () { return memoryStore.META_KEY_PROVIDER_ID; }
|
|
1252
|
+
});
|
|
1253
|
+
Object.defineProperty(exports, "PRAGMA_STATEMENTS", {
|
|
1254
|
+
enumerable: true,
|
|
1255
|
+
get: function () { return memoryStore.PRAGMA_STATEMENTS; }
|
|
1256
|
+
});
|
|
1257
|
+
Object.defineProperty(exports, "SCHEMA_STATEMENTS", {
|
|
1258
|
+
enumerable: true,
|
|
1259
|
+
get: function () { return memoryStore.SCHEMA_STATEMENTS; }
|
|
1260
|
+
});
|
|
1261
|
+
Object.defineProperty(exports, "VALID_BACKENDS", {
|
|
1262
|
+
enumerable: true,
|
|
1263
|
+
get: function () { return memoryStore.VALID_BACKENDS; }
|
|
1264
|
+
});
|
|
2291
1265
|
Object.defineProperty(exports, "appendDiaryEntry", {
|
|
2292
1266
|
enumerable: true,
|
|
2293
1267
|
get: function () { return memoryStore.appendDiaryEntry; }
|
|
@@ -2304,10 +1278,18 @@ Object.defineProperty(exports, "asMemoryRoot", {
|
|
|
2304
1278
|
enumerable: true,
|
|
2305
1279
|
get: function () { return memoryStore.asMemoryRoot; }
|
|
2306
1280
|
});
|
|
1281
|
+
Object.defineProperty(exports, "assertValidBackend", {
|
|
1282
|
+
enumerable: true,
|
|
1283
|
+
get: function () { return memoryStore.assertValidBackend; }
|
|
1284
|
+
});
|
|
2307
1285
|
Object.defineProperty(exports, "ceilingReachedError", {
|
|
2308
1286
|
enumerable: true,
|
|
2309
1287
|
get: function () { return memoryStore.ceilingReachedError; }
|
|
2310
1288
|
});
|
|
1289
|
+
Object.defineProperty(exports, "chunkMarkdown", {
|
|
1290
|
+
enumerable: true,
|
|
1291
|
+
get: function () { return memoryStore.chunkMarkdown; }
|
|
1292
|
+
});
|
|
2311
1293
|
Object.defineProperty(exports, "claudeProjectMemoryDir", {
|
|
2312
1294
|
enumerable: true,
|
|
2313
1295
|
get: function () { return memoryStore.claudeProjectMemoryDir; }
|
|
@@ -2316,6 +1298,14 @@ Object.defineProperty(exports, "collectMarkdownFiles", {
|
|
|
2316
1298
|
enumerable: true,
|
|
2317
1299
|
get: function () { return memoryStore.collectMarkdownFiles; }
|
|
2318
1300
|
});
|
|
1301
|
+
Object.defineProperty(exports, "createVectorIndex", {
|
|
1302
|
+
enumerable: true,
|
|
1303
|
+
get: function () { return memoryStore.createVectorIndex; }
|
|
1304
|
+
});
|
|
1305
|
+
Object.defineProperty(exports, "deepPhase", {
|
|
1306
|
+
enumerable: true,
|
|
1307
|
+
get: function () { return memoryStore.deepPhase; }
|
|
1308
|
+
});
|
|
2319
1309
|
Object.defineProperty(exports, "defaultIndexPath", {
|
|
2320
1310
|
enumerable: true,
|
|
2321
1311
|
get: function () { return memoryStore.defaultIndexPath; }
|
|
@@ -2332,18 +1322,42 @@ Object.defineProperty(exports, "discoverWikiFiles", {
|
|
|
2332
1322
|
enumerable: true,
|
|
2333
1323
|
get: function () { return memoryStore.discoverWikiFiles; }
|
|
2334
1324
|
});
|
|
1325
|
+
Object.defineProperty(exports, "dropVectorIndex", {
|
|
1326
|
+
enumerable: true,
|
|
1327
|
+
get: function () { return memoryStore.dropVectorIndex; }
|
|
1328
|
+
});
|
|
1329
|
+
Object.defineProperty(exports, "embedMissingChunks", {
|
|
1330
|
+
enumerable: true,
|
|
1331
|
+
get: function () { return memoryStore.embedMissingChunks; }
|
|
1332
|
+
});
|
|
2335
1333
|
Object.defineProperty(exports, "entryHash", {
|
|
2336
1334
|
enumerable: true,
|
|
2337
1335
|
get: function () { return memoryStore.entryHash; }
|
|
2338
1336
|
});
|
|
1337
|
+
Object.defineProperty(exports, "identityMatches", {
|
|
1338
|
+
enumerable: true,
|
|
1339
|
+
get: function () { return memoryStore.identityMatches; }
|
|
1340
|
+
});
|
|
2339
1341
|
Object.defineProperty(exports, "indexBudgetWarning", {
|
|
2340
1342
|
enumerable: true,
|
|
2341
1343
|
get: function () { return memoryStore.indexBudgetWarning; }
|
|
2342
1344
|
});
|
|
1345
|
+
Object.defineProperty(exports, "isLanceAvailable", {
|
|
1346
|
+
enumerable: true,
|
|
1347
|
+
get: function () { return memoryStore.isLanceAvailable; }
|
|
1348
|
+
});
|
|
2343
1349
|
Object.defineProperty(exports, "lanceStoragePath", {
|
|
2344
1350
|
enumerable: true,
|
|
2345
1351
|
get: function () { return memoryStore.lanceStoragePath; }
|
|
2346
1352
|
});
|
|
1353
|
+
Object.defineProperty(exports, "lightPhase", {
|
|
1354
|
+
enumerable: true,
|
|
1355
|
+
get: function () { return memoryStore.lightPhase; }
|
|
1356
|
+
});
|
|
1357
|
+
Object.defineProperty(exports, "loadSqliteVecExtension", {
|
|
1358
|
+
enumerable: true,
|
|
1359
|
+
get: function () { return memoryStore.loadSqliteVecExtension; }
|
|
1360
|
+
});
|
|
2347
1361
|
Object.defineProperty(exports, "memoryIndexRoot", {
|
|
2348
1362
|
enumerable: true,
|
|
2349
1363
|
get: function () { return memoryStore.memoryIndexRoot; }
|
|
@@ -2356,10 +1370,34 @@ Object.defineProperty(exports, "memoryReadRoots", {
|
|
|
2356
1370
|
enumerable: true,
|
|
2357
1371
|
get: function () { return memoryStore.memoryReadRoots; }
|
|
2358
1372
|
});
|
|
1373
|
+
Object.defineProperty(exports, "migrateLegacyJson", {
|
|
1374
|
+
enumerable: true,
|
|
1375
|
+
get: function () { return memoryStore.migrateLegacyJson; }
|
|
1376
|
+
});
|
|
1377
|
+
Object.defineProperty(exports, "migrateSqliteToLance", {
|
|
1378
|
+
enumerable: true,
|
|
1379
|
+
get: function () { return memoryStore.migrateSqliteToLance; }
|
|
1380
|
+
});
|
|
2359
1381
|
Object.defineProperty(exports, "notesDir", {
|
|
2360
1382
|
enumerable: true,
|
|
2361
1383
|
get: function () { return memoryStore.notesDir; }
|
|
2362
1384
|
});
|
|
1385
|
+
Object.defineProperty(exports, "openLanceIndex", {
|
|
1386
|
+
enumerable: true,
|
|
1387
|
+
get: function () { return memoryStore.openLanceIndex; }
|
|
1388
|
+
});
|
|
1389
|
+
Object.defineProperty(exports, "openMemoryDb", {
|
|
1390
|
+
enumerable: true,
|
|
1391
|
+
get: function () { return memoryStore.openMemoryDb; }
|
|
1392
|
+
});
|
|
1393
|
+
Object.defineProperty(exports, "packVector", {
|
|
1394
|
+
enumerable: true,
|
|
1395
|
+
get: function () { return memoryStore.packVector; }
|
|
1396
|
+
});
|
|
1397
|
+
Object.defineProperty(exports, "parseSearchOptions", {
|
|
1398
|
+
enumerable: true,
|
|
1399
|
+
get: function () { return memoryStore.parseSearchOptions; }
|
|
1400
|
+
});
|
|
2363
1401
|
Object.defineProperty(exports, "persistActiveMemoryTranscript", {
|
|
2364
1402
|
enumerable: true,
|
|
2365
1403
|
get: function () { return memoryStore.persistActiveMemoryTranscript; }
|
|
@@ -2372,6 +1410,10 @@ Object.defineProperty(exports, "readAllSqliteFacts", {
|
|
|
2372
1410
|
enumerable: true,
|
|
2373
1411
|
get: function () { return memoryStore.readAllSqliteFacts; }
|
|
2374
1412
|
});
|
|
1413
|
+
Object.defineProperty(exports, "readEmbeddingIdentity", {
|
|
1414
|
+
enumerable: true,
|
|
1415
|
+
get: function () { return memoryStore.readEmbeddingIdentity; }
|
|
1416
|
+
});
|
|
2375
1417
|
Object.defineProperty(exports, "readFacts", {
|
|
2376
1418
|
enumerable: true,
|
|
2377
1419
|
get: function () { return memoryStore.readFacts; }
|
|
@@ -2380,10 +1422,22 @@ Object.defineProperty(exports, "readFactsFromMarkdown", {
|
|
|
2380
1422
|
enumerable: true,
|
|
2381
1423
|
get: function () { return memoryStore.readFactsFromMarkdown; }
|
|
2382
1424
|
});
|
|
1425
|
+
Object.defineProperty(exports, "readMemoryFileBounded", {
|
|
1426
|
+
enumerable: true,
|
|
1427
|
+
get: function () { return memoryStore.readMemoryFileBounded; }
|
|
1428
|
+
});
|
|
1429
|
+
Object.defineProperty(exports, "remPhase", {
|
|
1430
|
+
enumerable: true,
|
|
1431
|
+
get: function () { return memoryStore.remPhase; }
|
|
1432
|
+
});
|
|
2383
1433
|
Object.defineProperty(exports, "renderDiaryEntry", {
|
|
2384
1434
|
enumerable: true,
|
|
2385
1435
|
get: function () { return memoryStore.renderDiaryEntry; }
|
|
2386
1436
|
});
|
|
1437
|
+
Object.defineProperty(exports, "resetMigrationStateForTests", {
|
|
1438
|
+
enumerable: true,
|
|
1439
|
+
get: function () { return memoryStore.resetMigrationStateForTests; }
|
|
1440
|
+
});
|
|
2387
1441
|
Object.defineProperty(exports, "resolveMaxFacts", {
|
|
2388
1442
|
enumerable: true,
|
|
2389
1443
|
get: function () { return memoryStore.resolveMaxFacts; }
|
|
@@ -2392,6 +1446,10 @@ Object.defineProperty(exports, "resolveMemoryRoot", {
|
|
|
2392
1446
|
enumerable: true,
|
|
2393
1447
|
get: function () { return memoryStore.resolveMemoryRoot; }
|
|
2394
1448
|
});
|
|
1449
|
+
Object.defineProperty(exports, "runDreamingSweep", {
|
|
1450
|
+
enumerable: true,
|
|
1451
|
+
get: function () { return memoryStore.runDreamingSweep; }
|
|
1452
|
+
});
|
|
2395
1453
|
Object.defineProperty(exports, "sessionSummaryPath", {
|
|
2396
1454
|
enumerable: true,
|
|
2397
1455
|
get: function () { return memoryStore.sessionSummaryPath; }
|
|
@@ -2400,10 +1458,22 @@ Object.defineProperty(exports, "sessionsDir", {
|
|
|
2400
1458
|
enumerable: true,
|
|
2401
1459
|
get: function () { return memoryStore.sessionsDir; }
|
|
2402
1460
|
});
|
|
1461
|
+
Object.defineProperty(exports, "upsertEmbedding", {
|
|
1462
|
+
enumerable: true,
|
|
1463
|
+
get: function () { return memoryStore.upsertEmbedding; }
|
|
1464
|
+
});
|
|
1465
|
+
Object.defineProperty(exports, "vectorSearch", {
|
|
1466
|
+
enumerable: true,
|
|
1467
|
+
get: function () { return memoryStore.vectorSearch; }
|
|
1468
|
+
});
|
|
2403
1469
|
Object.defineProperty(exports, "wikiDir", {
|
|
2404
1470
|
enumerable: true,
|
|
2405
1471
|
get: function () { return memoryStore.wikiDir; }
|
|
2406
1472
|
});
|
|
1473
|
+
Object.defineProperty(exports, "writeEmbeddingIdentity", {
|
|
1474
|
+
enumerable: true,
|
|
1475
|
+
get: function () { return memoryStore.writeEmbeddingIdentity; }
|
|
1476
|
+
});
|
|
2407
1477
|
Object.defineProperty(exports, "writeSessionSummary", {
|
|
2408
1478
|
enumerable: true,
|
|
2409
1479
|
get: function () { return memoryStore.writeSessionSummary; }
|
|
@@ -2412,75 +1482,41 @@ Object.defineProperty(exports, "createOpenAiCompatibleRuntime", {
|
|
|
2412
1482
|
enumerable: true,
|
|
2413
1483
|
get: function () { return memoryAdapters.createOpenAiCompatibleRuntime; }
|
|
2414
1484
|
});
|
|
2415
|
-
exports.ActiveMemoryCache = ActiveMemoryCache;
|
|
2416
1485
|
exports.CircuitBreaker = CircuitBreaker;
|
|
2417
1486
|
exports.DEFAULT_AZURE_OPENAI_EMBEDDING_MODEL = DEFAULT_AZURE_OPENAI_EMBEDDING_MODEL;
|
|
2418
1487
|
exports.DEFAULT_COHERE_EMBEDDING_MODEL = DEFAULT_COHERE_EMBEDDING_MODEL;
|
|
2419
1488
|
exports.DEFAULT_DEEPINFRA_EMBEDDING_MODEL = DEFAULT_DEEPINFRA_EMBEDDING_MODEL;
|
|
2420
1489
|
exports.DEFAULT_GEMINI_EMBEDDING_MODEL = DEFAULT_GEMINI_EMBEDDING_MODEL;
|
|
2421
1490
|
exports.DEFAULT_JINA_EMBEDDING_MODEL = DEFAULT_JINA_EMBEDDING_MODEL;
|
|
2422
|
-
exports.DEFAULT_MEMORY_READ_LINES = DEFAULT_MEMORY_READ_LINES;
|
|
2423
1491
|
exports.DEFAULT_MISTRAL_EMBEDDING_MODEL = DEFAULT_MISTRAL_EMBEDDING_MODEL;
|
|
2424
1492
|
exports.DEFAULT_OLLAMA_EMBEDDING_MODEL = DEFAULT_OLLAMA_EMBEDDING_MODEL;
|
|
2425
1493
|
exports.DEFAULT_OPENAI_EMBEDDING_MODEL = DEFAULT_OPENAI_EMBEDDING_MODEL;
|
|
2426
1494
|
exports.DEFAULT_OPENROUTER_EMBEDDING_MODEL = DEFAULT_OPENROUTER_EMBEDDING_MODEL;
|
|
2427
1495
|
exports.DEFAULT_VOYAGE_EMBEDDING_MODEL = DEFAULT_VOYAGE_EMBEDDING_MODEL;
|
|
2428
|
-
exports.IndexManager = IndexManager;
|
|
2429
|
-
exports.LanceIndex = LanceIndex;
|
|
2430
1496
|
exports.LanceMemoryAdapter = LanceMemoryAdapter;
|
|
2431
1497
|
exports.MEMORY_EMBEDDING_ADAPTERS = MEMORY_EMBEDDING_ADAPTERS;
|
|
2432
|
-
exports.META_KEY_DIMENSION = META_KEY_DIMENSION;
|
|
2433
|
-
exports.META_KEY_MODEL = META_KEY_MODEL;
|
|
2434
|
-
exports.META_KEY_PROVIDER_ID = META_KEY_PROVIDER_ID;
|
|
2435
|
-
exports.PRAGMA_STATEMENTS = PRAGMA_STATEMENTS;
|
|
2436
|
-
exports.SCHEMA_STATEMENTS = SCHEMA_STATEMENTS;
|
|
2437
|
-
exports.VALID_BACKENDS = VALID_BACKENDS;
|
|
2438
|
-
exports.assertValidBackend = assertValidBackend;
|
|
2439
1498
|
exports.azureOpenAiMemoryEmbeddingProviderAdapter = azureOpenAiMemoryEmbeddingProviderAdapter;
|
|
2440
1499
|
exports.buildErrorMetadata = buildErrorMetadata;
|
|
2441
|
-
exports.chunkMarkdown = chunkMarkdown;
|
|
2442
1500
|
exports.cohereMemoryEmbeddingProviderAdapter = cohereMemoryEmbeddingProviderAdapter;
|
|
2443
1501
|
exports.createCategorizedMemory = createCategorizedMemory;
|
|
2444
1502
|
exports.createInMemoryMarkdownProvider = createInMemoryMarkdownProvider;
|
|
2445
1503
|
exports.createMemoryGetTool = createMemoryGetTool;
|
|
2446
1504
|
exports.createMemorySearchTool = createMemorySearchTool;
|
|
2447
|
-
exports.createVectorIndex = createVectorIndex;
|
|
2448
|
-
exports.deepPhase = deepPhase;
|
|
2449
1505
|
exports.deepinfraMemoryEmbeddingProviderAdapter = deepinfraMemoryEmbeddingProviderAdapter;
|
|
2450
|
-
exports.dropVectorIndex = dropVectorIndex;
|
|
2451
|
-
exports.embedMissingChunks = embedMissingChunks;
|
|
2452
1506
|
exports.geminiMemoryEmbeddingProviderAdapter = geminiMemoryEmbeddingProviderAdapter;
|
|
2453
|
-
exports.identityMatches = identityMatches;
|
|
2454
|
-
exports.isLanceAvailable = isLanceAvailable;
|
|
2455
1507
|
exports.isSqliteVecLoaded = isSqliteVecLoaded;
|
|
2456
1508
|
exports.jinaMemoryEmbeddingProviderAdapter = jinaMemoryEmbeddingProviderAdapter;
|
|
2457
1509
|
exports.legacyMemoryJsonPath = legacyMemoryJsonPath;
|
|
2458
|
-
exports.lightPhase = lightPhase;
|
|
2459
1510
|
exports.listNotes = listNotes;
|
|
2460
|
-
exports.loadSqliteVecExtension = loadSqliteVecExtension;
|
|
2461
1511
|
exports.mapOpenAICompatibleError = mapOpenAICompatibleError;
|
|
2462
|
-
exports.migrateLegacyJson = migrateLegacyJson;
|
|
2463
|
-
exports.migrateSqliteToLance = migrateSqliteToLance;
|
|
2464
1512
|
exports.mistralMemoryEmbeddingProviderAdapter = mistralMemoryEmbeddingProviderAdapter;
|
|
2465
1513
|
exports.ollamaMemoryEmbeddingProviderAdapter = ollamaMemoryEmbeddingProviderAdapter;
|
|
2466
1514
|
exports.openAiMemoryEmbeddingProviderAdapter = openAiMemoryEmbeddingProviderAdapter;
|
|
2467
|
-
exports.openLanceIndex = openLanceIndex;
|
|
2468
|
-
exports.openMemoryDb = openMemoryDb;
|
|
2469
1515
|
exports.openRouterMemoryEmbeddingProviderAdapter = openRouterMemoryEmbeddingProviderAdapter;
|
|
2470
|
-
exports.packVector = packVector;
|
|
2471
1516
|
exports.parseRetryAfter = parseRetryAfter;
|
|
2472
|
-
exports.parseSearchOptions = parseSearchOptions;
|
|
2473
|
-
exports.readEmbeddingIdentity = readEmbeddingIdentity;
|
|
2474
|
-
exports.readMemoryFileBounded = readMemoryFileBounded;
|
|
2475
1517
|
exports.redactSecrets = redactSecrets;
|
|
2476
|
-
exports.remPhase = remPhase;
|
|
2477
|
-
exports.resetMigrationStateForTests = resetMigrationStateForTests;
|
|
2478
1518
|
exports.runActiveMemory = runActiveMemory;
|
|
2479
|
-
exports.runDreamingSweep = runDreamingSweep;
|
|
2480
1519
|
exports.truncateRaw = truncateRaw;
|
|
2481
|
-
exports.upsertEmbedding = upsertEmbedding;
|
|
2482
|
-
exports.vectorSearch = vectorSearch;
|
|
2483
1520
|
exports.voyageMemoryEmbeddingProviderAdapter = voyageMemoryEmbeddingProviderAdapter;
|
|
2484
|
-
exports.writeEmbeddingIdentity = writeEmbeddingIdentity;
|
|
2485
1521
|
//# sourceMappingURL=index.cjs.map
|
|
2486
1522
|
//# sourceMappingURL=index.cjs.map
|