dsh-cross-memory 0.2.12 → 0.2.14
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 +55 -16
- package/docs/DETAIL.md +13 -10
- package/docs/DETAIL.zh.md +13 -10
- package/lib/backfill.js +32 -1
- package/lib/client.js +3 -3
- package/lib/consolidate.js +41 -39
- package/lib/dense.js +47 -15
- package/lib/extract.js +39 -11
- package/lib/gate.js +35 -19
- package/lib/index.js +221 -131
- package/lib/mcp.js +330 -0
- package/lib/notify.js +10 -5
- package/lib/persona.js +99 -1
- package/lib/raw-recall.js +18 -7
- package/lib/reflection.js +10 -1
- package/lib/state.js +19 -7
- package/lib/storage.js +11 -1
- package/lib/sync.js +36 -14
- package/lib/test/archive.test.js +19 -0
- package/lib/test/consolidate.test.js +48 -10
- package/lib/test/extract.test.js +30 -1
- package/lib/test/loops.test.js +3 -2
- package/lib/test/mcp.test.js +103 -0
- package/lib/test/notices.test.js +67 -0
- package/lib/test/persona.test.js +40 -1
- package/lib/test/recall.test.js +54 -1
- package/lib/test/reflection.test.js +60 -1
- package/lib/test/subagent-contract.test.js +18 -12
- package/lib/test/sync.test.js +4 -0
- package/lib/tool.js +4 -3
- package/lib/types/backfill.d.ts +5 -0
- package/lib/types/consolidate.d.ts +34 -51
- package/lib/types/dense.d.ts +7 -2
- package/lib/types/extract.d.ts +14 -0
- package/lib/types/gate.d.ts +4 -0
- package/lib/types/index.d.ts +10 -0
- package/lib/types/mcp.d.ts +184 -0
- package/lib/types/notify.d.ts +3 -2
- package/lib/types/persona.d.ts +17 -0
- package/lib/types/raw-recall.d.ts +1 -0
- package/lib/types/sync.d.ts +7 -5
- package/lib/types/test/mcp.test.d.ts +1 -0
- package/package.json +14 -7
package/lib/dense.js
CHANGED
|
@@ -15,8 +15,8 @@
|
|
|
15
15
|
*
|
|
16
16
|
* @module dsh-cross-memory/dense
|
|
17
17
|
*/
|
|
18
|
-
import { createHash } from 'node:crypto';
|
|
19
|
-
import { mkdir, readFile, writeFile } from 'node:fs/promises';
|
|
18
|
+
import { createHash, randomUUID } from 'node:crypto';
|
|
19
|
+
import { mkdir, readFile, rename, unlink, writeFile } from 'node:fs/promises';
|
|
20
20
|
import { dirname } from 'node:path';
|
|
21
21
|
/** Where the embedding service is reached; the harness never calls outside the machine by default. */
|
|
22
22
|
export const DEFAULT_DENSE_URL = 'http://127.0.0.1:11434';
|
|
@@ -49,8 +49,14 @@ function normalize(vector) {
|
|
|
49
49
|
out[index] = vector[index] / norm;
|
|
50
50
|
return out;
|
|
51
51
|
}
|
|
52
|
+
function isConnRefused(error) {
|
|
53
|
+
if (typeof error !== 'object' || error === null)
|
|
54
|
+
return false;
|
|
55
|
+
const record = error;
|
|
56
|
+
return record.code === 'ECONNREFUSED' || record.cause?.code === 'ECONNREFUSED';
|
|
57
|
+
}
|
|
52
58
|
/** One embedding call, retried twice: ollama drops the first request after idle. */
|
|
53
|
-
async function callService(url, model, texts) {
|
|
59
|
+
async function callService(url, model, texts, timeoutMs = 5_000) {
|
|
54
60
|
const endpoint = `${url.replace(/\/+$/u, '')}/api/embed`;
|
|
55
61
|
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
56
62
|
try {
|
|
@@ -58,6 +64,7 @@ async function callService(url, model, texts) {
|
|
|
58
64
|
method: 'POST',
|
|
59
65
|
headers: { 'content-type': 'application/json' },
|
|
60
66
|
body: JSON.stringify({ model, input: texts }),
|
|
67
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
61
68
|
});
|
|
62
69
|
if (!response.ok)
|
|
63
70
|
throw new Error(`embedding service ${response.status}: ${await response.text()}`);
|
|
@@ -69,7 +76,7 @@ async function callService(url, model, texts) {
|
|
|
69
76
|
return vectors.map((vector) => normalize(Float32Array.from(vector)));
|
|
70
77
|
}
|
|
71
78
|
catch (error) {
|
|
72
|
-
if (attempt === 2)
|
|
79
|
+
if (attempt === 2 || isConnRefused(error))
|
|
73
80
|
throw error;
|
|
74
81
|
await new Promise((resolve) => setTimeout(resolve, 600));
|
|
75
82
|
}
|
|
@@ -80,45 +87,70 @@ async function callService(url, model, texts) {
|
|
|
80
87
|
* Embed texts, reusing the on-disk cache.
|
|
81
88
|
*
|
|
82
89
|
* Failures propagate: the caller decides whether to fall back. The cache is
|
|
83
|
-
* written only after every batch succeeded, so a partial run never
|
|
90
|
+
* written atomically only after every batch succeeded, so a partial run never
|
|
91
|
+
* poisons it. Ephemeral texts (like one-off queries) can pass `persistCount`
|
|
92
|
+
* to avoid bloating the on-disk cache with unshared query vectors.
|
|
84
93
|
*
|
|
85
94
|
* @param texts - texts to embed, in order.
|
|
86
95
|
* @param options - service location, model, and cache directory.
|
|
96
|
+
* @param persistCount - how many leading items belong in the persistent cache (defaults to all).
|
|
87
97
|
* @returns one unit vector per text.
|
|
88
98
|
*/
|
|
89
|
-
export async function embed(texts, options) {
|
|
99
|
+
export async function embed(texts, options, persistCount = texts.length) {
|
|
90
100
|
const path = `${options.cacheDir}/dense-${options.model.replace(/[^a-z0-9._-]/giu, '_')}.json`;
|
|
91
101
|
let cache = { model: options.model, vectors: {} };
|
|
92
102
|
try {
|
|
93
103
|
const parsed = JSON.parse(await readFile(path, 'utf8'));
|
|
94
|
-
if (parsed.model === options.model && typeof parsed.vectors === 'object')
|
|
104
|
+
if (parsed.model === options.model && typeof parsed.vectors === 'object' && parsed.vectors !== null)
|
|
95
105
|
cache = parsed;
|
|
96
106
|
}
|
|
97
107
|
catch {
|
|
98
108
|
cache = { model: options.model, vectors: {} };
|
|
99
109
|
}
|
|
100
110
|
const missing = [];
|
|
111
|
+
const ephemeral = new Map();
|
|
101
112
|
const seen = new Set();
|
|
102
|
-
for (
|
|
113
|
+
for (let index = 0; index < texts.length; index += 1) {
|
|
114
|
+
const text = texts[index];
|
|
103
115
|
const key = hashOf(text);
|
|
104
116
|
if (cache.vectors[key] !== undefined || seen.has(key))
|
|
105
117
|
continue;
|
|
106
118
|
seen.add(key);
|
|
107
|
-
missing.push({ key, text });
|
|
119
|
+
missing.push({ key, text, persist: index < persistCount });
|
|
108
120
|
}
|
|
109
121
|
const BATCH = 16;
|
|
122
|
+
let persistedNew = false;
|
|
110
123
|
for (let start = 0; start < missing.length; start += BATCH) {
|
|
111
124
|
const batch = missing.slice(start, start + BATCH);
|
|
125
|
+
const vectors = await callService(options.url, options.model, batch.map((item) => item.text), options.timeoutMs);
|
|
112
126
|
for (let index = 0; index < batch.length; index += 1) {
|
|
113
|
-
const
|
|
114
|
-
|
|
127
|
+
const encoded = encode(vectors[index]);
|
|
128
|
+
const item = batch[index];
|
|
129
|
+
if (item.persist) {
|
|
130
|
+
cache.vectors[item.key] = encoded;
|
|
131
|
+
persistedNew = true;
|
|
132
|
+
}
|
|
133
|
+
else {
|
|
134
|
+
ephemeral.set(item.key, encoded);
|
|
135
|
+
}
|
|
115
136
|
}
|
|
116
137
|
}
|
|
117
|
-
if (
|
|
138
|
+
if (persistedNew) {
|
|
118
139
|
await mkdir(dirname(path), { recursive: true });
|
|
119
|
-
|
|
140
|
+
const tmp = `${path}.${process.pid}.${randomUUID()}.tmp`;
|
|
141
|
+
try {
|
|
142
|
+
await writeFile(tmp, JSON.stringify(cache));
|
|
143
|
+
await rename(tmp, path);
|
|
144
|
+
}
|
|
145
|
+
catch (error) {
|
|
146
|
+
await unlink(tmp).catch(() => undefined);
|
|
147
|
+
throw error;
|
|
148
|
+
}
|
|
120
149
|
}
|
|
121
|
-
return texts.map((text) =>
|
|
150
|
+
return texts.map((text) => {
|
|
151
|
+
const key = hashOf(text);
|
|
152
|
+
return decode(cache.vectors[key] ?? ephemeral.get(key) ?? '');
|
|
153
|
+
});
|
|
122
154
|
}
|
|
123
155
|
/**
|
|
124
156
|
* Cosine similarity of two unit vectors (a dot product).
|
|
@@ -146,7 +178,7 @@ export async function denseScores(entries, query, options) {
|
|
|
146
178
|
if (entries.length === 0 || query.trim().length === 0)
|
|
147
179
|
return scores;
|
|
148
180
|
try {
|
|
149
|
-
const vectors = await embed([...entries.map(documentText), query], options);
|
|
181
|
+
const vectors = await embed([...entries.map(documentText), query], options, entries.length);
|
|
150
182
|
const queryVector = vectors[vectors.length - 1];
|
|
151
183
|
if (queryVector.length === 0)
|
|
152
184
|
return scores;
|
package/lib/extract.js
CHANGED
|
@@ -80,6 +80,7 @@ export const EXTRACT_SYSTEM = [
|
|
|
80
80
|
'NO POINTER MEMORIES: do not write 「详见 docs/某报告」「见某文档 §5」 and do not store a review report as a pointer to itself. The body must carry the FACT — the mechanism, the number, the decision, the trap — so a later session can act without opening anything. A pointer is only worth writing when the fact is nowhere else and the document is the authority; even then, state the fact first and name the document as a reference.',
|
|
81
81
|
'ORDER what you keep by value, and keep at most the requested number: 约定/承诺 > 日期/改口/冲突 > 身份/称呼/边界/第三方人物与变化 > 偏好/计划 > 其他明确事实. Greetings, small talk, repeated restatements and ordinary daily log flow are not worth a memory; when nothing qualifies, return nothing rather than padding.',
|
|
82
82
|
'REPORTS: when the transcript is an implementation/audit/review report (often a subagent\'s), record what the report LEARNED — the mechanism, the interface trap, the root cause, the measured result, the open gap — and skip what it was ASKED to do: the task boundary ("只改这 5 个文件", "不要 git commit"), the verification commands, the review verdict, the commit hash. Those expire with the task; the finding does not.',
|
|
83
|
+
'NO ROUTINE PATROL LOGS: do NOT record single readings from routine patrols or daily health checks — such as today\'s disk size (".dsh 1.72 GiB"), "0 items cleaned / no changes today", or periodic app-update check counts ("19 项有更新", "某软件仍未升级"). Only record a durable root cause, a new rule, or a structural change discovered during a patrol.',
|
|
83
84
|
'',
|
|
84
85
|
'Write every title and body in Simplified Chinese. Keep paths, commands, identifiers, product names and error strings exactly as they are.',
|
|
85
86
|
'The injected summary shows only the title and roughly the first 100 characters of the body (the budget forces short previews), so lead with the trigger and the decision; put the detail after.',
|
|
@@ -122,8 +123,9 @@ export const EXTRACT_SYSTEM = [
|
|
|
122
123
|
'- "dueAt" only when a deadline was actually said, as ISO date or date-time. Never invent one: a loop without a deadline is a note, and nagging somebody about a note turns help into supervision.',
|
|
123
124
|
'- PROGRESS: when the user reports that part of an existing obligation is done ("先还一件,还剩两件"), the loop text MUST be the REMAINING part with the original promise\'s wording kept ("还剩两件夜班见闻(原欠三件)"), because the ledger recognises it as the same promise and replaces the old amount. A loop that still states the full original amount ("三天内讲完欠的三件") is WRONG after a progress report: it leaves the ledger owing what is already done. Skip the obligation entirely only when nothing is left.',
|
|
124
125
|
'- Skip what the session shows as already done, and skip the assistant\'s own to-dos. An empty array is the normal result.',
|
|
126
|
+
'- CLOSING LOOPS: when "Current open loops" are listed below and the transcript clearly shows one of them has been completed, return its exact id in "closedLoops":[string]. Only close a loop when the transcript proves it is done.',
|
|
125
127
|
'Prefer few high-value memories over many trivial ones. Return at most the requested number. If the transcript only supports three, return three: padding a short session with one-off detail is how noise gets into the store and pushes real memories out of the summary.',
|
|
126
|
-
'Reply with JSON only, no prose and no code fence: {"memories":[{"scope":"global"|"project","kind":string,"title":string,"body":string,"tags":string[],"keys":string[],"entities":string[],"appliesTo":string,"quote":string,"voice":"user"|"assistant"}],"loops":[{"text":string,"dueAt":string?}],"summary":string}',
|
|
128
|
+
'Reply with JSON only, no prose and no code fence: {"memories":[{"scope":"global"|"project","kind":string,"title":string,"body":string,"tags":string[],"keys":string[],"entities":string[],"appliesTo":string,"quote":string,"voice":"user"|"assistant"}],"loops":[{"text":string,"dueAt":string?}],"closedLoops":[string],"summary":string}',
|
|
127
129
|
'Write the "memories" array first and the "summary" paragraph last: the reply is capped, and a summary written first can spend the whole budget before the first memory is complete.',
|
|
128
130
|
'Write "summary" as one paragraph (2-4 sentences) saying what this session was about — the task, the decisions, and anything that would help someone judge the memories above later. It is stored as the evidence behind them.',
|
|
129
131
|
'When nothing is worth remembering, reply exactly {"memories":[],"summary":""}.'
|
|
@@ -182,6 +184,10 @@ export const EXTRACT_JSON_SCHEMA = {
|
|
|
182
184
|
},
|
|
183
185
|
},
|
|
184
186
|
},
|
|
187
|
+
closedLoops: {
|
|
188
|
+
type: 'array',
|
|
189
|
+
items: { type: 'string' },
|
|
190
|
+
},
|
|
185
191
|
summary: { type: 'string' },
|
|
186
192
|
},
|
|
187
193
|
};
|
|
@@ -239,6 +245,7 @@ const SECRET_PATTERNS = [
|
|
|
239
245
|
/\beyJ[\w-]{10,}\.[\w-]{10,}\.[\w-]{10,}\b/gu,
|
|
240
246
|
/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?-----END [A-Z ]*PRIVATE KEY-----/gu,
|
|
241
247
|
/\b(?:api[_-]?key|apikey|access[_-]?token|auth[_-]?token|client[_-]?secret|password|passwd|secret|token)\b\s*[:=]\s*["']?[^\s"',;]{8,}["']?/giu,
|
|
248
|
+
/(?:(?:管理|登录|管理员|默认|root|wifi|路由器)?(?:密码|口令))\s*(?:[:=:为是]\s*|\s+)(?![不无别空未缺占位示例])["'「『]?[A-Za-z0-9!@#$%^&*_.-]{4,}["'」』]?/giu,
|
|
242
249
|
/\bBearer\s+[\w.-]{20,}/gu,
|
|
243
250
|
];
|
|
244
251
|
/**
|
|
@@ -388,17 +395,25 @@ export function collectExtractionWindow(session, afterSeq, maxMessages, maxChars
|
|
|
388
395
|
* @returns the route, or `undefined` when no route can be resolved.
|
|
389
396
|
*/
|
|
390
397
|
export function resolveLlmRoute(session, provider, model, fallback) {
|
|
391
|
-
|
|
392
|
-
|
|
398
|
+
const p = provider?.trim() ?? '';
|
|
399
|
+
const m = model?.trim() ?? '';
|
|
400
|
+
if (p.length > 0 && m.length > 0)
|
|
401
|
+
return { provider: p, model: m };
|
|
393
402
|
const header = session.requestHeader();
|
|
394
403
|
if (header !== undefined) {
|
|
395
404
|
const config = header.config;
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
405
|
+
const hp = typeof config.provider === 'string' ? config.provider.trim() : '';
|
|
406
|
+
const hm = typeof config.model === 'string' ? config.model.trim() : '';
|
|
407
|
+
if (hp.length > 0 && hm.length > 0) {
|
|
408
|
+
return config.reasoningEffort === undefined
|
|
409
|
+
? { provider: hp, model: hm }
|
|
410
|
+
: { provider: hp, model: hm, reasoningEffort: config.reasoningEffort };
|
|
411
|
+
}
|
|
399
412
|
}
|
|
400
|
-
|
|
401
|
-
|
|
413
|
+
const fp = fallback.provider?.trim() ?? '';
|
|
414
|
+
const fm = fallback.model?.trim() ?? '';
|
|
415
|
+
if (fp.length > 0 && fm.length > 0) {
|
|
416
|
+
return { provider: fp, model: fm };
|
|
402
417
|
}
|
|
403
418
|
return undefined;
|
|
404
419
|
}
|
|
@@ -418,7 +433,7 @@ export function resolveLlmRoute(session, provider, model, fallback) {
|
|
|
418
433
|
* @returns the drafts, the evidence summary, and how many were over the cap.
|
|
419
434
|
*/
|
|
420
435
|
export function parseExtraction(text, maxMemories, sessionId) {
|
|
421
|
-
const result = { drafts: [], loops: [], summary: '', dropped: 0 };
|
|
436
|
+
const result = { drafts: [], loops: [], closedLoops: [], summary: '', dropped: 0 };
|
|
422
437
|
const trimmed = text.trim().replace(/^```(?:json)?\s*/iu, '').replace(/```$/u, '').trim();
|
|
423
438
|
const start = trimmed.indexOf('{');
|
|
424
439
|
const end = trimmed.lastIndexOf('}');
|
|
@@ -505,6 +520,9 @@ export function parseExtraction(text, maxMemories, sessionId) {
|
|
|
505
520
|
result.drafts = usable.slice(0, Math.max(0, maxMemories));
|
|
506
521
|
result.dropped = usable.length - result.drafts.length;
|
|
507
522
|
result.loops = parseLoops(envelope.loops);
|
|
523
|
+
result.closedLoops = Array.isArray(envelope.closedLoops)
|
|
524
|
+
? [...new Set(envelope.closedLoops.filter((id) => typeof id === 'string' && id.trim().length > 0).map((id) => id.trim()))].slice(0, 20)
|
|
525
|
+
: [];
|
|
508
526
|
return result;
|
|
509
527
|
}
|
|
510
528
|
/**
|
|
@@ -650,7 +668,9 @@ const ANNOTATED_DATE = /^(\d{4}-\d{2}-\d{2})/u;
|
|
|
650
668
|
* shape as the reference implementation this was adapted from.
|
|
651
669
|
*/
|
|
652
670
|
const WORK_SALIENCE_STRONG = /今天|明天|昨天|前天|后天|大后天|下周|上周|这周|月底|月初|年初|年底|星期[一二三四五六日天]|周[一二三四五六日天]|\d{1,2}\s*[月日号]|\d{4}\s*[-/年]|\d{1,2}\s*[点时]|答应|约定|承诺|说好|提醒|记得|别忘|改口|说错|更正|其实|矛盾|两版|之前说|截止|到期|欠|借|还|决定|口径|规范|流程|必须|一律|禁止|不得|要求|确认|验收|发布|上线|部署|迁移|升级|回滚|报价|人天|合同|投标|方案|需求|修复|缺陷|根因|新增|改动|实现|评审|审计|测试|用例|报告|接口|字段|脚本|版本|提交|合并|分支|构建/gu;
|
|
653
|
-
const WORK_SALIENCE_WEAK =
|
|
671
|
+
const WORK_SALIENCE_WEAK = /叫|称呼|名字|负责|接手|登记|换|工作|职业|同事|师傅|老板|客户|供应商|喜欢|讨厌|不吃|不要|不能|不想|边界|打算|计划|准备|要去|想去|接口|字段|配置|权限|分支|提交|合并|构建|报错|异常|失败|超时|崩溃|日志|数据|数据库|表|文件|目录|路径|仓库|服务|端口|环境|依赖|锁|并发|幂等|回执|部署|切页|归档|回填|识别|查验|投递|生成|打包|镜像|快照/gui;
|
|
672
|
+
/** Routine patrol / daily health-check readings that must not be promoted to must-cover. */
|
|
673
|
+
const PATROL_NOISE_TURN = /(?:今日无变化|0\s*项清理|无待归位会话|版本对比巡检.*\d+\s*项|巡检.*\b\d+(?:\.\d+)?\s*(?:GiB|GB|MB)\b|\b\d+(?:\.\d+)?\s*(?:GiB|GB|MB)\b.*巡检)/u;
|
|
654
674
|
/** The salience score of one text: strong hits count double. */
|
|
655
675
|
function workSalience(text) {
|
|
656
676
|
const strong = (text.match(WORK_SALIENCE_STRONG) ?? []).length;
|
|
@@ -671,6 +691,7 @@ function workSalience(text) {
|
|
|
671
691
|
*/
|
|
672
692
|
export function mustCoverCandidates(sources, max = 6) {
|
|
673
693
|
const rows = sources
|
|
694
|
+
.filter((source) => !PATROL_NOISE_TURN.test(source.text))
|
|
674
695
|
.map((source) => ({
|
|
675
696
|
seq: source.seq,
|
|
676
697
|
score: workSalience(source.text),
|
|
@@ -769,6 +790,7 @@ export async function runExtraction(llm, request) {
|
|
|
769
790
|
return { kind: 'none', reason: 'no-route' };
|
|
770
791
|
const maxMemories = effectiveMaxMemories(request.maxMemories, request.window.messages);
|
|
771
792
|
const known = request.knownTitles ?? [];
|
|
793
|
+
const openLoops = request.openLoops ?? [];
|
|
772
794
|
const framed = [
|
|
773
795
|
`Workspace scope label: ${request.projectLabel}`,
|
|
774
796
|
`Today's date is ${localDate()} (the user's local date). Resolve every relative time in the transcript against it.`,
|
|
@@ -779,6 +801,11 @@ export async function runExtraction(llm, request) {
|
|
|
779
801
|
...known.map((title) => `- ${title}`),
|
|
780
802
|
'If the transcript adds to (or corrects) one of those, reuse its EXACT title so that entry is updated instead of duplicated. Only invent a new title for a genuinely new fact.',
|
|
781
803
|
],
|
|
804
|
+
...openLoops.length === 0 ? [] : [
|
|
805
|
+
'',
|
|
806
|
+
'Current open loops (return an id in "closedLoops" ONLY if the transcript clearly shows it is now DONE):',
|
|
807
|
+
...openLoops.map((loop) => `- [${loop.id}] ${loop.text}`),
|
|
808
|
+
],
|
|
782
809
|
// The must-cover list is built locally from the window, so it costs no model
|
|
783
810
|
// call: the turns most likely to be skipped (a new person, a changed name, a
|
|
784
811
|
// one-line agreement, an interface trap) are named up front.
|
|
@@ -844,6 +871,7 @@ export async function runExtraction(llm, request) {
|
|
|
844
871
|
kind: 'memories',
|
|
845
872
|
drafts: timed,
|
|
846
873
|
loops: salvaged.loops,
|
|
874
|
+
...salvaged.closedLoops.length === 0 ? {} : { closedLoops: salvaged.closedLoops },
|
|
847
875
|
summary: salvaged.summary,
|
|
848
876
|
dropped: salvaged.dropped,
|
|
849
877
|
unsupported: bound.unsupported,
|
|
@@ -866,7 +894,7 @@ export async function runExtraction(llm, request) {
|
|
|
866
894
|
if (bound.drafts.length === 0) {
|
|
867
895
|
return { kind: 'none', reason: 'unsupported-evidence', route, ...usage === undefined ? {} : { usage } };
|
|
868
896
|
}
|
|
869
|
-
return { kind: 'memories', drafts: timed, loops: parsed.loops, summary: parsed.summary, dropped: parsed.dropped, unsupported: bound.unsupported, ...bound.dropped.length === 0 ? {} : { droppedEvidence: bound.dropped }, route, ...usage === undefined ? {} : { usage } };
|
|
897
|
+
return { kind: 'memories', drafts: timed, loops: parsed.loops, ...parsed.closedLoops.length === 0 ? {} : { closedLoops: parsed.closedLoops }, summary: parsed.summary, dropped: parsed.dropped, unsupported: bound.unsupported, ...bound.dropped.length === 0 ? {} : { droppedEvidence: bound.dropped }, route, ...usage === undefined ? {} : { usage } };
|
|
870
898
|
}
|
|
871
899
|
/**
|
|
872
900
|
* Close a JSON reply the output cap cut in half.
|
package/lib/gate.js
CHANGED
|
@@ -43,6 +43,8 @@ export const GATE_JSON_SCHEMA = {
|
|
|
43
43
|
reason: { type: 'string' },
|
|
44
44
|
},
|
|
45
45
|
};
|
|
46
|
+
/** Output token cap for one gate call (leaves room for reasoning tokens). */
|
|
47
|
+
export const DEFAULT_GATE_MAX_OUTPUT_TOKENS = 2048;
|
|
46
48
|
/**
|
|
47
49
|
* Ask whether any of these is worth saying now.
|
|
48
50
|
*
|
|
@@ -67,7 +69,7 @@ export async function gateNotices(request) {
|
|
|
67
69
|
...request.persona === undefined || request.persona.trim().length === 0
|
|
68
70
|
? []
|
|
69
71
|
: ['## Who the user is', request.persona.trim(), ''],
|
|
70
|
-
'##
|
|
72
|
+
'## Candidates',
|
|
71
73
|
...request.candidates.map((candidate) => `- id: ${candidate.id}\n title: ${candidate.title}\n detail: ${candidate.detail}`),
|
|
72
74
|
].join('\n');
|
|
73
75
|
const messages = [createUserMessage({
|
|
@@ -79,16 +81,22 @@ export async function gateNotices(request) {
|
|
|
79
81
|
model: route.model,
|
|
80
82
|
messages,
|
|
81
83
|
system: GATE_SYSTEM,
|
|
82
|
-
maxTokens:
|
|
84
|
+
maxTokens: request.maxOutputTokens ?? DEFAULT_GATE_MAX_OUTPUT_TOKENS,
|
|
83
85
|
purpose: 'compaction',
|
|
84
86
|
sessionId: request.session.id,
|
|
85
87
|
signal: AbortSignal.any([request.signal, AbortSignal.timeout(request.timeoutMs)]),
|
|
86
88
|
};
|
|
87
89
|
let text = '';
|
|
90
|
+
let finishKind = 'stop';
|
|
88
91
|
try {
|
|
89
92
|
const assembler = new BlockAssembler();
|
|
90
93
|
for await (const chunk of request.llm.stream(options))
|
|
91
94
|
assembler.push(chunk);
|
|
95
|
+
const finish = assembler.finish;
|
|
96
|
+
finishKind = finish.kind;
|
|
97
|
+
if (finish.kind === 'error' || finish.kind === 'aborted') {
|
|
98
|
+
return { deliver: new Set(), reason: `gate call ${finish.kind}: ${finish.failure.message}`, skipped: 'failed' };
|
|
99
|
+
}
|
|
92
100
|
text = assembler.blocks()
|
|
93
101
|
.filter((block) => block.type === 'text')
|
|
94
102
|
.map((block) => block.text)
|
|
@@ -97,6 +105,9 @@ export async function gateNotices(request) {
|
|
|
97
105
|
catch (error) {
|
|
98
106
|
return { deliver: new Set(), reason: `gate call failed: ${error instanceof Error ? error.message : String(error)}`, skipped: 'failed' };
|
|
99
107
|
}
|
|
108
|
+
if (finishKind === 'max-tokens' && text.trim().length === 0) {
|
|
109
|
+
return { deliver: new Set(), reason: 'gate reply hit maxTokens before emitting text', skipped: 'failed' };
|
|
110
|
+
}
|
|
100
111
|
const parsed = parseGateReply(text, request.candidates);
|
|
101
112
|
return parsed.reason.length === 0 && parsed.deliver.size === 0 && parsed.failed
|
|
102
113
|
? { deliver: parsed.deliver, reason: 'reply was not usable JSON', skipped: 'failed' }
|
|
@@ -115,23 +126,28 @@ export async function gateNotices(request) {
|
|
|
115
126
|
export function parseGateReply(text, candidates) {
|
|
116
127
|
const known = new Set(candidates.map((candidate) => candidate.id));
|
|
117
128
|
const trimmed = text.trim().replace(/^```(?:json)?\s*/iu, '').replace(/```$/u, '').trim();
|
|
118
|
-
const
|
|
119
|
-
const
|
|
120
|
-
if (
|
|
129
|
+
const first = trimmed.indexOf('{');
|
|
130
|
+
const last = trimmed.lastIndexOf('}');
|
|
131
|
+
if (first < 0 || last <= first)
|
|
121
132
|
return { deliver: new Set(), reason: '', failed: true };
|
|
122
|
-
let
|
|
123
|
-
|
|
124
|
-
|
|
133
|
+
for (let start = first; start >= 0 && start < last; start = trimmed.indexOf('{', start + 1)) {
|
|
134
|
+
let parsed;
|
|
135
|
+
try {
|
|
136
|
+
parsed = JSON.parse(trimmed.slice(start, last + 1));
|
|
137
|
+
}
|
|
138
|
+
catch {
|
|
139
|
+
continue;
|
|
140
|
+
}
|
|
141
|
+
if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed))
|
|
142
|
+
continue;
|
|
143
|
+
const row = parsed;
|
|
144
|
+
if (!Array.isArray(row.deliver) && typeof row.reason !== 'string')
|
|
145
|
+
continue;
|
|
146
|
+
const deliver = new Set(Array.isArray(row.deliver)
|
|
147
|
+
? row.deliver.filter((id) => typeof id === 'string' && known.has(id))
|
|
148
|
+
: []);
|
|
149
|
+
const reason = typeof row.reason === 'string' ? row.reason.replace(/\s+/gu, ' ').trim().slice(0, 200) : '';
|
|
150
|
+
return { deliver, reason, failed: false };
|
|
125
151
|
}
|
|
126
|
-
|
|
127
|
-
return { deliver: new Set(), reason: '', failed: true };
|
|
128
|
-
}
|
|
129
|
-
if (typeof parsed !== 'object' || parsed === null)
|
|
130
|
-
return { deliver: new Set(), reason: '', failed: true };
|
|
131
|
-
const row = parsed;
|
|
132
|
-
const deliver = new Set(Array.isArray(row.deliver)
|
|
133
|
-
? row.deliver.filter((id) => typeof id === 'string' && known.has(id))
|
|
134
|
-
: []);
|
|
135
|
-
const reason = typeof row.reason === 'string' ? row.reason.replace(/\s+/gu, ' ').trim().slice(0, 200) : '';
|
|
136
|
-
return { deliver, reason, failed: false };
|
|
152
|
+
return { deliver: new Set(), reason: '', failed: true };
|
|
137
153
|
}
|