dsh-cortex-memory 0.3.1 → 0.4.11
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/README.md +41 -13
- package/client.js +33 -19
- package/cordis.patch.yml +1 -1
- package/index.js +8 -1
- package/package.json +3 -13
- package/src/adapters/shiori.js +1 -1
- package/src/api/routes.js +30 -3
- package/src/core/config.js +6 -0
- package/src/engines/develop.js +1 -1
- package/src/engines/extract.js +23 -4
- package/src/engines/growth.js +1 -1
- package/src/engines/life.js +56 -41
- package/src/engines/reflect.js +1 -1
- package/src/engines/retrieve.js +4 -0
- package/src/guardian/guardian.js +15 -1
- package/src/host/runtime.js +14 -4
- package/src/host/scheduler.js +11 -2
- package/src/llm/adapter.js +19 -7
- package/src/memory/query.js +1 -1
- package/src/self/appraisal.js +3 -3
- package/src/self/emotion.js +1 -1
- package/src/self/evolution.js +115 -4
- package/src/self/identity.js +1 -1
- package/src/self/policies.js +8 -1
- package/src/self/relationship.js +2 -2
- package/src/service/cortex.js +94 -13
- package/src/tools/definitions.js +19 -1
- package/src/web/search.js +97 -0
- package/bench/ab-engine.mjs +0 -60
- package/bench/ann-bench.mjs +0 -78
- package/bench/hnsw-bench.mjs +0 -79
- package/bench/locomo.js +0 -89
- package/bench/longmemeval.js +0 -83
- package/bench/metrics.js +0 -67
- package/bench/migration-bench.mjs +0 -69
- package/bench/run.js +0 -77
- package/bench/synthetic.js +0 -99
- package/bench/vector-ab.mjs +0 -76
- package/docs/install-windows.md +0 -144
- package/docs/models.md +0 -183
- package/docs/multimodal.md +0 -112
- package/docs/permissions.md +0 -49
- package/docs/privacy.md +0 -48
- package/docs/scopes.md +0 -142
- package/examples/README.md +0 -72
- package/examples/setup-cortex-bge.ps1 +0 -66
- package/examples/uninstall-cortex.ps1 +0 -91
package/src/service/cortex.js
CHANGED
|
@@ -180,7 +180,40 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
|
|
|
180
180
|
identityStore, selfStore, config,
|
|
181
181
|
});
|
|
182
182
|
const privacy = createPrivacyEngine({ db, traces, events, audit });
|
|
183
|
-
|
|
183
|
+
|
|
184
|
+
function retrievalQuality({ scopeId = config.scope, phase = 'after', baseline = null } = {}) {
|
|
185
|
+
const rows = db.prepare(`
|
|
186
|
+
SELECT id, title, content FROM traces
|
|
187
|
+
WHERE scope_id = ? AND state = 'active'
|
|
188
|
+
ORDER BY importance DESC, recorded_at DESC LIMIT 8
|
|
189
|
+
`).all(scopeId);
|
|
190
|
+
const probes = rows.map((row) => {
|
|
191
|
+
const title = String(row.title ?? '').trim();
|
|
192
|
+
const content = String(row.content ?? '').replace(/^\s*(用户|user)\s*[::]\s*/i, '').trim();
|
|
193
|
+
const query = title && !/^会话\s*\d+\s*的对话$/.test(title) ? title.slice(0, 100) : content.slice(0, 100);
|
|
194
|
+
return { id: row.id, query };
|
|
195
|
+
}).filter((probe) => probe.query.length >= 4).slice(0, 6);
|
|
196
|
+
if (probes.length < 5) return { ok: true, skipped: 'insufficient-samples', n: probes.length };
|
|
197
|
+
let hits = 0;
|
|
198
|
+
for (const probe of probes) {
|
|
199
|
+
try {
|
|
200
|
+
const result = retrieve.search(probe.query, { scopeId, limit: 5 });
|
|
201
|
+
if (result.items.some((item) => item.id === probe.id)) hits += 1;
|
|
202
|
+
} catch { /* one probe must not abort the guard */ }
|
|
203
|
+
}
|
|
204
|
+
const recall = hits / probes.length;
|
|
205
|
+
const after = { n: probes.length, hits, recall: Math.round(recall * 1000) / 1000 };
|
|
206
|
+
if (phase === 'before') return { ok: true, ...after };
|
|
207
|
+
if (baseline?.recall == null) return { ok: true, ...after, skipped: 'no-baseline' };
|
|
208
|
+
return {
|
|
209
|
+
ok: recall >= Math.max(0.4, baseline.recall - 0.25),
|
|
210
|
+
...after,
|
|
211
|
+
baselineRecall: baseline.recall,
|
|
212
|
+
threshold: Math.round(Math.max(0.4, baseline.recall - 0.25) * 1000) / 1000,
|
|
213
|
+
};
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
const evolution = createEvolutionEngine({ policies, identityStore, skills: skillsRepo, health, growth, audit, guard: config.evolution ?? null, qualityGuard: retrievalQuality });
|
|
184
217
|
const guardian = createGuardian({ db, config, events, traces, selfStore, identityStore, logger });
|
|
185
218
|
const circuit = createCircuitBreaker({ threshold: config.circuitThreshold ?? 5, cooldownMs: config.circuitCooldownMs ?? 60_000 });
|
|
186
219
|
const budget = createBudgetGuard({ maxCallsPerHour: config.maxCallsPerHour ?? 120, maxTokensPerHour: config.maxTokensPerHour ?? 120_000 });
|
|
@@ -192,6 +225,8 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
|
|
|
192
225
|
const life = createLifeEngine({
|
|
193
226
|
db, traces, reflect, development, working: workingStore, emotion, scopeId: config.scope,
|
|
194
227
|
consolidation, features: config.features ?? {},
|
|
228
|
+
selfName: config.persona?.selfName ?? '助手',
|
|
229
|
+
userAddress: config.persona?.userAddress ?? '你',
|
|
195
230
|
llm: llmAdapter ? (args) => llmAdapter.dream(args) : null,
|
|
196
231
|
diaryLlm: llmAdapter ? (args) => llmAdapter.diary(args) : null,
|
|
197
232
|
feelingLlm: llmAdapter ? (args) => llmAdapter.feeling(args) : null,
|
|
@@ -305,7 +340,7 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
|
|
|
305
340
|
eventId: result.event?.id ?? null,
|
|
306
341
|
recordedAt: result.trace?.recordedAt ?? null,
|
|
307
342
|
});
|
|
308
|
-
if (config.features?.graphCandidateAutoFacts === true) {
|
|
343
|
+
if (config.features?.autoGraphCandidates === true || config.features?.graphCandidateAutoFacts === true) {
|
|
309
344
|
const queued = [];
|
|
310
345
|
for (const resolution of result.autoFacts.resolved ?? []) {
|
|
311
346
|
const fact = resolution?.fact;
|
|
@@ -472,6 +507,26 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
|
|
|
472
507
|
return retrieve.timeline({ ...options, scopeId: options.scopeId ?? config.scope });
|
|
473
508
|
}
|
|
474
509
|
|
|
510
|
+
function recentTimeline({ scopeId = config.scope, limit = 20 } = {}) {
|
|
511
|
+
const rows = db.prepare(`
|
|
512
|
+
SELECT id, title, kind, content, importance, recorded_at
|
|
513
|
+
FROM traces WHERE scope_id = ? AND state = 'active'
|
|
514
|
+
ORDER BY recorded_at DESC LIMIT ?
|
|
515
|
+
`).all(scopeId, Math.max(1, Math.min(100, Number(limit) || 20)));
|
|
516
|
+
return {
|
|
517
|
+
items: rows.map((row) => ({
|
|
518
|
+
id: row.id,
|
|
519
|
+
title: row.title || String(row.content ?? '').slice(0, 50) || row.kind,
|
|
520
|
+
snippet: String(row.content ?? '').replace(/\s+/g, ' ').slice(0, 180),
|
|
521
|
+
recordedAt: row.recorded_at,
|
|
522
|
+
kind: row.kind,
|
|
523
|
+
layer: row.kind === 'reflection' ? 'L5' : 'L2',
|
|
524
|
+
importance: Number(row.importance ?? 0),
|
|
525
|
+
isAnchor: false,
|
|
526
|
+
})),
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
|
|
475
530
|
function self(scopeId = config.scope) {
|
|
476
531
|
const identity = identityStore.active(scopeId);
|
|
477
532
|
const identityText = identity ? `${identity.content.narrative}\n${(identity.content.values ?? []).join('、')}\n${(identity.content.boundaries ?? []).join('、')}` : '';
|
|
@@ -737,15 +792,30 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
|
|
|
737
792
|
return { cards: cards.length, volumes };
|
|
738
793
|
}
|
|
739
794
|
|
|
740
|
-
|
|
741
|
-
|
|
795
|
+
const summonSourceAt = new Map();
|
|
796
|
+
|
|
797
|
+
function rebuildSummonBook({ scopeId = config.scope, incremental = false } = {}) {
|
|
798
|
+
const latest = {
|
|
799
|
+
emotion: db.prepare('SELECT MAX(at) AS at FROM emotion_events WHERE scope_id = ?').get(scopeId)?.at ?? null,
|
|
800
|
+
fact: db.prepare('SELECT MAX(recorded_at) AS at FROM facts WHERE scope_id = ?').get(scopeId)?.at ?? null,
|
|
801
|
+
trace: db.prepare('SELECT MAX(recorded_at) AS at FROM traces WHERE scope_id = ?').get(scopeId)?.at ?? null,
|
|
802
|
+
};
|
|
803
|
+
const since = summonSourceAt.get(scopeId) ?? null;
|
|
804
|
+
if (incremental && since) {
|
|
805
|
+
const unchanged = Object.entries(latest).every(([kind, at]) => !at || String(at) <= String(since[kind] ?? ''));
|
|
806
|
+
if (unchanged) return { skipped: true, emotions: 0, facts: 0, traces: 0, merged: null };
|
|
807
|
+
}
|
|
808
|
+
const emotionSince = incremental && since?.emotion ? since.emotion : null;
|
|
809
|
+
const factSince = incremental && since?.fact ? since.fact : null;
|
|
810
|
+
const traceSince = incremental && since?.trace ? since.trace : null;
|
|
811
|
+
const emotions = db.prepare(`SELECT * FROM emotion_events WHERE scope_id = ?${emotionSince ? ' AND at > ?' : ''} ORDER BY at DESC LIMIT 1000`).all(scopeId, ...(emotionSince ? [emotionSince] : []));
|
|
742
812
|
for (const row of emotions) {
|
|
743
813
|
const parsed = (() => { try { return JSON.parse(row.emotions_json); } catch { return []; } })();
|
|
744
814
|
const labels = parsed.map((item) => item.name).filter(Boolean);
|
|
745
815
|
summons.upsertCard({
|
|
746
816
|
scopeId,
|
|
747
817
|
side: 'left',
|
|
748
|
-
title: `${labels.slice(0, 2).join(' / ') || '情感'} · ${row.target ?? '
|
|
818
|
+
title: `${labels.slice(0, 2).join(' / ') || '情感'} · ${row.target ?? '用户'}`,
|
|
749
819
|
content: row.text,
|
|
750
820
|
triggers: summonTriggers(row.text, labels),
|
|
751
821
|
category: labels[0] ?? '情感',
|
|
@@ -761,9 +831,9 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
|
|
|
761
831
|
FROM facts f
|
|
762
832
|
LEFT JOIN entities s ON s.id = f.subject_id
|
|
763
833
|
LEFT JOIN entities o ON o.id = f.object_id
|
|
764
|
-
WHERE f.scope_id = ? AND f.status = 'active' AND f.confidence >= 0.65
|
|
834
|
+
WHERE f.scope_id = ? AND f.status = 'active' AND f.confidence >= 0.65${factSince ? ' AND f.recorded_at > ?' : ''}
|
|
765
835
|
ORDER BY f.recorded_at DESC LIMIT 500
|
|
766
|
-
`).all(scopeId);
|
|
836
|
+
`).all(scopeId, ...(factSince ? [factSince] : []));
|
|
767
837
|
for (const fact of facts) {
|
|
768
838
|
const title = `${fact.subject_name || fact.subject_id} ${fact.predicate} ${fact.object_literal || fact.object_name || fact.object_id || ''}`.trim();
|
|
769
839
|
summons.upsertCard({
|
|
@@ -781,13 +851,13 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
|
|
|
781
851
|
}
|
|
782
852
|
const traces = db.prepare(`
|
|
783
853
|
SELECT * FROM traces WHERE scope_id = ?
|
|
784
|
-
AND (kind IN ('decision', 'reflection', 'identity') OR importance >= 0.6)
|
|
854
|
+
AND (kind IN ('decision', 'reflection', 'identity') OR importance >= 0.6)${traceSince ? ' AND recorded_at > ?' : ''}
|
|
785
855
|
ORDER BY recorded_at DESC LIMIT 800
|
|
786
|
-
`).all(scopeId);
|
|
856
|
+
`).all(scopeId, ...(traceSince ? [traceSince] : []));
|
|
787
857
|
for (const row of traces) {
|
|
788
858
|
const tags = (() => { try { return JSON.parse(row.tags_json); } catch { return []; } })();
|
|
789
859
|
const content = String(row.content ?? '');
|
|
790
|
-
const fallbackTitle = content.split(/\n/).map((line) => line.replace(/^\s*(
|
|
860
|
+
const fallbackTitle = content.split(/\n/).map((line) => line.replace(/^\s*(用户|助手|assistant|user)[::]\s*/i, '').trim()).find(Boolean) ?? '';
|
|
791
861
|
const title = /^会话\s*\d+\s*的对话/.test(String(row.title ?? ''))
|
|
792
862
|
? fallbackTitle.slice(0, 60)
|
|
793
863
|
: (row.title || fallbackTitle.slice(0, 60) || '工作记忆');
|
|
@@ -805,8 +875,9 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
|
|
|
805
875
|
});
|
|
806
876
|
}
|
|
807
877
|
const merged = mergeSummonVolumes({ scopeId });
|
|
808
|
-
|
|
809
|
-
|
|
878
|
+
summonSourceAt.set(scopeId, latest);
|
|
879
|
+
audit.record?.({ actor: 'self:summon', action: 'summon.rebuild', targetType: 'summon', targetId: scopeId, detail: { incremental, emotions: emotions.length, facts: facts.length, traces: traces.length, ...merged } });
|
|
880
|
+
return { incremental, emotions: emotions.length, facts: facts.length, traces: traces.length, ...merged };
|
|
810
881
|
}
|
|
811
882
|
|
|
812
883
|
function summonBook({ date = null, scopeId = config.scope } = {}) {
|
|
@@ -1311,7 +1382,16 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
|
|
|
1311
1382
|
memoryDay,
|
|
1312
1383
|
updateMemoryTrace,
|
|
1313
1384
|
updateMemoryEmotion,
|
|
1314
|
-
graphCandidates: ({ scopeId = config.scope, limit = 200 } = {}) =>
|
|
1385
|
+
graphCandidates: ({ scopeId = config.scope, limit = 200 } = {}) => {
|
|
1386
|
+
const rows = edges.listCandidates({ scopeId, limit });
|
|
1387
|
+
const labels = { at: '在', is: '是', will: '会', likes: '喜欢', dislikes: '不喜欢', related: '相关' };
|
|
1388
|
+
return rows.map((edge) => ({
|
|
1389
|
+
...edge,
|
|
1390
|
+
fromName: entities.get(edge.fromId)?.name ?? edge.fromId,
|
|
1391
|
+
toName: entities.get(edge.toId)?.name ?? edge.toId,
|
|
1392
|
+
relLabel: labels[edge.rel] ?? edge.rel,
|
|
1393
|
+
}));
|
|
1394
|
+
},
|
|
1315
1395
|
reviewGraphCandidate,
|
|
1316
1396
|
graphCandidateAction: ({ action, id, scopeId = config.scope, fromId, toId, rel, weight, confidence, sourceEventId, sourceTraceId, evidence, metadata, review = null } = {}) => {
|
|
1317
1397
|
if (!scopeWritable(scopeId)) throw new Error('scope-read-only');
|
|
@@ -1386,6 +1466,7 @@ export function createCortex({ config: rawConfig = {}, logger = null, llm: llmAd
|
|
|
1386
1466
|
},
|
|
1387
1467
|
get,
|
|
1388
1468
|
timeline,
|
|
1469
|
+
recentTimeline,
|
|
1389
1470
|
step: develop.step,
|
|
1390
1471
|
feedback: (input) => growth.applyFeedback({ ...input, scopeId: input.scopeId ?? config.scope }),
|
|
1391
1472
|
forget: (input) => {
|
package/src/tools/definitions.js
CHANGED
|
@@ -1,3 +1,12 @@
|
|
|
1
|
+
import path from 'node:path';
|
|
2
|
+
|
|
3
|
+
function guardPathAllowed(service, target) {
|
|
4
|
+
if (service?.config?.allowRestoreOutsideRoot === true) return true;
|
|
5
|
+
const root = path.resolve(String(service?.config?.dataRoot ?? process.cwd()));
|
|
6
|
+
const absolute = path.resolve(String(target ?? ''));
|
|
7
|
+
return absolute === root || absolute.startsWith(`${root}${path.sep}`);
|
|
8
|
+
}
|
|
9
|
+
|
|
1
10
|
const TEXT_OUTPUT = Object.freeze({
|
|
2
11
|
schema: {
|
|
3
12
|
type: 'object',
|
|
@@ -364,6 +373,7 @@ export function createToolDefinitions(service) {
|
|
|
364
373
|
isConcurrencySafe: () => false,
|
|
365
374
|
async execute(args = {}) {
|
|
366
375
|
if (args.action === 'backup') {
|
|
376
|
+
if (args.file && !guardPathAllowed(service, args.file)) return { text: '未执行:备份路径在 dataRoot 外。' };
|
|
367
377
|
const result = service.guardian.backup(args.file);
|
|
368
378
|
return { text: `备份完成:${result.path}(${result.bytes} B)` };
|
|
369
379
|
}
|
|
@@ -372,12 +382,18 @@ export function createToolDefinitions(service) {
|
|
|
372
382
|
return { text: result.ok ? `备份有效:${args.file}(${result.tables} 张表)` : `备份无效:${result.reason ?? result.missing?.join(',')}` };
|
|
373
383
|
}
|
|
374
384
|
if (args.action === 'restore') {
|
|
385
|
+
if (!args.file) return { text: '恢复失败:file-required' };
|
|
386
|
+
if (!args.target) return { text: '恢复失败:target-required' };
|
|
387
|
+
if (!guardPathAllowed(service, args.file) || !guardPathAllowed(service, args.target)) {
|
|
388
|
+
return { text: '未执行:恢复文件或目标在 dataRoot 外。' };
|
|
389
|
+
}
|
|
375
390
|
const result = service.guardian.restore(args.file, args.target);
|
|
376
391
|
return { text: result.restored ? `已恢复到离线库:${result.target}` : `恢复失败:${result.reason}${result.message ? `(${result.message})` : ''}` };
|
|
377
392
|
}
|
|
378
393
|
if (args.action === 'sync') {
|
|
379
394
|
const dir = args.dir;
|
|
380
395
|
if (!dir) return { text: '同步 Markdown 需要 dir。' };
|
|
396
|
+
if (!guardPathAllowed(service, dir)) return { text: '未执行:同步目录在 dataRoot 外。' };
|
|
381
397
|
if (args.dryRun !== true && !service.scopeWritable(args.scope ?? service.settings().scope)) return { text: '未执行:该 scope 只读共享。' };
|
|
382
398
|
const result = service.syncMarkdown(dir, { dryRun: args.dryRun === true, scopeId: args.scope });
|
|
383
399
|
return { text: `Markdown 同步${result.dryRun ? '(dry-run)' : ''}:更新 ${result.updated},新建 ${result.created},文件 ${result.files}` };
|
|
@@ -387,7 +403,9 @@ export function createToolDefinitions(service) {
|
|
|
387
403
|
return { text: `FTS 重建完成:${result.before} → ${result.after}(${result.reindexed} 条)` };
|
|
388
404
|
}
|
|
389
405
|
if (args.action === 'export') {
|
|
390
|
-
const
|
|
406
|
+
const dir = args.dir ?? path.join(service.config?.dataRoot ?? process.cwd(), 'cortex-mirror');
|
|
407
|
+
if (!guardPathAllowed(service, dir)) return { text: '未执行:导出目录在 dataRoot 外。' };
|
|
408
|
+
const result = service.exportMarkdown(dir);
|
|
391
409
|
return { text: `Markdown 镜像已导出:${result.root}\n文件:${result.files.join('、')}\n记忆 ${result.traces} 条(跳过 secret ${result.skippedSecrets} 条)` };
|
|
392
410
|
}
|
|
393
411
|
const report = service.guardian.check();
|
|
@@ -0,0 +1,97 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Small, dependency-free web search adapters.
|
|
3
|
+
*
|
|
4
|
+
* Wikipedia and SearXNG need no API key. Search results are returned as
|
|
5
|
+
* citeable sources; the caller decides whether to pass them to the LLM.
|
|
6
|
+
*/
|
|
7
|
+
const DEFAULT_TIMEOUT_MS = 8_000;
|
|
8
|
+
const MAX_RESULTS = 5;
|
|
9
|
+
|
|
10
|
+
function text(value, max = 500) {
|
|
11
|
+
return String(value ?? '').replace(/\s+/g, ' ').trim().slice(0, max);
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
function stripHtml(value) {
|
|
15
|
+
return text(String(value ?? '').replace(/<[^>]+>/g, ' '), 600);
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function withTimeout(ms) {
|
|
19
|
+
const controller = new AbortController();
|
|
20
|
+
const timer = setTimeout(() => controller.abort(new Error('web search timed out')), ms);
|
|
21
|
+
return { signal: controller.signal, done: () => clearTimeout(timer) };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
function sourcesFromWikipedia(payload, language) {
|
|
25
|
+
const rows = payload?.query?.search;
|
|
26
|
+
if (!Array.isArray(rows)) return [];
|
|
27
|
+
return rows.slice(0, MAX_RESULTS).map((row) => ({
|
|
28
|
+
title: text(row.title, 160),
|
|
29
|
+
url: `https://${language || 'zh'}.wikipedia.org/wiki/${encodeURIComponent(String(row.title ?? '').replace(/ /g, '_'))}`,
|
|
30
|
+
snippet: stripHtml(row.snippet),
|
|
31
|
+
provider: 'wikipedia',
|
|
32
|
+
})).filter((row) => row.title && row.url);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function sourcesFromSearxng(payload) {
|
|
36
|
+
const rows = payload?.results;
|
|
37
|
+
if (!Array.isArray(rows)) return [];
|
|
38
|
+
return rows.slice(0, MAX_RESULTS).map((row) => ({
|
|
39
|
+
title: text(row.title || row.url, 160),
|
|
40
|
+
url: text(row.url, 800),
|
|
41
|
+
snippet: text(row.content || row.snippet || '', 600),
|
|
42
|
+
provider: 'searxng',
|
|
43
|
+
})).filter((row) => row.url);
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function createWebSearch({
|
|
47
|
+
provider = 'wikipedia',
|
|
48
|
+
endpoint = 'http://127.0.0.1:8080',
|
|
49
|
+
language = 'zh',
|
|
50
|
+
maxResults = 3,
|
|
51
|
+
timeoutMs = DEFAULT_TIMEOUT_MS,
|
|
52
|
+
fetchImpl = fetch,
|
|
53
|
+
} = {}) {
|
|
54
|
+
const limit = Math.max(1, Math.min(MAX_RESULTS, Number(maxResults) || 3));
|
|
55
|
+
|
|
56
|
+
async function search({ query = '', maxResults: requested } = {}) {
|
|
57
|
+
const q = text(query, 500);
|
|
58
|
+
if (!q) return { sources: [], provider };
|
|
59
|
+
if (provider === 'none') throw new Error('联网未启用:请选择 Wikipedia 或 SearXNG');
|
|
60
|
+
if (typeof fetchImpl !== 'function') throw new Error('联网失败:当前运行环境没有 fetch');
|
|
61
|
+
const count = Math.max(1, Math.min(MAX_RESULTS, Number(requested) || limit));
|
|
62
|
+
const timeout = withTimeout(Math.max(1_000, Math.min(30_000, Number(timeoutMs) || DEFAULT_TIMEOUT_MS)));
|
|
63
|
+
try {
|
|
64
|
+
if (provider === 'wikipedia') {
|
|
65
|
+
const url = new URL(`https://${language || 'zh'}.wikipedia.org/w/api.php`);
|
|
66
|
+
url.searchParams.set('action', 'query');
|
|
67
|
+
url.searchParams.set('list', 'search');
|
|
68
|
+
url.searchParams.set('srsearch', q);
|
|
69
|
+
url.searchParams.set('srlimit', String(count));
|
|
70
|
+
url.searchParams.set('format', 'json');
|
|
71
|
+
url.searchParams.set('utf8', '1');
|
|
72
|
+
url.searchParams.set('origin', '*');
|
|
73
|
+
const response = await fetchImpl(url, { signal: timeout.signal, headers: { accept: 'application/json' } });
|
|
74
|
+
if (!response.ok) throw new Error(`Wikipedia HTTP ${response.status}`);
|
|
75
|
+
const payload = await response.json();
|
|
76
|
+
return { sources: sourcesFromWikipedia(payload, language), provider: 'wikipedia', query: q };
|
|
77
|
+
}
|
|
78
|
+
if (provider === 'searxng') {
|
|
79
|
+
if (!endpoint) throw new Error('SearXNG endpoint 为空');
|
|
80
|
+
const base = String(endpoint).replace(/\/+$/, '');
|
|
81
|
+
const url = new URL(`${base}/search`);
|
|
82
|
+
url.searchParams.set('q', q);
|
|
83
|
+
url.searchParams.set('format', 'json');
|
|
84
|
+
url.searchParams.set('language', language || 'zh');
|
|
85
|
+
const response = await fetchImpl(url, { signal: timeout.signal, headers: { accept: 'application/json' } });
|
|
86
|
+
if (!response.ok) throw new Error(`SearXNG HTTP ${response.status}`);
|
|
87
|
+
const payload = await response.json();
|
|
88
|
+
return { sources: sourcesFromSearxng(payload).slice(0, count), provider: 'searxng', query: q };
|
|
89
|
+
}
|
|
90
|
+
throw new Error(`未知联网 provider: ${provider}`);
|
|
91
|
+
} finally {
|
|
92
|
+
timeout.done();
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
return { search, provider, endpoint, language, maxResults: limit };
|
|
97
|
+
}
|
package/bench/ab-engine.mjs
DELETED
|
@@ -1,60 +0,0 @@
|
|
|
1
|
-
import { mkdtempSync, rmSync } from 'node:fs';
|
|
2
|
-
import os from 'node:os';
|
|
3
|
-
import path from 'node:path';
|
|
4
|
-
import { pathToFileURL } from 'node:url';
|
|
5
|
-
import { generateSynthetic } from './synthetic.js';
|
|
6
|
-
import { evaluateQueries, percentile } from './metrics.js';
|
|
7
|
-
|
|
8
|
-
const engineRoot = process.argv[2];
|
|
9
|
-
const task = process.argv[3] ?? 'paraphrase';
|
|
10
|
-
const count = Number(process.argv[4] ?? 5000);
|
|
11
|
-
const queryCount = Number(process.argv[5] ?? 100);
|
|
12
|
-
|
|
13
|
-
if (!engineRoot) {
|
|
14
|
-
console.error('usage: node bench/ab-engine.mjs <engine-root> [needle|theme|paraphrase] [count] [queries]');
|
|
15
|
-
process.exit(2);
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
const { createCortex } = await import(pathToFileURL(path.join(engineRoot, 'src', 'service', 'cortex.js')).href);
|
|
19
|
-
const dir = mkdtempSync(path.join(os.tmpdir(), 'cortex-ab-'));
|
|
20
|
-
const cortex = createCortex({ config: { dataRoot: dir, dbFile: path.join(dir, 'cortex.sqlite'), contextBudget: 2200 } });
|
|
21
|
-
try {
|
|
22
|
-
const dataset = generateSynthetic({ count, queries: queryCount, seed: 42, task });
|
|
23
|
-
const written = cortex.writeMany(dataset.traces.map((trace) => ({
|
|
24
|
-
text: trace.text,
|
|
25
|
-
title: trace.title,
|
|
26
|
-
tags: trace.tags,
|
|
27
|
-
importance: trace.importance,
|
|
28
|
-
explicit: true,
|
|
29
|
-
operationId: `ab:${trace.id}`,
|
|
30
|
-
now: Date.parse(trace.recordedAt),
|
|
31
|
-
})), { chunkSize: 250 });
|
|
32
|
-
const idMap = new Map();
|
|
33
|
-
for (let i = 0; i < written.length; i += 1) {
|
|
34
|
-
if (written[i].trace) idMap.set(dataset.traces[i].id, written[i].trace.id);
|
|
35
|
-
}
|
|
36
|
-
const results = [];
|
|
37
|
-
const latencies = [];
|
|
38
|
-
for (const query of dataset.queries) {
|
|
39
|
-
const start = performance.now();
|
|
40
|
-
const result = cortex.search(query.query, { limit: 10, budget: 2200 });
|
|
41
|
-
latencies.push(performance.now() - start);
|
|
42
|
-
results.push({
|
|
43
|
-
items: result.items,
|
|
44
|
-
relevant: query.relevant.map((id) => idMap.get(id)).filter(Boolean),
|
|
45
|
-
});
|
|
46
|
-
}
|
|
47
|
-
const metrics = evaluateQueries(results, { k: 10 });
|
|
48
|
-
console.log(JSON.stringify({
|
|
49
|
-
engine: engineRoot,
|
|
50
|
-
task,
|
|
51
|
-
count,
|
|
52
|
-
queries: dataset.queries.length,
|
|
53
|
-
p50Ms: Math.round((percentile(latencies, 50) ?? 0) * 100) / 100,
|
|
54
|
-
p95Ms: Math.round((percentile(latencies, 95) ?? 0) * 100) / 100,
|
|
55
|
-
...metrics,
|
|
56
|
-
}, null, 2));
|
|
57
|
-
} finally {
|
|
58
|
-
cortex.close();
|
|
59
|
-
rmSync(dir, { recursive: true, force: true });
|
|
60
|
-
}
|
package/bench/ann-bench.mjs
DELETED
|
@@ -1,78 +0,0 @@
|
|
|
1
|
-
import { createAnnIndex } from '../src/vector/ann.js';
|
|
2
|
-
|
|
3
|
-
function randomFactory(seed) {
|
|
4
|
-
let state = seed >>> 0;
|
|
5
|
-
return () => {
|
|
6
|
-
state = (state * 1664525 + 1013904223) >>> 0;
|
|
7
|
-
return state / 4294967296;
|
|
8
|
-
};
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
function makeVector(random, dim = 64) {
|
|
12
|
-
const value = Array.from({ length: dim }, () => random() * 2 - 1);
|
|
13
|
-
const norm = Math.sqrt(value.reduce((sum, item) => sum + item * item, 0)) || 1;
|
|
14
|
-
return value.map((item) => item / norm);
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
function cosine(a, b) {
|
|
18
|
-
let dot = 0;
|
|
19
|
-
for (let i = 0; i < a.length; i += 1) dot += a[i] * b[i];
|
|
20
|
-
return dot;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
function percentile(values, p) {
|
|
24
|
-
const sorted = [...values].sort((a, b) => a - b);
|
|
25
|
-
if (!sorted.length) return null;
|
|
26
|
-
return sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil((p / 100) * sorted.length) - 1))];
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
const count = Number(process.argv[2] ?? 5000);
|
|
30
|
-
const queries = Number(process.argv[3] ?? 100);
|
|
31
|
-
const ef = Number(process.argv[4] ?? 120);
|
|
32
|
-
const random = randomFactory(20261111);
|
|
33
|
-
const items = Array.from({ length: count }, (_, index) => ({ id: `a${index}`, vector: makeVector(random) }));
|
|
34
|
-
const queryVectors = Array.from({ length: queries }, () => makeVector(random));
|
|
35
|
-
const ann = createAnnIndex({ M: 24, efConstruction: 200, efSearch: ef, seed: 20261111 });
|
|
36
|
-
const buildStart = performance.now();
|
|
37
|
-
ann.rebuild(items);
|
|
38
|
-
const buildMs = performance.now() - buildStart;
|
|
39
|
-
|
|
40
|
-
const exactTimes = [];
|
|
41
|
-
const annTimes = [];
|
|
42
|
-
const exactResults = [];
|
|
43
|
-
const annResults = [];
|
|
44
|
-
for (const query of queryVectors) {
|
|
45
|
-
const exactStart = performance.now();
|
|
46
|
-
const exact = items
|
|
47
|
-
.map((item) => ({ id: item.id, score: cosine(item.vector, query) }))
|
|
48
|
-
.sort((a, b) => b.score - a.score)
|
|
49
|
-
.slice(0, 10);
|
|
50
|
-
exactTimes.push(performance.now() - exactStart);
|
|
51
|
-
exactResults.push(exact);
|
|
52
|
-
|
|
53
|
-
const annStart = performance.now();
|
|
54
|
-
const approx = ann.search(query, 10, { ef }).slice(0, 10);
|
|
55
|
-
annTimes.push(performance.now() - annStart);
|
|
56
|
-
annResults.push(approx);
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
let hits = 0;
|
|
60
|
-
let expectedTotal = 0;
|
|
61
|
-
for (let index = 0; index < exactResults.length; index += 1) {
|
|
62
|
-
const expected = new Set(exactResults[index].map((item) => item.id));
|
|
63
|
-
for (const item of annResults[index]) if (expected.has(item.id)) hits += 1;
|
|
64
|
-
expectedTotal += expected.size;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
console.log(JSON.stringify({
|
|
68
|
-
count,
|
|
69
|
-
queries,
|
|
70
|
-
dim: 64,
|
|
71
|
-
ef,
|
|
72
|
-
buildMs: Math.round(buildMs * 100) / 100,
|
|
73
|
-
recallAt10: expectedTotal ? Math.round((hits / expectedTotal) * 10000) / 10000 : null,
|
|
74
|
-
exactP50Ms: Math.round((percentile(exactTimes, 50) ?? 0) * 1000) / 1000,
|
|
75
|
-
annP50Ms: Math.round((percentile(annTimes, 50) ?? 0) * 1000) / 1000,
|
|
76
|
-
exactP95Ms: Math.round((percentile(exactTimes, 95) ?? 0) * 1000) / 1000,
|
|
77
|
-
annP95Ms: Math.round((percentile(annTimes, 95) ?? 0) * 1000) / 1000,
|
|
78
|
-
}, null, 2));
|
package/bench/hnsw-bench.mjs
DELETED
|
@@ -1,79 +0,0 @@
|
|
|
1
|
-
import { createHnswIndex } from '../src/vector/hnsw.js';
|
|
2
|
-
|
|
3
|
-
function randomFactory(seed) {
|
|
4
|
-
let state = seed >>> 0;
|
|
5
|
-
return () => {
|
|
6
|
-
state = (state * 1664525 + 1013904223) >>> 0;
|
|
7
|
-
return state / 4294967296;
|
|
8
|
-
};
|
|
9
|
-
}
|
|
10
|
-
|
|
11
|
-
function makeVector(random, dim = 64) {
|
|
12
|
-
const value = Array.from({ length: dim }, () => random() * 2 - 1);
|
|
13
|
-
const norm = Math.sqrt(value.reduce((sum, item) => sum + item * item, 0)) || 1;
|
|
14
|
-
return value.map((item) => item / norm);
|
|
15
|
-
}
|
|
16
|
-
|
|
17
|
-
function cosine(a, b) {
|
|
18
|
-
let dot = 0;
|
|
19
|
-
for (let i = 0; i < a.length; i += 1) dot += a[i] * b[i];
|
|
20
|
-
return dot;
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
function percentile(values, p) {
|
|
24
|
-
const sorted = [...values].sort((a, b) => a - b);
|
|
25
|
-
if (!sorted.length) return null;
|
|
26
|
-
return sorted[Math.min(sorted.length - 1, Math.max(0, Math.ceil((p / 100) * sorted.length) - 1))];
|
|
27
|
-
}
|
|
28
|
-
|
|
29
|
-
const count = Number(process.argv[2] ?? 5000);
|
|
30
|
-
const queries = Number(process.argv[3] ?? 100);
|
|
31
|
-
const ef = Number(process.argv[4] ?? 200);
|
|
32
|
-
const random = randomFactory(20261111);
|
|
33
|
-
const items = Array.from({ length: count }, (_, index) => ({ id: `h${index}`, vector: makeVector(random) }));
|
|
34
|
-
const queryVectors = Array.from({ length: queries }, () => makeVector(random));
|
|
35
|
-
const index = createHnswIndex({ M: 24, efConstruction: 200, efSearch: ef, seed: 20261111 });
|
|
36
|
-
const buildStart = performance.now();
|
|
37
|
-
index.rebuild(items);
|
|
38
|
-
const buildMs = performance.now() - buildStart;
|
|
39
|
-
|
|
40
|
-
const exactTimes = [];
|
|
41
|
-
const hnswTimes = [];
|
|
42
|
-
const exactResults = [];
|
|
43
|
-
const hnswResults = [];
|
|
44
|
-
for (const query of queryVectors) {
|
|
45
|
-
const exactStart = performance.now();
|
|
46
|
-
const exact = items
|
|
47
|
-
.map((item) => ({ id: item.id, score: cosine(item.vector, query) }))
|
|
48
|
-
.sort((a, b) => b.score - a.score)
|
|
49
|
-
.slice(0, 10);
|
|
50
|
-
exactTimes.push(performance.now() - exactStart);
|
|
51
|
-
exactResults.push(exact);
|
|
52
|
-
|
|
53
|
-
const hnswStart = performance.now();
|
|
54
|
-
const approx = index.search(query, 10, { ef }).slice(0, 10);
|
|
55
|
-
hnswTimes.push(performance.now() - hnswStart);
|
|
56
|
-
hnswResults.push(approx);
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
let hits = 0;
|
|
60
|
-
let expectedTotal = 0;
|
|
61
|
-
for (let index = 0; index < exactResults.length; index += 1) {
|
|
62
|
-
const expected = new Set(exactResults[index].map((item) => item.id));
|
|
63
|
-
for (const item of hnswResults[index]) if (expected.has(item.id)) hits += 1;
|
|
64
|
-
expectedTotal += expected.size;
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
console.log(JSON.stringify({
|
|
68
|
-
engine: 'hnsw',
|
|
69
|
-
count,
|
|
70
|
-
queries,
|
|
71
|
-
dim: 64,
|
|
72
|
-
ef,
|
|
73
|
-
buildMs: Math.round(buildMs * 100) / 100,
|
|
74
|
-
recallAt10: expectedTotal ? Math.round((hits / expectedTotal) * 10000) / 10000 : null,
|
|
75
|
-
exactP50Ms: Math.round((percentile(exactTimes, 50) ?? 0) * 1000) / 1000,
|
|
76
|
-
hnswP50Ms: Math.round((percentile(hnswTimes, 50) ?? 0) * 1000) / 1000,
|
|
77
|
-
exactP95Ms: Math.round((percentile(exactTimes, 95) ?? 0) * 1000) / 1000,
|
|
78
|
-
hnswP95Ms: Math.round((percentile(hnswTimes, 95) ?? 0) * 1000) / 1000,
|
|
79
|
-
}, null, 2));
|
package/bench/locomo.js
DELETED
|
@@ -1,89 +0,0 @@
|
|
|
1
|
-
import { evaluateQueries } from './metrics.js';
|
|
2
|
-
|
|
3
|
-
/**
|
|
4
|
-
* LoCoMo retrieval adapter (offline, no dataset bundled).
|
|
5
|
-
* Dataset/repo: https://github.com/snap-research/locomo
|
|
6
|
-
*
|
|
7
|
-
* The adapter is intentionally shape-tolerant: official samples expose
|
|
8
|
-
* conversation sessions as `session_1`, `session_2`, ... with `evidence` like
|
|
9
|
-
* `D1:2`. It evaluates retrieval only; it does not claim official QA scores.
|
|
10
|
-
*/
|
|
11
|
-
|
|
12
|
-
function sessionKeys(conversation) {
|
|
13
|
-
return Object.keys(conversation ?? {})
|
|
14
|
-
.filter((key) => /^session_\d+$/.test(key))
|
|
15
|
-
.sort((a, b) => Number(a.split('_')[1]) - Number(b.split('_')[1]));
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
function parseEvidence(evidence) {
|
|
19
|
-
const list = Array.isArray(evidence) ? evidence : [evidence];
|
|
20
|
-
const out = [];
|
|
21
|
-
for (const item of list) {
|
|
22
|
-
const match = String(item ?? '').match(/D(\d+):(\d+)/i);
|
|
23
|
-
if (match) out.push({ session: Number(match[1]), turn: Number(match[2]) });
|
|
24
|
-
}
|
|
25
|
-
return out;
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
export function buildLoCoMoIndex({ cortex, samples = [], scopeId = 'global' } = {}) {
|
|
29
|
-
if (!cortex) throw new Error('buildLoCoMoIndex needs cortex');
|
|
30
|
-
const turnTraceIds = new Map();
|
|
31
|
-
const queries = [];
|
|
32
|
-
let traces = 0;
|
|
33
|
-
|
|
34
|
-
for (const sample of samples) {
|
|
35
|
-
const sampleId = String(sample.sample_id ?? `sample-${queries.length}`);
|
|
36
|
-
const conversation = sample.conversation ?? {};
|
|
37
|
-
for (const key of sessionKeys(conversation)) {
|
|
38
|
-
const number = Number(key.split('_')[1]);
|
|
39
|
-
const date = conversation[`${key}_date_time`] ?? conversation[`${key}_date`] ?? null;
|
|
40
|
-
const turns = Array.isArray(conversation[key]) ? conversation[key] : [];
|
|
41
|
-
turns.forEach((turn, index) => {
|
|
42
|
-
const text = `${turn.speaker ?? turn.role ?? '用户'}:${turn.text ?? turn.content ?? ''}`;
|
|
43
|
-
if (!text.trim()) return;
|
|
44
|
-
const written = cortex.write({
|
|
45
|
-
text,
|
|
46
|
-
kind: 'episode',
|
|
47
|
-
title: `LoCoMo ${sampleId} D${number}:${index + 1}`,
|
|
48
|
-
tags: ['locomo'],
|
|
49
|
-
explicit: true,
|
|
50
|
-
importance: 0.5,
|
|
51
|
-
operationId: `locomo:${sampleId}:D${number}:${index + 1}`,
|
|
52
|
-
now: date ? Date.parse(date) : undefined,
|
|
53
|
-
});
|
|
54
|
-
if (written.trace) {
|
|
55
|
-
turnTraceIds.set(`${sampleId}:D${number}:${index + 1}`, written.trace.id);
|
|
56
|
-
traces += 1;
|
|
57
|
-
}
|
|
58
|
-
});
|
|
59
|
-
}
|
|
60
|
-
for (const item of sample.qa ?? []) {
|
|
61
|
-
const relevant = [];
|
|
62
|
-
for (const ref of parseEvidence(item.evidence)) {
|
|
63
|
-
const id = turnTraceIds.get(`${sampleId}:D${ref.session}:${ref.turn}`);
|
|
64
|
-
if (id) relevant.push(id);
|
|
65
|
-
}
|
|
66
|
-
queries.push({
|
|
67
|
-
id: `${sampleId}:${queries.length}`,
|
|
68
|
-
query: item.question ?? '',
|
|
69
|
-
answer: item.answer ?? null,
|
|
70
|
-
type: String(item.category ?? 'unknown'),
|
|
71
|
-
relevant,
|
|
72
|
-
evidence: item.evidence ?? [],
|
|
73
|
-
});
|
|
74
|
-
}
|
|
75
|
-
}
|
|
76
|
-
return { scopeId, traces, queries, turnTraceIds };
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
export async function evaluateLoCoMoRetrieval({ cortex, samples = [], limit = 10, includeAdversarial = false } = {}) {
|
|
80
|
-
const built = buildLoCoMoIndex({ cortex, samples });
|
|
81
|
-
const evaluated = built.queries.filter((query) => includeAdversarial || query.type !== '5');
|
|
82
|
-
const results = evaluated.map((query) => ({ items: cortex.search(query.query, { limit, budget: 3000 }).items, relevant: query.relevant, type: query.type }));
|
|
83
|
-
const overall = evaluateQueries(results, { k: limit });
|
|
84
|
-
const byType = {};
|
|
85
|
-
const buckets = {};
|
|
86
|
-
for (const result of results) (buckets[result.type] ??= []).push(result);
|
|
87
|
-
for (const [type, bucket] of Object.entries(buckets)) byType[type] = evaluateQueries(bucket, { k: limit });
|
|
88
|
-
return { ...overall, byType, built: { traces: built.traces, queries: built.queries.length, evaluated: evaluated.length } };
|
|
89
|
-
}
|