@theokit/sdk-memory 0.5.3 → 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.
- package/CHANGELOG.md +51 -0
- package/dist/in-memory-provider.d.ts +21 -1
- package/dist/in-memory-provider.d.ts.map +1 -1
- package/dist/index.cjs +178 -498
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +61 -464
- 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 -50
- package/dist/internal/dreaming/dreaming-phases.d.ts.map +1 -1
- package/dist/internal/dreaming/dreaming-run.d.ts +3 -78
- 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-schema.d.ts +1 -29
- package/dist/internal/index/index-schema.d.ts.map +1 -1
- package/dist/internal/index/memory-index.d.ts +1 -10
- package/dist/internal/index/memory-index.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/markdown-store.d.ts +1 -1
- package/dist/internal/store/markdown-store.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 +4 -4
package/dist/index.cjs
CHANGED
|
@@ -3,18 +3,19 @@
|
|
|
3
3
|
var promises = require('fs/promises');
|
|
4
4
|
var path = require('path');
|
|
5
5
|
var sdk = require('@theokit/sdk');
|
|
6
|
-
var persistence = require('@theokit/sdk/persistence');
|
|
7
6
|
var memoryStore = require('@theokit/sdk/internal/memory-store');
|
|
8
|
-
var
|
|
7
|
+
var persistence = require('@theokit/sdk/persistence');
|
|
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');
|
|
11
|
+
var crypto = require('crypto');
|
|
12
12
|
var fs = require('fs');
|
|
13
13
|
var module$1 = require('module');
|
|
14
14
|
|
|
15
15
|
var _documentCurrentScript = typeof document !== 'undefined' ? document.currentScript : null;
|
|
16
16
|
// src/in-memory-provider.ts
|
|
17
17
|
var ADAPTER_ID = "in-memory-md";
|
|
18
|
+
var IN_MEMORY_REMEDY = "merge or delete facts with the adapter's delete(id), or raise maxFacts";
|
|
18
19
|
var INTERNAL_STATE = /* @__PURE__ */ Symbol("sdk-memory.in-memory.state");
|
|
19
20
|
function buildCapabilities() {
|
|
20
21
|
return {
|
|
@@ -26,6 +27,19 @@ function buildCapabilities() {
|
|
|
26
27
|
prefetch: false
|
|
27
28
|
};
|
|
28
29
|
}
|
|
30
|
+
function admitNewFact(state) {
|
|
31
|
+
if (state.maxFacts !== void 0 && state.facts.size >= state.maxFacts) {
|
|
32
|
+
throw memoryStore.ceilingReachedError(
|
|
33
|
+
"the in-memory store",
|
|
34
|
+
state.facts.size,
|
|
35
|
+
state.maxFacts,
|
|
36
|
+
IN_MEMORY_REMEDY
|
|
37
|
+
);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
function isCeilingRefusal(cause) {
|
|
41
|
+
return cause instanceof sdk.ConfigurationError && cause.code === "memory_ceiling_reached";
|
|
42
|
+
}
|
|
29
43
|
function buildAdapter(state) {
|
|
30
44
|
return {
|
|
31
45
|
id: ADAPTER_ID,
|
|
@@ -36,6 +50,7 @@ function buildAdapter(state) {
|
|
|
36
50
|
async write(content, _ctx) {
|
|
37
51
|
const text = typeof content === "string" ? content : content.map((m) => m.content).join("\n");
|
|
38
52
|
const safeText = sdk.Security.redact(text);
|
|
53
|
+
admitNewFact(state);
|
|
39
54
|
const id = `${ADAPTER_ID}:${state.counter.next++}`;
|
|
40
55
|
state.facts.set(id, {
|
|
41
56
|
id,
|
|
@@ -181,6 +196,12 @@ function buildMemoryRememberTool(state) {
|
|
|
181
196
|
return JSON.stringify({ ok: false, error: "empty content" });
|
|
182
197
|
}
|
|
183
198
|
const safeContent = sdk.Security.redact(content);
|
|
199
|
+
try {
|
|
200
|
+
admitNewFact(state);
|
|
201
|
+
} catch (cause) {
|
|
202
|
+
if (!isCeilingRefusal(cause)) throw cause;
|
|
203
|
+
return JSON.stringify({ ok: false, code: cause.code, error: cause.message });
|
|
204
|
+
}
|
|
184
205
|
const id = `${ADAPTER_ID}:${state.counter.next++}`;
|
|
185
206
|
state.facts.set(id, {
|
|
186
207
|
id,
|
|
@@ -191,11 +212,13 @@ function buildMemoryRememberTool(state) {
|
|
|
191
212
|
}
|
|
192
213
|
};
|
|
193
214
|
}
|
|
194
|
-
function createInMemoryMarkdownProvider() {
|
|
215
|
+
function createInMemoryMarkdownProvider(options = {}) {
|
|
216
|
+
const maxFacts = memoryStore.resolveMaxFacts(options.maxFacts);
|
|
195
217
|
return {
|
|
196
218
|
async init(opts) {
|
|
197
219
|
const state = {
|
|
198
220
|
facts: /* @__PURE__ */ new Map(),
|
|
221
|
+
maxFacts,
|
|
199
222
|
counter: { next: 0 },
|
|
200
223
|
cwd: opts.cwd
|
|
201
224
|
};
|
|
@@ -482,48 +505,6 @@ var CircuitBreaker = class {
|
|
|
482
505
|
return this.opts.now?.() ?? Date.now();
|
|
483
506
|
}
|
|
484
507
|
};
|
|
485
|
-
var DEFAULT_TTL_MS = 15e3;
|
|
486
|
-
var DEFAULT_CAPACITY = 1e3;
|
|
487
|
-
var ActiveMemoryCache = class {
|
|
488
|
-
constructor(opts = {}) {
|
|
489
|
-
this.opts = opts;
|
|
490
|
-
}
|
|
491
|
-
opts;
|
|
492
|
-
map = /* @__PURE__ */ new Map();
|
|
493
|
-
get(userText, queryMode, tenantCtx) {
|
|
494
|
-
const key = cacheKey(userText, queryMode, tenantCtx);
|
|
495
|
-
const entry = this.map.get(key);
|
|
496
|
-
if (entry === void 0) return void 0;
|
|
497
|
-
if (this.now() >= entry.expiresAtMs) {
|
|
498
|
-
this.map.delete(key);
|
|
499
|
-
return void 0;
|
|
500
|
-
}
|
|
501
|
-
this.map.delete(key);
|
|
502
|
-
this.map.set(key, entry);
|
|
503
|
-
return entry.result;
|
|
504
|
-
}
|
|
505
|
-
set(userText, queryMode, result, tenantCtx) {
|
|
506
|
-
const key = cacheKey(userText, queryMode, tenantCtx);
|
|
507
|
-
if (this.map.size >= (this.opts.capacity ?? DEFAULT_CAPACITY)) {
|
|
508
|
-
const oldest = this.map.keys().next().value;
|
|
509
|
-
if (oldest !== void 0) this.map.delete(oldest);
|
|
510
|
-
}
|
|
511
|
-
this.map.set(key, {
|
|
512
|
-
expiresAtMs: this.now() + (this.opts.ttlMs ?? DEFAULT_TTL_MS),
|
|
513
|
-
result
|
|
514
|
-
});
|
|
515
|
-
}
|
|
516
|
-
size() {
|
|
517
|
-
return this.map.size;
|
|
518
|
-
}
|
|
519
|
-
now() {
|
|
520
|
-
return this.opts.now?.() ?? Date.now();
|
|
521
|
-
}
|
|
522
|
-
};
|
|
523
|
-
function cacheKey(userText, queryMode, ctx) {
|
|
524
|
-
const parts = [queryMode, ctx?.namespace ?? "", ctx?.userId ?? "", ctx?.scope ?? "", userText];
|
|
525
|
-
return crypto.createHash("sha256").update(parts.join("\0")).digest("hex");
|
|
526
|
-
}
|
|
527
508
|
|
|
528
509
|
// src/internal/embedding/azure-openai-embedding.ts
|
|
529
510
|
var DEFAULT_AZURE_OPENAI_EMBEDDING_MODEL = "text-embedding-3-small";
|
|
@@ -863,6 +844,8 @@ function legacyMemoryJsonPath(cwd, config) {
|
|
|
863
844
|
|
|
864
845
|
// src/internal/adapter-http-error.ts
|
|
865
846
|
var RAW_MAX_BYTES = 2048;
|
|
847
|
+
var PROVIDER_DETAIL_MAX_CHARS = 512;
|
|
848
|
+
var MISSING_MODEL_MESSAGE = /no endpoints found/i;
|
|
866
849
|
function parseRetryAfter(headers) {
|
|
867
850
|
if (headers === void 0) return void 0;
|
|
868
851
|
const raw = headers.get("retry-after");
|
|
@@ -874,8 +857,8 @@ function parseRetryAfter(headers) {
|
|
|
874
857
|
function truncateRaw(body) {
|
|
875
858
|
if (body === null || body === void 0) return void 0;
|
|
876
859
|
const s = typeof body === "string" ? body : JSON.stringify(body);
|
|
877
|
-
const
|
|
878
|
-
return
|
|
860
|
+
const redacted = redactSecrets(s);
|
|
861
|
+
return redacted.length <= RAW_MAX_BYTES ? redacted : `${redacted.slice(0, RAW_MAX_BYTES)}\u2026`;
|
|
879
862
|
}
|
|
880
863
|
function buildErrorMetadata(args) {
|
|
881
864
|
const retryAfter = parseRetryAfter(args.headers);
|
|
@@ -907,8 +890,16 @@ function mapOpenAICompatibleError(args) {
|
|
|
907
890
|
if (status === 429) {
|
|
908
891
|
return new errors.RateLimitError(message, { code: `${providerId}_rate_limit`, metadata });
|
|
909
892
|
}
|
|
893
|
+
if (status === 404 && code === "model_unavailable") {
|
|
894
|
+
const detailed = formatMessage(providerId, status, code, boundedProviderDetail(body));
|
|
895
|
+
return new errors.ConfigurationError(detailed, {
|
|
896
|
+
code: `${providerId}_model_unavailable`,
|
|
897
|
+
metadata
|
|
898
|
+
});
|
|
899
|
+
}
|
|
910
900
|
if (status === 400) {
|
|
911
|
-
|
|
901
|
+
const detailed = formatMessage(providerId, status, code, boundedProviderDetail(body));
|
|
902
|
+
return new errors.ConfigurationError(detailed, { code: `${providerId}_${code}`, metadata });
|
|
912
903
|
}
|
|
913
904
|
if (status === 408) {
|
|
914
905
|
return new errors.NetworkError(message, { code: `${providerId}_timeout`, metadata });
|
|
@@ -918,6 +909,18 @@ function mapOpenAICompatibleError(args) {
|
|
|
918
909
|
}
|
|
919
910
|
return new errors.UnknownAgentError(message, { code: `${providerId}_unknown`, metadata });
|
|
920
911
|
}
|
|
912
|
+
function extractOpenAiErrorMessage(body) {
|
|
913
|
+
if (body === null || typeof body !== "object") return void 0;
|
|
914
|
+
const err = body.error;
|
|
915
|
+
if (err === void 0 || err === null) return void 0;
|
|
916
|
+
return typeof err.message === "string" ? err.message : void 0;
|
|
917
|
+
}
|
|
918
|
+
function boundedProviderDetail(body) {
|
|
919
|
+
const raw = extractOpenAiErrorMessage(body);
|
|
920
|
+
if (raw === void 0 || raw.trim() === "") return void 0;
|
|
921
|
+
const redacted = redactSecrets(raw);
|
|
922
|
+
return redacted.length <= PROVIDER_DETAIL_MAX_CHARS ? redacted : `${redacted.slice(0, PROVIDER_DETAIL_MAX_CHARS)}\u2026`;
|
|
923
|
+
}
|
|
921
924
|
function extractOpenAiErrorCode(body) {
|
|
922
925
|
if (body === null || typeof body !== "object") return void 0;
|
|
923
926
|
const err = body.error;
|
|
@@ -940,6 +943,9 @@ function mapOpenAiStatusToCode(status, body) {
|
|
|
940
943
|
if (status === 402 || rawCode.includes("insufficient_quota") || rawCode.includes("quota_exceeded")) {
|
|
941
944
|
return "quota_exceeded";
|
|
942
945
|
}
|
|
946
|
+
if (status === 404 && MISSING_MODEL_MESSAGE.test(extractOpenAiErrorMessage(body) ?? "")) {
|
|
947
|
+
return "model_unavailable";
|
|
948
|
+
}
|
|
943
949
|
if (status === 401 || status === 403) return "auth_failed";
|
|
944
950
|
if (status === 429) return "rate_limit";
|
|
945
951
|
if (status === 408) return "timeout";
|
|
@@ -947,8 +953,9 @@ function mapOpenAiStatusToCode(status, body) {
|
|
|
947
953
|
if (status >= 500 && status < 600) return "server_error";
|
|
948
954
|
return "unknown";
|
|
949
955
|
}
|
|
950
|
-
function formatMessage(providerId, status, code) {
|
|
951
|
-
|
|
956
|
+
function formatMessage(providerId, status, code, detail) {
|
|
957
|
+
const base = `${providerId} API error: ${code} (HTTP ${status})`;
|
|
958
|
+
return detail === void 0 || detail === "" ? base : `${base}: ${detail}`;
|
|
952
959
|
}
|
|
953
960
|
var FACTS_HEADING = "## Facts";
|
|
954
961
|
function createCategorizedMemory(options) {
|
|
@@ -1076,293 +1083,6 @@ ${bullet}
|
|
|
1076
1083
|
return `${raw.slice(0, insertAt)}
|
|
1077
1084
|
${bullet}${raw.slice(insertAt)}`;
|
|
1078
1085
|
}
|
|
1079
|
-
|
|
1080
|
-
// src/internal/dreaming/dreaming-phases.ts
|
|
1081
|
-
var DEFAULT_DEDUP_THRESHOLD = 0.95;
|
|
1082
|
-
var DEFAULT_CLUSTER_THRESHOLD = 0.75;
|
|
1083
|
-
async function lightPhase(facts, embedding, threshold = DEFAULT_DEDUP_THRESHOLD) {
|
|
1084
|
-
if (facts.length <= 1) return { kept: [...facts], duplicatesRemoved: 0 };
|
|
1085
|
-
const vectors = await embedding.embed(facts.map((f) => f.text));
|
|
1086
|
-
const keptIdx = [];
|
|
1087
|
-
const keptVecs = [];
|
|
1088
|
-
for (let i = 0; i < facts.length; i++) {
|
|
1089
|
-
const vec = vectors[i] ?? [];
|
|
1090
|
-
const isDup = keptVecs.some((kept2) => cosineSimilarity(vec, kept2) >= threshold);
|
|
1091
|
-
if (isDup) continue;
|
|
1092
|
-
keptIdx.push(i);
|
|
1093
|
-
keptVecs.push(vec);
|
|
1094
|
-
}
|
|
1095
|
-
const kept = keptIdx.map((i) => facts[i]);
|
|
1096
|
-
return { kept, duplicatesRemoved: facts.length - kept.length };
|
|
1097
|
-
}
|
|
1098
|
-
var DEFAULT_MAX_FACTS_PER_SWEEP = 500;
|
|
1099
|
-
async function remPhase(facts, embedding, threshold = DEFAULT_CLUSTER_THRESHOLD, maxFactsPerSweep = DEFAULT_MAX_FACTS_PER_SWEEP) {
|
|
1100
|
-
if (facts.length === 0) return { clusters: [] };
|
|
1101
|
-
const capped = facts.length > maxFactsPerSweep ? facts.slice(0, maxFactsPerSweep) : facts;
|
|
1102
|
-
const vectors = await embedding.embed(capped.map((f) => f.text));
|
|
1103
|
-
const clusterOfIdx = unionFindByPairs(vectors, threshold);
|
|
1104
|
-
const groups = bucketFactsByClusterRoot(capped, clusterOfIdx);
|
|
1105
|
-
return { clusters: [...groups.values()].map(buildClusterFromMembers) };
|
|
1106
|
-
}
|
|
1107
|
-
function unionFindByPairs(vectors, threshold) {
|
|
1108
|
-
const clusterOfIdx = vectors.map((_, i) => i);
|
|
1109
|
-
for (let i = 0; i < vectors.length; i++) {
|
|
1110
|
-
for (let j = i + 1; j < vectors.length; j++) {
|
|
1111
|
-
if (cosineSimilarity(vectors[i] ?? [], vectors[j] ?? []) >= threshold) {
|
|
1112
|
-
unifyClusters(clusterOfIdx, i, j);
|
|
1113
|
-
}
|
|
1114
|
-
}
|
|
1115
|
-
}
|
|
1116
|
-
return clusterOfIdx;
|
|
1117
|
-
}
|
|
1118
|
-
function bucketFactsByClusterRoot(facts, clusterOfIdx) {
|
|
1119
|
-
const groups = /* @__PURE__ */ new Map();
|
|
1120
|
-
for (let i = 0; i < facts.length; i++) {
|
|
1121
|
-
const root = findRoot(clusterOfIdx, i);
|
|
1122
|
-
const list = groups.get(root) ?? [];
|
|
1123
|
-
list.push(facts[i]);
|
|
1124
|
-
groups.set(root, list);
|
|
1125
|
-
}
|
|
1126
|
-
return groups;
|
|
1127
|
-
}
|
|
1128
|
-
function buildClusterFromMembers(members) {
|
|
1129
|
-
const sorted = [...members].sort((a, b) => b.text.length - a.text.length);
|
|
1130
|
-
return { representativeText: sorted[0]?.text ?? "", members };
|
|
1131
|
-
}
|
|
1132
|
-
function deepPhase(clusters, timestampMs) {
|
|
1133
|
-
if (clusters.length === 0) return "";
|
|
1134
|
-
const isoStamp = new Date(timestampMs).toISOString();
|
|
1135
|
-
const lines = [`# Dreamed ${isoStamp}`, ""];
|
|
1136
|
-
for (let i = 0; i < clusters.length; i++) {
|
|
1137
|
-
const c = clusters[i];
|
|
1138
|
-
if (c === void 0) continue;
|
|
1139
|
-
lines.push(`## Cluster ${i + 1}: ${c.representativeText}`);
|
|
1140
|
-
lines.push("");
|
|
1141
|
-
for (const member of c.members) lines.push(`- ${member.text}`);
|
|
1142
|
-
lines.push("");
|
|
1143
|
-
}
|
|
1144
|
-
return `${lines.join("\n")}
|
|
1145
|
-
`;
|
|
1146
|
-
}
|
|
1147
|
-
function cosineSimilarity(a, b) {
|
|
1148
|
-
if (a.length === 0 || b.length === 0 || a.length !== b.length) return 0;
|
|
1149
|
-
let dot = 0;
|
|
1150
|
-
let aNorm = 0;
|
|
1151
|
-
let bNorm = 0;
|
|
1152
|
-
for (let i = 0; i < a.length; i++) {
|
|
1153
|
-
const ai = a[i] ?? 0;
|
|
1154
|
-
const bi = b[i] ?? 0;
|
|
1155
|
-
dot += ai * bi;
|
|
1156
|
-
aNorm += ai * ai;
|
|
1157
|
-
bNorm += bi * bi;
|
|
1158
|
-
}
|
|
1159
|
-
const denom = Math.sqrt(aNorm) * Math.sqrt(bNorm);
|
|
1160
|
-
return denom === 0 ? 0 : dot / denom;
|
|
1161
|
-
}
|
|
1162
|
-
function findRoot(parents, i) {
|
|
1163
|
-
let root = i;
|
|
1164
|
-
while (parents[root] !== root) {
|
|
1165
|
-
const next = parents[root] ?? root;
|
|
1166
|
-
if (next === root) break;
|
|
1167
|
-
root = next;
|
|
1168
|
-
}
|
|
1169
|
-
parents[i] = root;
|
|
1170
|
-
return root;
|
|
1171
|
-
}
|
|
1172
|
-
function unifyClusters(parents, a, b) {
|
|
1173
|
-
const rootA = findRoot(parents, a);
|
|
1174
|
-
const rootB = findRoot(parents, b);
|
|
1175
|
-
if (rootA !== rootB) parents[rootB] = rootA;
|
|
1176
|
-
}
|
|
1177
|
-
function runDreamingSweep(options) {
|
|
1178
|
-
return persistence.withCwdMutex(`dream:${options.cwd}`, () => runInner(options));
|
|
1179
|
-
}
|
|
1180
|
-
async function runInner(options) {
|
|
1181
|
-
const now = options.now ?? Date.now;
|
|
1182
|
-
const timestampMs = now();
|
|
1183
|
-
try {
|
|
1184
|
-
const facts = await memoryStore.readFactsFromMarkdown(options.cwd);
|
|
1185
|
-
if (facts.length === 0) {
|
|
1186
|
-
return emptyResult("skipped");
|
|
1187
|
-
}
|
|
1188
|
-
const dedup = await lightPhase(facts, options.embedding, options.dedupThreshold);
|
|
1189
|
-
const rem = await remPhase(dedup.kept, options.embedding, options.clusterThreshold);
|
|
1190
|
-
const notesWritten = await writeConsolidatedNotes(options.cwd, rem.clusters, timestampMs);
|
|
1191
|
-
const result = {
|
|
1192
|
-
status: "ok",
|
|
1193
|
-
factsBefore: facts.length,
|
|
1194
|
-
factsAfter: dedup.kept.length,
|
|
1195
|
-
duplicatesRemoved: dedup.duplicatesRemoved,
|
|
1196
|
-
clustersCreated: rem.clusters.length,
|
|
1197
|
-
notesWritten,
|
|
1198
|
-
diaryEntryHash: void 0
|
|
1199
|
-
};
|
|
1200
|
-
await memoryStore.appendDiaryEntry(memoryStore.resolveMemoryRoot(options.cwd), {
|
|
1201
|
-
timestampMs,
|
|
1202
|
-
factsBefore: result.factsBefore,
|
|
1203
|
-
factsAfter: result.factsAfter,
|
|
1204
|
-
duplicatesRemoved: result.duplicatesRemoved,
|
|
1205
|
-
clustersCreated: result.clustersCreated,
|
|
1206
|
-
notesWritten: result.notesWritten
|
|
1207
|
-
});
|
|
1208
|
-
return result;
|
|
1209
|
-
} catch (cause) {
|
|
1210
|
-
const message = cause instanceof Error ? cause.message : String(cause);
|
|
1211
|
-
process.stderr.write(`[theokit-sdk] dreaming sweep failed: ${message}
|
|
1212
|
-
`);
|
|
1213
|
-
return emptyResult("error");
|
|
1214
|
-
}
|
|
1215
|
-
}
|
|
1216
|
-
async function writeConsolidatedNotes(cwd, clusters, timestampMs) {
|
|
1217
|
-
if (clusters.length === 0) return 0;
|
|
1218
|
-
const notesDir3 = path.join(memoryStore.resolveMemoryRoot(cwd), "notes");
|
|
1219
|
-
await promises.mkdir(notesDir3, { recursive: true });
|
|
1220
|
-
const isoSlug = new Date(timestampMs).toISOString().replace(/[^\dT]/g, "-");
|
|
1221
|
-
const file = path.join(notesDir3, `dreamed-${isoSlug}.md`);
|
|
1222
|
-
const body = deepPhase(clusters, timestampMs);
|
|
1223
|
-
await persistence.replaceFileAtomic(file, body);
|
|
1224
|
-
return 1;
|
|
1225
|
-
}
|
|
1226
|
-
function emptyResult(status) {
|
|
1227
|
-
return {
|
|
1228
|
-
status,
|
|
1229
|
-
factsBefore: 0,
|
|
1230
|
-
factsAfter: 0,
|
|
1231
|
-
duplicatesRemoved: 0,
|
|
1232
|
-
clustersCreated: 0,
|
|
1233
|
-
notesWritten: 0,
|
|
1234
|
-
diaryEntryHash: void 0
|
|
1235
|
-
};
|
|
1236
|
-
}
|
|
1237
|
-
|
|
1238
|
-
// src/internal/index/index-schema.ts
|
|
1239
|
-
var SCHEMA_STATEMENTS = [
|
|
1240
|
-
`CREATE TABLE IF NOT EXISTS files (
|
|
1241
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1242
|
-
path TEXT UNIQUE NOT NULL,
|
|
1243
|
-
rel_path TEXT NOT NULL,
|
|
1244
|
-
mtime INTEGER NOT NULL,
|
|
1245
|
-
hash TEXT NOT NULL,
|
|
1246
|
-
source TEXT NOT NULL DEFAULT 'memory'
|
|
1247
|
-
)`,
|
|
1248
|
-
`CREATE TABLE IF NOT EXISTS chunks (
|
|
1249
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1250
|
-
file_id INTEGER NOT NULL REFERENCES files(id) ON DELETE CASCADE,
|
|
1251
|
-
start_line INTEGER NOT NULL,
|
|
1252
|
-
end_line INTEGER NOT NULL,
|
|
1253
|
-
text TEXT NOT NULL,
|
|
1254
|
-
hash TEXT NOT NULL,
|
|
1255
|
-
session_key TEXT
|
|
1256
|
-
)`,
|
|
1257
|
-
`CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5(
|
|
1258
|
-
text,
|
|
1259
|
-
content='chunks',
|
|
1260
|
-
content_rowid='id'
|
|
1261
|
-
)`,
|
|
1262
|
-
`CREATE TRIGGER IF NOT EXISTS chunks_fts_insert AFTER INSERT ON chunks BEGIN
|
|
1263
|
-
INSERT INTO chunks_fts(rowid, text) VALUES (new.id, new.text);
|
|
1264
|
-
END`,
|
|
1265
|
-
`CREATE TRIGGER IF NOT EXISTS chunks_fts_delete AFTER DELETE ON chunks BEGIN
|
|
1266
|
-
INSERT INTO chunks_fts(chunks_fts, rowid, text) VALUES ('delete', old.id, old.text);
|
|
1267
|
-
END`,
|
|
1268
|
-
`CREATE TABLE IF NOT EXISTS meta (
|
|
1269
|
-
key TEXT PRIMARY KEY,
|
|
1270
|
-
value TEXT
|
|
1271
|
-
)`,
|
|
1272
|
-
`CREATE INDEX IF NOT EXISTS idx_chunks_file_id ON chunks(file_id)`
|
|
1273
|
-
];
|
|
1274
|
-
var PRAGMA_STATEMENTS = [
|
|
1275
|
-
"PRAGMA synchronous=NORMAL",
|
|
1276
|
-
"PRAGMA foreign_keys=ON"
|
|
1277
|
-
];
|
|
1278
|
-
|
|
1279
|
-
// src/internal/index/index-db.ts
|
|
1280
|
-
async function openMemoryDb(opts) {
|
|
1281
|
-
return persistence.openSqliteResilient({
|
|
1282
|
-
filePath: opts.filePath,
|
|
1283
|
-
label: "memory-index",
|
|
1284
|
-
recoverCorrupt: opts.recoverCorrupt,
|
|
1285
|
-
onOpen: (db) => {
|
|
1286
|
-
for (const pragma of PRAGMA_STATEMENTS) db.exec(pragma);
|
|
1287
|
-
for (const stmt of SCHEMA_STATEMENTS) db.exec(stmt);
|
|
1288
|
-
}
|
|
1289
|
-
});
|
|
1290
|
-
}
|
|
1291
|
-
var HEADING_RE = /^(#{1,6})\s+(.+?)\s*$/;
|
|
1292
|
-
function chunkMarkdown(text, options = {}) {
|
|
1293
|
-
const maxChars = options.maxChars ?? 800;
|
|
1294
|
-
if (text.length === 0) return [];
|
|
1295
|
-
const lines = text.split("\n");
|
|
1296
|
-
const acc = { chunks: [], lines: [], start: 1, heading: void 0 };
|
|
1297
|
-
for (let i = 0; i < lines.length; i++) {
|
|
1298
|
-
const line = lines[i] ?? "";
|
|
1299
|
-
const lineNumber = i + 1;
|
|
1300
|
-
processLine(acc, line, lineNumber, maxChars);
|
|
1301
|
-
}
|
|
1302
|
-
flushAccumulator(acc, lines.length, maxChars);
|
|
1303
|
-
return acc.chunks;
|
|
1304
|
-
}
|
|
1305
|
-
function processLine(acc, line, lineNumber, maxChars) {
|
|
1306
|
-
const headingMatch = HEADING_RE.exec(line);
|
|
1307
|
-
const isBlank = line.trim().length === 0;
|
|
1308
|
-
if (headingMatch !== null && acc.lines.length > 0) {
|
|
1309
|
-
flushAccumulator(acc, lineNumber - 1, maxChars);
|
|
1310
|
-
}
|
|
1311
|
-
if (headingMatch !== null) acc.heading = headingMatch[2];
|
|
1312
|
-
acc.lines.push(line);
|
|
1313
|
-
if (isBlank && acc.lines.length > 1) {
|
|
1314
|
-
const joined = acc.lines.join("\n");
|
|
1315
|
-
if (joined.trim().length > 0) flushAccumulator(acc, lineNumber, maxChars);
|
|
1316
|
-
}
|
|
1317
|
-
}
|
|
1318
|
-
function flushAccumulator(acc, endLineExclusive, maxChars) {
|
|
1319
|
-
if (acc.lines.length === 0) return;
|
|
1320
|
-
const chunkText = acc.lines.join("\n");
|
|
1321
|
-
if (chunkText.trim().length === 0) {
|
|
1322
|
-
acc.lines = [];
|
|
1323
|
-
acc.start = endLineExclusive + 1;
|
|
1324
|
-
return;
|
|
1325
|
-
}
|
|
1326
|
-
if (chunkText.length > maxChars) {
|
|
1327
|
-
pushOversizedSlices(acc.chunks, chunkText, acc.start, acc.heading, maxChars);
|
|
1328
|
-
} else {
|
|
1329
|
-
acc.chunks.push(buildChunk(chunkText, acc.start, endLineExclusive, acc.heading));
|
|
1330
|
-
}
|
|
1331
|
-
acc.lines = [];
|
|
1332
|
-
acc.start = endLineExclusive + 1;
|
|
1333
|
-
}
|
|
1334
|
-
function buildChunk(text, startLine, endLine, heading) {
|
|
1335
|
-
return {
|
|
1336
|
-
startLine,
|
|
1337
|
-
endLine,
|
|
1338
|
-
text,
|
|
1339
|
-
hash: crypto.createHash("sha256").update(text).digest("hex"),
|
|
1340
|
-
...heading !== void 0 ? { heading } : {}
|
|
1341
|
-
};
|
|
1342
|
-
}
|
|
1343
|
-
function pushOversizedSlices(chunks, text, startLine, heading, maxChars) {
|
|
1344
|
-
let remaining = text;
|
|
1345
|
-
let lineCursor = startLine;
|
|
1346
|
-
while (remaining.length > maxChars) {
|
|
1347
|
-
const splitAt = findWordBoundarySplit(remaining, maxChars);
|
|
1348
|
-
const slice = remaining.slice(0, splitAt);
|
|
1349
|
-
const sliceLines = slice.split("\n").length;
|
|
1350
|
-
chunks.push(buildChunk(slice, lineCursor, lineCursor + sliceLines - 1, heading));
|
|
1351
|
-
remaining = remaining.slice(splitAt).replace(/^\s+/, "");
|
|
1352
|
-
lineCursor += sliceLines - 1;
|
|
1353
|
-
}
|
|
1354
|
-
if (remaining.length > 0) {
|
|
1355
|
-
const sliceLines = remaining.split("\n").length;
|
|
1356
|
-
chunks.push(buildChunk(remaining, lineCursor, lineCursor + sliceLines - 1, heading));
|
|
1357
|
-
}
|
|
1358
|
-
}
|
|
1359
|
-
function findWordBoundarySplit(text, maxChars) {
|
|
1360
|
-
if (text.length <= maxChars) return text.length;
|
|
1361
|
-
for (let i = maxChars; i > Math.max(0, maxChars - 200); i--) {
|
|
1362
|
-
if (/\s/.test(text[i] ?? "x")) return i;
|
|
1363
|
-
}
|
|
1364
|
-
return maxChars;
|
|
1365
|
-
}
|
|
1366
1086
|
function requireLance() {
|
|
1367
1087
|
try {
|
|
1368
1088
|
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)));
|
|
@@ -1488,14 +1208,6 @@ function isLanceAvailable() {
|
|
|
1488
1208
|
}
|
|
1489
1209
|
}
|
|
1490
1210
|
|
|
1491
|
-
// src/internal/index/memory-index.ts
|
|
1492
|
-
function parseSearchOptions(options = {}) {
|
|
1493
|
-
return {
|
|
1494
|
-
maxResults: Math.max(1, options.maxResults ?? 10),
|
|
1495
|
-
minScore: options.minScore ?? 0
|
|
1496
|
-
};
|
|
1497
|
-
}
|
|
1498
|
-
|
|
1499
1211
|
// src/internal/index/lance-memory-adapter.ts
|
|
1500
1212
|
var DEFAULT_NAMESPACE = "default";
|
|
1501
1213
|
var EMPTY_SYNC_RESULT = Object.freeze({
|
|
@@ -1521,7 +1233,7 @@ var LanceMemoryAdapter = class {
|
|
|
1521
1233
|
// readability (the bodies diverge sharply right after).
|
|
1522
1234
|
async search(query, options = {}) {
|
|
1523
1235
|
if (query.trim().length === 0) return [];
|
|
1524
|
-
const { maxResults, minScore } = parseSearchOptions(options);
|
|
1236
|
+
const { maxResults, minScore } = memoryStore.parseSearchOptions(options);
|
|
1525
1237
|
const lanceHits = await this.inner.search(query, {
|
|
1526
1238
|
namespace: DEFAULT_NAMESPACE,
|
|
1527
1239
|
limit: maxResults * 2,
|
|
@@ -1585,22 +1297,6 @@ async function openLanceIndex(opts) {
|
|
|
1585
1297
|
});
|
|
1586
1298
|
return new LanceMemoryAdapter(lance);
|
|
1587
1299
|
}
|
|
1588
|
-
async function loadSqliteVecExtension(db) {
|
|
1589
|
-
try {
|
|
1590
|
-
const mod = await import('sqlite-vec');
|
|
1591
|
-
const loadFn = mod.load;
|
|
1592
|
-
if (typeof loadFn !== "function") {
|
|
1593
|
-
throw new Error("sqlite-vec module exposes no `load` export");
|
|
1594
|
-
}
|
|
1595
|
-
loadFn(db);
|
|
1596
|
-
} catch (cause) {
|
|
1597
|
-
const message = cause instanceof Error ? cause.message : String(cause);
|
|
1598
|
-
throw new errors.ConfigurationError(
|
|
1599
|
-
`sqlite-vec extension unavailable. Install \`sqlite-vec\` and ensure the native binary matches your Node + OS. Cause: ${message}`,
|
|
1600
|
-
{ code: "sqlite_vec_unavailable", cause }
|
|
1601
|
-
);
|
|
1602
|
-
}
|
|
1603
|
-
}
|
|
1604
1300
|
function isSqliteVecLoaded(db) {
|
|
1605
1301
|
try {
|
|
1606
1302
|
const row = db.prepare("SELECT vec_version() as v").get();
|
|
@@ -1610,80 +1306,6 @@ function isSqliteVecLoaded(db) {
|
|
|
1610
1306
|
}
|
|
1611
1307
|
}
|
|
1612
1308
|
|
|
1613
|
-
// src/internal/index/vec-index.ts
|
|
1614
|
-
var META_KEY_PROVIDER_ID = "embedding.providerId";
|
|
1615
|
-
var META_KEY_MODEL = "embedding.model";
|
|
1616
|
-
var META_KEY_DIMENSION = "embedding.dimension";
|
|
1617
|
-
function readEmbeddingIdentity(db) {
|
|
1618
|
-
const get = (key) => {
|
|
1619
|
-
const row = db.prepare("SELECT value FROM meta WHERE key = ?").get(key);
|
|
1620
|
-
return row !== void 0 ? String(row.value) : void 0;
|
|
1621
|
-
};
|
|
1622
|
-
const providerId = get(META_KEY_PROVIDER_ID);
|
|
1623
|
-
const model = get(META_KEY_MODEL);
|
|
1624
|
-
const dimRaw = get(META_KEY_DIMENSION);
|
|
1625
|
-
if (providerId === void 0 || model === void 0 || dimRaw === void 0) return void 0;
|
|
1626
|
-
const dimension = Number(dimRaw);
|
|
1627
|
-
if (!Number.isFinite(dimension) || dimension <= 0) return void 0;
|
|
1628
|
-
return { providerId, model, dimension };
|
|
1629
|
-
}
|
|
1630
|
-
function writeEmbeddingIdentity(db, identity) {
|
|
1631
|
-
const stmt = db.prepare(
|
|
1632
|
-
"INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
|
|
1633
|
-
);
|
|
1634
|
-
stmt.run(META_KEY_PROVIDER_ID, identity.providerId);
|
|
1635
|
-
stmt.run(META_KEY_MODEL, identity.model);
|
|
1636
|
-
stmt.run(META_KEY_DIMENSION, String(identity.dimension));
|
|
1637
|
-
}
|
|
1638
|
-
function identityMatches(a, b) {
|
|
1639
|
-
return a.providerId === b.providerId && a.model === b.model && a.dimension === b.dimension;
|
|
1640
|
-
}
|
|
1641
|
-
function dropVectorIndex(db) {
|
|
1642
|
-
db.exec("DROP TABLE IF EXISTS embeddings");
|
|
1643
|
-
}
|
|
1644
|
-
function createVectorIndex(db, dimension) {
|
|
1645
|
-
db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS embeddings USING vec0(
|
|
1646
|
-
chunk_id INTEGER PRIMARY KEY,
|
|
1647
|
-
vec FLOAT[${dimension}]
|
|
1648
|
-
)`);
|
|
1649
|
-
}
|
|
1650
|
-
function packVector(vec) {
|
|
1651
|
-
const f32 = new Float32Array(vec.length);
|
|
1652
|
-
for (let i = 0; i < vec.length; i++) f32[i] = vec[i] ?? 0;
|
|
1653
|
-
return Buffer.from(f32.buffer);
|
|
1654
|
-
}
|
|
1655
|
-
function upsertEmbedding(db, chunkId, vec) {
|
|
1656
|
-
const id = BigInt(chunkId);
|
|
1657
|
-
db.prepare("DELETE FROM embeddings WHERE chunk_id = ?").run(id);
|
|
1658
|
-
db.prepare("INSERT INTO embeddings (chunk_id, vec) VALUES (?, ?)").run(id, packVector(vec));
|
|
1659
|
-
}
|
|
1660
|
-
function vectorSearch(db, query, k) {
|
|
1661
|
-
const rows = db.prepare(
|
|
1662
|
-
`SELECT chunk_id, distance FROM embeddings
|
|
1663
|
-
WHERE vec MATCH ? AND k = ?
|
|
1664
|
-
ORDER BY distance`
|
|
1665
|
-
).all(packVector(query), BigInt(k));
|
|
1666
|
-
return rows.map((row) => ({ chunk_id: Number(row.chunk_id), distance: Number(row.distance) }));
|
|
1667
|
-
}
|
|
1668
|
-
async function embedMissingChunks(args) {
|
|
1669
|
-
const rows = args.db.prepare(
|
|
1670
|
-
`SELECT chunks.id as id, chunks.text as text
|
|
1671
|
-
FROM chunks
|
|
1672
|
-
LEFT JOIN embeddings ON embeddings.chunk_id = chunks.id
|
|
1673
|
-
WHERE embeddings.chunk_id IS NULL`
|
|
1674
|
-
).all();
|
|
1675
|
-
if (rows.length === 0) return 0;
|
|
1676
|
-
const normalized = rows.map((row) => ({ id: Number(row.id), text: String(row.text ?? "") }));
|
|
1677
|
-
const vectors = await args.runtime.embed(normalized.map((r) => r.text));
|
|
1678
|
-
for (let i = 0; i < normalized.length; i++) {
|
|
1679
|
-
const row = normalized[i];
|
|
1680
|
-
const vector = vectors[i];
|
|
1681
|
-
if (row === void 0 || vector === void 0) continue;
|
|
1682
|
-
upsertEmbedding(args.db, row.id, vector);
|
|
1683
|
-
}
|
|
1684
|
-
return normalized.length;
|
|
1685
|
-
}
|
|
1686
|
-
|
|
1687
1309
|
// src/internal/index/index-manager.ts
|
|
1688
1310
|
var IndexManager = class _IndexManager {
|
|
1689
1311
|
constructor(memoryRoot, db, embedding) {
|
|
@@ -1706,24 +1328,24 @@ var IndexManager = class _IndexManager {
|
|
|
1706
1328
|
static async openSqliteInternal(opts) {
|
|
1707
1329
|
const memoryRoot = opts.memoryRoot ?? memoryStore.resolveMemoryRoot(opts.cwd);
|
|
1708
1330
|
const filePath = opts.filePath ?? memoryStore.defaultIndexPath(memoryStore.projectMemoryDir(opts.cwd));
|
|
1709
|
-
const db = await openMemoryDb({ filePath });
|
|
1331
|
+
const db = await memoryStore.openMemoryDb({ filePath });
|
|
1710
1332
|
const manager = new _IndexManager(memoryRoot, db, opts.embedding);
|
|
1711
1333
|
if (opts.embedding !== void 0) await manager.initVectorBackend(opts.embedding);
|
|
1712
1334
|
return manager;
|
|
1713
1335
|
}
|
|
1714
1336
|
async initVectorBackend(runtime) {
|
|
1715
|
-
await loadSqliteVecExtension(this.db);
|
|
1337
|
+
await memoryStore.loadSqliteVecExtension(this.db);
|
|
1716
1338
|
const currentIdentity = {
|
|
1717
1339
|
providerId: runtime.id,
|
|
1718
1340
|
model: runtime.model,
|
|
1719
1341
|
dimension: runtime.dimension
|
|
1720
1342
|
};
|
|
1721
|
-
const persisted = readEmbeddingIdentity(this.db);
|
|
1722
|
-
if (persisted !== void 0 && !identityMatches(persisted, currentIdentity)) {
|
|
1723
|
-
dropVectorIndex(this.db);
|
|
1343
|
+
const persisted = memoryStore.readEmbeddingIdentity(this.db);
|
|
1344
|
+
if (persisted !== void 0 && !memoryStore.identityMatches(persisted, currentIdentity)) {
|
|
1345
|
+
memoryStore.dropVectorIndex(this.db);
|
|
1724
1346
|
}
|
|
1725
|
-
createVectorIndex(this.db, runtime.dimension);
|
|
1726
|
-
writeEmbeddingIdentity(this.db, currentIdentity);
|
|
1347
|
+
memoryStore.createVectorIndex(this.db, runtime.dimension);
|
|
1348
|
+
memoryStore.writeEmbeddingIdentity(this.db, currentIdentity);
|
|
1727
1349
|
this.vectorReady = true;
|
|
1728
1350
|
}
|
|
1729
1351
|
/** Walk the memory corpus + (re)index changed files. */
|
|
@@ -1746,7 +1368,7 @@ var IndexManager = class _IndexManager {
|
|
|
1746
1368
|
entry.source
|
|
1747
1369
|
);
|
|
1748
1370
|
this.deleteChunksForFile(fileId);
|
|
1749
|
-
const chunks = chunkMarkdown(raw);
|
|
1371
|
+
const chunks = memoryStore.chunkMarkdown(raw);
|
|
1750
1372
|
for (const chunk of chunks) {
|
|
1751
1373
|
this.insertChunk(fileId, chunk.startLine, chunk.endLine, chunk.text, chunk.hash);
|
|
1752
1374
|
}
|
|
@@ -1755,14 +1377,14 @@ var IndexManager = class _IndexManager {
|
|
|
1755
1377
|
}
|
|
1756
1378
|
let chunksEmbedded = 0;
|
|
1757
1379
|
if (this.vectorReady && this.embedding !== void 0) {
|
|
1758
|
-
chunksEmbedded = await embedMissingChunks({ db: this.db, runtime: this.embedding });
|
|
1380
|
+
chunksEmbedded = await memoryStore.embedMissingChunks({ db: this.db, runtime: this.embedding });
|
|
1759
1381
|
}
|
|
1760
1382
|
this.lastSyncMs = Date.now();
|
|
1761
1383
|
return { filesScanned: files.length, filesUpdated, chunksWritten, chunksEmbedded };
|
|
1762
1384
|
}
|
|
1763
1385
|
async search(query, options = {}) {
|
|
1764
1386
|
if (query.trim().length === 0) return [];
|
|
1765
|
-
const { maxResults, minScore } = parseSearchOptions(options);
|
|
1387
|
+
const { maxResults, minScore } = memoryStore.parseSearchOptions(options);
|
|
1766
1388
|
const textHits = this.ftsSearch(query, maxResults * 2);
|
|
1767
1389
|
const vectorHitsById = await this.vectorSearchById(query, maxResults * 2);
|
|
1768
1390
|
const combined = this.combineHybridScores(textHits, vectorHitsById, options);
|
|
@@ -1825,7 +1447,7 @@ var IndexManager = class _IndexManager {
|
|
|
1825
1447
|
if (!this.vectorReady || this.embedding === void 0) return /* @__PURE__ */ new Map();
|
|
1826
1448
|
const [queryVec] = await this.embedding.embed([query]);
|
|
1827
1449
|
if (queryVec === void 0) return /* @__PURE__ */ new Map();
|
|
1828
|
-
const rows = vectorSearch(this.db, queryVec, limit);
|
|
1450
|
+
const rows = memoryStore.vectorSearch(this.db, queryVec, limit);
|
|
1829
1451
|
const out = /* @__PURE__ */ new Map();
|
|
1830
1452
|
for (const row of rows) {
|
|
1831
1453
|
const score = 1 / (1 + Math.max(0, row.distance));
|
|
@@ -2111,31 +1733,6 @@ async function migrateLegacyJson(cwd, config) {
|
|
|
2111
1733
|
function resetMigrationStateForTests() {
|
|
2112
1734
|
migrationRun.clear();
|
|
2113
1735
|
}
|
|
2114
|
-
var DEFAULT_MEMORY_READ_LINES = 200;
|
|
2115
|
-
async function readMemoryFileBounded(opts) {
|
|
2116
|
-
const absolutePath = path.resolve(opts.cwd, opts.relPath);
|
|
2117
|
-
const raw = await promises.readFile(absolutePath, "utf8");
|
|
2118
|
-
const allLines = raw.split("\n");
|
|
2119
|
-
const trimmedLines = allLines.length > 0 && allLines[allLines.length - 1] === "" ? allLines.slice(0, -1) : allLines;
|
|
2120
|
-
const totalLines = trimmedLines.length;
|
|
2121
|
-
const requestedFrom = Math.max(1, opts.from ?? 1);
|
|
2122
|
-
const requestedLines = Math.max(1, opts.lines ?? DEFAULT_MEMORY_READ_LINES);
|
|
2123
|
-
const startIdx = requestedFrom - 1;
|
|
2124
|
-
const endIdx = Math.min(totalLines, startIdx + requestedLines);
|
|
2125
|
-
const slice = trimmedLines.slice(startIdx, endIdx);
|
|
2126
|
-
const linesReturned = slice.length;
|
|
2127
|
-
const remainingLines = Math.max(0, totalLines - endIdx);
|
|
2128
|
-
const truncated = remainingLines > 0;
|
|
2129
|
-
return {
|
|
2130
|
-
path: opts.relPath,
|
|
2131
|
-
from: requestedFrom,
|
|
2132
|
-
linesReturned,
|
|
2133
|
-
totalLines,
|
|
2134
|
-
truncated,
|
|
2135
|
-
remainingLines,
|
|
2136
|
-
text: slice.join("\n")
|
|
2137
|
-
};
|
|
2138
|
-
}
|
|
2139
1736
|
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.";
|
|
2140
1737
|
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.";
|
|
2141
1738
|
var MEMORY_SEARCH_SCHEMA = {
|
|
@@ -2205,7 +1802,7 @@ function createMemoryGetTool(opts) {
|
|
|
2205
1802
|
};
|
|
2206
1803
|
if (from !== void 0) readArgs.from = from;
|
|
2207
1804
|
if (lines !== void 0) readArgs.lines = lines;
|
|
2208
|
-
const result = await readMemoryFileBounded(readArgs);
|
|
1805
|
+
const result = await memoryStore.readMemoryFileBounded(readArgs);
|
|
2209
1806
|
return JSON.stringify(result);
|
|
2210
1807
|
}
|
|
2211
1808
|
};
|
|
@@ -2252,6 +1849,14 @@ function isPathInside(root, candidate) {
|
|
|
2252
1849
|
return candidate === root || candidate.startsWith(normalizedRoot);
|
|
2253
1850
|
}
|
|
2254
1851
|
|
|
1852
|
+
Object.defineProperty(exports, "ActiveMemoryCache", {
|
|
1853
|
+
enumerable: true,
|
|
1854
|
+
get: function () { return memoryStore.ActiveMemoryCache; }
|
|
1855
|
+
});
|
|
1856
|
+
Object.defineProperty(exports, "DEFAULT_MEMORY_READ_LINES", {
|
|
1857
|
+
enumerable: true,
|
|
1858
|
+
get: function () { return memoryStore.DEFAULT_MEMORY_READ_LINES; }
|
|
1859
|
+
});
|
|
2255
1860
|
Object.defineProperty(exports, "MEMORY_INDEX_MAX_BYTES", {
|
|
2256
1861
|
enumerable: true,
|
|
2257
1862
|
get: function () { return memoryStore.MEMORY_INDEX_MAX_BYTES; }
|
|
@@ -2260,6 +1865,26 @@ Object.defineProperty(exports, "MEMORY_INDEX_MAX_LINES", {
|
|
|
2260
1865
|
enumerable: true,
|
|
2261
1866
|
get: function () { return memoryStore.MEMORY_INDEX_MAX_LINES; }
|
|
2262
1867
|
});
|
|
1868
|
+
Object.defineProperty(exports, "META_KEY_DIMENSION", {
|
|
1869
|
+
enumerable: true,
|
|
1870
|
+
get: function () { return memoryStore.META_KEY_DIMENSION; }
|
|
1871
|
+
});
|
|
1872
|
+
Object.defineProperty(exports, "META_KEY_MODEL", {
|
|
1873
|
+
enumerable: true,
|
|
1874
|
+
get: function () { return memoryStore.META_KEY_MODEL; }
|
|
1875
|
+
});
|
|
1876
|
+
Object.defineProperty(exports, "META_KEY_PROVIDER_ID", {
|
|
1877
|
+
enumerable: true,
|
|
1878
|
+
get: function () { return memoryStore.META_KEY_PROVIDER_ID; }
|
|
1879
|
+
});
|
|
1880
|
+
Object.defineProperty(exports, "PRAGMA_STATEMENTS", {
|
|
1881
|
+
enumerable: true,
|
|
1882
|
+
get: function () { return memoryStore.PRAGMA_STATEMENTS; }
|
|
1883
|
+
});
|
|
1884
|
+
Object.defineProperty(exports, "SCHEMA_STATEMENTS", {
|
|
1885
|
+
enumerable: true,
|
|
1886
|
+
get: function () { return memoryStore.SCHEMA_STATEMENTS; }
|
|
1887
|
+
});
|
|
2263
1888
|
Object.defineProperty(exports, "appendDiaryEntry", {
|
|
2264
1889
|
enumerable: true,
|
|
2265
1890
|
get: function () { return memoryStore.appendDiaryEntry; }
|
|
@@ -2276,6 +1901,14 @@ Object.defineProperty(exports, "asMemoryRoot", {
|
|
|
2276
1901
|
enumerable: true,
|
|
2277
1902
|
get: function () { return memoryStore.asMemoryRoot; }
|
|
2278
1903
|
});
|
|
1904
|
+
Object.defineProperty(exports, "ceilingReachedError", {
|
|
1905
|
+
enumerable: true,
|
|
1906
|
+
get: function () { return memoryStore.ceilingReachedError; }
|
|
1907
|
+
});
|
|
1908
|
+
Object.defineProperty(exports, "chunkMarkdown", {
|
|
1909
|
+
enumerable: true,
|
|
1910
|
+
get: function () { return memoryStore.chunkMarkdown; }
|
|
1911
|
+
});
|
|
2279
1912
|
Object.defineProperty(exports, "claudeProjectMemoryDir", {
|
|
2280
1913
|
enumerable: true,
|
|
2281
1914
|
get: function () { return memoryStore.claudeProjectMemoryDir; }
|
|
@@ -2284,6 +1917,14 @@ Object.defineProperty(exports, "collectMarkdownFiles", {
|
|
|
2284
1917
|
enumerable: true,
|
|
2285
1918
|
get: function () { return memoryStore.collectMarkdownFiles; }
|
|
2286
1919
|
});
|
|
1920
|
+
Object.defineProperty(exports, "createVectorIndex", {
|
|
1921
|
+
enumerable: true,
|
|
1922
|
+
get: function () { return memoryStore.createVectorIndex; }
|
|
1923
|
+
});
|
|
1924
|
+
Object.defineProperty(exports, "deepPhase", {
|
|
1925
|
+
enumerable: true,
|
|
1926
|
+
get: function () { return memoryStore.deepPhase; }
|
|
1927
|
+
});
|
|
2287
1928
|
Object.defineProperty(exports, "defaultIndexPath", {
|
|
2288
1929
|
enumerable: true,
|
|
2289
1930
|
get: function () { return memoryStore.defaultIndexPath; }
|
|
@@ -2300,10 +1941,22 @@ Object.defineProperty(exports, "discoverWikiFiles", {
|
|
|
2300
1941
|
enumerable: true,
|
|
2301
1942
|
get: function () { return memoryStore.discoverWikiFiles; }
|
|
2302
1943
|
});
|
|
1944
|
+
Object.defineProperty(exports, "dropVectorIndex", {
|
|
1945
|
+
enumerable: true,
|
|
1946
|
+
get: function () { return memoryStore.dropVectorIndex; }
|
|
1947
|
+
});
|
|
1948
|
+
Object.defineProperty(exports, "embedMissingChunks", {
|
|
1949
|
+
enumerable: true,
|
|
1950
|
+
get: function () { return memoryStore.embedMissingChunks; }
|
|
1951
|
+
});
|
|
2303
1952
|
Object.defineProperty(exports, "entryHash", {
|
|
2304
1953
|
enumerable: true,
|
|
2305
1954
|
get: function () { return memoryStore.entryHash; }
|
|
2306
1955
|
});
|
|
1956
|
+
Object.defineProperty(exports, "identityMatches", {
|
|
1957
|
+
enumerable: true,
|
|
1958
|
+
get: function () { return memoryStore.identityMatches; }
|
|
1959
|
+
});
|
|
2307
1960
|
Object.defineProperty(exports, "indexBudgetWarning", {
|
|
2308
1961
|
enumerable: true,
|
|
2309
1962
|
get: function () { return memoryStore.indexBudgetWarning; }
|
|
@@ -2312,6 +1965,14 @@ Object.defineProperty(exports, "lanceStoragePath", {
|
|
|
2312
1965
|
enumerable: true,
|
|
2313
1966
|
get: function () { return memoryStore.lanceStoragePath; }
|
|
2314
1967
|
});
|
|
1968
|
+
Object.defineProperty(exports, "lightPhase", {
|
|
1969
|
+
enumerable: true,
|
|
1970
|
+
get: function () { return memoryStore.lightPhase; }
|
|
1971
|
+
});
|
|
1972
|
+
Object.defineProperty(exports, "loadSqliteVecExtension", {
|
|
1973
|
+
enumerable: true,
|
|
1974
|
+
get: function () { return memoryStore.loadSqliteVecExtension; }
|
|
1975
|
+
});
|
|
2315
1976
|
Object.defineProperty(exports, "memoryIndexRoot", {
|
|
2316
1977
|
enumerable: true,
|
|
2317
1978
|
get: function () { return memoryStore.memoryIndexRoot; }
|
|
@@ -2328,6 +1989,18 @@ Object.defineProperty(exports, "notesDir", {
|
|
|
2328
1989
|
enumerable: true,
|
|
2329
1990
|
get: function () { return memoryStore.notesDir; }
|
|
2330
1991
|
});
|
|
1992
|
+
Object.defineProperty(exports, "openMemoryDb", {
|
|
1993
|
+
enumerable: true,
|
|
1994
|
+
get: function () { return memoryStore.openMemoryDb; }
|
|
1995
|
+
});
|
|
1996
|
+
Object.defineProperty(exports, "packVector", {
|
|
1997
|
+
enumerable: true,
|
|
1998
|
+
get: function () { return memoryStore.packVector; }
|
|
1999
|
+
});
|
|
2000
|
+
Object.defineProperty(exports, "parseSearchOptions", {
|
|
2001
|
+
enumerable: true,
|
|
2002
|
+
get: function () { return memoryStore.parseSearchOptions; }
|
|
2003
|
+
});
|
|
2331
2004
|
Object.defineProperty(exports, "persistActiveMemoryTranscript", {
|
|
2332
2005
|
enumerable: true,
|
|
2333
2006
|
get: function () { return memoryStore.persistActiveMemoryTranscript; }
|
|
@@ -2340,6 +2013,10 @@ Object.defineProperty(exports, "readAllSqliteFacts", {
|
|
|
2340
2013
|
enumerable: true,
|
|
2341
2014
|
get: function () { return memoryStore.readAllSqliteFacts; }
|
|
2342
2015
|
});
|
|
2016
|
+
Object.defineProperty(exports, "readEmbeddingIdentity", {
|
|
2017
|
+
enumerable: true,
|
|
2018
|
+
get: function () { return memoryStore.readEmbeddingIdentity; }
|
|
2019
|
+
});
|
|
2343
2020
|
Object.defineProperty(exports, "readFacts", {
|
|
2344
2021
|
enumerable: true,
|
|
2345
2022
|
get: function () { return memoryStore.readFacts; }
|
|
@@ -2348,14 +2025,30 @@ Object.defineProperty(exports, "readFactsFromMarkdown", {
|
|
|
2348
2025
|
enumerable: true,
|
|
2349
2026
|
get: function () { return memoryStore.readFactsFromMarkdown; }
|
|
2350
2027
|
});
|
|
2028
|
+
Object.defineProperty(exports, "readMemoryFileBounded", {
|
|
2029
|
+
enumerable: true,
|
|
2030
|
+
get: function () { return memoryStore.readMemoryFileBounded; }
|
|
2031
|
+
});
|
|
2032
|
+
Object.defineProperty(exports, "remPhase", {
|
|
2033
|
+
enumerable: true,
|
|
2034
|
+
get: function () { return memoryStore.remPhase; }
|
|
2035
|
+
});
|
|
2351
2036
|
Object.defineProperty(exports, "renderDiaryEntry", {
|
|
2352
2037
|
enumerable: true,
|
|
2353
2038
|
get: function () { return memoryStore.renderDiaryEntry; }
|
|
2354
2039
|
});
|
|
2040
|
+
Object.defineProperty(exports, "resolveMaxFacts", {
|
|
2041
|
+
enumerable: true,
|
|
2042
|
+
get: function () { return memoryStore.resolveMaxFacts; }
|
|
2043
|
+
});
|
|
2355
2044
|
Object.defineProperty(exports, "resolveMemoryRoot", {
|
|
2356
2045
|
enumerable: true,
|
|
2357
2046
|
get: function () { return memoryStore.resolveMemoryRoot; }
|
|
2358
2047
|
});
|
|
2048
|
+
Object.defineProperty(exports, "runDreamingSweep", {
|
|
2049
|
+
enumerable: true,
|
|
2050
|
+
get: function () { return memoryStore.runDreamingSweep; }
|
|
2051
|
+
});
|
|
2359
2052
|
Object.defineProperty(exports, "sessionSummaryPath", {
|
|
2360
2053
|
enumerable: true,
|
|
2361
2054
|
get: function () { return memoryStore.sessionSummaryPath; }
|
|
@@ -2364,10 +2057,22 @@ Object.defineProperty(exports, "sessionsDir", {
|
|
|
2364
2057
|
enumerable: true,
|
|
2365
2058
|
get: function () { return memoryStore.sessionsDir; }
|
|
2366
2059
|
});
|
|
2060
|
+
Object.defineProperty(exports, "upsertEmbedding", {
|
|
2061
|
+
enumerable: true,
|
|
2062
|
+
get: function () { return memoryStore.upsertEmbedding; }
|
|
2063
|
+
});
|
|
2064
|
+
Object.defineProperty(exports, "vectorSearch", {
|
|
2065
|
+
enumerable: true,
|
|
2066
|
+
get: function () { return memoryStore.vectorSearch; }
|
|
2067
|
+
});
|
|
2367
2068
|
Object.defineProperty(exports, "wikiDir", {
|
|
2368
2069
|
enumerable: true,
|
|
2369
2070
|
get: function () { return memoryStore.wikiDir; }
|
|
2370
2071
|
});
|
|
2072
|
+
Object.defineProperty(exports, "writeEmbeddingIdentity", {
|
|
2073
|
+
enumerable: true,
|
|
2074
|
+
get: function () { return memoryStore.writeEmbeddingIdentity; }
|
|
2075
|
+
});
|
|
2371
2076
|
Object.defineProperty(exports, "writeSessionSummary", {
|
|
2372
2077
|
enumerable: true,
|
|
2373
2078
|
get: function () { return memoryStore.writeSessionSummary; }
|
|
@@ -2376,14 +2081,12 @@ Object.defineProperty(exports, "createOpenAiCompatibleRuntime", {
|
|
|
2376
2081
|
enumerable: true,
|
|
2377
2082
|
get: function () { return memoryAdapters.createOpenAiCompatibleRuntime; }
|
|
2378
2083
|
});
|
|
2379
|
-
exports.ActiveMemoryCache = ActiveMemoryCache;
|
|
2380
2084
|
exports.CircuitBreaker = CircuitBreaker;
|
|
2381
2085
|
exports.DEFAULT_AZURE_OPENAI_EMBEDDING_MODEL = DEFAULT_AZURE_OPENAI_EMBEDDING_MODEL;
|
|
2382
2086
|
exports.DEFAULT_COHERE_EMBEDDING_MODEL = DEFAULT_COHERE_EMBEDDING_MODEL;
|
|
2383
2087
|
exports.DEFAULT_DEEPINFRA_EMBEDDING_MODEL = DEFAULT_DEEPINFRA_EMBEDDING_MODEL;
|
|
2384
2088
|
exports.DEFAULT_GEMINI_EMBEDDING_MODEL = DEFAULT_GEMINI_EMBEDDING_MODEL;
|
|
2385
2089
|
exports.DEFAULT_JINA_EMBEDDING_MODEL = DEFAULT_JINA_EMBEDDING_MODEL;
|
|
2386
|
-
exports.DEFAULT_MEMORY_READ_LINES = DEFAULT_MEMORY_READ_LINES;
|
|
2387
2090
|
exports.DEFAULT_MISTRAL_EMBEDDING_MODEL = DEFAULT_MISTRAL_EMBEDDING_MODEL;
|
|
2388
2091
|
exports.DEFAULT_OLLAMA_EMBEDDING_MODEL = DEFAULT_OLLAMA_EMBEDDING_MODEL;
|
|
2389
2092
|
exports.DEFAULT_OPENAI_EMBEDDING_MODEL = DEFAULT_OPENAI_EMBEDDING_MODEL;
|
|
@@ -2393,35 +2096,22 @@ exports.IndexManager = IndexManager;
|
|
|
2393
2096
|
exports.LanceIndex = LanceIndex;
|
|
2394
2097
|
exports.LanceMemoryAdapter = LanceMemoryAdapter;
|
|
2395
2098
|
exports.MEMORY_EMBEDDING_ADAPTERS = MEMORY_EMBEDDING_ADAPTERS;
|
|
2396
|
-
exports.META_KEY_DIMENSION = META_KEY_DIMENSION;
|
|
2397
|
-
exports.META_KEY_MODEL = META_KEY_MODEL;
|
|
2398
|
-
exports.META_KEY_PROVIDER_ID = META_KEY_PROVIDER_ID;
|
|
2399
|
-
exports.PRAGMA_STATEMENTS = PRAGMA_STATEMENTS;
|
|
2400
|
-
exports.SCHEMA_STATEMENTS = SCHEMA_STATEMENTS;
|
|
2401
2099
|
exports.VALID_BACKENDS = VALID_BACKENDS;
|
|
2402
2100
|
exports.assertValidBackend = assertValidBackend;
|
|
2403
2101
|
exports.azureOpenAiMemoryEmbeddingProviderAdapter = azureOpenAiMemoryEmbeddingProviderAdapter;
|
|
2404
2102
|
exports.buildErrorMetadata = buildErrorMetadata;
|
|
2405
|
-
exports.chunkMarkdown = chunkMarkdown;
|
|
2406
2103
|
exports.cohereMemoryEmbeddingProviderAdapter = cohereMemoryEmbeddingProviderAdapter;
|
|
2407
2104
|
exports.createCategorizedMemory = createCategorizedMemory;
|
|
2408
2105
|
exports.createInMemoryMarkdownProvider = createInMemoryMarkdownProvider;
|
|
2409
2106
|
exports.createMemoryGetTool = createMemoryGetTool;
|
|
2410
2107
|
exports.createMemorySearchTool = createMemorySearchTool;
|
|
2411
|
-
exports.createVectorIndex = createVectorIndex;
|
|
2412
|
-
exports.deepPhase = deepPhase;
|
|
2413
2108
|
exports.deepinfraMemoryEmbeddingProviderAdapter = deepinfraMemoryEmbeddingProviderAdapter;
|
|
2414
|
-
exports.dropVectorIndex = dropVectorIndex;
|
|
2415
|
-
exports.embedMissingChunks = embedMissingChunks;
|
|
2416
2109
|
exports.geminiMemoryEmbeddingProviderAdapter = geminiMemoryEmbeddingProviderAdapter;
|
|
2417
|
-
exports.identityMatches = identityMatches;
|
|
2418
2110
|
exports.isLanceAvailable = isLanceAvailable;
|
|
2419
2111
|
exports.isSqliteVecLoaded = isSqliteVecLoaded;
|
|
2420
2112
|
exports.jinaMemoryEmbeddingProviderAdapter = jinaMemoryEmbeddingProviderAdapter;
|
|
2421
2113
|
exports.legacyMemoryJsonPath = legacyMemoryJsonPath;
|
|
2422
|
-
exports.lightPhase = lightPhase;
|
|
2423
2114
|
exports.listNotes = listNotes;
|
|
2424
|
-
exports.loadSqliteVecExtension = loadSqliteVecExtension;
|
|
2425
2115
|
exports.mapOpenAICompatibleError = mapOpenAICompatibleError;
|
|
2426
2116
|
exports.migrateLegacyJson = migrateLegacyJson;
|
|
2427
2117
|
exports.migrateSqliteToLance = migrateSqliteToLance;
|
|
@@ -2429,22 +2119,12 @@ exports.mistralMemoryEmbeddingProviderAdapter = mistralMemoryEmbeddingProviderAd
|
|
|
2429
2119
|
exports.ollamaMemoryEmbeddingProviderAdapter = ollamaMemoryEmbeddingProviderAdapter;
|
|
2430
2120
|
exports.openAiMemoryEmbeddingProviderAdapter = openAiMemoryEmbeddingProviderAdapter;
|
|
2431
2121
|
exports.openLanceIndex = openLanceIndex;
|
|
2432
|
-
exports.openMemoryDb = openMemoryDb;
|
|
2433
2122
|
exports.openRouterMemoryEmbeddingProviderAdapter = openRouterMemoryEmbeddingProviderAdapter;
|
|
2434
|
-
exports.packVector = packVector;
|
|
2435
2123
|
exports.parseRetryAfter = parseRetryAfter;
|
|
2436
|
-
exports.parseSearchOptions = parseSearchOptions;
|
|
2437
|
-
exports.readEmbeddingIdentity = readEmbeddingIdentity;
|
|
2438
|
-
exports.readMemoryFileBounded = readMemoryFileBounded;
|
|
2439
2124
|
exports.redactSecrets = redactSecrets;
|
|
2440
|
-
exports.remPhase = remPhase;
|
|
2441
2125
|
exports.resetMigrationStateForTests = resetMigrationStateForTests;
|
|
2442
2126
|
exports.runActiveMemory = runActiveMemory;
|
|
2443
|
-
exports.runDreamingSweep = runDreamingSweep;
|
|
2444
2127
|
exports.truncateRaw = truncateRaw;
|
|
2445
|
-
exports.upsertEmbedding = upsertEmbedding;
|
|
2446
|
-
exports.vectorSearch = vectorSearch;
|
|
2447
2128
|
exports.voyageMemoryEmbeddingProviderAdapter = voyageMemoryEmbeddingProviderAdapter;
|
|
2448
|
-
exports.writeEmbeddingIdentity = writeEmbeddingIdentity;
|
|
2449
2129
|
//# sourceMappingURL=index.cjs.map
|
|
2450
2130
|
//# sourceMappingURL=index.cjs.map
|