dsh-cortex-memory 0.4.22 → 0.4.146
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 +2216 -7
- package/README.md +9 -9
- package/bench/migration-bench.mjs +1 -1
- package/bench/semantic-cn.js +7 -7
- package/bench/synthetic.js +2 -2
- package/bin/copy-db.mjs +47 -0
- package/bin/repair.mjs +328 -0
- package/bin/verify.mjs +202 -0
- package/cordis.patch.yml +1 -1
- package/docs/install-windows.md +2 -2
- package/docs/models.md +1 -1
- package/docs/quota-compaction-design.md +175 -0
- package/index.js +27 -3
- package/package.json +3 -3
- package/src/adapters/shiori.js +1 -1
- package/src/api/routes.js +1 -1
- package/src/core/feature-overrides.js +2 -2
- package/src/engines/compression.js +172 -3
- package/src/engines/consolidate.js +397 -26
- package/src/engines/encode.js +16 -3
- package/src/engines/extract.js +72 -8
- package/src/engines/fact-guard.js +51 -0
- package/src/engines/health.js +263 -3
- package/src/engines/inhibition.js +39 -0
- package/src/engines/life.js +12 -1
- package/src/engines/llm-facts.js +12 -9
- package/src/engines/narrative.js +150 -13
- package/src/engines/reflect.js +172 -14
- package/src/engines/retrieve.js +44 -5
- package/src/engines/summary-coverage.js +62 -0
- package/src/engines/summary-dedupe.js +77 -0
- package/src/engines/summon-rank.js +132 -0
- package/src/host/runtime.js +64 -4
- package/src/host/scheduler.js +224 -3
- package/src/llm/adapter.js +29 -8
- package/src/memory/query.js +1 -1
- package/src/memory/spacing.js +15 -0
- package/src/memory/tokenizer.js +1 -1
- package/src/prompt/tiers.js +88 -12
- package/src/self/alias.js +25 -0
- package/src/self/emotion.js +3 -1
- package/src/self/relationship.js +44 -13
- package/src/self/state.js +20 -2
- package/src/self/working.js +34 -3
- package/src/service/cortex.js +493 -53
- package/src/store/repositories/facts.js +34 -1
- package/src/store/repositories/summaries.js +8 -1
- package/src/store/repositories/traces.js +22 -2
- package/src/tools/definitions.js +118 -4
- package/src/vector/index.js +96 -7
- package/test/integration/acceptance.test.js +47 -47
- package/test/integration/api-contract.test.js +17 -17
- package/test/integration/backup-privacy.test.js +10 -10
- package/test/integration/consolidate.test.js +6 -2
- package/test/integration/edge-cases.test.js +16 -15
- package/test/integration/exchange.test.js +26 -26
- package/test/integration/life-loop.test.js +7 -6
- package/test/integration/load.test.js +4 -4
- package/test/integration/policy-query-api.test.js +4 -4
- package/test/integration/resilience-writes.test.js +7 -7
- package/test/integration/tools-contract.test.js +57 -57
- package/test/unit/alias.test.js +87 -0
- package/test/unit/api-client.test.js +3 -3
- package/test/unit/api-validate.test.js +3 -3
- package/test/unit/api.test.js +3 -3
- package/test/unit/auto-reflect.test.js +141 -0
- package/test/unit/capture-filter.test.js +296 -0
- package/test/unit/compaction-preview.test.js +91 -0
- package/test/unit/compression.test.js +4 -4
- package/test/unit/consolidate-dedupe.test.js +174 -0
- package/test/unit/consolidate-errors.test.js +63 -0
- package/test/unit/consolidate-gate.test.js +26 -0
- package/test/unit/consolidate-preview.test.js +168 -0
- package/test/unit/consolidate-protection.test.js +156 -0
- package/test/unit/consolidate-reason.test.js +206 -0
- package/test/unit/consolidate-retry.test.js +91 -0
- package/test/unit/consolidate-selection.test.js +103 -0
- package/test/unit/core.test.js +11 -11
- package/test/unit/coverage-rewrite.test.js +38 -0
- package/test/unit/dedupe-episodes.test.js +34 -0
- package/test/unit/dedupe-threshold.test.js +14 -0
- package/test/unit/develop.test.js +4 -4
- package/test/unit/edges-candidates.test.js +2 -2
- package/test/unit/emotion.test.js +2 -1
- package/test/unit/encode.test.js +6 -6
- package/test/unit/evolution.test.js +5 -5
- package/test/unit/extract-question.test.js +41 -0
- package/test/unit/fact-guard.test.js +51 -0
- package/test/unit/fact-noise-llm.test.js +44 -0
- package/test/unit/facts-belief.test.js +4 -4
- package/test/unit/facts-compat.test.js +62 -0
- package/test/unit/facts.test.js +5 -5
- package/test/unit/fts-migration.test.js +6 -6
- package/test/unit/growth-reflect.test.js +4 -3
- package/test/unit/guardian.test.js +1 -1
- package/test/unit/health-consolidation.test.js +52 -0
- package/test/unit/health-fts-scope.test.js +33 -0
- package/test/unit/health-privacy.test.js +6 -6
- package/test/unit/health-summaries.test.js +24 -0
- package/test/unit/health-text-maintain.test.js +33 -0
- package/test/unit/health-today.test.js +45 -0
- package/test/unit/host-runtime.test.js +8 -8
- package/test/unit/host.test.js +1 -1
- package/test/unit/induct-evaluate.test.js +3 -3
- package/test/unit/ingest-extracted.test.js +3 -3
- package/test/unit/inhibition.test.js +90 -0
- package/test/unit/jobs.test.js +4 -4
- package/test/unit/json-snapshot.test.js +1 -1
- package/test/unit/label-entities-skip.test.js +18 -0
- package/test/unit/llm-facts-integration.test.js +2 -2
- package/test/unit/llm-facts.test.js +3 -3
- package/test/unit/llm.test.js +5 -5
- package/test/unit/locomo.test.js +2 -2
- package/test/unit/longmemeval.test.js +2 -2
- package/test/unit/maintain-dispute.test.js +62 -0
- package/test/unit/maintain-duration.test.js +194 -0
- package/test/unit/markdown-import.test.js +5 -5
- package/test/unit/markdown.test.js +2 -2
- package/test/unit/memory-edit.test.js +5 -5
- package/test/unit/migration.test.js +1 -1
- package/test/unit/mood-saturation.test.js +33 -0
- package/test/unit/narrative-weave.test.js +271 -0
- package/test/unit/privacy-scope.test.js +1 -1
- package/test/unit/prompt.test.js +1 -1
- package/test/unit/providers.test.js +2 -2
- package/test/unit/qa.test.js +9 -9
- package/test/unit/query.test.js +10 -10
- package/test/unit/reflect-backfill.test.js +158 -0
- package/test/unit/reflect-coverage.test.js +35 -0
- package/test/unit/reflect-overview.test.js +22 -0
- package/test/unit/reflect-phrasing.test.js +75 -0
- package/test/unit/reflect-sampling.test.js +80 -0
- package/test/unit/reflect-source-budget.test.js +24 -0
- package/test/unit/relationship-dynamics.test.js +29 -0
- package/test/unit/retrieve.test.js +9 -9
- package/test/unit/revive-on-read.test.js +84 -0
- package/test/unit/scanner.test.js +2 -2
- package/test/unit/scenario.test.js +2 -2
- package/test/unit/scheduler-autoconsolidate.test.js +95 -0
- package/test/unit/scheduler-autodedupe.test.js +52 -0
- package/test/unit/scheduler-autosleep.test.js +50 -0
- package/test/unit/scheduler-cadence.test.js +33 -0
- package/test/unit/scheduler-deep.test.js +62 -0
- package/test/unit/scheduler-tick-gate.test.js +38 -0
- package/test/unit/scheduler.test.js +2 -1
- package/test/unit/service.test.js +5 -5
- package/test/unit/shiori-import.test.js +4 -4
- package/test/unit/spacing.test.js +14 -0
- package/test/unit/store.test.js +13 -13
- package/test/unit/summon-left-slot.test.js +51 -0
- package/test/unit/summon-rank.test.js +51 -0
- package/test/unit/tiers-gist.test.js +140 -0
- package/test/unit/tiers.test.js +1 -1
- package/test/unit/tokenizer-fts.test.js +6 -6
- package/test/unit/tools.test.js +5 -5
- package/test/unit/upgrade-0412.test.js +10 -10
- package/test/unit/upgrade-0413.test.js +5 -5
- package/test/unit/upgrade-0414.test.js +5 -5
- package/test/unit/vector-ann.test.js +3 -3
- package/test/unit/vector-async.test.js +7 -7
- package/test/unit/vector-coverage.test.js +34 -0
- package/test/unit/vector-override.test.js +37 -0
- package/test/unit/vector-typed-array.test.js +47 -0
- package/test/unit/vector.test.js +8 -8
- package/test/unit/working.test.js +19 -0
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { jaccard } from '../memory/tokenizer.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Find duplicated episode summaries.
|
|
5
|
+
*
|
|
6
|
+
* The v1 reflect logic wrote one episode every time it ran, and the candidate
|
|
7
|
+
* window was always "the last 24 hours", so several rows can describe almost the
|
|
8
|
+
* same day. Recomputing coverage fixed the numbers but not the duplication; this
|
|
9
|
+
* helper reports the clusters so `repair --dedupe-episodes` can merge them behind
|
|
10
|
+
* its backup gate. It never writes.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
function span(summary) {
|
|
14
|
+
const start = Date.parse(summary.periodStart ?? '');
|
|
15
|
+
const end = Date.parse(summary.periodEnd ?? '');
|
|
16
|
+
if (!Number.isFinite(start) || !Number.isFinite(end) || end <= start) return null;
|
|
17
|
+
return { start, end };
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function overlapRatio(a, b) {
|
|
21
|
+
const left = span(a);
|
|
22
|
+
const right = span(b);
|
|
23
|
+
if (!left || !right) return 0;
|
|
24
|
+
const overlap = Math.min(left.end, right.end) - Math.max(left.start, right.start);
|
|
25
|
+
if (overlap <= 0) return 0;
|
|
26
|
+
const smaller = Math.min(left.end - left.start, right.end - right.start);
|
|
27
|
+
return smaller > 0 ? overlap / smaller : 0;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
export function findDuplicateEpisodes({
|
|
31
|
+
db,
|
|
32
|
+
scopeId = 'global',
|
|
33
|
+
overlapThreshold = 0.9,
|
|
34
|
+
similarityThreshold = 0.8,
|
|
35
|
+
limit = 200,
|
|
36
|
+
} = {}) {
|
|
37
|
+
if (!db) throw new Error('findDuplicateEpisodes needs a db');
|
|
38
|
+
const rows = db.prepare(`
|
|
39
|
+
SELECT id, content, source_ids_json, coverage, period_start, period_end, created_at, model
|
|
40
|
+
FROM summaries
|
|
41
|
+
WHERE scope_id = ? AND level = 'episode'
|
|
42
|
+
ORDER BY created_at DESC LIMIT ?
|
|
43
|
+
`).all(scopeId, Math.max(1, Number(limit) || 200));
|
|
44
|
+
|
|
45
|
+
const summaries = rows.map((row) => ({
|
|
46
|
+
id: row.id,
|
|
47
|
+
content: String(row.content ?? ''),
|
|
48
|
+
sourceIds: (() => { try { return JSON.parse(row.source_ids_json ?? '[]'); } catch { return []; } })(),
|
|
49
|
+
coverage: Number(row.coverage ?? 0),
|
|
50
|
+
periodStart: row.period_start,
|
|
51
|
+
periodEnd: row.period_end,
|
|
52
|
+
createdAt: row.created_at,
|
|
53
|
+
model: row.model,
|
|
54
|
+
}));
|
|
55
|
+
|
|
56
|
+
// Greedy clustering: newest row wins, older near-duplicates join its cluster.
|
|
57
|
+
const used = new Set();
|
|
58
|
+
const clusters = [];
|
|
59
|
+
for (const summary of summaries) {
|
|
60
|
+
if (used.has(summary.id)) continue;
|
|
61
|
+
used.add(summary.id);
|
|
62
|
+
const cluster = { keep: summary, remove: [], unionSources: [...summary.sourceIds], contentSim: 1 };
|
|
63
|
+
for (const other of summaries) {
|
|
64
|
+
if (used.has(other.id)) continue;
|
|
65
|
+
const ratio = overlapRatio(summary, other);
|
|
66
|
+
if (ratio < overlapThreshold) continue;
|
|
67
|
+
const sim = jaccard(summary.content, other.content);
|
|
68
|
+
if (sim < similarityThreshold) continue;
|
|
69
|
+
used.add(other.id);
|
|
70
|
+
cluster.remove.push(other);
|
|
71
|
+
cluster.contentSim = Math.min(cluster.contentSim, Math.round(sim * 1000) / 1000);
|
|
72
|
+
for (const id of other.sourceIds) if (!cluster.unionSources.includes(id)) cluster.unionSources.push(id);
|
|
73
|
+
}
|
|
74
|
+
if (cluster.remove.length) clusters.push(cluster);
|
|
75
|
+
}
|
|
76
|
+
return { candidates: summaries.length, clusters };
|
|
77
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ranking for summon cards (历史参考卡片).
|
|
3
|
+
*
|
|
4
|
+
* The old rule picked by trigger score only, so a single busy day could fill the
|
|
5
|
+
* whole block with near-duplicates and the freshest history never surfaced. This
|
|
6
|
+
* module is pure so it can be tested without a database: trigger specificity,
|
|
7
|
+
* a small recency term, and a diversity pass that prefers one card per day and
|
|
8
|
+
* at most one card per category.
|
|
9
|
+
*
|
|
10
|
+
* `onDrop` (optional) is called with any card displaced by the side-coverage rule,
|
|
11
|
+
* so the caller can count drops instead of losing them silently.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
function triggerScore(card, query, frequency, cardCount) {
|
|
15
|
+
const triggers = (card.triggers ?? []).filter((item) => item.length >= 2 && item.length <= 12 && query.includes(item));
|
|
16
|
+
if (!triggers.length && !(card.title && query.includes(String(card.title).slice(0, Math.min(12, String(card.title).length))))) {
|
|
17
|
+
return { hits: [], score: 0 };
|
|
18
|
+
}
|
|
19
|
+
let score = triggers.reduce((sum, trigger) => {
|
|
20
|
+
const specificity = 1 + Math.log(1 + cardCount / (1 + (frequency.get(trigger) ?? 1)));
|
|
21
|
+
return sum + (1 + Math.min(4, trigger.length) * 0.25) * specificity;
|
|
22
|
+
}, 0);
|
|
23
|
+
if (card.title && query.includes(String(card.title).slice(0, Math.min(12, String(card.title).length)))) score += 1.5;
|
|
24
|
+
return { hits: triggers, score };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function dayDistance(day, now) {
|
|
28
|
+
const parsed = Date.parse(`${String(day ?? '')}T00:00:00Z`);
|
|
29
|
+
if (!Number.isFinite(parsed)) return 365;
|
|
30
|
+
return Math.max(0, (now - parsed) / 86_400_000);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function rankSummonCards(cards, { query = '', now = Date.now(), maxCards = 3, onDrop = null } = {}) {
|
|
34
|
+
const text = String(query ?? '').trim();
|
|
35
|
+
if (!text) return [];
|
|
36
|
+
const frequency = new Map();
|
|
37
|
+
for (const card of cards) {
|
|
38
|
+
for (const trigger of new Set((card.triggers ?? []).filter((item) => item.length >= 2 && item.length <= 12))) {
|
|
39
|
+
frequency.set(trigger, (frequency.get(trigger) ?? 0) + 1);
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
const scored = [];
|
|
43
|
+
for (const card of cards) {
|
|
44
|
+
const { hits, score } = triggerScore(card, text, frequency, cards.length);
|
|
45
|
+
if (!hits.length && score === 0) continue;
|
|
46
|
+
// Fresher memories are more likely to be the relevant "recent self".
|
|
47
|
+
const fresh = Math.max(0, 1.2 - dayDistance(card.day, now) * 0.12);
|
|
48
|
+
const importance = Number(card.importance ?? 0.5) * 0.4;
|
|
49
|
+
const category = card.category === 'utterance' ? 0 : 0.6;
|
|
50
|
+
scored.push({ card, hits, score: score + fresh + importance + category });
|
|
51
|
+
}
|
|
52
|
+
const specific = scored.filter((entry) => entry.card.category !== 'utterance');
|
|
53
|
+
const pool = (specific.length ? specific : scored).sort((a, b) => b.score - a.score);
|
|
54
|
+
|
|
55
|
+
// Diversity: one card per day first, then relax; never two from one category
|
|
56
|
+
// unless there is nothing else.
|
|
57
|
+
const chosen = [];
|
|
58
|
+
const days = new Set();
|
|
59
|
+
const categories = new Set();
|
|
60
|
+
const limit = Math.max(1, Math.min(5, Number(maxCards) || 3));
|
|
61
|
+
const push = (entry) => {
|
|
62
|
+
chosen.push(entry);
|
|
63
|
+
if (entry.card.day) days.add(entry.card.day);
|
|
64
|
+
if (entry.card.category) categories.add(entry.card.category);
|
|
65
|
+
};
|
|
66
|
+
for (const entry of pool) {
|
|
67
|
+
if (chosen.length >= limit) break;
|
|
68
|
+
if (entry.card.day && days.has(entry.card.day)) continue;
|
|
69
|
+
if (entry.card.category && categories.has(entry.card.category)) continue;
|
|
70
|
+
push(entry);
|
|
71
|
+
}
|
|
72
|
+
// Fill the remaining slots with whatever is left, but still prefer a new day
|
|
73
|
+
// and a new category before falling back to near-duplicates.
|
|
74
|
+
const remaining = pool
|
|
75
|
+
.filter((entry) => !chosen.some((item) => item.card.id === entry.card.id))
|
|
76
|
+
.sort((a, b) => {
|
|
77
|
+
const newDay = (entry) => (entry.card.day && !days.has(entry.card.day) ? 1 : 0);
|
|
78
|
+
const newCategory = (entry) => (entry.card.category && !categories.has(entry.card.category) ? 1 : 0);
|
|
79
|
+
if (newDay(a) !== newDay(b)) return newDay(b) - newDay(a);
|
|
80
|
+
if (newCategory(a) !== newCategory(b)) return newCategory(b) - newCategory(a);
|
|
81
|
+
return b.score - a.score;
|
|
82
|
+
});
|
|
83
|
+
for (const entry of remaining) {
|
|
84
|
+
if (chosen.length >= limit) break;
|
|
85
|
+
push(entry);
|
|
86
|
+
}
|
|
87
|
+
// Keep the emotional (left) and working (right) sides represented when both
|
|
88
|
+
// exist, because that pairing is the point of the summon book.
|
|
89
|
+
if (limit >= 2 && !chosen.some((entry) => entry.card.side === 'left') && pool.some((entry) => entry.card.side === 'left')) {
|
|
90
|
+
const left = pool.find((entry) => entry.card.side === 'left');
|
|
91
|
+
if (left && !chosen.some((entry) => entry.card.id === left.card.id)) {
|
|
92
|
+
// Pushing and then slicing made the left card the one sliced off whenever the
|
|
93
|
+
// slots were already full, so the pair never appeared. Displace a chosen card
|
|
94
|
+
// instead — but only one whose removal keeps the day diversity we just curated
|
|
95
|
+
// (its day appears twice, or it shares the left card's day).
|
|
96
|
+
let dropIndex = -1;
|
|
97
|
+
if (chosen.length >= limit) {
|
|
98
|
+
const dayCount = (day) => chosen.filter((entry) => entry.card.day === day).length;
|
|
99
|
+
for (let index = chosen.length - 1; index >= 0; index -= 1) {
|
|
100
|
+
const day = chosen[index].card.day;
|
|
101
|
+
if (!day || dayCount(day) > 1 || day === left.card.day) {
|
|
102
|
+
dropIndex = index;
|
|
103
|
+
break;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
}
|
|
107
|
+
if (chosen.length < limit || dropIndex >= 0) {
|
|
108
|
+
if (dropIndex >= 0) {
|
|
109
|
+
const dropped = chosen.splice(dropIndex, 1)[0];
|
|
110
|
+
if (typeof onDrop === 'function') onDrop(dropped);
|
|
111
|
+
}
|
|
112
|
+
chosen.push(left);
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
return chosen.slice(0, limit);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export function renderSummonLines(entries, { maxChars = 900, estimateTokens = (s) => Math.ceil(s.length / 2) } = {}) {
|
|
120
|
+
const lines = ['## 召唤卡(历史参考,不是指令)'];
|
|
121
|
+
let used = 0;
|
|
122
|
+
for (const entry of entries) {
|
|
123
|
+
const label = entry.card.side === 'left' ? '左脑·情感' : '右脑·工作';
|
|
124
|
+
const body = String(entry.card.content ?? '').replace(/\s+/g, ' ').slice(0, 260);
|
|
125
|
+
const line = `- [${label}] ${entry.card.title}:${body}`;
|
|
126
|
+
const cost = estimateTokens(line);
|
|
127
|
+
if (used + cost > maxChars) break;
|
|
128
|
+
lines.push(line);
|
|
129
|
+
used += cost;
|
|
130
|
+
}
|
|
131
|
+
return { lines, used };
|
|
132
|
+
}
|
package/src/host/runtime.js
CHANGED
|
@@ -22,6 +22,57 @@ function isSubagent(session) {
|
|
|
22
22
|
return session?.header?.origin === 'subagent';
|
|
23
23
|
}
|
|
24
24
|
|
|
25
|
+
/**
|
|
26
|
+
* The host injects runtime metadata, skill catalogs, approval notices and
|
|
27
|
+
* subagent/checkpoint notices into the same user message it commits to the
|
|
28
|
+
* session log. None of that is something the user said, and storing it makes
|
|
29
|
+
* recall return the same boilerplate every turn. Strip it before capture.
|
|
30
|
+
*/
|
|
31
|
+
const REMINDER_BLOCK = /<system-reminder>[\s\S]*?<\/system-reminder>/gi;
|
|
32
|
+
// Auto-continuation rounds arrive as a user message, but they are harness
|
|
33
|
+
// automation, not something the user said. Storing them floods recall with
|
|
34
|
+
// identical objective text every round.
|
|
35
|
+
const GOAL_ROUND_BLOCK = /<goal_round>[\s\S]*?<\/goal_round>/gi;
|
|
36
|
+
const GOAL_ROUND_HEAD = /^(?:<goal_round>|Objective:\s*")/i;
|
|
37
|
+
const GOAL_ROUND_SHAPE = /Round:\s*\d+\s*\/\s*\d+/i;
|
|
38
|
+
const RUNTIME_HEAD = /^(?:Time sampled while preparing turn|Current runtime context\.)/i;
|
|
39
|
+
const RUNTIME_TAIL = /^Elapsed since the preceding model-visible message:[^\n]*\n?/im;
|
|
40
|
+
const INJECTED_LINE = /^(?:Time sampled|Elapsed since the preceding|Browser time zone for this request:|Current runtime context\.|Current working directory:|Current DSH file policy:|Approval prompts are (?:enabled|disabled)|You are (?:the root agent|an AI agent)|Current DeepSeek Harness|A skill is a reusable|The following skills are available|Available skills:|Use the read tool|Use the glob tool|Use the grep tool|Use the bash|Do not call present|The runtime context names|Tokens prefixed with @|Non-zero exits are reported|web_search results are|create_goal may infer|Only create or modify scheduled|Use the workflow tool|Bash, formatters|Track every background job|Start independent delegations|Read an existing file|Use the pwsh|On Windows a killed process|## MCP resource servers|### MCP server:|Browser-first policy:)/i;
|
|
41
|
+
const DROP_WHOLE = /^(?:Background subagent .* finished|This is an automatically generated checkpoint|\[Automated\]|The user changed the approval policy|\[SCHEDULE REMINDER|This is a scheduled message from the user|reminders_json:|<goal_complete>)/i;
|
|
42
|
+
|
|
43
|
+
export function stripInjected(text) {
|
|
44
|
+
let value = String(text ?? '');
|
|
45
|
+
if (!value) return '';
|
|
46
|
+
value = value.replace(REMINDER_BLOCK, '\n');
|
|
47
|
+
value = value.replace(GOAL_ROUND_BLOCK, '\n');
|
|
48
|
+
if (GOAL_ROUND_HEAD.test(value.trimStart()) && GOAL_ROUND_SHAPE.test(value)) return '';
|
|
49
|
+
if (RUNTIME_HEAD.test(value.trimStart()) || value.includes('Current runtime context.')) {
|
|
50
|
+
const tail = RUNTIME_TAIL.exec(value);
|
|
51
|
+
if (tail) value = value.slice(tail.index + tail[0].length);
|
|
52
|
+
}
|
|
53
|
+
const kept = [];
|
|
54
|
+
for (const line of value.split('\n')) {
|
|
55
|
+
const trimmed = line.trim();
|
|
56
|
+
if (!trimmed) { kept.push(''); continue; }
|
|
57
|
+
if (DROP_WHOLE.test(trimmed)) break;
|
|
58
|
+
if (INJECTED_LINE.test(trimmed)) continue;
|
|
59
|
+
kept.push(line);
|
|
60
|
+
}
|
|
61
|
+
return kept.join('\n').replace(/\n{3,}/g, '\n\n').trim();
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function deriveHostTitle(user, turn = null, selfName = null) {
|
|
65
|
+
const prefixes = ['用户', '助手', 'user', 'assistant', String(selfName ?? '').trim()].filter(Boolean);
|
|
66
|
+
const strip = new RegExp(`^\\s*(?:${prefixes.join('|')})[::]\\s*`, 'i');
|
|
67
|
+
const first = String(user ?? '')
|
|
68
|
+
.split('\n')
|
|
69
|
+
.map((line) => line.replace(strip, '').trim())
|
|
70
|
+
.find(Boolean) ?? '';
|
|
71
|
+
const title = first.replace(/\s+/g, ' ').slice(0, 40).trim();
|
|
72
|
+
if (title) return title;
|
|
73
|
+
return turn ? `会话 ${turn}` : null;
|
|
74
|
+
}
|
|
75
|
+
|
|
25
76
|
export function createHostRuntime({ cortex, config = {}, logger = null } = {}) {
|
|
26
77
|
if (!cortex) throw new Error('host runtime needs a cortex service');
|
|
27
78
|
const buffers = new Map();
|
|
@@ -111,9 +162,13 @@ export function createHostRuntime({ cortex, config = {}, logger = null } = {}) {
|
|
|
111
162
|
const buffer = buffers.get(key);
|
|
112
163
|
if (!buffer) return { skipped: true, reason: 'empty' };
|
|
113
164
|
buffers.delete(key);
|
|
114
|
-
const
|
|
115
|
-
const
|
|
116
|
-
|
|
165
|
+
const maxChars = Math.max(500, Number(config.captureMaxChars) || 4000);
|
|
166
|
+
const rawUser = buffer.user.trim();
|
|
167
|
+
const user = stripInjected(rawUser).slice(0, maxChars);
|
|
168
|
+
const assistant = buffer.assistant.trim().slice(0, maxChars);
|
|
169
|
+
if (!user && !assistant) {
|
|
170
|
+
return { skipped: true, reason: rawUser ? 'injected-only' : 'empty' };
|
|
171
|
+
}
|
|
117
172
|
const text = [
|
|
118
173
|
user ? `用户:${user}` : '',
|
|
119
174
|
assistant ? `${config.persona?.selfName ?? '助手'}:${assistant}` : '',
|
|
@@ -122,13 +177,18 @@ export function createHostRuntime({ cortex, config = {}, logger = null } = {}) {
|
|
|
122
177
|
const written = cortex.write({
|
|
123
178
|
text,
|
|
124
179
|
kind: 'utterance',
|
|
125
|
-
|
|
180
|
+
// Turns whose user part was pure injected context still need a readable
|
|
181
|
+
// title; fall back to the assistant line instead of "会话 N".
|
|
182
|
+
title: deriveHostTitle(user, null, config.persona?.selfName)
|
|
183
|
+
|| deriveHostTitle(assistant, null, config.persona?.selfName)
|
|
184
|
+
|| `会话 ${effectiveTurn}`,
|
|
126
185
|
source: 'host:turn',
|
|
127
186
|
sessionId: String(session?.id ?? ''),
|
|
128
187
|
turnId: String(effectiveTurn ?? ''),
|
|
129
188
|
operationId: `host:${keyOf(session)}:${effectiveTurn ?? 0}`,
|
|
130
189
|
explicit: true,
|
|
131
190
|
importance: 0.55,
|
|
191
|
+
metadata: { capture: 'host', stripped: rawUser !== user, truncated: rawUser.length > maxChars },
|
|
132
192
|
now: at,
|
|
133
193
|
});
|
|
134
194
|
return { skipped: Boolean(written.skipped), reason: written.skipped ? written.reason : null, trace: written.trace ?? null, turn: effectiveTurn, reason };
|
package/src/host/scheduler.js
CHANGED
|
@@ -19,7 +19,19 @@ export function createScheduler({
|
|
|
19
19
|
let autoEvolveAt = 0;
|
|
20
20
|
let lastReviewAt = 0;
|
|
21
21
|
let lastSummonSyncAt = 0;
|
|
22
|
+
let lastMaintenanceAt = 0;
|
|
23
|
+
// While the vector queue still has a backlog the pass runs every two minutes
|
|
24
|
+
// (each pass only drains for a bounded slice, so it needs repetition); once
|
|
25
|
+
// the queue is empty it falls back to the normal ten-minute cadence.
|
|
26
|
+
let maintenanceGapMs = 10 * 60_000;
|
|
22
27
|
let lastGuardianDeepAt = 0;
|
|
28
|
+
// Near-duplicate merging is cheap to check and expensive to forget: without a
|
|
29
|
+
// periodic pass the merge layer stayed empty forever (dedupe only ran when a
|
|
30
|
+
// caller asked for it by hand).
|
|
31
|
+
let lastDedupeAt = 0;
|
|
32
|
+
// One wider consolidation pass a day, so the 30-minute delta trigger is not the
|
|
33
|
+
// only thing that ever looks at the store.
|
|
34
|
+
let lastDeepDay = '';
|
|
23
35
|
const autoDreamDays = new Set();
|
|
24
36
|
const edgeReviewSeen = new Set();
|
|
25
37
|
|
|
@@ -30,7 +42,7 @@ export function createScheduler({
|
|
|
30
42
|
|
|
31
43
|
async function runLifeAutomation(report) {
|
|
32
44
|
const features = cortex.config?.features ?? {};
|
|
33
|
-
if (!cortex.life || (features.autoDiary !== true && features.autoDream !== true && features.autoFeeling !== true)) return;
|
|
45
|
+
if (!cortex.life || (features.autoDiary !== true && features.autoDream !== true && features.autoFeeling !== true && features.autoSleep !== true)) return;
|
|
34
46
|
if (typeof cortex.scopeWritable === 'function' && !cortex.scopeWritable(cortex.config?.scope ?? 'global')) return;
|
|
35
47
|
const at = now();
|
|
36
48
|
const date = new Date(at);
|
|
@@ -85,6 +97,21 @@ export function createScheduler({
|
|
|
85
97
|
report.steps.autoDream = { error: error instanceof Error ? error.message : String(error) };
|
|
86
98
|
}
|
|
87
99
|
}
|
|
100
|
+
|
|
101
|
+
// Nothing used to call life.sleep() on a schedule, so `consolidateOnSleep`
|
|
102
|
+
// never had a chance to run. Sleep is only started when the host is idle and
|
|
103
|
+
// the previous sleep is at least 20h old (or none exists).
|
|
104
|
+
if (features.autoSleep === true && isIdle()) {
|
|
105
|
+
try {
|
|
106
|
+
const latestSleep = cortex.life.sleepRuns({ limit: 1 })[0] ?? null;
|
|
107
|
+
const lastAt = latestSleep ? Date.parse(latestSleep.at) : NaN;
|
|
108
|
+
if (!Number.isFinite(lastAt) || at - lastAt >= 20 * 3_600_000) {
|
|
109
|
+
report.steps.autoSleep = await cortex.life.sleep({ at });
|
|
110
|
+
}
|
|
111
|
+
} catch (error) {
|
|
112
|
+
report.steps.autoSleep = { error: error instanceof Error ? error.message : String(error) };
|
|
113
|
+
}
|
|
114
|
+
}
|
|
88
115
|
}
|
|
89
116
|
|
|
90
117
|
async function runGraphAuto(report) {
|
|
@@ -155,6 +182,61 @@ export function createScheduler({
|
|
|
155
182
|
}
|
|
156
183
|
}
|
|
157
184
|
|
|
185
|
+
/**
|
|
186
|
+
* Timestamp of the last consolidation that was NOT caused by the per-tick path.
|
|
187
|
+
* The tick path has no interval gate, so when features.consolidateOnTick is on
|
|
188
|
+
* it writes a run every minute and a naive "last run" would make the delta
|
|
189
|
+
* trigger permanently "too soon".
|
|
190
|
+
*/
|
|
191
|
+
function lastRealConsolidationAt(scopeId) {
|
|
192
|
+
try {
|
|
193
|
+
// audit has no scope column, so resolve the scope through dream_runs.
|
|
194
|
+
const row = cortex.db?.prepare?.(
|
|
195
|
+
"SELECT a.at FROM audit a JOIN dream_runs d ON d.id = a.target_id WHERE a.action = 'consolidation.run' AND a.detail_json NOT LIKE '%\"caller\":\"tick\"%' AND d.scope_id = ? ORDER BY a.at DESC LIMIT 1",
|
|
196
|
+
)?.get?.(scopeId);
|
|
197
|
+
if (row?.at) return Date.parse(row.at);
|
|
198
|
+
} catch { /* fall back to the run table */ }
|
|
199
|
+
const last = cortex.consolidation.list?.({ scopeId, limit: 1 })?.[0] ?? null;
|
|
200
|
+
return last?.at ? Date.parse(last.at) : null;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
async function runAutoConsolidate(report) {
|
|
204
|
+
const features = cortex.config?.features ?? {};
|
|
205
|
+
if (features.consolidateOnTraceDelta !== true || !cortex.consolidation?.run) return;
|
|
206
|
+
const scopeId = cortex.config?.scope ?? 'global';
|
|
207
|
+
if (typeof cortex.scopeWritable === 'function' && !cortex.scopeWritable(scopeId)) return;
|
|
208
|
+
const at = now();
|
|
209
|
+
const lastAt = lastRealConsolidationAt(scopeId);
|
|
210
|
+
// minutes → ms; the floor is one minute, not 60_000 (that would be 3.6e9 ms).
|
|
211
|
+
const minGapMs = Math.max(1, Number(features.consolidateTraceGapMinutes ?? 30)) * 60_000;
|
|
212
|
+
if (lastAt && Number.isFinite(lastAt) && at - lastAt < minGapMs) {
|
|
213
|
+
report.steps.autoConsolidate = { skipped: 'too-soon', minutesSinceLast: Math.round((at - lastAt) / 60_000) };
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
const minNewTraces = Math.max(1, Number(features.consolidateTraceDelta ?? 20));
|
|
217
|
+
const since = lastAt && Number.isFinite(lastAt) ? new Date(lastAt + 1).toISOString() : new Date(at - 24 * 3_600_000).toISOString();
|
|
218
|
+
let fresh = 0;
|
|
219
|
+
try {
|
|
220
|
+
fresh = cortex.repos?.traces?.listSince?.(scopeId, since, { limit: 500 })?.length ?? 0;
|
|
221
|
+
} catch (error) {
|
|
222
|
+
report.steps.autoConsolidate = { error: error instanceof Error ? error.message : String(error) };
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
if (fresh < minNewTraces) {
|
|
226
|
+
report.steps.autoConsolidate = { skipped: 'not-enough-new-traces', fresh, need: minNewTraces };
|
|
227
|
+
return;
|
|
228
|
+
}
|
|
229
|
+
const result = await cortex.consolidation.run({ scopeId, limit: 30, now: at, caller: 'auto-trace-delta' });
|
|
230
|
+
report.steps.autoConsolidate = {
|
|
231
|
+
fresh,
|
|
232
|
+
status: result.run.status,
|
|
233
|
+
model: result.run.model,
|
|
234
|
+
decisions: result.decisions.length,
|
|
235
|
+
applied: result.applied.length,
|
|
236
|
+
error: result.run.error ?? null,
|
|
237
|
+
};
|
|
238
|
+
}
|
|
239
|
+
|
|
158
240
|
async function runAutoEvolve(report) {
|
|
159
241
|
const features = cortex.config?.features ?? {};
|
|
160
242
|
if (features.autoEvolve !== true || !cortex.evolution?.autoEvolve) return;
|
|
@@ -169,6 +251,109 @@ export function createScheduler({
|
|
|
169
251
|
}
|
|
170
252
|
}
|
|
171
253
|
|
|
254
|
+
function localDayOf(value) {
|
|
255
|
+
const date = new Date(value);
|
|
256
|
+
return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')}`;
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
/**
|
|
260
|
+
* One deep pass a day, after deepConsolidateHour (local). The regular delta
|
|
261
|
+
* trigger only sees "20 new traces since the last real run" and 30 candidates;
|
|
262
|
+
* a day's housekeeping deserves a wider window. A fixed hour keeps the extra
|
|
263
|
+
* LLM cost predictable, and the audit row (caller=deep-daily) prevents a
|
|
264
|
+
* restart from running it twice in one day.
|
|
265
|
+
*/
|
|
266
|
+
async function runDeepConsolidate(report) {
|
|
267
|
+
if (!cortex.consolidation?.run) return;
|
|
268
|
+
if (cortex.config?.deepConsolidateOnSchedule === false) return;
|
|
269
|
+
const scopeId = cortex.config?.scope ?? 'global';
|
|
270
|
+
if (typeof cortex.scopeWritable === 'function' && !cortex.scopeWritable(scopeId)) return;
|
|
271
|
+
const at = now();
|
|
272
|
+
const hour = Math.max(0, Math.min(23, Number(cortex.config?.deepConsolidateHour ?? 4)));
|
|
273
|
+
if (new Date(at).getHours() < hour) return;
|
|
274
|
+
const day = localDayOf(at);
|
|
275
|
+
if (lastDeepDay === day) return;
|
|
276
|
+
let alreadyToday = false;
|
|
277
|
+
try {
|
|
278
|
+
const row = cortex.db?.prepare?.("SELECT at FROM audit WHERE action = 'consolidation.run' AND detail_json LIKE '%\"caller\":\"deep-daily\"%' ORDER BY at DESC LIMIT 1")?.get?.();
|
|
279
|
+
if (row?.at) alreadyToday = localDayOf(row.at) === day;
|
|
280
|
+
} catch { /* fall through to the in-memory guard */ }
|
|
281
|
+
if (alreadyToday) { lastDeepDay = day; return; }
|
|
282
|
+
try {
|
|
283
|
+
const result = await cortex.consolidation.run({
|
|
284
|
+
scopeId,
|
|
285
|
+
now: at,
|
|
286
|
+
limit: Math.max(1, Math.min(80, Number(cortex.config?.deepConsolidateLimit ?? 60))),
|
|
287
|
+
caller: 'deep-daily',
|
|
288
|
+
spread: true,
|
|
289
|
+
});
|
|
290
|
+
lastDeepDay = day;
|
|
291
|
+
report.steps.deepConsolidate = {
|
|
292
|
+
status: result.run?.status ?? null,
|
|
293
|
+
decisions: result.decisions?.length ?? 0,
|
|
294
|
+
applied: result.applied?.length ?? 0,
|
|
295
|
+
skipped: result.skipped ?? null,
|
|
296
|
+
};
|
|
297
|
+
} catch (error) {
|
|
298
|
+
report.steps.deepConsolidate = { error: error instanceof Error ? error.message : String(error) };
|
|
299
|
+
}
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
async function runAutoDedupe(report) {
|
|
303
|
+
if (!cortex.consolidation?.dedupe) return;
|
|
304
|
+
if (cortex.config?.dedupeOnSchedule === false) return;
|
|
305
|
+
const scopeId = cortex.config?.scope ?? 'global';
|
|
306
|
+
if (typeof cortex.scopeWritable === 'function' && !cortex.scopeWritable(scopeId)) return;
|
|
307
|
+
const at = now();
|
|
308
|
+
const gapHours = Math.max(1, Number(cortex.config?.dedupeGapHours ?? 6));
|
|
309
|
+
if (lastDedupeAt && at - lastDedupeAt < gapHours * 3_600_000) return;
|
|
310
|
+
try {
|
|
311
|
+
const result = await cortex.consolidation.dedupe({
|
|
312
|
+
scopeId,
|
|
313
|
+
now: at,
|
|
314
|
+
limit: Number(cortex.config?.dedupeLimit ?? 200),
|
|
315
|
+
threshold: 0.8,
|
|
316
|
+
caller: 'auto-dedupe',
|
|
317
|
+
});
|
|
318
|
+
lastDedupeAt = at;
|
|
319
|
+
report.steps.autoDedupe = {
|
|
320
|
+
status: result.run?.status ?? null,
|
|
321
|
+
applied: result.applied?.length ?? 0,
|
|
322
|
+
groups: result.decisions?.length ?? 0,
|
|
323
|
+
skipped: result.skipped ?? null,
|
|
324
|
+
};
|
|
325
|
+
} catch (error) {
|
|
326
|
+
report.steps.autoDedupe = { error: error instanceof Error ? error.message : String(error) };
|
|
327
|
+
}
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
async function runMaintenance(report) {
|
|
331
|
+
const at = now();
|
|
332
|
+
if (lastMaintenanceAt && at - lastMaintenanceAt < maintenanceGapMs) return;
|
|
333
|
+
if (typeof cortex.scopeWritable === 'function' && !cortex.scopeWritable(cortex.config?.scope ?? 'global')) return;
|
|
334
|
+
const scopeId = cortex.config?.scope ?? 'global';
|
|
335
|
+
try {
|
|
336
|
+
if (cortex.maintain) report.steps.maintain = cortex.maintain({ now: at, scopeId });
|
|
337
|
+
if (cortex.vectorMaintain) {
|
|
338
|
+
// A thousand+ traces can be missing embeddings after an upgrade. The
|
|
339
|
+
// old 40/20 per pass needed hours; the queue is cheap to drain in bigger
|
|
340
|
+
// batches because embedding is async and the pass is rare.
|
|
341
|
+
report.steps.vectorMaintain = await cortex.vectorMaintain({
|
|
342
|
+
scopeId,
|
|
343
|
+
backfill: Number(cortex.config?.vectorBackfillBatch ?? 200),
|
|
344
|
+
drain: Number(cortex.config?.vectorDrainBatch ?? 50),
|
|
345
|
+
budgetMs: Number(cortex.config?.vectorDrainBudgetMs ?? 45000),
|
|
346
|
+
});
|
|
347
|
+
const pending = Number(report.steps.vectorMaintain?.pending ?? 0);
|
|
348
|
+
const queued = Number(report.steps.vectorMaintain?.queued ?? 0);
|
|
349
|
+
maintenanceGapMs = (pending > 0 || queued > 0) ? 2 * 60_000 : 10 * 60_000;
|
|
350
|
+
}
|
|
351
|
+
lastMaintenanceAt = at;
|
|
352
|
+
} catch (error) {
|
|
353
|
+
report.steps.maintain = { error: error instanceof Error ? error.message : String(error) };
|
|
354
|
+
}
|
|
355
|
+
}
|
|
356
|
+
|
|
172
357
|
async function runOnce() {
|
|
173
358
|
if (running) return { skipped: true, reason: 'busy' };
|
|
174
359
|
running = true;
|
|
@@ -196,21 +381,52 @@ export function createScheduler({
|
|
|
196
381
|
}
|
|
197
382
|
if (consolidateOnTick && cortex.consolidation?.run) {
|
|
198
383
|
try {
|
|
199
|
-
|
|
384
|
+
// The tick path used to fire on every tick (once a minute with the live
|
|
385
|
+
// interval) — 1921 no-llm rows prove it. Even with the flag on, honour the
|
|
386
|
+
// same gap so enabling it cannot turn into a per-minute LLM call.
|
|
387
|
+
const scopeId = cortex.config?.scope ?? 'global';
|
|
388
|
+
const gapMs = Math.max(1, Number(cortex.config?.features?.consolidateTraceGapMinutes ?? 30)) * 60_000;
|
|
389
|
+
const recent = cortex.consolidation.list?.({ scopeId, limit: 1 })?.[0] ?? null;
|
|
390
|
+
const recentAt = recent?.at ? Date.parse(recent.at) : null;
|
|
391
|
+
if (recentAt && Number.isFinite(recentAt) && now() - recentAt < gapMs) {
|
|
392
|
+
report.steps.consolidation = { skipped: 'too-soon', minutesSinceLast: Math.round((now() - recentAt) / 60_000) };
|
|
393
|
+
} else {
|
|
394
|
+
report.steps.consolidation = await cortex.consolidation.run({ scopeId, now: now(), limit: 10, caller: 'tick' });
|
|
395
|
+
}
|
|
200
396
|
} catch (error) {
|
|
201
397
|
report.steps.consolidation = { error: error instanceof Error ? error.message : String(error) };
|
|
202
398
|
}
|
|
203
399
|
}
|
|
400
|
+
try {
|
|
401
|
+
await runAutoConsolidate(report);
|
|
402
|
+
} catch (error) {
|
|
403
|
+
report.steps.autoConsolidate = { error: error instanceof Error ? error.message : String(error) };
|
|
404
|
+
}
|
|
405
|
+
try {
|
|
406
|
+
await runDeepConsolidate(report);
|
|
407
|
+
} catch (error) {
|
|
408
|
+
report.steps.deepConsolidate = { error: error instanceof Error ? error.message : String(error) };
|
|
409
|
+
}
|
|
204
410
|
try {
|
|
205
411
|
await runAutoEvolve(report);
|
|
206
412
|
} catch (error) {
|
|
207
413
|
report.steps.autoEvolve = { error: error instanceof Error ? error.message : String(error) };
|
|
208
414
|
}
|
|
415
|
+
try {
|
|
416
|
+
await runAutoDedupe(report);
|
|
417
|
+
} catch (error) {
|
|
418
|
+
report.steps.autoDedupe = { error: error instanceof Error ? error.message : String(error) };
|
|
419
|
+
}
|
|
209
420
|
try {
|
|
210
421
|
await runGraphAuto(report);
|
|
211
422
|
} catch (error) {
|
|
212
423
|
report.steps.autoGraph = { error: error instanceof Error ? error.message : String(error) };
|
|
213
424
|
}
|
|
425
|
+
try {
|
|
426
|
+
await runMaintenance(report);
|
|
427
|
+
} catch (error) {
|
|
428
|
+
report.steps.maintain = { error: error instanceof Error ? error.message : String(error) };
|
|
429
|
+
}
|
|
214
430
|
try {
|
|
215
431
|
await runLifeAutomation(report);
|
|
216
432
|
} catch (error) {
|
|
@@ -237,6 +453,11 @@ export function createScheduler({
|
|
|
237
453
|
} catch (error) {
|
|
238
454
|
report.steps.guardian = { error: error instanceof Error ? error.message : String(error) };
|
|
239
455
|
}
|
|
456
|
+
try {
|
|
457
|
+
if (cortex.emitTick) cortex.emitTick(report);
|
|
458
|
+
} catch (error) {
|
|
459
|
+
report.steps.tick = { error: error instanceof Error ? error.message : String(error) };
|
|
460
|
+
}
|
|
240
461
|
running = false;
|
|
241
462
|
return report;
|
|
242
463
|
}
|
|
@@ -259,5 +480,5 @@ export function createScheduler({
|
|
|
259
480
|
return true;
|
|
260
481
|
}
|
|
261
482
|
|
|
262
|
-
return { start, stop, runOnce, status: () => ({ running: Boolean(timer), intervalMs: Math.max(5_000, Number(intervalMs) || 60_000) }) };
|
|
483
|
+
return { start, stop, runOnce, status: () => ({ running: Boolean(timer), intervalMs: Math.max(5_000, Number(intervalMs) || 60_000), maintenanceGapMs }) };
|
|
263
484
|
}
|
package/src/llm/adapter.js
CHANGED
|
@@ -6,7 +6,9 @@
|
|
|
6
6
|
export function createLlmAdapter({ ctx = null, llm = null, defaultModel = null, agents = null, logger = null, persona = null } = {}) {
|
|
7
7
|
const selfName = typeof persona?.selfName === 'string' && persona.selfName.trim() ? persona.selfName.trim() : '助手';
|
|
8
8
|
const userAddress = typeof persona?.userAddress === 'string' && persona.userAddress.trim() ? persona.userAddress.trim() : '你';
|
|
9
|
-
const personaDescription =
|
|
9
|
+
const personaDescription = typeof persona?.description === 'string' && persona.description.trim()
|
|
10
|
+
? persona.description.trim()
|
|
11
|
+
: `你是${selfName},一个本地记忆助手。`;
|
|
10
12
|
const get = (name) => {
|
|
11
13
|
try {
|
|
12
14
|
if (ctx?.get) return ctx.get(name);
|
|
@@ -34,10 +36,25 @@ export function createLlmAdapter({ ctx = null, llm = null, defaultModel = null,
|
|
|
34
36
|
return Boolean(service && typeof service.stream === 'function' && selection());
|
|
35
37
|
}
|
|
36
38
|
|
|
37
|
-
|
|
39
|
+
// Last failure reason, so callers can record *why* a call came back empty
|
|
40
|
+
// instead of a bare `llm-empty` that hides four different causes. `onReason`
|
|
41
|
+
// scopes the reason to one call: concurrent callers (dream / feeling /
|
|
42
|
+
// consolidate) must not read each other's failure.
|
|
43
|
+
let lastFailure = null;
|
|
44
|
+
const failure = (reason, onReason = null) => {
|
|
45
|
+
lastFailure = reason;
|
|
46
|
+
if (typeof onReason === 'function') {
|
|
47
|
+
try { onReason(reason); } catch { /* a bad callback must not mask the failure */ }
|
|
48
|
+
}
|
|
49
|
+
return null;
|
|
50
|
+
};
|
|
51
|
+
|
|
52
|
+
async function complete({ system = '', prompt = '', maxTokens = 400, temperature = 0.7, purpose = 'cortex', onReason = null } = {}) {
|
|
53
|
+
lastFailure = null;
|
|
54
|
+
const fail = (reason) => failure(reason, onReason);
|
|
38
55
|
const service = get('llm');
|
|
39
56
|
const sel = selection();
|
|
40
|
-
if (!service || typeof service.stream !== 'function' || !sel) return
|
|
57
|
+
if (!service || typeof service.stream !== 'function' || !sel) return fail('no-selection');
|
|
41
58
|
let sessionId = null;
|
|
42
59
|
try {
|
|
43
60
|
const agent = get('agents')?.currentInitiator?.();
|
|
@@ -65,16 +82,20 @@ export function createLlmAdapter({ ctx = null, llm = null, defaultModel = null,
|
|
|
65
82
|
finish = chunk.reason ?? null;
|
|
66
83
|
if (finish?.kind === 'error') {
|
|
67
84
|
logger?.warn?.(`cortex llm finish error: ${JSON.stringify(finish).slice(0, 1000)}`);
|
|
68
|
-
return
|
|
85
|
+
return fail('finish-error');
|
|
69
86
|
}
|
|
70
87
|
}
|
|
71
88
|
}
|
|
72
89
|
} catch (error) {
|
|
73
90
|
logger?.warn?.(`cortex llm failed: ${error instanceof Error ? error.message : String(error)}`);
|
|
74
|
-
return
|
|
91
|
+
return fail('exception');
|
|
92
|
+
}
|
|
93
|
+
if (!text.trim()) {
|
|
94
|
+
logger?.warn?.(`cortex llm empty finish: ${JSON.stringify(finish).slice(0, 500)}`);
|
|
95
|
+
const kind = finish?.kind ?? finish?.type ?? 'no-finish';
|
|
96
|
+
return fail(`empty-text:${kind}`);
|
|
75
97
|
}
|
|
76
|
-
|
|
77
|
-
return text.trim() || null;
|
|
98
|
+
return text.trim();
|
|
78
99
|
}
|
|
79
100
|
|
|
80
101
|
async function dream({ pieces = [], emotions = '', web = '' } = {}) {
|
|
@@ -159,5 +180,5 @@ export function createLlmAdapter({ ctx = null, llm = null, defaultModel = null,
|
|
|
159
180
|
});
|
|
160
181
|
}
|
|
161
182
|
|
|
162
|
-
return { available, complete, dream, diary, feeling, reviewEdge, summarize, selection };
|
|
183
|
+
return { available, complete, dream, diary, feeling, reviewEdge, summarize, selection, lastFailure: () => lastFailure };
|
|
163
184
|
}
|