@nandoblanco/opencode-local-memory 1.0.0 → 1.0.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/index.js +215 -41
- package/package.json +1 -1
- package/tui.ts +95 -63
package/index.js
CHANGED
|
@@ -10,6 +10,7 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
|
10
10
|
const cliName = "open" + "code";
|
|
11
11
|
|
|
12
12
|
let embedderPromise = null;
|
|
13
|
+
let activeSyncPromise = null;
|
|
13
14
|
let cachedEntries = null;
|
|
14
15
|
let cachedRootDir = "";
|
|
15
16
|
let cachedMtime = 0;
|
|
@@ -47,12 +48,108 @@ function resolveConfigDir(customConfigDir) {
|
|
|
47
48
|
}
|
|
48
49
|
return path.resolve(customConfigDir);
|
|
49
50
|
}
|
|
51
|
+
if (process.env.OPENCODE_CONFIG_DIR) {
|
|
52
|
+
return path.resolve(process.env.OPENCODE_CONFIG_DIR);
|
|
53
|
+
}
|
|
50
54
|
const configBase = process.env.XDG_CONFIG_HOME
|
|
51
55
|
? path.resolve(process.env.XDG_CONFIG_HOME)
|
|
52
56
|
: path.join(os.homedir(), ".config");
|
|
53
57
|
return path.join(configBase, cliName);
|
|
54
58
|
}
|
|
55
59
|
|
|
60
|
+
function findPluginsArraySpan(raw) {
|
|
61
|
+
const keyRe = /"plugins"\s*:\s*\[/g;
|
|
62
|
+
const match = keyRe.exec(raw);
|
|
63
|
+
if (!match) return null;
|
|
64
|
+
const openBracketIdx = match.index + match[0].length - 1;
|
|
65
|
+
let depth = 0;
|
|
66
|
+
let inString = false;
|
|
67
|
+
let escaped = false;
|
|
68
|
+
for (let i = openBracketIdx; i < raw.length; i++) {
|
|
69
|
+
const ch = raw[i];
|
|
70
|
+
if (inString) {
|
|
71
|
+
if (escaped) {
|
|
72
|
+
escaped = false;
|
|
73
|
+
} else if (ch === "\\") {
|
|
74
|
+
escaped = true;
|
|
75
|
+
} else if (ch === '"') {
|
|
76
|
+
inString = false;
|
|
77
|
+
}
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
if (ch === "/" && raw[i + 1] === "/") {
|
|
81
|
+
const nl = raw.indexOf("\n", i + 2);
|
|
82
|
+
if (nl === -1) break;
|
|
83
|
+
i = nl;
|
|
84
|
+
continue;
|
|
85
|
+
}
|
|
86
|
+
if (ch === "/" && raw[i + 1] === "*") {
|
|
87
|
+
const endComment = raw.indexOf("*/", i + 2);
|
|
88
|
+
if (endComment === -1) break;
|
|
89
|
+
i = endComment + 1;
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
if (ch === '"') {
|
|
93
|
+
inString = true;
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
if (ch === "[") depth++;
|
|
97
|
+
else if (ch === "]") {
|
|
98
|
+
depth--;
|
|
99
|
+
if (depth === 0) {
|
|
100
|
+
return {
|
|
101
|
+
start: match.index,
|
|
102
|
+
openEnd: openBracketIdx + 1,
|
|
103
|
+
closeStart: i,
|
|
104
|
+
end: i + 1
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
return null;
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
function findLastCodeCharIndex(str) {
|
|
113
|
+
let lastIdx = -1;
|
|
114
|
+
let inString = false;
|
|
115
|
+
let escaped = false;
|
|
116
|
+
for (let i = 0; i < str.length; i++) {
|
|
117
|
+
const ch = str[i];
|
|
118
|
+
if (inString) {
|
|
119
|
+
lastIdx = i;
|
|
120
|
+
if (escaped) {
|
|
121
|
+
escaped = false;
|
|
122
|
+
} else if (ch === "\\") {
|
|
123
|
+
escaped = true;
|
|
124
|
+
} else if (ch === '"') {
|
|
125
|
+
inString = false;
|
|
126
|
+
}
|
|
127
|
+
continue;
|
|
128
|
+
}
|
|
129
|
+
if (ch === "/" && str[i + 1] === "/") {
|
|
130
|
+
const nl = str.indexOf("\n", i + 2);
|
|
131
|
+
if (nl === -1) break;
|
|
132
|
+
i = nl;
|
|
133
|
+
continue;
|
|
134
|
+
}
|
|
135
|
+
if (ch === "/" && str[i + 1] === "*") {
|
|
136
|
+
const endComment = str.indexOf("*/", i + 2);
|
|
137
|
+
if (endComment === -1) break;
|
|
138
|
+
i = endComment + 1;
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
if (ch === '"') {
|
|
142
|
+
inString = true;
|
|
143
|
+
lastIdx = i;
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
if (!/\s/.test(ch)) {
|
|
147
|
+
lastIdx = i;
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
return lastIdx;
|
|
151
|
+
}
|
|
152
|
+
|
|
56
153
|
function addPluginToJsoncFile(filePath, schemaUrl, pluginEntryStr, pkgName) {
|
|
57
154
|
if (!fs.existsSync(filePath)) {
|
|
58
155
|
const content = [
|
|
@@ -73,28 +170,39 @@ function addPluginToJsoncFile(filePath, schemaUrl, pluginEntryStr, pkgName) {
|
|
|
73
170
|
return "already-present";
|
|
74
171
|
}
|
|
75
172
|
|
|
76
|
-
const
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
const
|
|
80
|
-
const
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
173
|
+
const span = findPluginsArraySpan(raw);
|
|
174
|
+
if (span) {
|
|
175
|
+
const open = raw.slice(span.start, span.openEnd);
|
|
176
|
+
const body = raw.slice(span.openEnd, span.closeStart);
|
|
177
|
+
const close = raw.slice(span.closeStart, span.end);
|
|
178
|
+
const lastCodeIdx = findLastCodeCharIndex(body);
|
|
179
|
+
let replacement;
|
|
180
|
+
if (lastCodeIdx === -1) {
|
|
181
|
+
replacement = open + "\n " + pluginEntryStr + "\n " + close;
|
|
182
|
+
} else {
|
|
183
|
+
const needsComma = body[lastCodeIdx] !== ",";
|
|
184
|
+
const withComma = needsComma
|
|
185
|
+
? body.slice(0, lastCodeIdx + 1) + "," + body.slice(lastCodeIdx + 1)
|
|
186
|
+
: body;
|
|
187
|
+
const trimmedBody = withComma.replace(/\s*$/, "");
|
|
188
|
+
replacement = open + trimmedBody + "\n " + pluginEntryStr + "\n " + close;
|
|
189
|
+
}
|
|
190
|
+
const updated = raw.slice(0, span.start) + replacement + raw.slice(span.end);
|
|
88
191
|
fs.writeFileSync(filePath, updated, "utf8");
|
|
89
192
|
return "updated";
|
|
90
193
|
}
|
|
91
194
|
|
|
92
195
|
const lastBrace = raw.lastIndexOf("}");
|
|
93
196
|
if (lastBrace !== -1) {
|
|
94
|
-
const
|
|
95
|
-
const
|
|
96
|
-
const
|
|
97
|
-
const
|
|
197
|
+
const beforeSlice = raw.slice(0, lastBrace);
|
|
198
|
+
const lastCodeIdx = findLastCodeCharIndex(beforeSlice);
|
|
199
|
+
const lastChar = lastCodeIdx !== -1 ? beforeSlice[lastCodeIdx] : "{";
|
|
200
|
+
const needsComma = lastChar !== "{" && lastChar !== ",";
|
|
201
|
+
const withComma = (needsComma && lastCodeIdx !== -1)
|
|
202
|
+
? beforeSlice.slice(0, lastCodeIdx + 1) + "," + beforeSlice.slice(lastCodeIdx + 1)
|
|
203
|
+
: beforeSlice;
|
|
204
|
+
const before = withComma.replace(/\s*$/, "");
|
|
205
|
+
const updated = before + '\n "plugins": [\n ' + pluginEntryStr + "\n ]\n}\n";
|
|
98
206
|
fs.writeFileSync(filePath, updated, "utf8");
|
|
99
207
|
return "updated";
|
|
100
208
|
}
|
|
@@ -119,9 +227,11 @@ async function installPlugin(options) {
|
|
|
119
227
|
const cliConfigFile = path.join(configDir, "cli.json");
|
|
120
228
|
|
|
121
229
|
const serverEntryStr = opts.directory
|
|
122
|
-
? JSON.stringify(
|
|
230
|
+
? JSON.stringify([pkgName, { directory: opts.directory }])
|
|
231
|
+
: JSON.stringify(pkgName);
|
|
232
|
+
const cliEntryStr = opts.directory
|
|
233
|
+
? JSON.stringify([pkgName, { directory: opts.directory }])
|
|
123
234
|
: JSON.stringify(pkgName);
|
|
124
|
-
const cliEntryStr = JSON.stringify(pkgName);
|
|
125
235
|
|
|
126
236
|
const serverStatus = addPluginToJsoncFile(serverConfigFile, "https://" + cliName + ".ai/config.json", serverEntryStr, matchKey);
|
|
127
237
|
const cliStatus = addPluginToJsoncFile(cliConfigFile, "https://" + cliName + ".ai/v2/cli.json", cliEntryStr, matchKey);
|
|
@@ -201,7 +311,10 @@ async function getEmbedder() {
|
|
|
201
311
|
pipelineFn = mod.pipeline;
|
|
202
312
|
}
|
|
203
313
|
return pipelineFn("feature-extraction", "Xenova/all-MiniLM-L6-v2");
|
|
204
|
-
})()
|
|
314
|
+
})().catch(function (err) {
|
|
315
|
+
embedderPromise = null;
|
|
316
|
+
throw err;
|
|
317
|
+
});
|
|
205
318
|
return embedderPromise;
|
|
206
319
|
}
|
|
207
320
|
|
|
@@ -212,7 +325,16 @@ async function embedText(text) {
|
|
|
212
325
|
}
|
|
213
326
|
const embed = await getEmbedder();
|
|
214
327
|
const out = await embed(text, { pooling: "mean", normalize: true });
|
|
215
|
-
const vec = Array.from(out.data)
|
|
328
|
+
const vec = Array.from(out.data, function (v) {
|
|
329
|
+
return Math.round(v * 1e6) / 1e6;
|
|
330
|
+
});
|
|
331
|
+
if (out && typeof out.dispose === "function") {
|
|
332
|
+
try {
|
|
333
|
+
out.dispose();
|
|
334
|
+
} catch {
|
|
335
|
+
// ignore dispose errors
|
|
336
|
+
}
|
|
337
|
+
}
|
|
216
338
|
if (queryVecCache.size >= 128) {
|
|
217
339
|
const firstKey = queryVecCache.keys().next().value;
|
|
218
340
|
queryVecCache.delete(firstKey);
|
|
@@ -298,7 +420,32 @@ function parseSessionEntries(rootDir) {
|
|
|
298
420
|
return entries;
|
|
299
421
|
}
|
|
300
422
|
|
|
301
|
-
|
|
423
|
+
function serializeVectorsJson(entries) {
|
|
424
|
+
if (!entries || entries.length === 0) return "[]\n";
|
|
425
|
+
const lines = entries.map(function (e) {
|
|
426
|
+
return " " + JSON.stringify({
|
|
427
|
+
id: e.id,
|
|
428
|
+
date: e.date,
|
|
429
|
+
file: e.file,
|
|
430
|
+
tags: e.tags,
|
|
431
|
+
fact: e.fact,
|
|
432
|
+
vector: e.vector
|
|
433
|
+
});
|
|
434
|
+
});
|
|
435
|
+
return "[\n" + lines.join(",\n") + "\n]\n";
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
function prepareEntryCacheFields(item) {
|
|
439
|
+
if (!item) return;
|
|
440
|
+
if (!item._haystack) {
|
|
441
|
+
item._haystack = (item.id + " " + item.tags + " " + item.fact + " " + item.file).toLowerCase();
|
|
442
|
+
}
|
|
443
|
+
if (Array.isArray(item.vector) && !(item._vec instanceof Float32Array)) {
|
|
444
|
+
item._vec = new Float32Array(item.vector);
|
|
445
|
+
}
|
|
446
|
+
}
|
|
447
|
+
|
|
448
|
+
async function runSyncVectors(rootDir) {
|
|
302
449
|
ensureMemoryLayout(rootDir);
|
|
303
450
|
const vecFile = path.join(rootDir, "vectors.json");
|
|
304
451
|
const existingMap = new Map();
|
|
@@ -329,16 +476,14 @@ async function syncVectors(rootDir) {
|
|
|
329
476
|
entry.vector = await embedText(entry.fact + " " + entry.tags);
|
|
330
477
|
embeddedCount++;
|
|
331
478
|
}
|
|
479
|
+
prepareEntryCacheFields(entry);
|
|
332
480
|
}
|
|
333
481
|
|
|
334
482
|
const changed = embeddedCount > 0 || parsed.length !== existingMap.size;
|
|
335
483
|
if (changed || !fs.existsSync(vecFile)) {
|
|
336
|
-
fs.writeFileSync(vecFile,
|
|
484
|
+
fs.writeFileSync(vecFile, serializeVectorsJson(parsed), "utf8");
|
|
337
485
|
}
|
|
338
486
|
|
|
339
|
-
for (const item of parsed) {
|
|
340
|
-
item._haystack = (item.id + " " + item.tags + " " + item.fact + " " + item.file).toLowerCase();
|
|
341
|
-
}
|
|
342
487
|
cachedEntries = parsed;
|
|
343
488
|
cachedRootDir = path.resolve(rootDir);
|
|
344
489
|
cachedMtime = fs.existsSync(vecFile) ? fs.statSync(vecFile).mtimeMs : Date.now();
|
|
@@ -348,19 +493,40 @@ async function syncVectors(rootDir) {
|
|
|
348
493
|
return { total: parsed.length, embedded: embeddedCount, reused: reusedCount, vecFile: vecFile };
|
|
349
494
|
}
|
|
350
495
|
|
|
496
|
+
async function syncVectors(rootDir) {
|
|
497
|
+
if (activeSyncPromise) {
|
|
498
|
+
try {
|
|
499
|
+
await activeSyncPromise;
|
|
500
|
+
} catch {
|
|
501
|
+
// Proceed with fresh sync
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
const p = runSyncVectors(rootDir);
|
|
505
|
+
activeSyncPromise = p;
|
|
506
|
+
try {
|
|
507
|
+
return await p;
|
|
508
|
+
} finally {
|
|
509
|
+
if (activeSyncPromise === p) {
|
|
510
|
+
activeSyncPromise = null;
|
|
511
|
+
}
|
|
512
|
+
}
|
|
513
|
+
}
|
|
514
|
+
|
|
351
515
|
function loadCachedVectors(rootDir) {
|
|
352
516
|
const resolved = path.resolve(rootDir);
|
|
353
517
|
const vecFile = path.join(resolved, "vectors.json");
|
|
354
|
-
|
|
355
|
-
|
|
518
|
+
let stat;
|
|
519
|
+
try {
|
|
520
|
+
stat = fs.statSync(vecFile);
|
|
521
|
+
} catch {
|
|
522
|
+
return [];
|
|
523
|
+
}
|
|
356
524
|
if (cachedEntries && cachedRootDir === resolved && cachedMtime === stat.mtimeMs) {
|
|
357
525
|
return cachedEntries;
|
|
358
526
|
}
|
|
359
527
|
const parsed = JSON.parse(fs.readFileSync(vecFile, "utf8"));
|
|
360
528
|
for (const item of parsed) {
|
|
361
|
-
|
|
362
|
-
item._haystack = (item.id + " " + item.tags + " " + item.fact + " " + item.file).toLowerCase();
|
|
363
|
-
}
|
|
529
|
+
prepareEntryCacheFields(item);
|
|
364
530
|
}
|
|
365
531
|
cachedEntries = parsed;
|
|
366
532
|
cachedRootDir = resolved;
|
|
@@ -406,13 +572,14 @@ async function searchMemory(rootDir, query, mode, topN) {
|
|
|
406
572
|
|
|
407
573
|
let queryVec = null;
|
|
408
574
|
if (searchMode === "semantic" || searchMode === "hybrid") {
|
|
409
|
-
|
|
575
|
+
const rawQueryVec = await embedText(cleanQuery);
|
|
576
|
+
queryVec = rawQueryVec instanceof Float32Array ? rawQueryVec : new Float32Array(rawQueryVec);
|
|
410
577
|
}
|
|
411
578
|
|
|
412
579
|
for (const entry of entries) {
|
|
413
580
|
let semanticScore = 0;
|
|
414
|
-
if (queryVec && Array.isArray(entry.vector)) {
|
|
415
|
-
semanticScore = dotProduct(queryVec, entry.vector);
|
|
581
|
+
if (queryVec && (entry._vec || Array.isArray(entry.vector))) {
|
|
582
|
+
semanticScore = dotProduct(queryVec, entry._vec || entry.vector);
|
|
416
583
|
}
|
|
417
584
|
|
|
418
585
|
let lexicalScore = 0;
|
|
@@ -455,6 +622,13 @@ function nextTopicId(topicText, topicSlug) {
|
|
|
455
622
|
}
|
|
456
623
|
|
|
457
624
|
async function storeMemoryFact(rootDir, input) {
|
|
625
|
+
if (activeSyncPromise) {
|
|
626
|
+
try {
|
|
627
|
+
await activeSyncPromise;
|
|
628
|
+
} catch {
|
|
629
|
+
// Ignore background sync error
|
|
630
|
+
}
|
|
631
|
+
}
|
|
458
632
|
ensureMemoryLayout(rootDir);
|
|
459
633
|
const rawTopic = String(input.topic || "decisions").toLowerCase().replace(/[^a-z0-9-_]/g, "-");
|
|
460
634
|
const topicFile = path.join(rootDir, "topics", rawTopic + ".md");
|
|
@@ -475,11 +649,15 @@ async function storeMemoryFact(rootDir, input) {
|
|
|
475
649
|
}
|
|
476
650
|
}
|
|
477
651
|
|
|
478
|
-
const
|
|
652
|
+
const rawId = input.id
|
|
653
|
+
? String(input.id).replace(/[\[\]]+/g, "").replace(/[\r\n\s]+/g, "-").replace(/-+/g, "-").replace(/^-+|-+$/g, "")
|
|
654
|
+
: "";
|
|
655
|
+
const id = rawId || nextTopicId(existingText, rawTopic);
|
|
479
656
|
const today = new Date().toISOString().split("T")[0];
|
|
480
|
-
const
|
|
657
|
+
const rawTags = Array.isArray(input.tags)
|
|
481
658
|
? input.tags.map(function (t) { return String(t).trim(); }).filter(Boolean).join(", ")
|
|
482
659
|
: String(input.tags || rawTopic).trim();
|
|
660
|
+
const tagsList = rawTags.replace(/[\[\]]+/g, "").replace(/[\r\n\s]+/g, " ").trim() || rawTopic;
|
|
483
661
|
const cleanFact = String(input.fact || "").replace(/\s+/g, " ").trim();
|
|
484
662
|
|
|
485
663
|
const block = [
|
|
@@ -504,12 +682,9 @@ async function storeMemoryFact(rootDir, input) {
|
|
|
504
682
|
fact: cleanFact,
|
|
505
683
|
vector: vec
|
|
506
684
|
};
|
|
685
|
+
prepareEntryCacheFields(newEntry);
|
|
507
686
|
entries.push(newEntry);
|
|
508
|
-
|
|
509
|
-
return { id: e.id, date: e.date, file: e.file, tags: e.tags, fact: e.fact, vector: e.vector };
|
|
510
|
-
});
|
|
511
|
-
fs.writeFileSync(vecFile, JSON.stringify(serializable, null, 1), "utf8");
|
|
512
|
-
newEntry._haystack = (newEntry.id + " " + newEntry.tags + " " + newEntry.fact + " " + newEntry.file).toLowerCase();
|
|
687
|
+
fs.writeFileSync(vecFile, serializeVectorsJson(entries), "utf8");
|
|
513
688
|
cachedEntries = entries;
|
|
514
689
|
cachedRootDir = path.resolve(rootDir);
|
|
515
690
|
cachedMtime = fs.statSync(vecFile).mtimeMs;
|
|
@@ -599,7 +774,6 @@ function createPluginDefinition() {
|
|
|
599
774
|
const topK = Number(options.topK || 6);
|
|
600
775
|
|
|
601
776
|
loadCachedVectors(rootDir);
|
|
602
|
-
getEmbedder().catch(function () {});
|
|
603
777
|
syncVectors(rootDir).catch(function (err) {
|
|
604
778
|
console.error("local-memory sync error:", err);
|
|
605
779
|
});
|
package/package.json
CHANGED
package/tui.ts
CHANGED
|
@@ -61,36 +61,60 @@ function splitHighlightedText(
|
|
|
61
61
|
if (!term || !term.trim()) {
|
|
62
62
|
return [{ text, match: false }];
|
|
63
63
|
}
|
|
64
|
-
const
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
64
|
+
const words = term
|
|
65
|
+
.trim()
|
|
66
|
+
.toLowerCase()
|
|
67
|
+
.split(/\s+/)
|
|
68
|
+
.filter((w) => w.length >= 2 && !w.includes(":"));
|
|
69
|
+
if (!words.length) {
|
|
70
|
+
const fallback = term.trim().toLowerCase();
|
|
71
|
+
if (fallback && !fallback.includes(":")) words.push(fallback);
|
|
72
|
+
}
|
|
73
|
+
if (!words.length) return [{ text, match: false }];
|
|
71
74
|
|
|
72
75
|
const parts: Array<{ text: string; match: boolean }> = [];
|
|
73
76
|
const lower = text.toLowerCase();
|
|
74
77
|
let cursor = 0;
|
|
75
78
|
|
|
76
79
|
while (cursor < text.length) {
|
|
77
|
-
|
|
78
|
-
|
|
80
|
+
let bestIdx = -1;
|
|
81
|
+
let bestLen = 0;
|
|
82
|
+
for (const w of words) {
|
|
83
|
+
const idx = lower.indexOf(w, cursor);
|
|
84
|
+
if (idx !== -1 && (bestIdx === -1 || idx < bestIdx || (idx === bestIdx && w.length > bestLen))) {
|
|
85
|
+
bestIdx = idx;
|
|
86
|
+
bestLen = w.length;
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
if (bestIdx === -1) {
|
|
79
90
|
parts.push({ text: text.slice(cursor), match: false });
|
|
80
91
|
break;
|
|
81
92
|
}
|
|
82
|
-
if (
|
|
83
|
-
parts.push({ text: text.slice(cursor,
|
|
93
|
+
if (bestIdx > cursor) {
|
|
94
|
+
parts.push({ text: text.slice(cursor, bestIdx), match: false });
|
|
84
95
|
}
|
|
85
|
-
parts.push({ text: text.slice(
|
|
86
|
-
cursor =
|
|
96
|
+
parts.push({ text: text.slice(bestIdx, bestIdx + bestLen), match: true });
|
|
97
|
+
cursor = bestIdx + bestLen;
|
|
87
98
|
}
|
|
88
99
|
return parts.length ? parts : [{ text, match: false }];
|
|
89
100
|
}
|
|
90
101
|
|
|
102
|
+
function isSafeSubPath(parentDir: string, targetPath: string): boolean {
|
|
103
|
+
const rel = path.relative(path.resolve(parentDir), path.resolve(targetPath));
|
|
104
|
+
return Boolean(rel && !rel.startsWith("..") && !path.isAbsolute(rel));
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function isSafeRegexPattern(pattern: string): boolean {
|
|
108
|
+
if (!pattern || pattern.length > 256) return false;
|
|
109
|
+
// Reject nested quantifiers such as (a+)+, (.*)*, ([a-z]+){2,} that cause catastrophic backtracking
|
|
110
|
+
if (/(\([^()]*[+*?][^()]*\))\s*[+*?{]/.test(pattern)) return false;
|
|
111
|
+
return true;
|
|
112
|
+
}
|
|
113
|
+
|
|
91
114
|
function readFullSessionMarkdown(rootDir: string, relFile: string): string {
|
|
92
115
|
try {
|
|
93
|
-
const fullPath = path.
|
|
116
|
+
const fullPath = path.resolve(rootDir, relFile);
|
|
117
|
+
if (!isSafeSubPath(rootDir, fullPath)) return "";
|
|
94
118
|
if (fs.existsSync(fullPath)) {
|
|
95
119
|
return fs.readFileSync(fullPath, "utf8").replace(/\r\n/g, "\n").trim();
|
|
96
120
|
}
|
|
@@ -107,7 +131,7 @@ interface DialogProps {
|
|
|
107
131
|
close: () => void;
|
|
108
132
|
}
|
|
109
133
|
|
|
110
|
-
|
|
134
|
+
function createTuiRenderer() {
|
|
111
135
|
function el(
|
|
112
136
|
tag: string,
|
|
113
137
|
props?: Record<string, unknown> | null,
|
|
@@ -287,10 +311,11 @@ async function loadTuiRenderer() {
|
|
|
287
311
|
try {
|
|
288
312
|
const lastSlash = q.startsWith("/") ? q.lastIndexOf("/") : -1;
|
|
289
313
|
const pattern = lastSlash > 0 ? q.slice(1, lastSlash) : q;
|
|
314
|
+
if (!isSafeRegexPattern(pattern)) return [];
|
|
290
315
|
const flags = lastSlash > 0 ? q.slice(lastSlash + 1) || "i" : "i";
|
|
291
316
|
const re = new RegExp(pattern, flags);
|
|
292
317
|
return subset
|
|
293
|
-
.filter((e) => re.test(`${e.id} ${e.tags} ${e.fact} ${e.file}`))
|
|
318
|
+
.filter((e) => re.test(e._haystack || `${e.id} ${e.tags} ${e.fact} ${e.file}`))
|
|
294
319
|
.map((e) => ({ score: 1, semanticScore: 0, entry: e }));
|
|
295
320
|
} catch {
|
|
296
321
|
return [];
|
|
@@ -493,22 +518,30 @@ async function loadTuiRenderer() {
|
|
|
493
518
|
|
|
494
519
|
if (
|
|
495
520
|
name === "down" ||
|
|
496
|
-
(event.ctrl && name === "n") ||
|
|
497
|
-
(focusPane()
|
|
521
|
+
(event.ctrl && (name === "n" || name === "j")) ||
|
|
522
|
+
(focusPane() !== "input" && !event.ctrl && name === "j")
|
|
498
523
|
) {
|
|
499
524
|
event.preventDefault();
|
|
500
525
|
event.stopPropagation();
|
|
501
|
-
|
|
526
|
+
if (focusPane() === "preview" && !event.ctrl && name === "j") {
|
|
527
|
+
previewScrollRef?.scrollBy?.(2);
|
|
528
|
+
} else {
|
|
529
|
+
moveSelection(1);
|
|
530
|
+
}
|
|
502
531
|
return;
|
|
503
532
|
}
|
|
504
533
|
if (
|
|
505
534
|
name === "up" ||
|
|
506
|
-
(event.ctrl && name === "k") ||
|
|
507
|
-
(focusPane()
|
|
535
|
+
(event.ctrl && (name === "p" || name === "k")) ||
|
|
536
|
+
(focusPane() !== "input" && !event.ctrl && name === "k")
|
|
508
537
|
) {
|
|
509
538
|
event.preventDefault();
|
|
510
539
|
event.stopPropagation();
|
|
511
|
-
|
|
540
|
+
if (focusPane() === "preview" && !event.ctrl && name === "k") {
|
|
541
|
+
previewScrollRef?.scrollBy?.(-2);
|
|
542
|
+
} else {
|
|
543
|
+
moveSelection(-1);
|
|
544
|
+
}
|
|
512
545
|
return;
|
|
513
546
|
}
|
|
514
547
|
if (name === "pagedown" || (event.ctrl && name === "d")) {
|
|
@@ -1016,15 +1049,10 @@ export default {
|
|
|
1016
1049
|
return;
|
|
1017
1050
|
}
|
|
1018
1051
|
const rootDir = resolveMemoryDir((context as any)?.options?.directory);
|
|
1019
|
-
const
|
|
1052
|
+
const renderDialog = createTuiRenderer();
|
|
1020
1053
|
|
|
1021
1054
|
const openMemoryPopup = async (rawArgs?: string) => {
|
|
1022
1055
|
const initialQuery = typeof rawArgs === "string" ? rawArgs.trim() : "";
|
|
1023
|
-
const renderDialog = await renderDialogPromise;
|
|
1024
|
-
if (!renderDialog) {
|
|
1025
|
-
await openFallbackSelectDialog(context, rootDir, initialQuery);
|
|
1026
|
-
return;
|
|
1027
|
-
}
|
|
1028
1056
|
|
|
1029
1057
|
try {
|
|
1030
1058
|
context.ui.dialog.show(() =>
|
|
@@ -1074,46 +1102,50 @@ export default {
|
|
|
1074
1102
|
}
|
|
1075
1103
|
};
|
|
1076
1104
|
|
|
1105
|
+
let layerRegistered = false;
|
|
1077
1106
|
context.ui.slot({
|
|
1078
1107
|
append: "app",
|
|
1079
1108
|
render() {
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
"
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
id: "local.memory.add",
|
|
1101
|
-
title: "Store local memory fact (0 tokens)...",
|
|
1102
|
-
description:
|
|
1103
|
-
"Zero-token slash command to store a memory fact directly: /memory-add <topic> | <tags> | <fact>",
|
|
1104
|
-
category: "Memory",
|
|
1105
|
-
palette: false,
|
|
1106
|
-
slash: {
|
|
1107
|
-
name: "memory-add",
|
|
1108
|
-
arguments: true,
|
|
1109
|
+
if (!layerRegistered) {
|
|
1110
|
+
layerRegistered = true;
|
|
1111
|
+
context.keymap.layer(() => ({
|
|
1112
|
+
mode: "global",
|
|
1113
|
+
commands: [
|
|
1114
|
+
{
|
|
1115
|
+
id: "local.memory.search",
|
|
1116
|
+
title: "Search local memory (0 tokens)...",
|
|
1117
|
+
description:
|
|
1118
|
+
"Interactive zero-token popup to search local memories (topics/*.md + sessions/*.md) with semantic + keyword + regex matching",
|
|
1119
|
+
category: "Memory",
|
|
1120
|
+
palette: true,
|
|
1121
|
+
slash: {
|
|
1122
|
+
name: "memory",
|
|
1123
|
+
arguments: true,
|
|
1124
|
+
},
|
|
1125
|
+
run: (input) => {
|
|
1126
|
+
const rawArgs = typeof input === "string" ? input : (input as any)?.arguments;
|
|
1127
|
+
void openMemoryPopup(rawArgs);
|
|
1128
|
+
},
|
|
1109
1129
|
},
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1130
|
+
{
|
|
1131
|
+
id: "local.memory.add",
|
|
1132
|
+
title: "Store local memory fact (0 tokens)...",
|
|
1133
|
+
description:
|
|
1134
|
+
"Zero-token slash command to store a memory fact directly: /memory-add <topic> | <tags> | <fact>",
|
|
1135
|
+
category: "Memory",
|
|
1136
|
+
palette: false,
|
|
1137
|
+
slash: {
|
|
1138
|
+
name: "memory-add",
|
|
1139
|
+
arguments: true,
|
|
1140
|
+
},
|
|
1141
|
+
run: (input) => {
|
|
1142
|
+
const rawArgs = typeof input === "string" ? input : (input as any)?.arguments;
|
|
1143
|
+
void quickStoreFromSlash(rawArgs);
|
|
1144
|
+
},
|
|
1113
1145
|
},
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
}
|
|
1146
|
+
],
|
|
1147
|
+
}));
|
|
1148
|
+
}
|
|
1117
1149
|
return null;
|
|
1118
1150
|
},
|
|
1119
1151
|
});
|