@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.d.cts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { createInMemoryMarkdownProvider } from "./in-memory-provider.js";
|
|
1
|
+
export { createInMemoryMarkdownProvider, type InMemoryMarkdownProviderOptions, } from "./in-memory-provider.js";
|
|
2
2
|
export * from "./internal/active-memory/active-memory.js";
|
|
3
3
|
export * from "./internal/circuit-breaker.js";
|
|
4
4
|
export * from "./internal/embedding/embedding-adapter.js";
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { createInMemoryMarkdownProvider } from "./in-memory-provider.js";
|
|
1
|
+
export { createInMemoryMarkdownProvider, type InMemoryMarkdownProviderOptions, } from "./in-memory-provider.js";
|
|
2
2
|
export * from "./internal/active-memory/active-memory.js";
|
|
3
3
|
export * from "./internal/circuit-breaker.js";
|
|
4
4
|
export * from "./internal/embedding/embedding-adapter.js";
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAMA,OAAO,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAMA,OAAO,EACL,8BAA8B,EAC9B,KAAK,+BAA+B,GACrC,MAAM,yBAAyB,CAAC;AAcjC,cAAc,2CAA2C,CAAC;AAO1D,cAAc,+BAA+B,CAAC;AAO9C,cAAc,2CAA2C,CAAC;AAkB1D,cAAc,iDAAiD,CAAC;AAOhE,cAAc,iDAAiD,CAAC;AAChE,cAAc,+BAA+B,CAAC;AAC9C,cAAc,kCAAkC,CAAC;AAGjD,cAAc,kCAAkC,CAAC;AAWjD,cAAc,uCAAuC,CAAC;AAQtD,cAAc,wCAAwC,CAAC;AAgBvD,cAAc,qCAAqC,CAAC;AAEpD,cAAc,gDAAgD,CAAC;AAC/D,cAAc,0CAA0C,CAAC;AACzD,cAAc,6CAA6C,CAAC;AAC5D,cAAc,0CAA0C,CAAC;AACzD,cAAc,wCAAwC,CAAC;AACvD,cAAc,2CAA2C,CAAC;AAC1D,cAAc,0CAA0C,CAAC;AAuBzD,cAAc,2CAA2C,CAAC;AAmB1D,cAAc,0CAA0C,CAAC;AACzD,cAAc,8CAA8C,CAAC;AAC7D,cAAc,0CAA0C,CAAC;AAezD,cAAc,8BAA8B,CAAC;AAiB7C,cAAc,mCAAmC,CAAC;AAOlD,cAAc,4CAA4C,CAAC;AAW3D,cAAc,4CAA4C,CAAC;AAK3D,cAAc,kCAAkC,CAAC;AAajD,cAAc,iCAAiC,CAAC;AAchD,cAAc,0CAA0C,CAAC;AAWzD,cAAc,kCAAkC,CAAC;AAiBjD,cAAc,6CAA6C,CAAC;AAc5D,cAAc,+BAA+B,CAAC;AAQ9C,cAAc,uCAAuC,CAAC;AActD,cAAc,+BAA+B,CAAC;AAW9C,cAAc,4BAA4B,CAAC;AAQ3C,cAAc,oCAAoC,CAAC;AAanD,cAAc,oCAAoC,CAAC;AAUnD,cAAc,4BAA4B,CAAC;AAU3C,cAAc,oCAAoC,CAAC;AAanD,cAAc,4CAA4C,CAAC;AAY3D,cAAc,sCAAsC,CAAC;AASrD,cAAc,iCAAiC,CAAC;AAehD,cAAc,qBAAqB,CAAC"}
|
package/dist/index.js
CHANGED
|
@@ -1,19 +1,20 @@
|
|
|
1
1
|
import { mkdir, readdir, readFile, stat, access, unlink } from 'fs/promises';
|
|
2
2
|
import { join, resolve } from 'path';
|
|
3
|
-
import { Security } from '@theokit/sdk';
|
|
4
|
-
import {
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
import { createHash } from 'crypto';
|
|
3
|
+
import { Security, ConfigurationError as ConfigurationError$1 } from '@theokit/sdk';
|
|
4
|
+
import { resolveMaxFacts, notesDir, resolveMemoryRoot, persistActiveMemoryTranscript, lanceStoragePath, parseSearchOptions, defaultIndexPath, projectMemoryDir, openMemoryDb, loadSqliteVecExtension, readEmbeddingIdentity, identityMatches, dropVectorIndex, createVectorIndex, writeEmbeddingIdentity, collectMarkdownFiles, chunkMarkdown, embedMissingChunks, vectorSearch, readAllSqliteFacts, memoryMdPath, readMemoryFileBounded, appendFactToMarkdown, ceilingReachedError } from '@theokit/sdk/internal/memory-store';
|
|
5
|
+
export { ActiveMemoryCache, DEFAULT_MEMORY_READ_LINES, MEMORY_INDEX_MAX_BYTES, MEMORY_INDEX_MAX_LINES, META_KEY_DIMENSION, META_KEY_MODEL, META_KEY_PROVIDER_ID, PRAGMA_STATEMENTS, SCHEMA_STATEMENTS, appendDiaryEntry, appendFact, appendFactToMarkdown, asMemoryRoot, ceilingReachedError, chunkMarkdown, claudeProjectMemoryDir, collectMarkdownFiles, createVectorIndex, deepPhase, defaultIndexPath, diaryPath, discoverSessionFiles, discoverWikiFiles, dropVectorIndex, embedMissingChunks, entryHash, identityMatches, indexBudgetWarning, lanceStoragePath, lightPhase, loadSqliteVecExtension, memoryIndexRoot, memoryMdPath, memoryReadRoots, notesDir, openMemoryDb, packVector, parseSearchOptions, persistActiveMemoryTranscript, projectMemoryDir, readAllSqliteFacts, readEmbeddingIdentity, readFacts, readFactsFromMarkdown, readMemoryFileBounded, remPhase, renderDiaryEntry, resolveMaxFacts, resolveMemoryRoot, runDreamingSweep, sessionSummaryPath, sessionsDir, upsertEmbedding, vectorSearch, wikiDir, writeEmbeddingIdentity, writeSessionSummary } from '@theokit/sdk/internal/memory-store';
|
|
6
|
+
import { replaceFileAtomic, sanitizeFts5Query, withCwdMutex } from '@theokit/sdk/persistence';
|
|
8
7
|
import { createOpenAiCompatibleRuntime } from '@theokit/sdk/internal/memory-adapters';
|
|
9
8
|
export { createOpenAiCompatibleRuntime } from '@theokit/sdk/internal/memory-adapters';
|
|
10
9
|
import { AuthenticationError, RateLimitError, ConfigurationError, NetworkError, UnknownAgentError } from '@theokit/sdk/errors';
|
|
11
10
|
import { sanitizeIdentifier, safePathJoin } from '@theokit/sdk/path-safety';
|
|
11
|
+
import { createHash } from 'crypto';
|
|
12
12
|
import { mkdirSync, existsSync, rmSync, renameSync } from 'fs';
|
|
13
13
|
import { createRequire } from 'module';
|
|
14
14
|
|
|
15
15
|
// src/in-memory-provider.ts
|
|
16
16
|
var ADAPTER_ID = "in-memory-md";
|
|
17
|
+
var IN_MEMORY_REMEDY = "merge or delete facts with the adapter's delete(id), or raise maxFacts";
|
|
17
18
|
var INTERNAL_STATE = /* @__PURE__ */ Symbol("sdk-memory.in-memory.state");
|
|
18
19
|
function buildCapabilities() {
|
|
19
20
|
return {
|
|
@@ -25,6 +26,19 @@ function buildCapabilities() {
|
|
|
25
26
|
prefetch: false
|
|
26
27
|
};
|
|
27
28
|
}
|
|
29
|
+
function admitNewFact(state) {
|
|
30
|
+
if (state.maxFacts !== void 0 && state.facts.size >= state.maxFacts) {
|
|
31
|
+
throw ceilingReachedError(
|
|
32
|
+
"the in-memory store",
|
|
33
|
+
state.facts.size,
|
|
34
|
+
state.maxFacts,
|
|
35
|
+
IN_MEMORY_REMEDY
|
|
36
|
+
);
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
function isCeilingRefusal(cause) {
|
|
40
|
+
return cause instanceof ConfigurationError$1 && cause.code === "memory_ceiling_reached";
|
|
41
|
+
}
|
|
28
42
|
function buildAdapter(state) {
|
|
29
43
|
return {
|
|
30
44
|
id: ADAPTER_ID,
|
|
@@ -35,6 +49,7 @@ function buildAdapter(state) {
|
|
|
35
49
|
async write(content, _ctx) {
|
|
36
50
|
const text = typeof content === "string" ? content : content.map((m) => m.content).join("\n");
|
|
37
51
|
const safeText = Security.redact(text);
|
|
52
|
+
admitNewFact(state);
|
|
38
53
|
const id = `${ADAPTER_ID}:${state.counter.next++}`;
|
|
39
54
|
state.facts.set(id, {
|
|
40
55
|
id,
|
|
@@ -180,6 +195,12 @@ function buildMemoryRememberTool(state) {
|
|
|
180
195
|
return JSON.stringify({ ok: false, error: "empty content" });
|
|
181
196
|
}
|
|
182
197
|
const safeContent = Security.redact(content);
|
|
198
|
+
try {
|
|
199
|
+
admitNewFact(state);
|
|
200
|
+
} catch (cause) {
|
|
201
|
+
if (!isCeilingRefusal(cause)) throw cause;
|
|
202
|
+
return JSON.stringify({ ok: false, code: cause.code, error: cause.message });
|
|
203
|
+
}
|
|
183
204
|
const id = `${ADAPTER_ID}:${state.counter.next++}`;
|
|
184
205
|
state.facts.set(id, {
|
|
185
206
|
id,
|
|
@@ -190,11 +211,13 @@ function buildMemoryRememberTool(state) {
|
|
|
190
211
|
}
|
|
191
212
|
};
|
|
192
213
|
}
|
|
193
|
-
function createInMemoryMarkdownProvider() {
|
|
214
|
+
function createInMemoryMarkdownProvider(options = {}) {
|
|
215
|
+
const maxFacts = resolveMaxFacts(options.maxFacts);
|
|
194
216
|
return {
|
|
195
217
|
async init(opts) {
|
|
196
218
|
const state = {
|
|
197
219
|
facts: /* @__PURE__ */ new Map(),
|
|
220
|
+
maxFacts,
|
|
198
221
|
counter: { next: 0 },
|
|
199
222
|
cwd: opts.cwd
|
|
200
223
|
};
|
|
@@ -481,48 +504,6 @@ var CircuitBreaker = class {
|
|
|
481
504
|
return this.opts.now?.() ?? Date.now();
|
|
482
505
|
}
|
|
483
506
|
};
|
|
484
|
-
var DEFAULT_TTL_MS = 15e3;
|
|
485
|
-
var DEFAULT_CAPACITY = 1e3;
|
|
486
|
-
var ActiveMemoryCache = class {
|
|
487
|
-
constructor(opts = {}) {
|
|
488
|
-
this.opts = opts;
|
|
489
|
-
}
|
|
490
|
-
opts;
|
|
491
|
-
map = /* @__PURE__ */ new Map();
|
|
492
|
-
get(userText, queryMode, tenantCtx) {
|
|
493
|
-
const key = cacheKey(userText, queryMode, tenantCtx);
|
|
494
|
-
const entry = this.map.get(key);
|
|
495
|
-
if (entry === void 0) return void 0;
|
|
496
|
-
if (this.now() >= entry.expiresAtMs) {
|
|
497
|
-
this.map.delete(key);
|
|
498
|
-
return void 0;
|
|
499
|
-
}
|
|
500
|
-
this.map.delete(key);
|
|
501
|
-
this.map.set(key, entry);
|
|
502
|
-
return entry.result;
|
|
503
|
-
}
|
|
504
|
-
set(userText, queryMode, result, tenantCtx) {
|
|
505
|
-
const key = cacheKey(userText, queryMode, tenantCtx);
|
|
506
|
-
if (this.map.size >= (this.opts.capacity ?? DEFAULT_CAPACITY)) {
|
|
507
|
-
const oldest = this.map.keys().next().value;
|
|
508
|
-
if (oldest !== void 0) this.map.delete(oldest);
|
|
509
|
-
}
|
|
510
|
-
this.map.set(key, {
|
|
511
|
-
expiresAtMs: this.now() + (this.opts.ttlMs ?? DEFAULT_TTL_MS),
|
|
512
|
-
result
|
|
513
|
-
});
|
|
514
|
-
}
|
|
515
|
-
size() {
|
|
516
|
-
return this.map.size;
|
|
517
|
-
}
|
|
518
|
-
now() {
|
|
519
|
-
return this.opts.now?.() ?? Date.now();
|
|
520
|
-
}
|
|
521
|
-
};
|
|
522
|
-
function cacheKey(userText, queryMode, ctx) {
|
|
523
|
-
const parts = [queryMode, ctx?.namespace ?? "", ctx?.userId ?? "", ctx?.scope ?? "", userText];
|
|
524
|
-
return createHash("sha256").update(parts.join("\0")).digest("hex");
|
|
525
|
-
}
|
|
526
507
|
|
|
527
508
|
// src/internal/embedding/azure-openai-embedding.ts
|
|
528
509
|
var DEFAULT_AZURE_OPENAI_EMBEDDING_MODEL = "text-embedding-3-small";
|
|
@@ -862,6 +843,8 @@ function legacyMemoryJsonPath(cwd, config) {
|
|
|
862
843
|
|
|
863
844
|
// src/internal/adapter-http-error.ts
|
|
864
845
|
var RAW_MAX_BYTES = 2048;
|
|
846
|
+
var PROVIDER_DETAIL_MAX_CHARS = 512;
|
|
847
|
+
var MISSING_MODEL_MESSAGE = /no endpoints found/i;
|
|
865
848
|
function parseRetryAfter(headers) {
|
|
866
849
|
if (headers === void 0) return void 0;
|
|
867
850
|
const raw = headers.get("retry-after");
|
|
@@ -873,8 +856,8 @@ function parseRetryAfter(headers) {
|
|
|
873
856
|
function truncateRaw(body) {
|
|
874
857
|
if (body === null || body === void 0) return void 0;
|
|
875
858
|
const s = typeof body === "string" ? body : JSON.stringify(body);
|
|
876
|
-
const
|
|
877
|
-
return
|
|
859
|
+
const redacted = redactSecrets(s);
|
|
860
|
+
return redacted.length <= RAW_MAX_BYTES ? redacted : `${redacted.slice(0, RAW_MAX_BYTES)}\u2026`;
|
|
878
861
|
}
|
|
879
862
|
function buildErrorMetadata(args) {
|
|
880
863
|
const retryAfter = parseRetryAfter(args.headers);
|
|
@@ -906,8 +889,16 @@ function mapOpenAICompatibleError(args) {
|
|
|
906
889
|
if (status === 429) {
|
|
907
890
|
return new RateLimitError(message, { code: `${providerId}_rate_limit`, metadata });
|
|
908
891
|
}
|
|
892
|
+
if (status === 404 && code === "model_unavailable") {
|
|
893
|
+
const detailed = formatMessage(providerId, status, code, boundedProviderDetail(body));
|
|
894
|
+
return new ConfigurationError(detailed, {
|
|
895
|
+
code: `${providerId}_model_unavailable`,
|
|
896
|
+
metadata
|
|
897
|
+
});
|
|
898
|
+
}
|
|
909
899
|
if (status === 400) {
|
|
910
|
-
|
|
900
|
+
const detailed = formatMessage(providerId, status, code, boundedProviderDetail(body));
|
|
901
|
+
return new ConfigurationError(detailed, { code: `${providerId}_${code}`, metadata });
|
|
911
902
|
}
|
|
912
903
|
if (status === 408) {
|
|
913
904
|
return new NetworkError(message, { code: `${providerId}_timeout`, metadata });
|
|
@@ -917,6 +908,18 @@ function mapOpenAICompatibleError(args) {
|
|
|
917
908
|
}
|
|
918
909
|
return new UnknownAgentError(message, { code: `${providerId}_unknown`, metadata });
|
|
919
910
|
}
|
|
911
|
+
function extractOpenAiErrorMessage(body) {
|
|
912
|
+
if (body === null || typeof body !== "object") return void 0;
|
|
913
|
+
const err = body.error;
|
|
914
|
+
if (err === void 0 || err === null) return void 0;
|
|
915
|
+
return typeof err.message === "string" ? err.message : void 0;
|
|
916
|
+
}
|
|
917
|
+
function boundedProviderDetail(body) {
|
|
918
|
+
const raw = extractOpenAiErrorMessage(body);
|
|
919
|
+
if (raw === void 0 || raw.trim() === "") return void 0;
|
|
920
|
+
const redacted = redactSecrets(raw);
|
|
921
|
+
return redacted.length <= PROVIDER_DETAIL_MAX_CHARS ? redacted : `${redacted.slice(0, PROVIDER_DETAIL_MAX_CHARS)}\u2026`;
|
|
922
|
+
}
|
|
920
923
|
function extractOpenAiErrorCode(body) {
|
|
921
924
|
if (body === null || typeof body !== "object") return void 0;
|
|
922
925
|
const err = body.error;
|
|
@@ -939,6 +942,9 @@ function mapOpenAiStatusToCode(status, body) {
|
|
|
939
942
|
if (status === 402 || rawCode.includes("insufficient_quota") || rawCode.includes("quota_exceeded")) {
|
|
940
943
|
return "quota_exceeded";
|
|
941
944
|
}
|
|
945
|
+
if (status === 404 && MISSING_MODEL_MESSAGE.test(extractOpenAiErrorMessage(body) ?? "")) {
|
|
946
|
+
return "model_unavailable";
|
|
947
|
+
}
|
|
942
948
|
if (status === 401 || status === 403) return "auth_failed";
|
|
943
949
|
if (status === 429) return "rate_limit";
|
|
944
950
|
if (status === 408) return "timeout";
|
|
@@ -946,8 +952,9 @@ function mapOpenAiStatusToCode(status, body) {
|
|
|
946
952
|
if (status >= 500 && status < 600) return "server_error";
|
|
947
953
|
return "unknown";
|
|
948
954
|
}
|
|
949
|
-
function formatMessage(providerId, status, code) {
|
|
950
|
-
|
|
955
|
+
function formatMessage(providerId, status, code, detail) {
|
|
956
|
+
const base = `${providerId} API error: ${code} (HTTP ${status})`;
|
|
957
|
+
return detail === void 0 || detail === "" ? base : `${base}: ${detail}`;
|
|
951
958
|
}
|
|
952
959
|
var FACTS_HEADING = "## Facts";
|
|
953
960
|
function createCategorizedMemory(options) {
|
|
@@ -1075,293 +1082,6 @@ ${bullet}
|
|
|
1075
1082
|
return `${raw.slice(0, insertAt)}
|
|
1076
1083
|
${bullet}${raw.slice(insertAt)}`;
|
|
1077
1084
|
}
|
|
1078
|
-
|
|
1079
|
-
// src/internal/dreaming/dreaming-phases.ts
|
|
1080
|
-
var DEFAULT_DEDUP_THRESHOLD = 0.95;
|
|
1081
|
-
var DEFAULT_CLUSTER_THRESHOLD = 0.75;
|
|
1082
|
-
async function lightPhase(facts, embedding, threshold = DEFAULT_DEDUP_THRESHOLD) {
|
|
1083
|
-
if (facts.length <= 1) return { kept: [...facts], duplicatesRemoved: 0 };
|
|
1084
|
-
const vectors = await embedding.embed(facts.map((f) => f.text));
|
|
1085
|
-
const keptIdx = [];
|
|
1086
|
-
const keptVecs = [];
|
|
1087
|
-
for (let i = 0; i < facts.length; i++) {
|
|
1088
|
-
const vec = vectors[i] ?? [];
|
|
1089
|
-
const isDup = keptVecs.some((kept2) => cosineSimilarity(vec, kept2) >= threshold);
|
|
1090
|
-
if (isDup) continue;
|
|
1091
|
-
keptIdx.push(i);
|
|
1092
|
-
keptVecs.push(vec);
|
|
1093
|
-
}
|
|
1094
|
-
const kept = keptIdx.map((i) => facts[i]);
|
|
1095
|
-
return { kept, duplicatesRemoved: facts.length - kept.length };
|
|
1096
|
-
}
|
|
1097
|
-
var DEFAULT_MAX_FACTS_PER_SWEEP = 500;
|
|
1098
|
-
async function remPhase(facts, embedding, threshold = DEFAULT_CLUSTER_THRESHOLD, maxFactsPerSweep = DEFAULT_MAX_FACTS_PER_SWEEP) {
|
|
1099
|
-
if (facts.length === 0) return { clusters: [] };
|
|
1100
|
-
const capped = facts.length > maxFactsPerSweep ? facts.slice(0, maxFactsPerSweep) : facts;
|
|
1101
|
-
const vectors = await embedding.embed(capped.map((f) => f.text));
|
|
1102
|
-
const clusterOfIdx = unionFindByPairs(vectors, threshold);
|
|
1103
|
-
const groups = bucketFactsByClusterRoot(capped, clusterOfIdx);
|
|
1104
|
-
return { clusters: [...groups.values()].map(buildClusterFromMembers) };
|
|
1105
|
-
}
|
|
1106
|
-
function unionFindByPairs(vectors, threshold) {
|
|
1107
|
-
const clusterOfIdx = vectors.map((_, i) => i);
|
|
1108
|
-
for (let i = 0; i < vectors.length; i++) {
|
|
1109
|
-
for (let j = i + 1; j < vectors.length; j++) {
|
|
1110
|
-
if (cosineSimilarity(vectors[i] ?? [], vectors[j] ?? []) >= threshold) {
|
|
1111
|
-
unifyClusters(clusterOfIdx, i, j);
|
|
1112
|
-
}
|
|
1113
|
-
}
|
|
1114
|
-
}
|
|
1115
|
-
return clusterOfIdx;
|
|
1116
|
-
}
|
|
1117
|
-
function bucketFactsByClusterRoot(facts, clusterOfIdx) {
|
|
1118
|
-
const groups = /* @__PURE__ */ new Map();
|
|
1119
|
-
for (let i = 0; i < facts.length; i++) {
|
|
1120
|
-
const root = findRoot(clusterOfIdx, i);
|
|
1121
|
-
const list = groups.get(root) ?? [];
|
|
1122
|
-
list.push(facts[i]);
|
|
1123
|
-
groups.set(root, list);
|
|
1124
|
-
}
|
|
1125
|
-
return groups;
|
|
1126
|
-
}
|
|
1127
|
-
function buildClusterFromMembers(members) {
|
|
1128
|
-
const sorted = [...members].sort((a, b) => b.text.length - a.text.length);
|
|
1129
|
-
return { representativeText: sorted[0]?.text ?? "", members };
|
|
1130
|
-
}
|
|
1131
|
-
function deepPhase(clusters, timestampMs) {
|
|
1132
|
-
if (clusters.length === 0) return "";
|
|
1133
|
-
const isoStamp = new Date(timestampMs).toISOString();
|
|
1134
|
-
const lines = [`# Dreamed ${isoStamp}`, ""];
|
|
1135
|
-
for (let i = 0; i < clusters.length; i++) {
|
|
1136
|
-
const c = clusters[i];
|
|
1137
|
-
if (c === void 0) continue;
|
|
1138
|
-
lines.push(`## Cluster ${i + 1}: ${c.representativeText}`);
|
|
1139
|
-
lines.push("");
|
|
1140
|
-
for (const member of c.members) lines.push(`- ${member.text}`);
|
|
1141
|
-
lines.push("");
|
|
1142
|
-
}
|
|
1143
|
-
return `${lines.join("\n")}
|
|
1144
|
-
`;
|
|
1145
|
-
}
|
|
1146
|
-
function cosineSimilarity(a, b) {
|
|
1147
|
-
if (a.length === 0 || b.length === 0 || a.length !== b.length) return 0;
|
|
1148
|
-
let dot = 0;
|
|
1149
|
-
let aNorm = 0;
|
|
1150
|
-
let bNorm = 0;
|
|
1151
|
-
for (let i = 0; i < a.length; i++) {
|
|
1152
|
-
const ai = a[i] ?? 0;
|
|
1153
|
-
const bi = b[i] ?? 0;
|
|
1154
|
-
dot += ai * bi;
|
|
1155
|
-
aNorm += ai * ai;
|
|
1156
|
-
bNorm += bi * bi;
|
|
1157
|
-
}
|
|
1158
|
-
const denom = Math.sqrt(aNorm) * Math.sqrt(bNorm);
|
|
1159
|
-
return denom === 0 ? 0 : dot / denom;
|
|
1160
|
-
}
|
|
1161
|
-
function findRoot(parents, i) {
|
|
1162
|
-
let root = i;
|
|
1163
|
-
while (parents[root] !== root) {
|
|
1164
|
-
const next = parents[root] ?? root;
|
|
1165
|
-
if (next === root) break;
|
|
1166
|
-
root = next;
|
|
1167
|
-
}
|
|
1168
|
-
parents[i] = root;
|
|
1169
|
-
return root;
|
|
1170
|
-
}
|
|
1171
|
-
function unifyClusters(parents, a, b) {
|
|
1172
|
-
const rootA = findRoot(parents, a);
|
|
1173
|
-
const rootB = findRoot(parents, b);
|
|
1174
|
-
if (rootA !== rootB) parents[rootB] = rootA;
|
|
1175
|
-
}
|
|
1176
|
-
function runDreamingSweep(options) {
|
|
1177
|
-
return withCwdMutex(`dream:${options.cwd}`, () => runInner(options));
|
|
1178
|
-
}
|
|
1179
|
-
async function runInner(options) {
|
|
1180
|
-
const now = options.now ?? Date.now;
|
|
1181
|
-
const timestampMs = now();
|
|
1182
|
-
try {
|
|
1183
|
-
const facts = await readFactsFromMarkdown(options.cwd);
|
|
1184
|
-
if (facts.length === 0) {
|
|
1185
|
-
return emptyResult("skipped");
|
|
1186
|
-
}
|
|
1187
|
-
const dedup = await lightPhase(facts, options.embedding, options.dedupThreshold);
|
|
1188
|
-
const rem = await remPhase(dedup.kept, options.embedding, options.clusterThreshold);
|
|
1189
|
-
const notesWritten = await writeConsolidatedNotes(options.cwd, rem.clusters, timestampMs);
|
|
1190
|
-
const result = {
|
|
1191
|
-
status: "ok",
|
|
1192
|
-
factsBefore: facts.length,
|
|
1193
|
-
factsAfter: dedup.kept.length,
|
|
1194
|
-
duplicatesRemoved: dedup.duplicatesRemoved,
|
|
1195
|
-
clustersCreated: rem.clusters.length,
|
|
1196
|
-
notesWritten,
|
|
1197
|
-
diaryEntryHash: void 0
|
|
1198
|
-
};
|
|
1199
|
-
await appendDiaryEntry(resolveMemoryRoot(options.cwd), {
|
|
1200
|
-
timestampMs,
|
|
1201
|
-
factsBefore: result.factsBefore,
|
|
1202
|
-
factsAfter: result.factsAfter,
|
|
1203
|
-
duplicatesRemoved: result.duplicatesRemoved,
|
|
1204
|
-
clustersCreated: result.clustersCreated,
|
|
1205
|
-
notesWritten: result.notesWritten
|
|
1206
|
-
});
|
|
1207
|
-
return result;
|
|
1208
|
-
} catch (cause) {
|
|
1209
|
-
const message = cause instanceof Error ? cause.message : String(cause);
|
|
1210
|
-
process.stderr.write(`[theokit-sdk] dreaming sweep failed: ${message}
|
|
1211
|
-
`);
|
|
1212
|
-
return emptyResult("error");
|
|
1213
|
-
}
|
|
1214
|
-
}
|
|
1215
|
-
async function writeConsolidatedNotes(cwd, clusters, timestampMs) {
|
|
1216
|
-
if (clusters.length === 0) return 0;
|
|
1217
|
-
const notesDir3 = join(resolveMemoryRoot(cwd), "notes");
|
|
1218
|
-
await mkdir(notesDir3, { recursive: true });
|
|
1219
|
-
const isoSlug = new Date(timestampMs).toISOString().replace(/[^\dT]/g, "-");
|
|
1220
|
-
const file = join(notesDir3, `dreamed-${isoSlug}.md`);
|
|
1221
|
-
const body = deepPhase(clusters, timestampMs);
|
|
1222
|
-
await replaceFileAtomic(file, body);
|
|
1223
|
-
return 1;
|
|
1224
|
-
}
|
|
1225
|
-
function emptyResult(status) {
|
|
1226
|
-
return {
|
|
1227
|
-
status,
|
|
1228
|
-
factsBefore: 0,
|
|
1229
|
-
factsAfter: 0,
|
|
1230
|
-
duplicatesRemoved: 0,
|
|
1231
|
-
clustersCreated: 0,
|
|
1232
|
-
notesWritten: 0,
|
|
1233
|
-
diaryEntryHash: void 0
|
|
1234
|
-
};
|
|
1235
|
-
}
|
|
1236
|
-
|
|
1237
|
-
// src/internal/index/index-schema.ts
|
|
1238
|
-
var SCHEMA_STATEMENTS = [
|
|
1239
|
-
`CREATE TABLE IF NOT EXISTS files (
|
|
1240
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1241
|
-
path TEXT UNIQUE NOT NULL,
|
|
1242
|
-
rel_path TEXT NOT NULL,
|
|
1243
|
-
mtime INTEGER NOT NULL,
|
|
1244
|
-
hash TEXT NOT NULL,
|
|
1245
|
-
source TEXT NOT NULL DEFAULT 'memory'
|
|
1246
|
-
)`,
|
|
1247
|
-
`CREATE TABLE IF NOT EXISTS chunks (
|
|
1248
|
-
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1249
|
-
file_id INTEGER NOT NULL REFERENCES files(id) ON DELETE CASCADE,
|
|
1250
|
-
start_line INTEGER NOT NULL,
|
|
1251
|
-
end_line INTEGER NOT NULL,
|
|
1252
|
-
text TEXT NOT NULL,
|
|
1253
|
-
hash TEXT NOT NULL,
|
|
1254
|
-
session_key TEXT
|
|
1255
|
-
)`,
|
|
1256
|
-
`CREATE VIRTUAL TABLE IF NOT EXISTS chunks_fts USING fts5(
|
|
1257
|
-
text,
|
|
1258
|
-
content='chunks',
|
|
1259
|
-
content_rowid='id'
|
|
1260
|
-
)`,
|
|
1261
|
-
`CREATE TRIGGER IF NOT EXISTS chunks_fts_insert AFTER INSERT ON chunks BEGIN
|
|
1262
|
-
INSERT INTO chunks_fts(rowid, text) VALUES (new.id, new.text);
|
|
1263
|
-
END`,
|
|
1264
|
-
`CREATE TRIGGER IF NOT EXISTS chunks_fts_delete AFTER DELETE ON chunks BEGIN
|
|
1265
|
-
INSERT INTO chunks_fts(chunks_fts, rowid, text) VALUES ('delete', old.id, old.text);
|
|
1266
|
-
END`,
|
|
1267
|
-
`CREATE TABLE IF NOT EXISTS meta (
|
|
1268
|
-
key TEXT PRIMARY KEY,
|
|
1269
|
-
value TEXT
|
|
1270
|
-
)`,
|
|
1271
|
-
`CREATE INDEX IF NOT EXISTS idx_chunks_file_id ON chunks(file_id)`
|
|
1272
|
-
];
|
|
1273
|
-
var PRAGMA_STATEMENTS = [
|
|
1274
|
-
"PRAGMA synchronous=NORMAL",
|
|
1275
|
-
"PRAGMA foreign_keys=ON"
|
|
1276
|
-
];
|
|
1277
|
-
|
|
1278
|
-
// src/internal/index/index-db.ts
|
|
1279
|
-
async function openMemoryDb(opts) {
|
|
1280
|
-
return openSqliteResilient({
|
|
1281
|
-
filePath: opts.filePath,
|
|
1282
|
-
label: "memory-index",
|
|
1283
|
-
recoverCorrupt: opts.recoverCorrupt,
|
|
1284
|
-
onOpen: (db) => {
|
|
1285
|
-
for (const pragma of PRAGMA_STATEMENTS) db.exec(pragma);
|
|
1286
|
-
for (const stmt of SCHEMA_STATEMENTS) db.exec(stmt);
|
|
1287
|
-
}
|
|
1288
|
-
});
|
|
1289
|
-
}
|
|
1290
|
-
var HEADING_RE = /^(#{1,6})\s+(.+?)\s*$/;
|
|
1291
|
-
function chunkMarkdown(text, options = {}) {
|
|
1292
|
-
const maxChars = options.maxChars ?? 800;
|
|
1293
|
-
if (text.length === 0) return [];
|
|
1294
|
-
const lines = text.split("\n");
|
|
1295
|
-
const acc = { chunks: [], lines: [], start: 1, heading: void 0 };
|
|
1296
|
-
for (let i = 0; i < lines.length; i++) {
|
|
1297
|
-
const line = lines[i] ?? "";
|
|
1298
|
-
const lineNumber = i + 1;
|
|
1299
|
-
processLine(acc, line, lineNumber, maxChars);
|
|
1300
|
-
}
|
|
1301
|
-
flushAccumulator(acc, lines.length, maxChars);
|
|
1302
|
-
return acc.chunks;
|
|
1303
|
-
}
|
|
1304
|
-
function processLine(acc, line, lineNumber, maxChars) {
|
|
1305
|
-
const headingMatch = HEADING_RE.exec(line);
|
|
1306
|
-
const isBlank = line.trim().length === 0;
|
|
1307
|
-
if (headingMatch !== null && acc.lines.length > 0) {
|
|
1308
|
-
flushAccumulator(acc, lineNumber - 1, maxChars);
|
|
1309
|
-
}
|
|
1310
|
-
if (headingMatch !== null) acc.heading = headingMatch[2];
|
|
1311
|
-
acc.lines.push(line);
|
|
1312
|
-
if (isBlank && acc.lines.length > 1) {
|
|
1313
|
-
const joined = acc.lines.join("\n");
|
|
1314
|
-
if (joined.trim().length > 0) flushAccumulator(acc, lineNumber, maxChars);
|
|
1315
|
-
}
|
|
1316
|
-
}
|
|
1317
|
-
function flushAccumulator(acc, endLineExclusive, maxChars) {
|
|
1318
|
-
if (acc.lines.length === 0) return;
|
|
1319
|
-
const chunkText = acc.lines.join("\n");
|
|
1320
|
-
if (chunkText.trim().length === 0) {
|
|
1321
|
-
acc.lines = [];
|
|
1322
|
-
acc.start = endLineExclusive + 1;
|
|
1323
|
-
return;
|
|
1324
|
-
}
|
|
1325
|
-
if (chunkText.length > maxChars) {
|
|
1326
|
-
pushOversizedSlices(acc.chunks, chunkText, acc.start, acc.heading, maxChars);
|
|
1327
|
-
} else {
|
|
1328
|
-
acc.chunks.push(buildChunk(chunkText, acc.start, endLineExclusive, acc.heading));
|
|
1329
|
-
}
|
|
1330
|
-
acc.lines = [];
|
|
1331
|
-
acc.start = endLineExclusive + 1;
|
|
1332
|
-
}
|
|
1333
|
-
function buildChunk(text, startLine, endLine, heading) {
|
|
1334
|
-
return {
|
|
1335
|
-
startLine,
|
|
1336
|
-
endLine,
|
|
1337
|
-
text,
|
|
1338
|
-
hash: createHash("sha256").update(text).digest("hex"),
|
|
1339
|
-
...heading !== void 0 ? { heading } : {}
|
|
1340
|
-
};
|
|
1341
|
-
}
|
|
1342
|
-
function pushOversizedSlices(chunks, text, startLine, heading, maxChars) {
|
|
1343
|
-
let remaining = text;
|
|
1344
|
-
let lineCursor = startLine;
|
|
1345
|
-
while (remaining.length > maxChars) {
|
|
1346
|
-
const splitAt = findWordBoundarySplit(remaining, maxChars);
|
|
1347
|
-
const slice = remaining.slice(0, splitAt);
|
|
1348
|
-
const sliceLines = slice.split("\n").length;
|
|
1349
|
-
chunks.push(buildChunk(slice, lineCursor, lineCursor + sliceLines - 1, heading));
|
|
1350
|
-
remaining = remaining.slice(splitAt).replace(/^\s+/, "");
|
|
1351
|
-
lineCursor += sliceLines - 1;
|
|
1352
|
-
}
|
|
1353
|
-
if (remaining.length > 0) {
|
|
1354
|
-
const sliceLines = remaining.split("\n").length;
|
|
1355
|
-
chunks.push(buildChunk(remaining, lineCursor, lineCursor + sliceLines - 1, heading));
|
|
1356
|
-
}
|
|
1357
|
-
}
|
|
1358
|
-
function findWordBoundarySplit(text, maxChars) {
|
|
1359
|
-
if (text.length <= maxChars) return text.length;
|
|
1360
|
-
for (let i = maxChars; i > Math.max(0, maxChars - 200); i--) {
|
|
1361
|
-
if (/\s/.test(text[i] ?? "x")) return i;
|
|
1362
|
-
}
|
|
1363
|
-
return maxChars;
|
|
1364
|
-
}
|
|
1365
1085
|
function requireLance() {
|
|
1366
1086
|
try {
|
|
1367
1087
|
const r = createRequire(import.meta.url);
|
|
@@ -1487,14 +1207,6 @@ function isLanceAvailable() {
|
|
|
1487
1207
|
}
|
|
1488
1208
|
}
|
|
1489
1209
|
|
|
1490
|
-
// src/internal/index/memory-index.ts
|
|
1491
|
-
function parseSearchOptions(options = {}) {
|
|
1492
|
-
return {
|
|
1493
|
-
maxResults: Math.max(1, options.maxResults ?? 10),
|
|
1494
|
-
minScore: options.minScore ?? 0
|
|
1495
|
-
};
|
|
1496
|
-
}
|
|
1497
|
-
|
|
1498
1210
|
// src/internal/index/lance-memory-adapter.ts
|
|
1499
1211
|
var DEFAULT_NAMESPACE = "default";
|
|
1500
1212
|
var EMPTY_SYNC_RESULT = Object.freeze({
|
|
@@ -1584,22 +1296,6 @@ async function openLanceIndex(opts) {
|
|
|
1584
1296
|
});
|
|
1585
1297
|
return new LanceMemoryAdapter(lance);
|
|
1586
1298
|
}
|
|
1587
|
-
async function loadSqliteVecExtension(db) {
|
|
1588
|
-
try {
|
|
1589
|
-
const mod = await import('sqlite-vec');
|
|
1590
|
-
const loadFn = mod.load;
|
|
1591
|
-
if (typeof loadFn !== "function") {
|
|
1592
|
-
throw new Error("sqlite-vec module exposes no `load` export");
|
|
1593
|
-
}
|
|
1594
|
-
loadFn(db);
|
|
1595
|
-
} catch (cause) {
|
|
1596
|
-
const message = cause instanceof Error ? cause.message : String(cause);
|
|
1597
|
-
throw new ConfigurationError(
|
|
1598
|
-
`sqlite-vec extension unavailable. Install \`sqlite-vec\` and ensure the native binary matches your Node + OS. Cause: ${message}`,
|
|
1599
|
-
{ code: "sqlite_vec_unavailable", cause }
|
|
1600
|
-
);
|
|
1601
|
-
}
|
|
1602
|
-
}
|
|
1603
1299
|
function isSqliteVecLoaded(db) {
|
|
1604
1300
|
try {
|
|
1605
1301
|
const row = db.prepare("SELECT vec_version() as v").get();
|
|
@@ -1609,80 +1305,6 @@ function isSqliteVecLoaded(db) {
|
|
|
1609
1305
|
}
|
|
1610
1306
|
}
|
|
1611
1307
|
|
|
1612
|
-
// src/internal/index/vec-index.ts
|
|
1613
|
-
var META_KEY_PROVIDER_ID = "embedding.providerId";
|
|
1614
|
-
var META_KEY_MODEL = "embedding.model";
|
|
1615
|
-
var META_KEY_DIMENSION = "embedding.dimension";
|
|
1616
|
-
function readEmbeddingIdentity(db) {
|
|
1617
|
-
const get = (key) => {
|
|
1618
|
-
const row = db.prepare("SELECT value FROM meta WHERE key = ?").get(key);
|
|
1619
|
-
return row !== void 0 ? String(row.value) : void 0;
|
|
1620
|
-
};
|
|
1621
|
-
const providerId = get(META_KEY_PROVIDER_ID);
|
|
1622
|
-
const model = get(META_KEY_MODEL);
|
|
1623
|
-
const dimRaw = get(META_KEY_DIMENSION);
|
|
1624
|
-
if (providerId === void 0 || model === void 0 || dimRaw === void 0) return void 0;
|
|
1625
|
-
const dimension = Number(dimRaw);
|
|
1626
|
-
if (!Number.isFinite(dimension) || dimension <= 0) return void 0;
|
|
1627
|
-
return { providerId, model, dimension };
|
|
1628
|
-
}
|
|
1629
|
-
function writeEmbeddingIdentity(db, identity) {
|
|
1630
|
-
const stmt = db.prepare(
|
|
1631
|
-
"INSERT INTO meta (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = excluded.value"
|
|
1632
|
-
);
|
|
1633
|
-
stmt.run(META_KEY_PROVIDER_ID, identity.providerId);
|
|
1634
|
-
stmt.run(META_KEY_MODEL, identity.model);
|
|
1635
|
-
stmt.run(META_KEY_DIMENSION, String(identity.dimension));
|
|
1636
|
-
}
|
|
1637
|
-
function identityMatches(a, b) {
|
|
1638
|
-
return a.providerId === b.providerId && a.model === b.model && a.dimension === b.dimension;
|
|
1639
|
-
}
|
|
1640
|
-
function dropVectorIndex(db) {
|
|
1641
|
-
db.exec("DROP TABLE IF EXISTS embeddings");
|
|
1642
|
-
}
|
|
1643
|
-
function createVectorIndex(db, dimension) {
|
|
1644
|
-
db.exec(`CREATE VIRTUAL TABLE IF NOT EXISTS embeddings USING vec0(
|
|
1645
|
-
chunk_id INTEGER PRIMARY KEY,
|
|
1646
|
-
vec FLOAT[${dimension}]
|
|
1647
|
-
)`);
|
|
1648
|
-
}
|
|
1649
|
-
function packVector(vec) {
|
|
1650
|
-
const f32 = new Float32Array(vec.length);
|
|
1651
|
-
for (let i = 0; i < vec.length; i++) f32[i] = vec[i] ?? 0;
|
|
1652
|
-
return Buffer.from(f32.buffer);
|
|
1653
|
-
}
|
|
1654
|
-
function upsertEmbedding(db, chunkId, vec) {
|
|
1655
|
-
const id = BigInt(chunkId);
|
|
1656
|
-
db.prepare("DELETE FROM embeddings WHERE chunk_id = ?").run(id);
|
|
1657
|
-
db.prepare("INSERT INTO embeddings (chunk_id, vec) VALUES (?, ?)").run(id, packVector(vec));
|
|
1658
|
-
}
|
|
1659
|
-
function vectorSearch(db, query, k) {
|
|
1660
|
-
const rows = db.prepare(
|
|
1661
|
-
`SELECT chunk_id, distance FROM embeddings
|
|
1662
|
-
WHERE vec MATCH ? AND k = ?
|
|
1663
|
-
ORDER BY distance`
|
|
1664
|
-
).all(packVector(query), BigInt(k));
|
|
1665
|
-
return rows.map((row) => ({ chunk_id: Number(row.chunk_id), distance: Number(row.distance) }));
|
|
1666
|
-
}
|
|
1667
|
-
async function embedMissingChunks(args) {
|
|
1668
|
-
const rows = args.db.prepare(
|
|
1669
|
-
`SELECT chunks.id as id, chunks.text as text
|
|
1670
|
-
FROM chunks
|
|
1671
|
-
LEFT JOIN embeddings ON embeddings.chunk_id = chunks.id
|
|
1672
|
-
WHERE embeddings.chunk_id IS NULL`
|
|
1673
|
-
).all();
|
|
1674
|
-
if (rows.length === 0) return 0;
|
|
1675
|
-
const normalized = rows.map((row) => ({ id: Number(row.id), text: String(row.text ?? "") }));
|
|
1676
|
-
const vectors = await args.runtime.embed(normalized.map((r) => r.text));
|
|
1677
|
-
for (let i = 0; i < normalized.length; i++) {
|
|
1678
|
-
const row = normalized[i];
|
|
1679
|
-
const vector = vectors[i];
|
|
1680
|
-
if (row === void 0 || vector === void 0) continue;
|
|
1681
|
-
upsertEmbedding(args.db, row.id, vector);
|
|
1682
|
-
}
|
|
1683
|
-
return normalized.length;
|
|
1684
|
-
}
|
|
1685
|
-
|
|
1686
1308
|
// src/internal/index/index-manager.ts
|
|
1687
1309
|
var IndexManager = class _IndexManager {
|
|
1688
1310
|
constructor(memoryRoot, db, embedding) {
|
|
@@ -2110,31 +1732,6 @@ async function migrateLegacyJson(cwd, config) {
|
|
|
2110
1732
|
function resetMigrationStateForTests() {
|
|
2111
1733
|
migrationRun.clear();
|
|
2112
1734
|
}
|
|
2113
|
-
var DEFAULT_MEMORY_READ_LINES = 200;
|
|
2114
|
-
async function readMemoryFileBounded(opts) {
|
|
2115
|
-
const absolutePath = resolve(opts.cwd, opts.relPath);
|
|
2116
|
-
const raw = await readFile(absolutePath, "utf8");
|
|
2117
|
-
const allLines = raw.split("\n");
|
|
2118
|
-
const trimmedLines = allLines.length > 0 && allLines[allLines.length - 1] === "" ? allLines.slice(0, -1) : allLines;
|
|
2119
|
-
const totalLines = trimmedLines.length;
|
|
2120
|
-
const requestedFrom = Math.max(1, opts.from ?? 1);
|
|
2121
|
-
const requestedLines = Math.max(1, opts.lines ?? DEFAULT_MEMORY_READ_LINES);
|
|
2122
|
-
const startIdx = requestedFrom - 1;
|
|
2123
|
-
const endIdx = Math.min(totalLines, startIdx + requestedLines);
|
|
2124
|
-
const slice = trimmedLines.slice(startIdx, endIdx);
|
|
2125
|
-
const linesReturned = slice.length;
|
|
2126
|
-
const remainingLines = Math.max(0, totalLines - endIdx);
|
|
2127
|
-
const truncated = remainingLines > 0;
|
|
2128
|
-
return {
|
|
2129
|
-
path: opts.relPath,
|
|
2130
|
-
from: requestedFrom,
|
|
2131
|
-
linesReturned,
|
|
2132
|
-
totalLines,
|
|
2133
|
-
truncated,
|
|
2134
|
-
remainingLines,
|
|
2135
|
-
text: slice.join("\n")
|
|
2136
|
-
};
|
|
2137
|
-
}
|
|
2138
1735
|
var SEARCH_DESCRIPTION = "Mandatory recall step: semantically search MEMORY.md + memory/notes/*.md (and optional wiki supplements) before answering questions about prior work, decisions, dates, people, preferences, or todos. `corpus=memory` (default) restricts to indexed memory files; `corpus=wiki` restricts to read-only wiki supplements; `corpus=all` returns both. Returns ranked `{ path, startLine, endLine, score, snippet, citation }` hits.";
|
|
2139
1736
|
var GET_DESCRIPTION = "Safe exact excerpt read from MEMORY.md or memory/notes/*.md. Defaults to a bounded excerpt (200 lines). Returns `{ path, from, linesReturned, totalLines, truncated, remainingLines, text }`. Paths are resolved against the memory root \u2014 attempts to read outside `.theokit/memory/` are rejected.";
|
|
2140
1737
|
var MEMORY_SEARCH_SCHEMA = {
|
|
@@ -2251,6 +1848,6 @@ function isPathInside(root, candidate) {
|
|
|
2251
1848
|
return candidate === root || candidate.startsWith(normalizedRoot);
|
|
2252
1849
|
}
|
|
2253
1850
|
|
|
2254
|
-
export {
|
|
1851
|
+
export { CircuitBreaker, DEFAULT_AZURE_OPENAI_EMBEDDING_MODEL, DEFAULT_COHERE_EMBEDDING_MODEL, DEFAULT_DEEPINFRA_EMBEDDING_MODEL, DEFAULT_GEMINI_EMBEDDING_MODEL, DEFAULT_JINA_EMBEDDING_MODEL, DEFAULT_MISTRAL_EMBEDDING_MODEL, DEFAULT_OLLAMA_EMBEDDING_MODEL, DEFAULT_OPENAI_EMBEDDING_MODEL, DEFAULT_OPENROUTER_EMBEDDING_MODEL, DEFAULT_VOYAGE_EMBEDDING_MODEL, IndexManager, LanceIndex, LanceMemoryAdapter, MEMORY_EMBEDDING_ADAPTERS, VALID_BACKENDS, assertValidBackend, azureOpenAiMemoryEmbeddingProviderAdapter, buildErrorMetadata, cohereMemoryEmbeddingProviderAdapter, createCategorizedMemory, createInMemoryMarkdownProvider, createMemoryGetTool, createMemorySearchTool, deepinfraMemoryEmbeddingProviderAdapter, geminiMemoryEmbeddingProviderAdapter, isLanceAvailable, isSqliteVecLoaded, jinaMemoryEmbeddingProviderAdapter, legacyMemoryJsonPath, listNotes, mapOpenAICompatibleError, migrateLegacyJson, migrateSqliteToLance, mistralMemoryEmbeddingProviderAdapter, ollamaMemoryEmbeddingProviderAdapter, openAiMemoryEmbeddingProviderAdapter, openLanceIndex, openRouterMemoryEmbeddingProviderAdapter, parseRetryAfter, redactSecrets, resetMigrationStateForTests, runActiveMemory, truncateRaw, voyageMemoryEmbeddingProviderAdapter };
|
|
2255
1852
|
//# sourceMappingURL=index.js.map
|
|
2256
1853
|
//# sourceMappingURL=index.js.map
|