@kenz1117/dsh-engram 0.11.3 → 0.11.5
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 +19 -1
- package/lib/client.js +1 -1
- package/lib/client.js.map +1 -1
- package/lib/index.js +283 -142
- package/package.json +1 -1
package/lib/index.js
CHANGED
|
@@ -231,6 +231,7 @@ const zh$5 = {
|
|
|
231
231
|
"core.warnHistoryBackfillFailed": "[dsh-engram] 历史回填失败:",
|
|
232
232
|
"core.warnDisposeFinalFailed": "[dsh-engram] 会话结束的收尾处理异常(不影响对话):",
|
|
233
233
|
"core.warnReflectFailed": "[dsh-engram] 会话结束的信念巩固异常({scope},不影响对话):",
|
|
234
|
+
"core.warnReflectBatchDropped": "[dsh-engram] 信念巩固丢弃 {count} 条候选({reason};未被巩固、下次巩固继续取材)",
|
|
234
235
|
"core.warnDecayStartupFailed": "[dsh-engram] 启动衰减调度失败(跳过):",
|
|
235
236
|
"core.warnDecayPeriodicFailed": "[dsh-engram] 周期衰减调度失败(跳过):",
|
|
236
237
|
"core.warnConsolidationFailed": "[dsh-engram] 闭馆整理失败(不影响对话):",
|
|
@@ -287,6 +288,7 @@ const en$5 = {
|
|
|
287
288
|
"core.warnHistoryBackfillFailed": "[dsh-engram] History backfill failed:",
|
|
288
289
|
"core.warnDisposeFinalFailed": "[dsh-engram] Session-end finalisation threw (conversation unaffected):",
|
|
289
290
|
"core.warnReflectFailed": "[dsh-engram] Belief consolidation at session end threw ({scope}, conversation unaffected):",
|
|
291
|
+
"core.warnReflectBatchDropped": "[dsh-engram] Belief consolidation dropped {count} candidates ({reason}; not consolidated, will be picked up next consolidation)",
|
|
290
292
|
"core.warnDecayStartupFailed": "[dsh-engram] Startup decay scheduling failed (skipped):",
|
|
291
293
|
"core.warnDecayPeriodicFailed": "[dsh-engram] Periodic decay scheduling failed (skipped):",
|
|
292
294
|
"core.warnConsolidationFailed": "[dsh-engram] Closing-time consolidation failed (conversation unaffected):",
|
|
@@ -890,6 +892,7 @@ const zh$1 = {
|
|
|
890
892
|
"tool.reflectDone": "信念巩固完成:取材池 {pool} 条,新证据 {candidates} 条、待复核信念 {staleReviewed} 条;新建 {formed},细化 {refined},维持 {confirmed},否定 {refuted},跳过 {skipped}。",
|
|
891
893
|
"tool.reflectNote": "信念是叠加在原始记忆之上的抽象层(证据 id 与证据数已留存,原始记忆未归档)。",
|
|
892
894
|
"tool.reflectConsumed": "同时消费了 {count} 条会话结束时登记的待巩固任务。",
|
|
895
|
+
"tool.reflectDropped": "另有 {count} 条候选因输出预算/解析失败被丢弃(未被巩固,可重跑补做)。",
|
|
893
896
|
"tool.examineDescription": "渐进式披露:按 id 批量拉取记忆完整铭牌(content + 房间 + 状态 + 边关系)。仅在已通过 engram_search/timeline/neighbors 拿到候选 id 后调用,避免一次性吞全文。建议 ≤16 个 id,超出会按入参顺序保留前 N 条。",
|
|
894
897
|
"tool.examineIdsDescription": "记忆 id 列表",
|
|
895
898
|
"tool.examineIdsRequired": "engram_examine: ids 必填且至少含 1 条",
|
|
@@ -1223,6 +1226,7 @@ const en$1 = {
|
|
|
1223
1226
|
"tool.reflectDone": "Belief consolidation complete: a pool of {pool} memories, {candidates} new evidence items, {staleReviewed} beliefs to re-check; {formed} formed, {refined} refined, {confirmed} confirmed, {refuted} refuted, {skipped} skipped.",
|
|
1224
1227
|
"tool.reflectNote": "Beliefs are an abstraction layer stacked on top of the raw memories (evidence ids and counts are kept; the raw memories are not archived).",
|
|
1225
1228
|
"tool.reflectConsumed": "Also consumed {count} consolidation tasks registered at session end.",
|
|
1229
|
+
"tool.reflectDropped": "Additionally, {count} candidates were dropped (output budget/parse failure; not consolidated, rerun to pick up).",
|
|
1226
1230
|
"tool.examineDescription": "Progressive disclosure: fetch the complete nameplates of memories by id in a batch (content + room + status + edges). Call it only after you already have candidate ids from engram_search/timeline/neighbors, so you do not swallow full texts at once. At most 16 ids are advised; extras keep the first N in the order given.",
|
|
1227
1231
|
"tool.examineIdsDescription": "list of memory ids",
|
|
1228
1232
|
"tool.examineIdsRequired": "engram_examine: ids is required and must hold at least 1 id",
|
|
@@ -5848,6 +5852,13 @@ function finishError(finish) {
|
|
|
5848
5852
|
}
|
|
5849
5853
|
}
|
|
5850
5854
|
/**
|
|
5855
|
+
* 判别 max-tokens 终止错误(finishError 打上 LLM_MAX_TOKENS code)。摄取分片重试与
|
|
5856
|
+
* 信念巩固分片重试共用(#42 附带 / #45)。
|
|
5857
|
+
*/
|
|
5858
|
+
function isMaxTokensError(error) {
|
|
5859
|
+
return error?.code === "LLM_MAX_TOKENS";
|
|
5860
|
+
}
|
|
5861
|
+
/**
|
|
5851
5862
|
* 一次辅助 LLM 调用:流式收集文本输出。
|
|
5852
5863
|
* @param ctx - 提供 llm 服务的上下文。
|
|
5853
5864
|
* @param params.route - 模型路由(来自日志解析或显式配置)。
|
|
@@ -6348,10 +6359,6 @@ const INGEST_MAX_TOKENS = 4e3;
|
|
|
6348
6359
|
/** 提取切块的最小文本粒度(字符):切到低于此长度仍超输出预算的块直接放弃(贡献 0 条候选)。
|
|
6349
6360
|
正常文本到这个量级输出预算绰绰有余;触发即说明模型输出退化(复读死循环),再切只是空烧。 */
|
|
6350
6361
|
const EXTRACT_MIN_CHUNK = 80;
|
|
6351
|
-
/** max-tokens 终止错误的判别(llm/client.ts 的 finishError 打上 LLM_MAX_TOKENS code)。 */
|
|
6352
|
-
function isMaxTokensError(error) {
|
|
6353
|
-
return error?.code === "LLM_MAX_TOKENS";
|
|
6354
|
-
}
|
|
6355
6362
|
/** 单块提取的解析失败(含空答案重试后仍失败)——携带原始输出,交上层按 reason 分类报告。 */
|
|
6356
6363
|
var ExtractFailure = class extends Error {
|
|
6357
6364
|
raw;
|
|
@@ -7199,8 +7206,8 @@ async function selectSessions(deps, rules) {
|
|
|
7199
7206
|
const cwd = header.cwd;
|
|
7200
7207
|
if (cwd === void 0 || cwd === "") return {
|
|
7201
7208
|
header,
|
|
7202
|
-
events,
|
|
7203
7209
|
turns,
|
|
7210
|
+
loadEvents: () => loadSession(source, header.id),
|
|
7204
7211
|
openStore: deps.openUserStore,
|
|
7205
7212
|
routing: {
|
|
7206
7213
|
writeScope: "user",
|
|
@@ -7210,8 +7217,8 @@ async function selectSessions(deps, rules) {
|
|
|
7210
7217
|
const projectCwd = cwd;
|
|
7211
7218
|
return {
|
|
7212
7219
|
header,
|
|
7213
|
-
events,
|
|
7214
7220
|
turns,
|
|
7221
|
+
loadEvents: () => loadSession(source, header.id),
|
|
7215
7222
|
openStore: () => deps.resolveStore(projectCwd),
|
|
7216
7223
|
routing: ingestWriteRouting(projectCwd, deps.resolveStore, deps.openUserStore)
|
|
7217
7224
|
};
|
|
@@ -7327,11 +7334,23 @@ async function runHistoryBackfill(deps, defaults, overrides, onProgress, signal)
|
|
|
7327
7334
|
onProgress({ ...progress });
|
|
7328
7335
|
for (const candidate of candidates) {
|
|
7329
7336
|
if (signal.aborted) break;
|
|
7337
|
+
const events = await candidate.loadEvents();
|
|
7338
|
+
if (events === void 0) {
|
|
7339
|
+
progress.turnsSkipped += candidate.turns.length;
|
|
7340
|
+
progress.skipReasons["session-unreadable"] = (progress.skipReasons["session-unreadable"] ?? 0) + candidate.turns.length;
|
|
7341
|
+
progress.turnsDone += candidate.turns.length;
|
|
7342
|
+
progress.sessionsDone += 1;
|
|
7343
|
+
onProgress({
|
|
7344
|
+
...progress,
|
|
7345
|
+
currentSession: candidate.header.id
|
|
7346
|
+
});
|
|
7347
|
+
continue;
|
|
7348
|
+
}
|
|
7330
7349
|
for (const turn of candidate.turns) {
|
|
7331
7350
|
if (signal.aborted) break;
|
|
7332
7351
|
try {
|
|
7333
7352
|
const outcome = await ingestPreviousTurn({
|
|
7334
|
-
events
|
|
7353
|
+
events,
|
|
7335
7354
|
sessionId: candidate.header.id,
|
|
7336
7355
|
turn,
|
|
7337
7356
|
slice: turn,
|
|
@@ -7368,7 +7387,7 @@ async function runHistoryBackfill(deps, defaults, overrides, onProgress, signal)
|
|
|
7368
7387
|
});
|
|
7369
7388
|
}
|
|
7370
7389
|
await ensureSessionSummary({
|
|
7371
|
-
events
|
|
7390
|
+
events,
|
|
7372
7391
|
sessionId: candidate.header.id,
|
|
7373
7392
|
openStore: () => candidate.openStore(),
|
|
7374
7393
|
call: deps.call,
|
|
@@ -7492,13 +7511,13 @@ async function runConsolidation(store, embedder, opts = {}) {
|
|
|
7492
7511
|
const key = record.content.slice(0, 60);
|
|
7493
7512
|
const existing = seen.get(key);
|
|
7494
7513
|
if (existing === void 0) seen.set(key, record);
|
|
7495
|
-
else
|
|
7514
|
+
else try {
|
|
7496
7515
|
const survivor = await store.supersedeMany({
|
|
7497
7516
|
scope,
|
|
7498
7517
|
kind: record.kind,
|
|
7499
7518
|
content: record.content,
|
|
7500
|
-
importance: record.importance,
|
|
7501
|
-
confidence: record.confidence
|
|
7519
|
+
importance: Math.max(existing.importance, record.importance),
|
|
7520
|
+
confidence: Math.max(existing.confidence, record.confidence)
|
|
7502
7521
|
}, [existing.id, record.id]);
|
|
7503
7522
|
merged += 1;
|
|
7504
7523
|
seen.set(key, survivor);
|
|
@@ -7600,14 +7619,21 @@ async function runConsolidation(store, embedder, opts = {}) {
|
|
|
7600
7619
|
const REFLECT_POOL = 300;
|
|
7601
7620
|
/** 单次巩固喂给 LLM 的新证据条数上限(协议内常量:单次辅助调用的可控上下文)。 */
|
|
7602
7621
|
const REFLECT_MAX_INPUT = 30;
|
|
7622
|
+
/** 单次 LLM 调用的候选分片大小(#45:30 条候选一次调用必然超输出预算整批丢弃;分片后单片失败只丢该片)。 */
|
|
7623
|
+
const REFLECT_CHUNK = 10;
|
|
7624
|
+
/** 候选原文截断字符数(#45:与 stale 证据的 REFLECT_EVIDENCE_SLICE 同纪律——候选此前整篇进 prompt)。 */
|
|
7625
|
+
const REFLECT_CANDIDATE_SLICE = 200;
|
|
7603
7626
|
/** 单次喂给 LLM 的待复核 stale 信念上限。 */
|
|
7604
7627
|
const REFLECT_MAX_STALE = 5;
|
|
7605
7628
|
/** 单条 stale 信念附带的证据原文条数上限。 */
|
|
7606
7629
|
const REFLECT_STALE_EVIDENCE_LIMIT = 6;
|
|
7607
7630
|
/** stale 证据原文截断字符数(控制总上下文)。 */
|
|
7608
7631
|
const REFLECT_EVIDENCE_SLICE = 120;
|
|
7609
|
-
/**
|
|
7610
|
-
|
|
7632
|
+
/** 输出预算按批量缩放:底价 + 单动作配额,封顶 8000(#45 实测 10 动作需 ~8000;推理模型的
|
|
7633
|
+
reasoning_tokens 计入 completion 预算,固定 900 对 30 动作必然截断)。 */
|
|
7634
|
+
const REFLECT_TOKENS_BASE = 400;
|
|
7635
|
+
const REFLECT_TOKENS_PER_ACTION = 500;
|
|
7636
|
+
const REFLECT_TOKENS_CAP = 8e3;
|
|
7611
7637
|
/** 信念向量近邻归并阈值:新信念与既有信念余弦达到该值则并入同一条(持续细化)。 */
|
|
7612
7638
|
const REFLECT_MERGE_THRESHOLD = .9;
|
|
7613
7639
|
/** 新鲜度阈值:新证据与既有信念余弦达到该值(低于归并阈值,语义更宽)则把信念标 stale 待复核。 */
|
|
@@ -7624,6 +7650,27 @@ function reflectSystemPrompt() {
|
|
|
7624
7650
|
});
|
|
7625
7651
|
}
|
|
7626
7652
|
/**
|
|
7653
|
+
* 巩固输出预算:底价 + 按本片动作数缩放,封顶 REFLECT_TOKENS_CAP。#45 实测 10 动作需
|
|
7654
|
+
* ~8000 tokens;推理模型的 reasoning_tokens 计入 completion 预算,固定小预算对大批必然
|
|
7655
|
+
* 截断——预算必须随喂入量走,而不是拍一个常数。
|
|
7656
|
+
*/
|
|
7657
|
+
function reflectMaxTokens(actionCount) {
|
|
7658
|
+
return Math.min(REFLECT_TOKENS_CAP, REFLECT_TOKENS_BASE + REFLECT_TOKENS_PER_ACTION * actionCount);
|
|
7659
|
+
}
|
|
7660
|
+
/**
|
|
7661
|
+
* 单片巩固的确定性失败(#45 分片自愈的内部信号):max-tokens 由调用层对半递归重试,
|
|
7662
|
+
* unparseable 由调用层把该片候选计入 dropped。网络等瞬时错误不用它承载、原样上抛
|
|
7663
|
+
* (整批失败仍由 reflectObservations 抛给调用层,由调用层决定是否落 pending)。
|
|
7664
|
+
*/
|
|
7665
|
+
var ReflectBatchFailure = class extends Error {
|
|
7666
|
+
reason;
|
|
7667
|
+
constructor(reason) {
|
|
7668
|
+
super("reflect-batch-failure");
|
|
7669
|
+
this.reason = reason;
|
|
7670
|
+
this.name = "ReflectBatchFailure";
|
|
7671
|
+
}
|
|
7672
|
+
};
|
|
7673
|
+
/**
|
|
7627
7674
|
* 执行一次信念巩固。纯异步:LLM/解析失败抛错(调用层决定是否落 pending),
|
|
7628
7675
|
* 单条动作的写入失败计入 skipped 不中断整批。
|
|
7629
7676
|
*/
|
|
@@ -7636,7 +7683,8 @@ async function reflectObservations(deps) {
|
|
|
7636
7683
|
refined: 0,
|
|
7637
7684
|
confirmed: 0,
|
|
7638
7685
|
refuted: 0,
|
|
7639
|
-
skipped: 0
|
|
7686
|
+
skipped: 0,
|
|
7687
|
+
dropped: 0
|
|
7640
7688
|
};
|
|
7641
7689
|
const pool = await deps.store.topActive(deps.scope, REFLECT_POOL);
|
|
7642
7690
|
outcome.pool = pool.length;
|
|
@@ -7666,86 +7714,127 @@ async function reflectObservations(deps) {
|
|
|
7666
7714
|
outcome.candidates = candidates.length;
|
|
7667
7715
|
outcome.staleReviewed = stale.length;
|
|
7668
7716
|
if (candidates.length === 0 && stale.length === 0) return outcome;
|
|
7669
|
-
const candidateIds = new Set(candidates.map((record) => String(record.id)));
|
|
7670
7717
|
const staleIds = new Set(stale.map((observation) => String(observation.id)));
|
|
7671
|
-
|
|
7672
|
-
|
|
7673
|
-
|
|
7674
|
-
|
|
7675
|
-
|
|
7676
|
-
|
|
7677
|
-
const
|
|
7678
|
-
|
|
7679
|
-
|
|
7680
|
-
|
|
7681
|
-
|
|
7682
|
-
count: String(observation.proofCount),
|
|
7683
|
-
belief: observation.belief
|
|
7684
|
-
})}\n${evidence}`);
|
|
7718
|
+
/**
|
|
7719
|
+
* 单片巩固:组装(候选原文截断)→调用(预算按批量缩放)→解析→逐动作落库。
|
|
7720
|
+
* 输出超预算抛 ReflectBatchFailure('max-tokens') 供上层对半递归;解析失败抛
|
|
7721
|
+
* ReflectBatchFailure('unparseable') 由上层计入 dropped;网络等错误原样上抛。
|
|
7722
|
+
*/
|
|
7723
|
+
const applySlice = async (slice, includeStale) => {
|
|
7724
|
+
const sliceIds = new Set(slice.map((record) => String(record.id)));
|
|
7725
|
+
const sections = [];
|
|
7726
|
+
if (slice.length > 0) {
|
|
7727
|
+
const lines = slice.map((record) => `[${String(record.id)}] (${record.kind}, importance ${record.importance.toFixed(2)}) ${record.content.slice(0, REFLECT_CANDIDATE_SLICE)}`);
|
|
7728
|
+
sections.push(`${message("llm.reflectMarkerNewMemories")}\n${lines.join("\n")}`);
|
|
7685
7729
|
}
|
|
7686
|
-
|
|
7687
|
-
|
|
7688
|
-
|
|
7689
|
-
|
|
7690
|
-
|
|
7691
|
-
|
|
7692
|
-
|
|
7693
|
-
|
|
7694
|
-
|
|
7695
|
-
|
|
7696
|
-
|
|
7697
|
-
|
|
7698
|
-
|
|
7699
|
-
|
|
7700
|
-
|
|
7701
|
-
|
|
7702
|
-
|
|
7703
|
-
|
|
7704
|
-
|
|
7705
|
-
|
|
7706
|
-
|
|
7730
|
+
if (includeStale && stale.length > 0) {
|
|
7731
|
+
const blocks = [];
|
|
7732
|
+
for (const observation of stale) {
|
|
7733
|
+
const evidence = (await deps.store.getMany(observation.sourceIds.slice(0, REFLECT_STALE_EVIDENCE_LIMIT))).map((record) => ` - ${record.content.slice(0, REFLECT_EVIDENCE_SLICE)}`).join("\n");
|
|
7734
|
+
blocks.push(`${message("llm.reflectStaleLine", {
|
|
7735
|
+
id: String(observation.id),
|
|
7736
|
+
count: String(observation.proofCount),
|
|
7737
|
+
belief: observation.belief
|
|
7738
|
+
})}\n${evidence}`);
|
|
7739
|
+
}
|
|
7740
|
+
sections.push(`${message("llm.reflectMarkerBeliefs")}\n${blocks.join("\n")}`);
|
|
7741
|
+
}
|
|
7742
|
+
const userText = sections.join("\n\n");
|
|
7743
|
+
const maxTokens = reflectMaxTokens(slice.length + (includeStale ? stale.length : 0));
|
|
7744
|
+
deps.logRequest({
|
|
7745
|
+
route: deps.route,
|
|
7746
|
+
scope: deps.scope,
|
|
7747
|
+
candidateCount: slice.length,
|
|
7748
|
+
staleCount: includeStale ? stale.length : 0,
|
|
7749
|
+
maxTokens
|
|
7750
|
+
});
|
|
7751
|
+
let raw;
|
|
7707
7752
|
try {
|
|
7708
|
-
|
|
7709
|
-
|
|
7710
|
-
|
|
7711
|
-
|
|
7712
|
-
|
|
7713
|
-
|
|
7714
|
-
|
|
7715
|
-
|
|
7716
|
-
|
|
7717
|
-
|
|
7718
|
-
|
|
7719
|
-
continue;
|
|
7720
|
-
}
|
|
7721
|
-
const sourceIds = requireCandidateIds(action.sourceIds, candidateIds);
|
|
7722
|
-
if (sourceIds === void 0) {
|
|
7723
|
-
outcome.skipped += 1;
|
|
7724
|
-
continue;
|
|
7725
|
-
}
|
|
7726
|
-
await refineWithEmbedding(deps, observationId, action.belief.trim(), sourceIds);
|
|
7727
|
-
outcome.refined += 1;
|
|
7728
|
-
} else if (action.action === "still") {
|
|
7729
|
-
const observationId = requireObservationId(action.observationId, staleIds);
|
|
7730
|
-
if (observationId === void 0) {
|
|
7731
|
-
outcome.skipped += 1;
|
|
7732
|
-
continue;
|
|
7733
|
-
}
|
|
7734
|
-
await deps.store.confirmObservation(observationId);
|
|
7735
|
-
outcome.confirmed += 1;
|
|
7736
|
-
} else if (action.action === "refute") {
|
|
7737
|
-
const observationId = requireObservationId(action.observationId, staleIds);
|
|
7738
|
-
if (observationId === void 0) {
|
|
7739
|
-
outcome.skipped += 1;
|
|
7740
|
-
continue;
|
|
7741
|
-
}
|
|
7742
|
-
await deps.store.refuteObservation(observationId);
|
|
7743
|
-
outcome.refuted += 1;
|
|
7744
|
-
} else outcome.skipped += 1;
|
|
7745
|
-
} catch {
|
|
7746
|
-
outcome.skipped += 1;
|
|
7753
|
+
raw = await deps.call({
|
|
7754
|
+
route: deps.route,
|
|
7755
|
+
system: reflectSystemPrompt(),
|
|
7756
|
+
userText,
|
|
7757
|
+
maxTokens,
|
|
7758
|
+
purpose: "engram-reflect",
|
|
7759
|
+
signal: deps.signal
|
|
7760
|
+
});
|
|
7761
|
+
} catch (error) {
|
|
7762
|
+
if (isMaxTokensError(error)) throw new ReflectBatchFailure("max-tokens");
|
|
7763
|
+
throw error;
|
|
7747
7764
|
}
|
|
7748
|
-
|
|
7765
|
+
const parsed = parseJsonArray(raw);
|
|
7766
|
+
if (parsed === void 0) throw new ReflectBatchFailure("unparseable");
|
|
7767
|
+
for (const item of parsed) {
|
|
7768
|
+
const action = item;
|
|
7769
|
+
try {
|
|
7770
|
+
if (action.action === "form") {
|
|
7771
|
+
if (await applyForm(deps, action, sliceIds) === "refined") outcome.refined += 1;
|
|
7772
|
+
else outcome.formed += 1;
|
|
7773
|
+
} else if (action.action === "refine") {
|
|
7774
|
+
const observationId = requireObservationId(action.observationId, staleIds);
|
|
7775
|
+
if (observationId === void 0) {
|
|
7776
|
+
outcome.skipped += 1;
|
|
7777
|
+
continue;
|
|
7778
|
+
}
|
|
7779
|
+
if (typeof action.belief !== "string" || action.belief.trim() === "") {
|
|
7780
|
+
outcome.skipped += 1;
|
|
7781
|
+
continue;
|
|
7782
|
+
}
|
|
7783
|
+
const sourceIds = requireCandidateIds(action.sourceIds, sliceIds);
|
|
7784
|
+
if (sourceIds === void 0) {
|
|
7785
|
+
outcome.skipped += 1;
|
|
7786
|
+
continue;
|
|
7787
|
+
}
|
|
7788
|
+
await refineWithEmbedding(deps, observationId, action.belief.trim(), sourceIds);
|
|
7789
|
+
outcome.refined += 1;
|
|
7790
|
+
} else if (action.action === "still") {
|
|
7791
|
+
const observationId = requireObservationId(action.observationId, staleIds);
|
|
7792
|
+
if (observationId === void 0) {
|
|
7793
|
+
outcome.skipped += 1;
|
|
7794
|
+
continue;
|
|
7795
|
+
}
|
|
7796
|
+
await deps.store.confirmObservation(observationId);
|
|
7797
|
+
outcome.confirmed += 1;
|
|
7798
|
+
} else if (action.action === "refute") {
|
|
7799
|
+
const observationId = requireObservationId(action.observationId, staleIds);
|
|
7800
|
+
if (observationId === void 0) {
|
|
7801
|
+
outcome.skipped += 1;
|
|
7802
|
+
continue;
|
|
7803
|
+
}
|
|
7804
|
+
await deps.store.refuteObservation(observationId);
|
|
7805
|
+
outcome.refuted += 1;
|
|
7806
|
+
} else outcome.skipped += 1;
|
|
7807
|
+
} catch {
|
|
7808
|
+
outcome.skipped += 1;
|
|
7809
|
+
}
|
|
7810
|
+
}
|
|
7811
|
+
};
|
|
7812
|
+
/**
|
|
7813
|
+
* 单片失败自愈(#45):输出超预算对半递归重试(两半各自独立调用——合回同一请求体积
|
|
7814
|
+
* 几乎不减、必然再超限);切到单片仍超限则该候选计入 dropped(未被巩固、无信念引用,
|
|
7815
|
+
* 下次巩固仍会取材),不再空烧;解析失败直接丢弃该片;其余错误原样上抛。
|
|
7816
|
+
*/
|
|
7817
|
+
const runSlice = async (slice, includeStale) => {
|
|
7818
|
+
try {
|
|
7819
|
+
await applySlice(slice, includeStale);
|
|
7820
|
+
return;
|
|
7821
|
+
} catch (error) {
|
|
7822
|
+
if (!(error instanceof ReflectBatchFailure)) throw error;
|
|
7823
|
+
if (error.reason === "unparseable") {
|
|
7824
|
+
outcome.dropped += slice.length;
|
|
7825
|
+
return;
|
|
7826
|
+
}
|
|
7827
|
+
}
|
|
7828
|
+
if (slice.length <= 1) {
|
|
7829
|
+
outcome.dropped += slice.length;
|
|
7830
|
+
return;
|
|
7831
|
+
}
|
|
7832
|
+
const mid = Math.ceil(slice.length / 2);
|
|
7833
|
+
await runSlice(slice.slice(0, mid), includeStale);
|
|
7834
|
+
await runSlice(slice.slice(mid), false);
|
|
7835
|
+
};
|
|
7836
|
+
if (candidates.length === 0) await runSlice([], true);
|
|
7837
|
+
for (let start = 0; start < candidates.length; start += REFLECT_CHUNK) await runSlice(candidates.slice(start, start + REFLECT_CHUNK), start === 0);
|
|
7749
7838
|
try {
|
|
7750
7839
|
await deps.store.audit("reflect", "AUX", JSON.stringify({
|
|
7751
7840
|
scope: deps.scope,
|
|
@@ -7756,7 +7845,8 @@ async function reflectObservations(deps) {
|
|
|
7756
7845
|
refined: outcome.refined,
|
|
7757
7846
|
confirmed: outcome.confirmed,
|
|
7758
7847
|
refuted: outcome.refuted,
|
|
7759
|
-
skipped: outcome.skipped
|
|
7848
|
+
skipped: outcome.skipped,
|
|
7849
|
+
dropped: outcome.dropped
|
|
7760
7850
|
}));
|
|
7761
7851
|
} catch {}
|
|
7762
7852
|
return outcome;
|
|
@@ -8187,6 +8277,35 @@ async function readJsonBody(req, limit = BODY_LIMIT_BYTES) {
|
|
|
8187
8277
|
//#endregion
|
|
8188
8278
|
//#region src/jev/client.ts
|
|
8189
8279
|
/**
|
|
8280
|
+
* HTTP-клиент модели Jev (System One): задаёт пачке «Noul»-вопросов (да/нет) по
|
|
8281
|
+
* одному тексту состояния и получает вероятности. Формат запроса — JSON вида
|
|
8282
|
+
* state/questions (POST на адрес соединения), он не совместим с OpenAI-chat,
|
|
8283
|
+
* поэтому роутинг через хостовый `ctx.llm` невозможен и клиент остаётся свой.
|
|
8284
|
+
*
|
|
8285
|
+
* Реквизиты соединения (адрес, ключ, модель) клиент не хранит и не читает сам:
|
|
8286
|
+
* их собирает мост `./host.ts` из данных хоста DSH — так провайдер и токен
|
|
8287
|
+
* вводятся ровно в одном месте, у хоста.
|
|
8288
|
+
*
|
|
8289
|
+
* Сетевой сбой, не-2xx, отсутствие полей в ответе — всё бросает ошибку наверх,
|
|
8290
|
+
* а вызывающий по каждой точке молча откатывается к чистым правилам.
|
|
8291
|
+
* @module @kenz1117/dsh-engram/jev/client
|
|
8292
|
+
*/
|
|
8293
|
+
/**
|
|
8294
|
+
* opencode.ai 系端点的稳定会话头(#46):Go 通道对缺该头的 System One 请求一律
|
|
8295
|
+
* 400 MissingSessionID。进程内生成一次、全程稳定(opencode 文档要求「每次对话带
|
|
8296
|
+
* 稳定的 x-opencode-session」;插件即一个客户端)。
|
|
8297
|
+
*/
|
|
8298
|
+
const OPENCODE_SESSION_ID = randomUUID();
|
|
8299
|
+
/** 端点是否属于 opencode.ai(该家要求 x-opencode-session;别家不发多余的头)。 */
|
|
8300
|
+
function isOpencodeEndpoint(endpoint) {
|
|
8301
|
+
try {
|
|
8302
|
+
const host = new URL(endpoint).hostname;
|
|
8303
|
+
return host === "opencode.ai" || host.endsWith(".opencode.ai");
|
|
8304
|
+
} catch {
|
|
8305
|
+
return false;
|
|
8306
|
+
}
|
|
8307
|
+
}
|
|
8308
|
+
/**
|
|
8190
8309
|
* Отказ вызова Jev с разобранной причиной.
|
|
8191
8310
|
*
|
|
8192
8311
|
* Класс, а не строка: панель показывает не только текст ошибки, но и вид отказа и
|
|
@@ -8205,6 +8324,20 @@ var JevCallError = class extends Error {
|
|
|
8205
8324
|
}
|
|
8206
8325
|
};
|
|
8207
8326
|
/**
|
|
8327
|
+
* 从上游错误响应体提取可读摘录(#46):JSON 时取 error.message(兼容 {error:{message}}
|
|
8328
|
+
* 与 {type:'error',error:{...}} 两种形状),非 JSON 取原文截断。空体返回空串。
|
|
8329
|
+
*/
|
|
8330
|
+
function jevUpstreamDetail(body) {
|
|
8331
|
+
if (body.trim() === "") return "";
|
|
8332
|
+
const excerpt = (text) => text.length > 200 ? `${text.slice(0, 200)}…` : text;
|
|
8333
|
+
try {
|
|
8334
|
+
const parsed = JSON.parse(body);
|
|
8335
|
+
return ` — ${excerpt((typeof parsed.error?.message === "string" ? parsed.error.message : body).trim())}`;
|
|
8336
|
+
} catch {
|
|
8337
|
+
return ` — ${excerpt(body.trim())}`;
|
|
8338
|
+
}
|
|
8339
|
+
}
|
|
8340
|
+
/**
|
|
8208
8341
|
* Причина отказа из брошенного значения: тайм-аут отличается от сети по имени ошибки,
|
|
8209
8342
|
* всё остальное — сеть (fetch отверг соединение, DNS, TLS).
|
|
8210
8343
|
* @param error - то, что попало в catch.
|
|
@@ -8232,7 +8365,8 @@ async function askNoul(connection, state, questions, signal = new AbortControlle
|
|
|
8232
8365
|
method: "POST",
|
|
8233
8366
|
headers: {
|
|
8234
8367
|
Authorization: `Bearer ${connection.apiKey}`,
|
|
8235
|
-
"Content-Type": "application/json"
|
|
8368
|
+
"Content-Type": "application/json",
|
|
8369
|
+
...isOpencodeEndpoint(connection.endpoint) ? { "x-opencode-session": OPENCODE_SESSION_ID } : {}
|
|
8236
8370
|
},
|
|
8237
8371
|
body: JSON.stringify({
|
|
8238
8372
|
model: connection.model,
|
|
@@ -8247,7 +8381,10 @@ async function askNoul(connection, state, questions, signal = new AbortControlle
|
|
|
8247
8381
|
} catch (error) {
|
|
8248
8382
|
throw new JevCallError(failureKind(error), error instanceof Error ? error.message : String(error));
|
|
8249
8383
|
}
|
|
8250
|
-
if (!response.ok)
|
|
8384
|
+
if (!response.ok) {
|
|
8385
|
+
const body = await response.text().catch(() => "");
|
|
8386
|
+
throw new JevCallError("http", `jev: HTTP ${response.status} from ${connection.endpoint}${jevUpstreamDetail(body)}`, response.status);
|
|
8387
|
+
}
|
|
8251
8388
|
const payload = await response.json();
|
|
8252
8389
|
if (payload.answers === void 0 || payload.answers === null) throw new JevCallError("shape", "jev: response missing answers");
|
|
8253
8390
|
const result = {};
|
|
@@ -16656,6 +16793,7 @@ function createEngramTools(baseDeps) {
|
|
|
16656
16793
|
skipped: outcome.skipped
|
|
16657
16794
|
}), message("tool.reflectNote")];
|
|
16658
16795
|
if (consumed > 0) lines.push(message("tool.reflectConsumed", { count: consumed }));
|
|
16796
|
+
if (outcome.dropped > 0) lines.push(message("tool.reflectDropped", { count: outcome.dropped }));
|
|
16659
16797
|
return { text: lines.join("\n") };
|
|
16660
16798
|
}
|
|
16661
16799
|
}),
|
|
@@ -17215,7 +17353,7 @@ function estimateTokens(text) {
|
|
|
17215
17353
|
}
|
|
17216
17354
|
//#endregion
|
|
17217
17355
|
//#region package.json
|
|
17218
|
-
var version = "0.11.
|
|
17356
|
+
var version = "0.11.5";
|
|
17219
17357
|
//#endregion
|
|
17220
17358
|
//#region src/index.ts
|
|
17221
17359
|
/**
|
|
@@ -18716,57 +18854,60 @@ async function apply(ctx, config = {}) {
|
|
|
18716
18854
|
console.warn(message("core.warnDisposeFinalFailed"), error);
|
|
18717
18855
|
});
|
|
18718
18856
|
});
|
|
18719
|
-
if (resolved.reflect !== "off")
|
|
18720
|
-
const
|
|
18721
|
-
|
|
18722
|
-
|
|
18723
|
-
|
|
18724
|
-
|
|
18725
|
-
|
|
18726
|
-
|
|
18727
|
-
|
|
18728
|
-
|
|
18729
|
-
|
|
18730
|
-
|
|
18731
|
-
|
|
18732
|
-
|
|
18733
|
-
|
|
18734
|
-
|
|
18735
|
-
|
|
18736
|
-
const
|
|
18857
|
+
if (resolved.reflect !== "off") {
|
|
18858
|
+
const REFLECT_TIMEOUT_MS = 12e4;
|
|
18859
|
+
ctx.on("session/disposed", (session) => {
|
|
18860
|
+
const events = session.snapshotEvents();
|
|
18861
|
+
const sessionId = String(session.id);
|
|
18862
|
+
const cwd = sessionCwd(session);
|
|
18863
|
+
const route = resolved.routeOverride ?? routeFromEvents(events);
|
|
18864
|
+
const targets = [{
|
|
18865
|
+
scope: "user",
|
|
18866
|
+
open: () => openStore("user")
|
|
18867
|
+
}];
|
|
18868
|
+
if (cwd !== void 0 && existsSync(join(resolved.dbDir, dbNameForCwd(cwd)))) targets.push({
|
|
18869
|
+
scope: "project",
|
|
18870
|
+
open: () => openStoreForProjectCwd(cwd)
|
|
18871
|
+
});
|
|
18872
|
+
(async () => {
|
|
18873
|
+
for (const target of targets) try {
|
|
18874
|
+
const store = await target.open();
|
|
18875
|
+
if (resolved.reflect === "suggest") {
|
|
18876
|
+
const detail = JSON.stringify({
|
|
18877
|
+
scope: target.scope,
|
|
18878
|
+
sessionId
|
|
18879
|
+
});
|
|
18880
|
+
if (!await store.hasAudit("reflect-pending", detail)) await store.audit("reflect-pending", "AUX", detail);
|
|
18881
|
+
continue;
|
|
18882
|
+
}
|
|
18883
|
+
if (route === void 0) continue;
|
|
18884
|
+
const outcome = await reflectObservations({
|
|
18885
|
+
store,
|
|
18886
|
+
embedder: await embedderAttempt(),
|
|
18737
18887
|
scope: target.scope,
|
|
18738
|
-
|
|
18888
|
+
call: (params) => streamText(ctx, {
|
|
18889
|
+
...params,
|
|
18890
|
+
sessionId: session.id
|
|
18891
|
+
}),
|
|
18892
|
+
logRequest: (data) => {
|
|
18893
|
+
store.audit("reflect-request", "AUX", JSON.stringify(data)).catch(() => {});
|
|
18894
|
+
},
|
|
18895
|
+
route,
|
|
18896
|
+
signal: AbortSignal.timeout(REFLECT_TIMEOUT_MS)
|
|
18739
18897
|
});
|
|
18740
|
-
if (
|
|
18741
|
-
|
|
18898
|
+
if (outcome.formed + outcome.refined + outcome.confirmed + outcome.refuted > 0) console.log(message("core.logReflectDone", {
|
|
18899
|
+
scope: target.scope,
|
|
18900
|
+
formed: outcome.formed,
|
|
18901
|
+
refined: outcome.refined,
|
|
18902
|
+
confirmed: outcome.confirmed,
|
|
18903
|
+
refuted: outcome.refuted
|
|
18904
|
+
}));
|
|
18905
|
+
} catch (error) {
|
|
18906
|
+
console.warn(message("core.warnReflectFailed", { scope: target.scope }), error);
|
|
18742
18907
|
}
|
|
18743
|
-
|
|
18744
|
-
|
|
18745
|
-
|
|
18746
|
-
embedder: await embedderAttempt(),
|
|
18747
|
-
scope: target.scope,
|
|
18748
|
-
call: (params) => streamText(ctx, {
|
|
18749
|
-
...params,
|
|
18750
|
-
sessionId: session.id
|
|
18751
|
-
}),
|
|
18752
|
-
logRequest: (data) => {
|
|
18753
|
-
store.audit("reflect-request", "AUX", JSON.stringify(data)).catch(() => {});
|
|
18754
|
-
},
|
|
18755
|
-
route,
|
|
18756
|
-
signal: AbortSignal.timeout(FINAL_INGEST_TIMEOUT_MS)
|
|
18757
|
-
});
|
|
18758
|
-
if (outcome.formed + outcome.refined + outcome.confirmed + outcome.refuted > 0) console.log(message("core.logReflectDone", {
|
|
18759
|
-
scope: target.scope,
|
|
18760
|
-
formed: outcome.formed,
|
|
18761
|
-
refined: outcome.refined,
|
|
18762
|
-
confirmed: outcome.confirmed,
|
|
18763
|
-
refuted: outcome.refuted
|
|
18764
|
-
}));
|
|
18765
|
-
} catch (error) {
|
|
18766
|
-
console.warn(message("core.warnReflectFailed", { scope: target.scope }), error);
|
|
18767
|
-
}
|
|
18768
|
-
})();
|
|
18769
|
-
});
|
|
18908
|
+
})();
|
|
18909
|
+
});
|
|
18910
|
+
}
|
|
18770
18911
|
const OP_LOG_RETENTION_DAYS = 366;
|
|
18771
18912
|
const runDecay = async () => {
|
|
18772
18913
|
const targets = [{
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kenz1117/dsh-engram",
|
|
3
3
|
"description": "Local-first cross-session long-term memory for DeepSeek Harness: dual-scope SQLite stores, hybrid FTS5 + local-vector retrieval with RRF, an evidence gate, provenance audit and SM-2 spaced repetition. 23 narrow tools, zero external services, zero API keys.",
|
|
4
|
-
"version": "0.11.
|
|
4
|
+
"version": "0.11.5",
|
|
5
5
|
"icon": "icon.svg",
|
|
6
6
|
"logo": "icon-256.svg",
|
|
7
7
|
"publishConfig": {
|