dsh-plugin-om 0.0.47 → 0.0.49
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 +15 -14
- package/dist/client/OmCompactionCard.d.ts +8 -1
- package/dist/client/OmCompactionCard.d.ts.map +1 -1
- package/dist/client/OmConfigCard.d.ts +2 -2
- package/dist/client/OmConfigCard.d.ts.map +1 -1
- package/dist/client/OmWarningCard.d.ts +2 -2
- package/dist/client/OmWarningCard.d.ts.map +1 -1
- package/dist/client/definition.d.ts +8 -8
- package/dist/client/definition.d.ts.map +1 -1
- package/dist/client/index.d.ts +1 -1
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/locales.d.ts +5 -5
- package/dist/client/locales.d.ts.map +1 -1
- package/dist/client.js +202 -93
- package/dist/client.js.map +1 -1
- package/dist/compaction-log.d.ts +17 -24
- package/dist/compaction-log.d.ts.map +1 -1
- package/dist/compress-loop.d.ts.map +1 -1
- package/dist/compress.d.ts +4 -2
- package/dist/compress.d.ts.map +1 -1
- package/dist/config.d.ts +2 -2
- package/dist/config.d.ts.map +1 -1
- package/dist/constants.d.ts +3 -3
- package/dist/constants.d.ts.map +1 -1
- package/dist/degrade.d.ts +5 -6
- package/dist/degrade.d.ts.map +1 -1
- package/dist/embedding.d.ts +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.mjs +460 -444
- package/dist/log-index.d.ts +1 -1
- package/dist/om-event.d.ts +14 -27
- package/dist/om-event.d.ts.map +1 -1
- package/dist/recall-output.d.ts +2 -2
- package/dist/recall-output.d.ts.map +1 -1
- package/dist/recall-xml.d.ts +1 -1
- package/dist/recall.d.ts +31 -10
- package/dist/recall.d.ts.map +1 -1
- package/dist/semantic-recall.d.ts +32 -26
- package/dist/semantic-recall.d.ts.map +1 -1
- package/dist/system-reminder.d.ts +35 -0
- package/dist/system-reminder.d.ts.map +1 -0
- package/dist/types.d.ts +19 -10
- package/dist/types.d.ts.map +1 -1
- package/package.json +4 -2
- package/dist/progress-reminder.d.ts +0 -18
- package/dist/progress-reminder.d.ts.map +0 -1
package/dist/index.mjs
CHANGED
|
@@ -36,21 +36,17 @@ const HISTORY_TAG = "history";
|
|
|
36
36
|
/** 压缩日志块开标签的 tip 属性(对 AI 的提醒:本块是历史压缩产物,不要复述)。 */
|
|
37
37
|
const HISTORY_TIP = "当前块是历史消息的压缩产物,不要复述";
|
|
38
38
|
/**
|
|
39
|
-
*
|
|
39
|
+
* 「完整消息」定义(压缩提示词与主会话 system-reminder 共用)。
|
|
40
40
|
* 完整消息是摘要日志与 recall 共用的定位单位;首条 index 为 0,按会话顺序递增、全局稳定。
|
|
41
41
|
*/
|
|
42
42
|
const COMPLETE_MESSAGE_DEFINITION = "`完整消息`指一条`用户消息`、`系统消息`、`模型输出文本`或`具有result的toolcall`;首条 index 为 0,按会话顺序递增。";
|
|
43
43
|
/**
|
|
44
|
-
* 最终 <history> 块内文块首的格式说明注释(XML
|
|
45
|
-
*
|
|
44
|
+
* 最终 <history> 块内文块首的格式说明注释(XML 注释)。通用部分(条目标签语义 +
|
|
45
|
+
* CDATA 约定 + toolcall 结构)始终保留;<user_message> / <sys> /
|
|
46
46
|
* <skill_content> / <ask-user-question> 的条目说明仅在块内存在对应条目时追加。
|
|
47
47
|
*/
|
|
48
48
|
function historyFormatNote(sections = {}) {
|
|
49
|
-
const parts = [
|
|
50
|
-
COMPLETE_MESSAGE_DEFINITION,
|
|
51
|
-
"<TAG index=\"N\">表示单条完整消息,<TAG start=\"A\" end=\"B\"> 表示多条连续消息,start/end 是首尾完整消息的 index;消息块的内容是用CDATA包裹的纯文本",
|
|
52
|
-
"<assistant type=\"toolcall\" tool-name=\"T\" callId=\"C\" index=\"N\"> 表示工具调用,内含 <tool-args> 与 <tool-result> 两个CDATA子元素(调用参数与工具返回内容)"
|
|
53
|
-
];
|
|
49
|
+
const parts = ["<TAG index=\"N\">表示单条完整消息,<TAG start=\"A\" end=\"B\"> 表示多条连续消息,start/end 是首尾完整消息的 index;消息块的内容是用CDATA包裹的纯文本", "<assistant type=\"toolcall\" tool-name=\"T\" callId=\"C\" index=\"N\"> 表示工具调用,内含 <tool-args> 与 <tool-result> 两个CDATA子元素(调用参数与工具返回内容)"];
|
|
54
50
|
if (sections.user) parts.push("<user_message index=\"N\"> 表示用户消息原文");
|
|
55
51
|
if (sections.sys) parts.push("<sys type=\"KIND\" index=\"N\"> 表示被压缩的系统消息,块中为空");
|
|
56
52
|
if (sections.skill) parts.push("<skill_content name=\"S\" index=\"N\"> 表示未压缩的原始 skill");
|
|
@@ -194,162 +190,149 @@ function phaseLabel(phase) {
|
|
|
194
190
|
function compressionRecordLabel(phase, rounds, success) {
|
|
195
191
|
return `OM 压缩${success ? "会话记录" : "失败日志"}(${phaseLabel(phase)} · ${rounds} 轮)`;
|
|
196
192
|
}
|
|
197
|
-
/**
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
function
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
const sum = (a, b) => a === void 0 && b === void 0 ? void 0 : (a ?? 0) + (b ?? 0);
|
|
212
|
-
const merged = {
|
|
213
|
-
inputTokens: (total.inputTokens ?? 0) + (round.usage.inputTokens ?? 0),
|
|
214
|
-
outputTokens: (total.outputTokens ?? 0) + (round.usage.outputTokens ?? 0)
|
|
215
|
-
};
|
|
216
|
-
const cacheRead = sum(total.cacheReadTokens, round.usage.cacheReadTokens);
|
|
217
|
-
const cacheWrite = sum(total.cacheWriteTokens, round.usage.cacheWriteTokens);
|
|
218
|
-
const reasoning = sum(total.reasoningTokens, round.usage.reasoningTokens);
|
|
219
|
-
if (cacheRead !== void 0) merged.cacheReadTokens = cacheRead;
|
|
220
|
-
if (cacheWrite !== void 0) merged.cacheWriteTokens = cacheWrite;
|
|
221
|
-
if (reasoning !== void 0) merged.reasoningTokens = reasoning;
|
|
222
|
-
total = merged;
|
|
223
|
-
}
|
|
224
|
-
return total;
|
|
193
|
+
/**
|
|
194
|
+
* 构造一个 seed 事件信封:seq 由调用方按顺序传入,surface 事件附 surfaceOp:'append'。
|
|
195
|
+
* 宿主 seed 边界校验信封字段(type/seq/time/data/surfaceOp)与消息形状,并原样保留
|
|
196
|
+
* time(append 路径会强制改写为 Date.now()),故诊断记录经 seed 重建时间线。信封为
|
|
197
|
+
* 判别联合,泛型构造需一次断言(与 tests/helpers.ts 同法)。
|
|
198
|
+
*/
|
|
199
|
+
function seedEvent(type, seq, time, data, surfaceOp) {
|
|
200
|
+
return {
|
|
201
|
+
type,
|
|
202
|
+
seq,
|
|
203
|
+
time,
|
|
204
|
+
data,
|
|
205
|
+
...surfaceOp === void 0 ? {} : { surfaceOp }
|
|
206
|
+
};
|
|
225
207
|
}
|
|
226
208
|
/**
|
|
227
|
-
*
|
|
228
|
-
*
|
|
209
|
+
* 重建压缩循环的 seed 事件时间线:descriptor + turn/step 生命周期 + 逐消息事件。每个
|
|
210
|
+
* 事件携带从循环统计推导的 time——turn 边界取循环起止、第 k 个 assistant 取第 k 轮
|
|
211
|
+
* 起止(step/start = startedAt、assistant/message = startedAt + durationMs)、工具调用
|
|
212
|
+
* 与结果与其 assistant 同刻(内存工具瞬时)——并把逐轮 usage 附加到 assistant/message。
|
|
213
|
+
* 时间全程单调不减;轮次数组短于 assistant 数时(流错误注入的部分 assistant)回落上一
|
|
214
|
+
* 轮结束时刻与循环结束时刻。
|
|
229
215
|
*/
|
|
230
|
-
function
|
|
231
|
-
const
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
}
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
216
|
+
function buildCompressionSeed(messages, stats, label) {
|
|
217
|
+
const seed = [];
|
|
218
|
+
const push = (type, time, data, surfaceOp) => {
|
|
219
|
+
seed.push(seedEvent(type, seed.length, time, data, surfaceOp));
|
|
220
|
+
};
|
|
221
|
+
let cursor = stats.startedAt;
|
|
222
|
+
const at = (time) => {
|
|
223
|
+
cursor = Math.max(cursor, time);
|
|
224
|
+
return cursor;
|
|
225
|
+
};
|
|
226
|
+
const executed = new Set(messages.filter((message) => message.role === "tool").map((message) => message.toolCallId));
|
|
227
|
+
push("subagent/descriptor", at(stats.startedAt), {
|
|
228
|
+
version: SUBAGENT_DESCRIPTOR_VERSION,
|
|
229
|
+
mode: "one-shot",
|
|
230
|
+
provider: COMPACTION_LOG_PROVIDER,
|
|
231
|
+
label
|
|
232
|
+
});
|
|
233
|
+
push("turn/start", at(stats.startedAt), { turn: 1 });
|
|
234
|
+
let step = 0;
|
|
235
|
+
let assistantIndex = 0;
|
|
236
|
+
let stepTime = stats.startedAt;
|
|
237
|
+
let pending = [];
|
|
238
|
+
const closeStep = () => {
|
|
239
|
+
if (step === 0) return;
|
|
240
|
+
for (const call of pending) {
|
|
241
|
+
if (executed.has(call.id)) continue;
|
|
242
|
+
const repair = createToolResultMessage({
|
|
243
|
+
callId: call.id,
|
|
244
|
+
content: [{
|
|
245
|
+
type: "text",
|
|
246
|
+
text: "压缩循环未执行此工具调用"
|
|
247
|
+
}],
|
|
248
|
+
isError: true
|
|
249
|
+
});
|
|
250
|
+
push("tool/result", at(stepTime), {
|
|
251
|
+
turn: 1,
|
|
252
|
+
step,
|
|
253
|
+
message: {
|
|
254
|
+
...repair,
|
|
255
|
+
id: `forked-tool-result-${call.id}-${uuid()}`
|
|
256
|
+
},
|
|
257
|
+
error: {
|
|
258
|
+
name: "ToolNotStartedError",
|
|
259
|
+
code: "TOOL_NOT_STARTED"
|
|
260
|
+
}
|
|
261
|
+
}, "append");
|
|
262
|
+
}
|
|
263
|
+
push("step/end", at(stepTime), {
|
|
264
|
+
turn: 1,
|
|
265
|
+
step
|
|
266
|
+
});
|
|
267
|
+
pending = [];
|
|
268
|
+
};
|
|
269
|
+
for (const message of messages) if (message.role === "assistant") {
|
|
270
|
+
closeStep();
|
|
271
|
+
step += 1;
|
|
272
|
+
const round = stats.rounds[assistantIndex];
|
|
273
|
+
assistantIndex += 1;
|
|
274
|
+
const startAt = round?.startedAt ?? stepTime;
|
|
275
|
+
const completedAt = round === void 0 ? stats.completedAt : round.startedAt + round.durationMs;
|
|
276
|
+
push("step/start", at(startAt), {
|
|
277
|
+
turn: 1,
|
|
278
|
+
step
|
|
279
|
+
});
|
|
280
|
+
const assistant = message;
|
|
281
|
+
const assistantTime = at(completedAt);
|
|
282
|
+
push("assistant/message", assistantTime, {
|
|
283
|
+
turn: 1,
|
|
284
|
+
step,
|
|
285
|
+
message: assistant,
|
|
286
|
+
stream: [],
|
|
287
|
+
...round?.usage === void 0 ? {} : { usage: round.usage }
|
|
288
|
+
}, "append");
|
|
289
|
+
stepTime = assistantTime;
|
|
290
|
+
pending = assistant.content.filter((block) => block.type === "tool-call");
|
|
291
|
+
for (const call of pending) {
|
|
292
|
+
if (!executed.has(call.id)) continue;
|
|
293
|
+
push("tool/call", at(stepTime), {
|
|
294
|
+
turn: 1,
|
|
295
|
+
step,
|
|
296
|
+
callId: call.id,
|
|
297
|
+
name: call.name,
|
|
298
|
+
arguments: call.arguments
|
|
299
|
+
});
|
|
300
|
+
}
|
|
301
|
+
} else if (message.role === "tool") push("tool/result", at(stepTime), {
|
|
302
|
+
turn: 1,
|
|
303
|
+
step,
|
|
304
|
+
message
|
|
305
|
+
}, "append");
|
|
306
|
+
else push("user/message", at(step === 0 ? stats.startedAt : stepTime), message, "append");
|
|
307
|
+
closeStep();
|
|
308
|
+
push("turn/end", at(stats.completedAt), {
|
|
309
|
+
turn: 1,
|
|
310
|
+
reason: { kind: "completed" }
|
|
255
311
|
});
|
|
312
|
+
return seed;
|
|
256
313
|
}
|
|
257
314
|
/**
|
|
258
|
-
*
|
|
259
|
-
*
|
|
260
|
-
* cwd
|
|
261
|
-
*
|
|
262
|
-
*
|
|
263
|
-
*
|
|
264
|
-
* 落盘自身绝不抛错,任何失败仅 logger.warn 并返回 undefined。
|
|
315
|
+
* 把一次压缩工具循环的完整会话消息组落盘为子会话:以重建时间线的 seed 事件经
|
|
316
|
+
* ctx.sessions.create 构造子会话(header origin 'subagent'、parentSession 指向主会话、
|
|
317
|
+
* delegationDepth = 父 + 1、cwd 继承主会话;首事件 one-shot descriptor,provider
|
|
318
|
+
* om-compaction-log,label 含压缩阶段与轮数),flush 持久化,在父会话登记
|
|
319
|
+
* subagent/catalog,返回子会话 id。成功与失败均调用;落盘自身绝不抛错,任何失败仅
|
|
320
|
+
* logger.warn 并返回 undefined。
|
|
265
321
|
*/
|
|
266
322
|
async function recordCompressionSession(ctx, parentSession, options) {
|
|
267
323
|
const logger = makeLogger(ctx, options.debug);
|
|
268
324
|
try {
|
|
269
325
|
const header = parentSession.header;
|
|
270
|
-
const child = ctx.sessions.create(SessionId(`om-compaction-log-${uuid()}`), { meta: {
|
|
271
|
-
...header.cwd === void 0 ? {} : { cwd: header.cwd },
|
|
272
|
-
parentSession: parentSession.id,
|
|
273
|
-
origin: "subagent",
|
|
274
|
-
delegationDepth: (header.delegationDepth ?? 0) + 1
|
|
275
|
-
} });
|
|
276
326
|
const label = compressionRecordLabel(options.phase, options.stats.rounds.length, options.success);
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
const executed = new Set(options.messages.filter((message) => message.role === "tool").map((message) => message.toolCallId));
|
|
286
|
-
let pending = [];
|
|
287
|
-
const closeStep = () => {
|
|
288
|
-
if (step === 0) return;
|
|
289
|
-
for (const call of pending) {
|
|
290
|
-
if (executed.has(call.id)) continue;
|
|
291
|
-
const repair = createToolResultMessage({
|
|
292
|
-
callId: call.id,
|
|
293
|
-
content: [{
|
|
294
|
-
type: "text",
|
|
295
|
-
text: "压缩循环未执行此工具调用"
|
|
296
|
-
}],
|
|
297
|
-
isError: true
|
|
298
|
-
});
|
|
299
|
-
child.append("tool/result", {
|
|
300
|
-
turn: 1,
|
|
301
|
-
step,
|
|
302
|
-
message: {
|
|
303
|
-
...repair,
|
|
304
|
-
id: `forked-tool-result-${call.id}-${uuid()}`
|
|
305
|
-
},
|
|
306
|
-
error: {
|
|
307
|
-
name: "ToolNotStartedError",
|
|
308
|
-
code: "TOOL_NOT_STARTED"
|
|
309
|
-
}
|
|
310
|
-
}, { surfaceOp: "append" });
|
|
311
|
-
}
|
|
312
|
-
child.append("step/end", {
|
|
313
|
-
turn: 1,
|
|
314
|
-
step
|
|
315
|
-
});
|
|
316
|
-
pending = [];
|
|
317
|
-
};
|
|
318
|
-
for (const message of options.messages) if (message.role === "assistant") {
|
|
319
|
-
closeStep();
|
|
320
|
-
step += 1;
|
|
321
|
-
child.append("step/start", {
|
|
322
|
-
turn: 1,
|
|
323
|
-
step
|
|
324
|
-
});
|
|
325
|
-
child.append("assistant/message", {
|
|
326
|
-
turn: 1,
|
|
327
|
-
step,
|
|
328
|
-
message,
|
|
329
|
-
stream: []
|
|
330
|
-
}, { surfaceOp: "append" });
|
|
331
|
-
pending = message.content.filter((block) => block.type === "tool-call");
|
|
332
|
-
for (const call of pending) {
|
|
333
|
-
if (!executed.has(call.id)) continue;
|
|
334
|
-
child.append("tool/call", {
|
|
335
|
-
turn: 1,
|
|
336
|
-
step,
|
|
337
|
-
callId: call.id,
|
|
338
|
-
name: call.name,
|
|
339
|
-
arguments: call.arguments
|
|
340
|
-
});
|
|
327
|
+
const seed = buildCompressionSeed(options.messages, options.stats, label);
|
|
328
|
+
const child = ctx.sessions.create(SessionId(`om-compaction-log-${uuid()}`), {
|
|
329
|
+
seed,
|
|
330
|
+
meta: {
|
|
331
|
+
...header.cwd === void 0 ? {} : { cwd: header.cwd },
|
|
332
|
+
parentSession: parentSession.id,
|
|
333
|
+
origin: "subagent",
|
|
334
|
+
delegationDepth: (header.delegationDepth ?? 0) + 1
|
|
341
335
|
}
|
|
342
|
-
} else if (message.role === "tool") child.append("tool/result", {
|
|
343
|
-
turn: 1,
|
|
344
|
-
step,
|
|
345
|
-
message
|
|
346
|
-
}, { surfaceOp: "append" });
|
|
347
|
-
else child.append("user/message", message, { surfaceOp: "append" });
|
|
348
|
-
closeStep();
|
|
349
|
-
child.append("user/message", makeStatsMessage(formatCompressionStats(options.phase, options.success, options.stats)), { surfaceOp: "append" });
|
|
350
|
-
child.append("turn/end", {
|
|
351
|
-
turn: 1,
|
|
352
|
-
reason: { kind: "completed" }
|
|
353
336
|
});
|
|
354
337
|
const persistence = ctx.get("sessionPersistence");
|
|
355
338
|
if (persistence === void 0) throw new Error("宿主未提供 sessionPersistence 服务");
|
|
@@ -7648,7 +7631,7 @@ function renderToolResultText(session, cm, pruner) {
|
|
|
7648
7631
|
const message = toolResultMessageOf(session, cm, pruner);
|
|
7649
7632
|
return message ? renderMessageText(message) : "";
|
|
7650
7633
|
}
|
|
7651
|
-
/** 渲染一条完整消息为「文本 + 图片」(recall
|
|
7634
|
+
/** 渲染一条完整消息为「文本 + 图片」(recall 输出用):
|
|
7652
7635
|
* user/sys 取消息原文,assistant 取文本块,toolcall 为调用块 + 结果文本
|
|
7653
7636
|
* (pruner 裁剪超大结果);同时收集该条完整消息携带的图片附件(含 tool-result 嵌套,
|
|
7654
7637
|
* pruner 裁剪掉的图片不收集)。
|
|
@@ -9028,7 +9011,6 @@ async function runCompressionLoop(ctx, session, options) {
|
|
|
9028
9011
|
};
|
|
9029
9012
|
const recordSessionId = async (success, stats) => recordCompressionSession(ctx, session, {
|
|
9030
9013
|
phase: options.phase,
|
|
9031
|
-
target: options.target,
|
|
9032
9014
|
messages,
|
|
9033
9015
|
stats,
|
|
9034
9016
|
success,
|
|
@@ -9148,30 +9130,18 @@ async function runCompressionLoop(ctx, session, options) {
|
|
|
9148
9130
|
}
|
|
9149
9131
|
//#endregion
|
|
9150
9132
|
//#region src/om-event.ts
|
|
9151
|
-
/** om
|
|
9152
|
-
const OM_EVENT_PREFIX = "om:1:";
|
|
9153
|
-
/**
|
|
9154
|
-
* 解码一条会话事件为 om 私有事件:仅识别 feedback/record 中带 om 信封前缀的
|
|
9155
|
-
* text;前缀缺失、JSON 非法、kind 未知或载荷字段缺失时返回 undefined。
|
|
9156
|
-
*/
|
|
9133
|
+
/** 解码一条会话事件为 om 私有事件:仅识别 plugin:dsh-plugin-om:*。 */
|
|
9157
9134
|
function readOmEvent(event) {
|
|
9158
|
-
if (event === void 0 || event === null
|
|
9159
|
-
const
|
|
9160
|
-
if (typeof
|
|
9161
|
-
|
|
9162
|
-
|
|
9163
|
-
|
|
9164
|
-
|
|
9165
|
-
return;
|
|
9166
|
-
}
|
|
9167
|
-
if (envelope === null || typeof envelope !== "object" || Array.isArray(envelope)) return void 0;
|
|
9168
|
-
const { kind, ...rest } = envelope;
|
|
9169
|
-
switch (kind) {
|
|
9170
|
-
case "om/warning": {
|
|
9171
|
-
const { problem, message } = rest;
|
|
9135
|
+
if (event === void 0 || event === null) return void 0;
|
|
9136
|
+
const data = event.data;
|
|
9137
|
+
if (data === null || typeof data !== "object" || Array.isArray(data)) return void 0;
|
|
9138
|
+
const record = data;
|
|
9139
|
+
switch (event.type) {
|
|
9140
|
+
case "plugin:dsh-plugin-om:warning": {
|
|
9141
|
+
const { problem, message } = record;
|
|
9172
9142
|
if (typeof problem !== "string" || typeof message !== "string") return void 0;
|
|
9173
9143
|
return {
|
|
9174
|
-
kind,
|
|
9144
|
+
kind: event.type,
|
|
9175
9145
|
data: {
|
|
9176
9146
|
problem,
|
|
9177
9147
|
message
|
|
@@ -9179,20 +9149,20 @@ function readOmEvent(event) {
|
|
|
9179
9149
|
seq: event.seq
|
|
9180
9150
|
};
|
|
9181
9151
|
}
|
|
9182
|
-
case "om
|
|
9183
|
-
const { triggerMessageIndex } =
|
|
9152
|
+
case "plugin:dsh-plugin-om:observe-pending": {
|
|
9153
|
+
const { triggerMessageIndex } = record;
|
|
9184
9154
|
if (typeof triggerMessageIndex !== "number" || !Number.isSafeInteger(triggerMessageIndex)) return void 0;
|
|
9185
9155
|
return {
|
|
9186
|
-
kind,
|
|
9156
|
+
kind: event.type,
|
|
9187
9157
|
data: { triggerMessageIndex },
|
|
9188
9158
|
seq: event.seq
|
|
9189
9159
|
};
|
|
9190
9160
|
}
|
|
9191
|
-
case "om
|
|
9192
|
-
const { pendingSeq } =
|
|
9161
|
+
case "plugin:dsh-plugin-om:observe-invalidate": {
|
|
9162
|
+
const { pendingSeq } = record;
|
|
9193
9163
|
if (typeof pendingSeq !== "number" || !Number.isSafeInteger(pendingSeq)) return void 0;
|
|
9194
9164
|
return {
|
|
9195
|
-
kind,
|
|
9165
|
+
kind: event.type,
|
|
9196
9166
|
data: { pendingSeq },
|
|
9197
9167
|
seq: event.seq
|
|
9198
9168
|
};
|
|
@@ -9200,16 +9170,9 @@ function readOmEvent(event) {
|
|
|
9200
9170
|
default: return;
|
|
9201
9171
|
}
|
|
9202
9172
|
}
|
|
9203
|
-
/**
|
|
9204
|
-
function encodeOmEvent(kind, data) {
|
|
9205
|
-
return `${OM_EVENT_PREFIX}${JSON.stringify({
|
|
9206
|
-
kind,
|
|
9207
|
-
...data
|
|
9208
|
-
})}`;
|
|
9209
|
-
}
|
|
9210
|
-
/** 追加一条 om 私有事件(借用 feedback/record,log-only,不进 surface),返回事件 seq。 */
|
|
9173
|
+
/** 追加一条 om 私有事件(log-only,不进 surface),返回事件 seq。 */
|
|
9211
9174
|
function appendOmEvent(session, kind, data) {
|
|
9212
|
-
return session.append(
|
|
9175
|
+
return session.append(kind, data).seq;
|
|
9213
9176
|
}
|
|
9214
9177
|
function findOmEvents(session, kind) {
|
|
9215
9178
|
const result = [];
|
|
@@ -9225,36 +9188,35 @@ function findOmEvents(session, kind) {
|
|
|
9225
9188
|
* 降级报告:压缩流程中的挂载失败统一出口。
|
|
9226
9189
|
* 导出 reportDegrade / DEGRADE_PROBLEMS / DegradedProblem。
|
|
9227
9190
|
*
|
|
9228
|
-
*
|
|
9229
|
-
*
|
|
9230
|
-
*
|
|
9231
|
-
*
|
|
9232
|
-
*
|
|
9233
|
-
*
|
|
9191
|
+
* 挂载失败类问题(服务缺失、服务调用异常)console.warn 到宿主进程外部输出,
|
|
9192
|
+
* 并向会话日志追加 log-only 的 plugin:dsh-plugin-om:warning 事件,
|
|
9193
|
+
* 客户端渲染为「功能降级」警告行。
|
|
9194
|
+
* 同一会话同一问题只报告一次(按日志扫描去重,重启不重复)。
|
|
9195
|
+
* 报告动作自身绝不抛错,追加失败只记日志,不阻塞压缩。
|
|
9196
|
+
* 辅助函数的普通运行时报错不走本模块,仅记日志。
|
|
9234
9197
|
*/
|
|
9235
|
-
/** 各降级问题面向用户的简短说明(om
|
|
9198
|
+
/** 各降级问题面向用户的简短说明(plugin:dsh-plugin-om:warning 载荷 message;客户端警告行直接展示)。 */
|
|
9236
9199
|
const DEGRADE_PROBLEMS = {
|
|
9237
9200
|
"systemPrompt-missing": "系统提示词服务未挂载,上下文压力估算不扣除系统提示词 tokens(压缩触发会偏早)",
|
|
9238
9201
|
"tokenMeter-unavailable": "token 计量服务异常,上下文压力估算降级(可能跳过压缩或按 0 计)",
|
|
9239
9202
|
"reasoning-effort-unavailable": "配置的压缩思考等级不被压缩目标模型支持,压缩降级为模型默认思考等级"
|
|
9240
9203
|
};
|
|
9241
9204
|
/**
|
|
9242
|
-
* 报告一次挂载失败类降级:console.warn
|
|
9243
|
-
* 出现时,向会话日志追加 log-only om
|
|
9244
|
-
*
|
|
9245
|
-
* 日志扫描/事件追加失败只记日志,绝不抛错、不阻塞压缩。
|
|
9205
|
+
* 报告一次挂载失败类降级:console.warn 输出到宿主进程外部;同会话同问题首次
|
|
9206
|
+
* 出现时,向会话日志追加 log-only plugin:dsh-plugin-om:warning 事件并输出 logger.warn。
|
|
9207
|
+
* 日志扫描/事件追加失败只记日志,不抛错、不阻塞压缩。
|
|
9246
9208
|
*/
|
|
9247
9209
|
function reportDegrade(session, logger, problem) {
|
|
9248
9210
|
const message = DEGRADE_PROBLEMS[problem];
|
|
9249
9211
|
let first = true;
|
|
9250
9212
|
try {
|
|
9251
|
-
first = !findOmEvents(session, "om
|
|
9213
|
+
first = !findOmEvents(session, "plugin:dsh-plugin-om:warning").some((om) => om.data.problem === problem);
|
|
9252
9214
|
} catch {}
|
|
9253
9215
|
if (!first) return;
|
|
9254
9216
|
console.warn(`${PLUGIN_LABEL}: ${message}`);
|
|
9255
9217
|
logger.warn(message);
|
|
9256
9218
|
try {
|
|
9257
|
-
appendOmEvent(session, "om
|
|
9219
|
+
appendOmEvent(session, "plugin:dsh-plugin-om:warning", {
|
|
9258
9220
|
problem,
|
|
9259
9221
|
message
|
|
9260
9222
|
});
|
|
@@ -9268,7 +9230,7 @@ function reportDegrade(session, logger, problem) {
|
|
|
9268
9230
|
/**
|
|
9269
9231
|
* 两级自动压缩(观察/反思)与 compaction 生命周期提交。
|
|
9270
9232
|
* 导出 estimateTextTokens / isPairBalancedAfter / computeCompressRange / historySection /
|
|
9271
|
-
* findObservePending / reflectPass / observePass / maybeCompress。
|
|
9233
|
+
* hasHistoryBlock / findObservePending / reflectPass / observePass / maybeCompress。
|
|
9272
9234
|
*
|
|
9273
9235
|
* - 摘要生成走工具驱动的压缩循环(compress-loop.ts runCompressionLoop):首条 user
|
|
9274
9236
|
* 消息仅含压缩指令与 start/end 区间,模型经 getHistory / compressHistory /
|
|
@@ -9282,8 +9244,8 @@ function reportDegrade(session, logger, problem) {
|
|
|
9282
9244
|
* tailMessageCount 时,把压缩边界至触发点的全部消息作为压缩视图替换为新 <history>
|
|
9283
9245
|
* 块(旧块保留),等待期间的新消息成为下一轮未压缩尾部(延迟窗口内压力允许
|
|
9284
9246
|
* 短暂超阈值);tailMessageCount=0 时触发当轮直接执行(不落待定标记)
|
|
9285
|
-
* - 待定标记以 log-only
|
|
9286
|
-
* om
|
|
9247
|
+
* - 待定标记以 log-only 自定义会话事件(kind 为 plugin:dsh-plugin-om:observe-pending /
|
|
9248
|
+
* plugin:dsh-plugin-om:observe-invalidate,见 om-event.ts)持久化在会话日志中(重启后从日志恢复);
|
|
9287
9249
|
* 压缩失败保留待定,下个 pre-step 直接重试执行
|
|
9288
9250
|
* - 两级在 pre-step 阻塞串行执行(先反思后观察);仅主会话生效;omEnabled=false 关闭
|
|
9289
9251
|
* - 压缩目标默认跟随会话路由;compressProvider + compressModel 成对配置时覆盖路由
|
|
@@ -9298,7 +9260,7 @@ function reportDegrade(session, logger, problem) {
|
|
|
9298
9260
|
* - 提交走宿主 compaction/* 生命周期事件(start 带 phase → summary → 替换消息 → end),
|
|
9299
9261
|
* 失败补 end(error,实际报错 + 诊断子会话 sessionId);替换消息 source 标记插件标识供 UI 认领
|
|
9300
9262
|
* - 挂载失败类问题(systemPrompt/tokenMeter 服务异常)始终 console 到外部进程,并追加
|
|
9301
|
-
* log-only om
|
|
9263
|
+
* log-only plugin:dsh-plugin-om:warning 事件(客户端渲染功能降级警告行,每会话同一
|
|
9302
9264
|
* 问题至多一次);
|
|
9303
9265
|
* 辅助估算的普通运行时报错仅记日志。降级与报错都不阻塞压缩(tokenMeter 压力数据
|
|
9304
9266
|
* 缺失时本轮跳过观察)
|
|
@@ -9470,9 +9432,14 @@ function historySection(session) {
|
|
|
9470
9432
|
boundarySeq
|
|
9471
9433
|
};
|
|
9472
9434
|
}
|
|
9435
|
+
/** 表层是否存在合法 <history> 压缩日志块。 */
|
|
9436
|
+
function hasHistoryBlock(session) {
|
|
9437
|
+
for (const seq of session.surface.nodes) if (historyTextOf(session.snapshotEvents()[seq]) !== void 0) return true;
|
|
9438
|
+
return false;
|
|
9439
|
+
}
|
|
9473
9440
|
/**
|
|
9474
|
-
* 查找当前活跃的观察压缩待定标记:按日志顺序取最后一条 om
|
|
9475
|
-
* 其后须无引用它的 om
|
|
9441
|
+
* 查找当前活跃的观察压缩待定标记:按日志顺序取最后一条 plugin:dsh-plugin-om:observe-pending 事件,
|
|
9442
|
+
* 其后须无引用它的 plugin:dsh-plugin-om:observe-invalidate(已失效),且其后的压缩边界 seq 不大于标记
|
|
9476
9443
|
* seq(边界后移说明标记期间已发生过压缩,标记过期——兜底「执行成功但失效标记未写出」
|
|
9477
9444
|
* 的崩溃窗口)。无活跃标记返回 undefined。
|
|
9478
9445
|
*/
|
|
@@ -9482,24 +9449,24 @@ function findObservePending(session) {
|
|
|
9482
9449
|
const event = session.snapshotEvents()[seq];
|
|
9483
9450
|
if (!event) continue;
|
|
9484
9451
|
const om = readOmEvent(event);
|
|
9485
|
-
if (om?.kind === "om
|
|
9452
|
+
if (om?.kind === "plugin:dsh-plugin-om:observe-pending") pending = {
|
|
9486
9453
|
seq,
|
|
9487
9454
|
triggerMessageIndex: om.data.triggerMessageIndex
|
|
9488
9455
|
};
|
|
9489
|
-
else if (om?.kind === "om
|
|
9456
|
+
else if (om?.kind === "plugin:dsh-plugin-om:observe-invalidate" && pending !== void 0 && om.data.pendingSeq === pending.seq) pending = void 0;
|
|
9490
9457
|
}
|
|
9491
9458
|
if (pending === void 0) return void 0;
|
|
9492
9459
|
const { boundarySeq } = historySection(session);
|
|
9493
9460
|
if (boundarySeq !== void 0 && boundarySeq > pending.seq) return void 0;
|
|
9494
9461
|
return pending;
|
|
9495
9462
|
}
|
|
9496
|
-
/** 追加观察压缩待定标记(log-only
|
|
9463
|
+
/** 追加观察压缩待定标记(log-only 事件):记录触发点完整消息 index,返回事件 seq。 */
|
|
9497
9464
|
function appendObservePending(session, triggerMessageIndex) {
|
|
9498
|
-
return appendOmEvent(session, "om
|
|
9465
|
+
return appendOmEvent(session, "plugin:dsh-plugin-om:observe-pending", { triggerMessageIndex });
|
|
9499
9466
|
}
|
|
9500
|
-
/** 追加观察压缩待定失效标记(log-only
|
|
9467
|
+
/** 追加观察压缩待定失效标记(log-only 事件):声明指定 pending 已失效,返回事件 seq。 */
|
|
9501
9468
|
function appendObserveInvalidate(session, pendingSeq) {
|
|
9502
|
-
return appendOmEvent(session, "om
|
|
9469
|
+
return appendOmEvent(session, "plugin:dsh-plugin-om:observe-invalidate", { pendingSeq });
|
|
9503
9470
|
}
|
|
9504
9471
|
/** 当前打开中的 turn 号(最近 turn/start 且未被 turn/end 关闭);无则 null。 */
|
|
9505
9472
|
function openTurnOf(session) {
|
|
@@ -9963,7 +9930,7 @@ async function maybeCompress(ctx, agent, config, signal) {
|
|
|
9963
9930
|
//#endregion
|
|
9964
9931
|
//#region src/model-download.ts
|
|
9965
9932
|
/**
|
|
9966
|
-
* 嵌入模型下载原语:recall
|
|
9933
|
+
* 嵌入模型下载原语:recall 语义增强运行时按需下载与开发手动预下载(scripts/
|
|
9967
9934
|
* download-model.mjs)共用。导出 EMBEDDING_MODEL_ID / ONNX_REL / MODEL_SMALL_FILES /
|
|
9968
9935
|
* modelSourceUrl / modelTargetPath / needsDownload / downloadModel 及 DownloadResult /
|
|
9969
9936
|
* ModelFetch 类型。
|
|
@@ -10043,7 +10010,7 @@ async function downloadModel(modelDir, { force = false, fetchImpl = fetch, log =
|
|
|
10043
10010
|
//#endregion
|
|
10044
10011
|
//#region src/embedding.ts
|
|
10045
10012
|
/**
|
|
10046
|
-
* 本地语义嵌入(recall
|
|
10013
|
+
* 本地语义嵌入(recall 语义增强的向量引擎):Xenova/paraphrase-multilingual-MiniLM-L12-v2
|
|
10047
10014
|
* 量化 ONNX,懒加载 + 批量推理 + cosine 相似度,模型缺失时按需后台下载。
|
|
10048
10015
|
* 导出 BUNDLED_MODEL_DIR / EMBEDDING_MODEL_ID / resolveDshHome / sharedModelDir /
|
|
10049
10016
|
* ensureModelSmallFiles / getEmbedder / resetEmbedder / ensureModelReady /
|
|
@@ -10259,7 +10226,7 @@ function resolveConfig(raw) {
|
|
|
10259
10226
|
config.omEnabled = resolveBoolean(input.omEnabled, true);
|
|
10260
10227
|
config.debug = resolveBoolean(input.debug, process.env.NODE_ENV !== "production");
|
|
10261
10228
|
config.recallEnabled = resolveBoolean(input.recallEnabled, true);
|
|
10262
|
-
config.semanticRecallEnabled = resolveBoolean(input.semanticRecallEnabled, true);
|
|
10229
|
+
config.semanticRecallEnabled = config.recallEnabled && resolveBoolean(input.semanticRecallEnabled, true);
|
|
10263
10230
|
const modelDir = input.modelDir;
|
|
10264
10231
|
if (typeof modelDir === "string" && modelDir.trim() !== "") config.modelDir = modelDir;
|
|
10265
10232
|
config.compressProvider = resolveOptionalString(input.compressProvider);
|
|
@@ -10268,57 +10235,6 @@ function resolveConfig(raw) {
|
|
|
10268
10235
|
return Object.freeze(config);
|
|
10269
10236
|
}
|
|
10270
10237
|
//#endregion
|
|
10271
|
-
//#region src/progress-reminder.ts
|
|
10272
|
-
/**
|
|
10273
|
-
* 进度提醒:以 <system-reminder> 用户消息提示模型边做边简述计划与进展。
|
|
10274
|
-
* 提醒不进系统提示词;每个 step 检查表层,被压缩遮蔽或文本过期时补发,保证模型请求中恒有一条。
|
|
10275
|
-
* 导出 PROGRESS_REMINDER_SOURCE_KIND / ProgressReminderSource / PROGRESS_REMINDER_TEXT /
|
|
10276
|
-
* progressReminderMessage / ensureProgressReminder。
|
|
10277
|
-
*/
|
|
10278
|
-
/** 提醒消息的 producer-owned source kind(区别于压缩日志消息的 plugin:dsh-plugin-om)。 */
|
|
10279
|
-
const PROGRESS_REMINDER_SOURCE_KIND = "plugin:dsh-plugin-om:progress";
|
|
10280
|
-
/** 提醒全文(含 system-reminder 包裹)。 */
|
|
10281
|
-
const PROGRESS_REMINDER_TEXT = [
|
|
10282
|
-
"<system-reminder>",
|
|
10283
|
-
"Narrate your progress while you work, not only when the task is finished.",
|
|
10284
|
-
"- Before your first tool call on a task, state your plan in one or two sentences.",
|
|
10285
|
-
"- After each meaningful chunk of work (a group of related tool calls, a finished investigation, a completed edit), briefly report what you found or did and what you will do next, then continue.",
|
|
10286
|
-
"- Do not narrate every individual tool call; one short note per chunk is enough.",
|
|
10287
|
-
"- Do not save all commentary for the final answer. The final answer summarizes outcomes.",
|
|
10288
|
-
"This reminder does not override system, developer, or direct user instructions.",
|
|
10289
|
-
"</system-reminder>"
|
|
10290
|
-
].join("\n");
|
|
10291
|
-
/** 构造一条新的提醒消息。 */
|
|
10292
|
-
function progressReminderMessage() {
|
|
10293
|
-
return createUserMessage({
|
|
10294
|
-
content: [{
|
|
10295
|
-
type: "text",
|
|
10296
|
-
text: PROGRESS_REMINDER_TEXT
|
|
10297
|
-
}],
|
|
10298
|
-
source: {
|
|
10299
|
-
kind: PROGRESS_REMINDER_SOURCE_KIND,
|
|
10300
|
-
form: "instructions"
|
|
10301
|
-
}
|
|
10302
|
-
});
|
|
10303
|
-
}
|
|
10304
|
-
/** 消息是否为当前文本的提醒。 */
|
|
10305
|
-
function isCurrentReminder(source, content) {
|
|
10306
|
-
return source.kind === "plugin:dsh-plugin-om:progress" && content.length === 1 && content[0]?.type === "text" && content[0].text === PROGRESS_REMINDER_TEXT;
|
|
10307
|
-
}
|
|
10308
|
-
/**
|
|
10309
|
-
* 保证本 step 之后的消息列表中有一条当前提醒:本 step 已带上或表层已有则原样返回,
|
|
10310
|
-
* 否则在末尾追加。返回新数组,不修改入参。
|
|
10311
|
-
*/
|
|
10312
|
-
function ensureProgressReminder(session, messages) {
|
|
10313
|
-
if (messages.some((message) => isCurrentReminder(message.source, message.content))) return [...messages];
|
|
10314
|
-
const events = session.snapshotEvents();
|
|
10315
|
-
for (const seq of session.surface.nodes) {
|
|
10316
|
-
const event = events[seq];
|
|
10317
|
-
if (event?.type === "user/message" && isCurrentReminder(event.data.source, event.data.content)) return [...messages];
|
|
10318
|
-
}
|
|
10319
|
-
return [...messages, progressReminderMessage()];
|
|
10320
|
-
}
|
|
10321
|
-
//#endregion
|
|
10322
10238
|
//#region src/json-schema.ts
|
|
10323
10239
|
/**
|
|
10324
10240
|
* zod schema → 工具 wire 参数 JSON Schema 的转换工具。导出 parametersFromZod。
|
|
@@ -10333,7 +10249,7 @@ function parametersFromZod(schema) {
|
|
|
10333
10249
|
//#endregion
|
|
10334
10250
|
//#region src/recall-output.ts
|
|
10335
10251
|
/**
|
|
10336
|
-
* recall
|
|
10252
|
+
* recall 输出契约:输出值为固定形态 { text, images }。
|
|
10337
10253
|
* text 为完整消息的 XML 条目序列(形态见 recall-xml.ts,图片位置以 XML 注释标注),
|
|
10338
10254
|
* images 为图片附件元数据(按 attachmentId 引用,不含字节)。
|
|
10339
10255
|
* 导出 ImageRefValue / RecallOutputValue / RECALL_OUTPUT_SCHEMA / textOnly / imageNote /
|
|
@@ -10526,107 +10442,18 @@ function renderCompleteMessageXml(session, cm, options = {}) {
|
|
|
10526
10442
|
};
|
|
10527
10443
|
}
|
|
10528
10444
|
//#endregion
|
|
10529
|
-
//#region src/recall.ts
|
|
10530
|
-
/**
|
|
10531
|
-
* recall 工具:按完整消息 index 区间回看原始会话(含被压缩内容)。
|
|
10532
|
-
* 导出 recallArgsSchema / RecallArgs / parseRecallArgs / buildRecallTool。
|
|
10533
|
-
* 输出值为 { text, images }(契约见 recall-output.ts),text 为 XML 条目序列
|
|
10534
|
-
* (形态见 recall-xml.ts);recall 自身不设输出上限,超大工具结果由 tool-result-pruner 裁剪。
|
|
10535
|
-
*/
|
|
10536
|
-
/**
|
|
10537
|
-
* recall 工具参数 schema:start 必填;end 与 offset 至少提供一个(同时给出时 end 优先)。
|
|
10538
|
-
* 各字段描述经 .describe() 透传到 wire JSON Schema。
|
|
10539
|
-
*/
|
|
10540
|
-
const recallArgsSchema = z.object({
|
|
10541
|
-
start: z.number().describe("完整消息 index,基准边界,与 end 或 offset 配合指定区间;end 与 offset 至少提供一个(同时给出时 end 优先)。"),
|
|
10542
|
-
end: z.number().optional().describe("与 offset 互斥,指定区间另一边界。"),
|
|
10543
|
-
offset: z.number().optional().describe("与 end 互斥,相对 start 的步数(正向后、负向前)。")
|
|
10544
|
-
}).refine((args) => args.end !== void 0 || args.offset !== void 0, { message: "end 与 offset 至少提供一个" });
|
|
10545
|
-
/** 解析并校验 recall 调用参数:失败时抛出首个校验问题的可读消息(普通 Error,兼容 SDK 展示)。 */
|
|
10546
|
-
function parseRecallArgs(raw) {
|
|
10547
|
-
const result = recallArgsSchema.safeParse(raw);
|
|
10548
|
-
if (!result.success) throw new Error(result.error.issues.map((issue) => `${issue.path.join(".") || "args"}: ${issue.message}`).join("; "));
|
|
10549
|
-
return result.data;
|
|
10550
|
-
}
|
|
10551
|
-
/**
|
|
10552
|
-
* 构建 recall 工具定义:按 start/end/offset 定位完整消息区间并渲染原始内容(标 index)。
|
|
10553
|
-
* getPruner 返回 tool-result-pruner(可选),用于裁剪超大工具结果。
|
|
10554
|
-
*/
|
|
10555
|
-
function buildRecallTool(getPruner) {
|
|
10556
|
-
return {
|
|
10557
|
-
name: "recall",
|
|
10558
|
-
description: `在你需要查看历史消息时调用。${COMPLETE_MESSAGE_DEFINITION}此工具按 index 区间精确返回区间内全部完整消息的内容。`,
|
|
10559
|
-
parameters: parametersFromZod(recallArgsSchema),
|
|
10560
|
-
output: {
|
|
10561
|
-
schema: RECALL_OUTPUT_SCHEMA,
|
|
10562
|
-
render: (_args, value) => renderRecallOutput(value)
|
|
10563
|
-
},
|
|
10564
|
-
async execute(args, exec) {
|
|
10565
|
-
const { start, end, offset } = parseRecallArgs(args);
|
|
10566
|
-
const session = exec.agent?.session;
|
|
10567
|
-
if (!session) return textOnly("会话异常");
|
|
10568
|
-
if (!isMainSession(session)) return textOnly("recall 仅主会话可用");
|
|
10569
|
-
const cms = indexCompleteMessages(session);
|
|
10570
|
-
const startIndex = Number.isFinite(start) ? Math.floor(start) : 0;
|
|
10571
|
-
if (startIndex < 0 || startIndex >= cms.length) return textOnly(`start ${start} 越界(完整消息共 ${cms.length} 条,index 范围 0..${cms.length - 1})`);
|
|
10572
|
-
let endIndex;
|
|
10573
|
-
if (end !== void 0) {
|
|
10574
|
-
const e = Number.isFinite(end) ? Math.floor(end) : 0;
|
|
10575
|
-
if (e < 0 || e >= cms.length) return textOnly(`end ${end} 越界(完整消息共 ${cms.length} 条,index 范围 0..${cms.length - 1})`);
|
|
10576
|
-
endIndex = e;
|
|
10577
|
-
} else {
|
|
10578
|
-
const raw = offset ?? 0;
|
|
10579
|
-
endIndex = startIndex + (Number.isFinite(raw) ? Math.floor(raw) : 0);
|
|
10580
|
-
}
|
|
10581
|
-
const lo = Math.max(0, Math.min(startIndex, endIndex));
|
|
10582
|
-
const hi = Math.min(cms.length - 1, Math.max(startIndex, endIndex));
|
|
10583
|
-
const pruner = getPruner?.();
|
|
10584
|
-
const parts = [];
|
|
10585
|
-
const images = [];
|
|
10586
|
-
for (let i = lo; i <= hi; i += 1) {
|
|
10587
|
-
const cm = cms[i];
|
|
10588
|
-
if (!cm) continue;
|
|
10589
|
-
try {
|
|
10590
|
-
const rendered = renderCompleteMessageXml(session, cm, { pruner });
|
|
10591
|
-
parts.push(rendered.xml);
|
|
10592
|
-
images.push(...rendered.images);
|
|
10593
|
-
} catch {}
|
|
10594
|
-
}
|
|
10595
|
-
if (parts.length === 0) return textOnly("指定区间没有完整消息");
|
|
10596
|
-
return {
|
|
10597
|
-
text: parts.join("\n"),
|
|
10598
|
-
images
|
|
10599
|
-
};
|
|
10600
|
-
}
|
|
10601
|
-
};
|
|
10602
|
-
}
|
|
10603
|
-
//#endregion
|
|
10604
10445
|
//#region src/semantic-recall.ts
|
|
10605
10446
|
/**
|
|
10606
|
-
* recall
|
|
10447
|
+
* recall 语义增强的检索实现:按自然语言 query 对会话全部完整消息(含被压缩/遮蔽的)做
|
|
10607
10448
|
* 语义检索,返回最匹配的完整消息与匹配说明。
|
|
10608
|
-
* 导出
|
|
10609
|
-
*
|
|
10449
|
+
* 导出 SemanticOptions / RangeArgs / resolveSemanticRange / tokenize / matchExplanation /
|
|
10450
|
+
* SEMANTIC_MODEL_NOT_READY_MESSAGE / semanticSearch。
|
|
10610
10451
|
* 向量为本地 ONNX 嵌入(cosine 相似度);只匹配文本,纯图片消息不进候选池;
|
|
10611
10452
|
* 区间缺省检索全部、区间不合法回退全量并在输出中告知;输出契约同 recall
|
|
10612
10453
|
* ({ text, images },条目为 XML 形态见 recall-xml.ts,超大结果由 tool-result-pruner
|
|
10613
10454
|
* 裁剪);候选池排除本次调用自身的 toolcall 完整消息(其渲染文本含 query 原文,
|
|
10614
|
-
*
|
|
10455
|
+
* 必居榜首)。工具入口与参数校验见 recall.ts。
|
|
10615
10456
|
*/
|
|
10616
|
-
/** recall-semantic 工具参数 schema:query 必填;top_k 默认 3(1-10);区间参数均可选。 */
|
|
10617
|
-
const semanticRecallArgsSchema = z.object({
|
|
10618
|
-
query: z.string().describe("要找的内容的自然语言 query(中英文与代码术语皆可,如 \"修复 retry backoff 的逻辑\"),不能为空。"),
|
|
10619
|
-
top_k: z.number().int().min(1).max(10).optional().describe("返回最匹配条数(1-10,默认 3)。"),
|
|
10620
|
-
start: z.number().optional().describe("完整消息 index,基准边界,与 end/offset 配合指定搜索区间;缺省检索全部。"),
|
|
10621
|
-
end: z.number().optional().describe("须与 start 配合,与 offset 互斥,指定搜索区间另一边界。"),
|
|
10622
|
-
offset: z.number().optional().describe("须与 start 配合,与 end 互斥,相对 start 的步数(正向后、负向前)。")
|
|
10623
|
-
}).refine((args) => args.query.trim().length > 0, { message: "query 不能为空" });
|
|
10624
|
-
/** 解析并校验参数:失败时抛出可读错误(普通 Error 而非 ZodError)。 */
|
|
10625
|
-
function parseSemanticRecallArgs(raw) {
|
|
10626
|
-
const result = semanticRecallArgsSchema.safeParse(raw);
|
|
10627
|
-
if (!result.success) throw new Error(result.error.issues.map((issue) => `${issue.path.join(".") || "args"}:${issue.message}`).join("; "));
|
|
10628
|
-
return result.data;
|
|
10629
|
-
}
|
|
10630
10457
|
/**
|
|
10631
10458
|
* 解析检索区间(完整消息 index,含端点)。
|
|
10632
10459
|
* start 未提供 → 全量(fallback=false);start/end 越界或区间为空 → fallback=true
|
|
@@ -10693,85 +10520,194 @@ function matchExplanation(query, text, score) {
|
|
|
10693
10520
|
}
|
|
10694
10521
|
/** 模型未就绪时返回给模型的文案(下载完成后直接再次调用即可)。 */
|
|
10695
10522
|
const SEMANTIC_MODEL_NOT_READY_MESSAGE = "语义检索暂不可用,本地向量模型尚未就绪。";
|
|
10696
|
-
/**
|
|
10697
|
-
function
|
|
10698
|
-
const
|
|
10523
|
+
/** 在会话完整消息中做语义检索,返回 TOP-K 命中条目。 */
|
|
10524
|
+
async function semanticSearch(input) {
|
|
10525
|
+
const { session, query, topK, start, end, offset, selfCallId, getPruner, options } = input;
|
|
10699
10526
|
const embed = options?.embedder ?? ((texts) => getEmbedder().then((fn) => fn(texts)));
|
|
10527
|
+
if ((await options?.modelStatus?.() ?? "ready") !== "ready") return textOnly(SEMANTIC_MODEL_NOT_READY_MESSAGE);
|
|
10528
|
+
const cms = indexCompleteMessages(session);
|
|
10529
|
+
if (cms.length === 0) return textOnly("会话中没有可检索的消息");
|
|
10530
|
+
const range = resolveSemanticRange(cms.length, {
|
|
10531
|
+
start,
|
|
10532
|
+
end,
|
|
10533
|
+
offset
|
|
10534
|
+
});
|
|
10535
|
+
const candidates = [];
|
|
10536
|
+
for (let i = range.lo; i <= range.hi; i += 1) {
|
|
10537
|
+
const cm = cms[i];
|
|
10538
|
+
if (!cm) continue;
|
|
10539
|
+
if (selfCallId !== "" && cm.type === "toolcall" && cm.callId === selfCallId) continue;
|
|
10540
|
+
let text = "";
|
|
10541
|
+
try {
|
|
10542
|
+
text = renderCompleteMessage(session, cm);
|
|
10543
|
+
} catch {}
|
|
10544
|
+
if (text.trim().length > 0) candidates.push({
|
|
10545
|
+
cm,
|
|
10546
|
+
text
|
|
10547
|
+
});
|
|
10548
|
+
}
|
|
10549
|
+
if (candidates.length === 0) return textOnly("指定范围内没有可检索的消息");
|
|
10550
|
+
const [queryVec] = await embed([query]);
|
|
10551
|
+
if (!queryVec) return textOnly("语义检索失败:无法生成查询向量");
|
|
10552
|
+
const vectors = await embed(candidates.map((c) => c.text));
|
|
10553
|
+
const scored = candidates.map((c, i) => ({
|
|
10554
|
+
cm: c.cm,
|
|
10555
|
+
text: c.text,
|
|
10556
|
+
score: cosineSimilarity(queryVec, vectors[i] ?? /* @__PURE__ */ new Float32Array(0))
|
|
10557
|
+
}));
|
|
10558
|
+
scored.sort((a, b) => b.score - a.score);
|
|
10559
|
+
const limit = topK ?? 3;
|
|
10560
|
+
const hits = scored.slice(0, limit);
|
|
10561
|
+
const parts = [];
|
|
10562
|
+
const images = [];
|
|
10563
|
+
const rangeNote = range.fallback ? "指定区间不合法(start/end 越界等),已回退检索全部消息" : start === void 0 ? `检索全部消息(${candidates.length} 条可嵌入)` : `检索区间 [${range.lo}..${range.hi}](${candidates.length} 条可嵌入)`;
|
|
10564
|
+
parts.push(`<!-- ${xmlCommentText(`查询: ${query}`)} -->`);
|
|
10565
|
+
parts.push(`<!-- ${xmlCommentText(rangeNote)} -->`);
|
|
10566
|
+
parts.push(`<!-- ${xmlCommentText(`匹配 TOP-${hits.length}(共 ${scored.length} 条候选)`)} -->`);
|
|
10567
|
+
for (let i = 0; i < hits.length; i += 1) {
|
|
10568
|
+
const hit = hits[i];
|
|
10569
|
+
if (!hit) continue;
|
|
10570
|
+
const note = `<!-- ${xmlCommentText(`${i + 1}. ${matchExplanation(query, hit.text, hit.score)}`)} -->`;
|
|
10571
|
+
let xml;
|
|
10572
|
+
let hitImages = [];
|
|
10573
|
+
try {
|
|
10574
|
+
const pruner = getPruner();
|
|
10575
|
+
const rendered = renderCompleteMessageXml(session, hit.cm, {
|
|
10576
|
+
pruner,
|
|
10577
|
+
fallbackText: hit.text
|
|
10578
|
+
});
|
|
10579
|
+
xml = rendered.xml;
|
|
10580
|
+
hitImages = rendered.images;
|
|
10581
|
+
} catch {
|
|
10582
|
+
xml = hit.text;
|
|
10583
|
+
}
|
|
10584
|
+
parts.push(note);
|
|
10585
|
+
parts.push(xml);
|
|
10586
|
+
images.push(...hitImages);
|
|
10587
|
+
}
|
|
10700
10588
|
return {
|
|
10701
|
-
|
|
10702
|
-
|
|
10703
|
-
|
|
10589
|
+
text: parts.join("\n"),
|
|
10590
|
+
images
|
|
10591
|
+
};
|
|
10592
|
+
}
|
|
10593
|
+
//#endregion
|
|
10594
|
+
//#region src/recall.ts
|
|
10595
|
+
/**
|
|
10596
|
+
* recall 工具:回看原始会话(含被压缩内容),语义增强启用时额外支持按含义检索。
|
|
10597
|
+
* 导出 recallArgsSchema / enhancedRecallArgsSchema / RecallArgs / parseRecallArgs / buildRecallTool。
|
|
10598
|
+
* - 区间模式:按完整消息 index 的 start/end/offset 精确返回区间内全部完整消息。
|
|
10599
|
+
* - 语义模式(仅增强启用且带 query):语义检索见 semantic-recall.ts。
|
|
10600
|
+
* 输出值为 { text, images }(契约见 recall-output.ts),text 为 XML 条目序列
|
|
10601
|
+
* (形态见 recall-xml.ts);recall 自身不设输出上限,超大工具结果由 tool-result-pruner 裁剪。
|
|
10602
|
+
*/
|
|
10603
|
+
/**
|
|
10604
|
+
* 基础 recall 参数 schema:start 必填;end 与 offset 至少提供一个(同时给出时 end 优先)。
|
|
10605
|
+
* 各字段描述经 .describe() 透传到 wire JSON Schema。
|
|
10606
|
+
*/
|
|
10607
|
+
const recallArgsSchema = z.object({
|
|
10608
|
+
start: z.number().describe("完整消息 index,基准边界,与 end 或 offset 配合指定区间;end 与 offset 至少提供一个(同时给出时 end 优先)。"),
|
|
10609
|
+
end: z.number().optional().describe("与 offset 互斥,指定区间另一边界。"),
|
|
10610
|
+
offset: z.number().optional().describe("与 end 互斥,相对 start 的步数(正向后、负向前)。")
|
|
10611
|
+
}).refine((args) => args.end !== void 0 || args.offset !== void 0, { message: "end 与 offset 至少提供一个" });
|
|
10612
|
+
/**
|
|
10613
|
+
* 语义增强 recall 参数 schema:带 query 走语义模式(区间可选,用于限定检索范围),
|
|
10614
|
+
* 不带 query 时与基础 schema 的校验一致。
|
|
10615
|
+
*/
|
|
10616
|
+
const enhancedRecallArgsSchema = z.object({
|
|
10617
|
+
query: z.string().optional().describe("按含义检索的自然语言 query(中英文与代码术语皆可,如 \"修复 retry backoff 的逻辑\");提供时 start/end/offset 仅用于限定搜索区间,缺省检索全部。"),
|
|
10618
|
+
top_k: z.number().int().min(1).max(10).optional().describe("仅 query 模式:返回最匹配条数(1-10,默认 3)。"),
|
|
10619
|
+
start: z.number().optional().describe("完整消息 index,基准边界,与 end 或 offset 配合指定区间;未提供 query 时必填,且 end 与 offset 至少提供一个(同时给出时 end 优先)。"),
|
|
10620
|
+
end: z.number().optional().describe("与 offset 互斥,指定区间另一边界。"),
|
|
10621
|
+
offset: z.number().optional().describe("与 end 互斥,相对 start 的步数(正向后、负向前)。")
|
|
10622
|
+
}).superRefine((args, ctx) => {
|
|
10623
|
+
if (args.query !== void 0) {
|
|
10624
|
+
if (args.query.trim().length === 0) ctx.addIssue({
|
|
10625
|
+
code: "custom",
|
|
10626
|
+
path: ["query"],
|
|
10627
|
+
message: "query 不能为空"
|
|
10628
|
+
});
|
|
10629
|
+
return;
|
|
10630
|
+
}
|
|
10631
|
+
if (args.start === void 0) ctx.addIssue({
|
|
10632
|
+
code: "custom",
|
|
10633
|
+
path: ["start"],
|
|
10634
|
+
message: "未提供 query 时 start 必填"
|
|
10635
|
+
});
|
|
10636
|
+
else if (args.end === void 0 && args.offset === void 0) ctx.addIssue({
|
|
10637
|
+
code: "custom",
|
|
10638
|
+
path: ["end"],
|
|
10639
|
+
message: "end 与 offset 至少提供一个"
|
|
10640
|
+
});
|
|
10641
|
+
});
|
|
10642
|
+
/** 解析并校验 recall 调用参数(semantic 为语义增强是否启用):失败时抛出首个校验问题的可读消息。 */
|
|
10643
|
+
function parseRecallArgs(raw, semantic = false) {
|
|
10644
|
+
const result = (semantic ? enhancedRecallArgsSchema : recallArgsSchema).safeParse(raw);
|
|
10645
|
+
if (!result.success) throw new Error(result.error.issues.map((issue) => `${issue.path.join(".") || "args"}: ${issue.message}`).join("; "));
|
|
10646
|
+
return result.data;
|
|
10647
|
+
}
|
|
10648
|
+
/** 基础工具描述。 */
|
|
10649
|
+
const RECALL_DESCRIPTION = "在你需要查看历史消息时调用。此工具按 index 区间精确返回区间内全部完整消息的内容。";
|
|
10650
|
+
/** 语义增强启用时的工具描述。 */
|
|
10651
|
+
const ENHANCED_RECALL_DESCRIPTION = "在你需要查看历史消息时调用。两种用法:1) 给出 start 与 end 或 offset,按 index 区间精确返回区间内全部完整消息的内容;2) 给出 query,按自然语言含义检索最符合的完整消息,默认全量搜索,可用 start/end/offset 限定区间。注意:query 只匹配文本。";
|
|
10652
|
+
/**
|
|
10653
|
+
* 构建 recall 工具定义:按 start/end/offset 定位完整消息区间并渲染原始内容(标 index);
|
|
10654
|
+
* 传入 semantic 选项时额外支持 query 语义检索。
|
|
10655
|
+
*/
|
|
10656
|
+
function buildRecallTool(options) {
|
|
10657
|
+
const getPruner = options?.getPruner;
|
|
10658
|
+
const semantic = options?.semantic;
|
|
10659
|
+
return {
|
|
10660
|
+
name: "recall",
|
|
10661
|
+
description: semantic ? ENHANCED_RECALL_DESCRIPTION : RECALL_DESCRIPTION,
|
|
10662
|
+
parameters: parametersFromZod(semantic ? enhancedRecallArgsSchema : recallArgsSchema),
|
|
10704
10663
|
output: {
|
|
10705
10664
|
schema: RECALL_OUTPUT_SCHEMA,
|
|
10706
10665
|
render: (_args, value) => renderRecallOutput(value)
|
|
10707
10666
|
},
|
|
10708
10667
|
async execute(args, exec) {
|
|
10709
|
-
const { query, top_k, start, end, offset } =
|
|
10668
|
+
const { query, top_k, start, end, offset } = parseRecallArgs(args, semantic !== void 0);
|
|
10710
10669
|
const session = exec.agent?.session;
|
|
10711
10670
|
if (!session) return textOnly("会话异常");
|
|
10712
|
-
if (!isMainSession(session)) return textOnly("recall
|
|
10713
|
-
if (
|
|
10714
|
-
|
|
10715
|
-
|
|
10716
|
-
|
|
10671
|
+
if (!isMainSession(session)) return textOnly("recall 仅主会话可用");
|
|
10672
|
+
if (query !== void 0) return semanticSearch({
|
|
10673
|
+
session,
|
|
10674
|
+
query,
|
|
10675
|
+
topK: top_k,
|
|
10717
10676
|
start,
|
|
10718
10677
|
end,
|
|
10719
|
-
offset
|
|
10678
|
+
offset,
|
|
10679
|
+
selfCallId: String(exec.callId ?? ""),
|
|
10680
|
+
getPruner: () => getPruner?.(),
|
|
10681
|
+
options: semantic
|
|
10720
10682
|
});
|
|
10721
|
-
|
|
10722
|
-
const
|
|
10723
|
-
|
|
10724
|
-
|
|
10725
|
-
|
|
10726
|
-
|
|
10727
|
-
|
|
10728
|
-
|
|
10729
|
-
|
|
10730
|
-
|
|
10731
|
-
|
|
10732
|
-
|
|
10733
|
-
text
|
|
10734
|
-
});
|
|
10683
|
+
if (start === void 0) return textOnly("start 必填");
|
|
10684
|
+
const cms = indexCompleteMessages(session);
|
|
10685
|
+
const startIndex = Number.isFinite(start) ? Math.floor(start) : 0;
|
|
10686
|
+
if (startIndex < 0 || startIndex >= cms.length) return textOnly(`start ${start} 越界(完整消息共 ${cms.length} 条,index 范围 0..${cms.length - 1})`);
|
|
10687
|
+
let endIndex;
|
|
10688
|
+
if (end !== void 0) {
|
|
10689
|
+
const e = Number.isFinite(end) ? Math.floor(end) : 0;
|
|
10690
|
+
if (e < 0 || e >= cms.length) return textOnly(`end ${end} 越界(完整消息共 ${cms.length} 条,index 范围 0..${cms.length - 1})`);
|
|
10691
|
+
endIndex = e;
|
|
10692
|
+
} else {
|
|
10693
|
+
const raw = offset ?? 0;
|
|
10694
|
+
endIndex = startIndex + (Number.isFinite(raw) ? Math.floor(raw) : 0);
|
|
10735
10695
|
}
|
|
10736
|
-
|
|
10737
|
-
const
|
|
10738
|
-
|
|
10739
|
-
const vectors = await embed(candidates.map((c) => c.text));
|
|
10740
|
-
const scored = candidates.map((c, i) => ({
|
|
10741
|
-
cm: c.cm,
|
|
10742
|
-
text: c.text,
|
|
10743
|
-
score: cosineSimilarity(queryVec, vectors[i] ?? /* @__PURE__ */ new Float32Array(0))
|
|
10744
|
-
}));
|
|
10745
|
-
scored.sort((a, b) => b.score - a.score);
|
|
10746
|
-
const limit = top_k ?? 3;
|
|
10747
|
-
const hits = scored.slice(0, limit);
|
|
10696
|
+
const lo = Math.max(0, Math.min(startIndex, endIndex));
|
|
10697
|
+
const hi = Math.min(cms.length - 1, Math.max(startIndex, endIndex));
|
|
10698
|
+
const pruner = getPruner?.();
|
|
10748
10699
|
const parts = [];
|
|
10749
10700
|
const images = [];
|
|
10750
|
-
|
|
10751
|
-
|
|
10752
|
-
|
|
10753
|
-
parts.push(`<!-- ${xmlCommentText(`匹配 TOP-${hits.length}(共 ${scored.length} 条候选)`)} -->`);
|
|
10754
|
-
for (let i = 0; i < hits.length; i += 1) {
|
|
10755
|
-
const hit = hits[i];
|
|
10756
|
-
if (!hit) continue;
|
|
10757
|
-
const note = `<!-- ${xmlCommentText(`${i + 1}. ${matchExplanation(query, hit.text, hit.score)}`)} -->`;
|
|
10758
|
-
let xml;
|
|
10759
|
-
let hitImages = [];
|
|
10701
|
+
for (let i = lo; i <= hi; i += 1) {
|
|
10702
|
+
const cm = cms[i];
|
|
10703
|
+
if (!cm) continue;
|
|
10760
10704
|
try {
|
|
10761
|
-
const
|
|
10762
|
-
|
|
10763
|
-
|
|
10764
|
-
|
|
10765
|
-
});
|
|
10766
|
-
xml = rendered.xml;
|
|
10767
|
-
hitImages = rendered.images;
|
|
10768
|
-
} catch {
|
|
10769
|
-
xml = hit.text;
|
|
10770
|
-
}
|
|
10771
|
-
parts.push(note);
|
|
10772
|
-
parts.push(xml);
|
|
10773
|
-
images.push(...hitImages);
|
|
10705
|
+
const rendered = renderCompleteMessageXml(session, cm, { pruner });
|
|
10706
|
+
parts.push(rendered.xml);
|
|
10707
|
+
images.push(...rendered.images);
|
|
10708
|
+
} catch {}
|
|
10774
10709
|
}
|
|
10710
|
+
if (parts.length === 0) return textOnly("指定区间没有完整消息");
|
|
10775
10711
|
return {
|
|
10776
10712
|
text: parts.join("\n"),
|
|
10777
10713
|
images
|
|
@@ -10780,6 +10716,84 @@ function buildSemanticRecallTool(options) {
|
|
|
10780
10716
|
};
|
|
10781
10717
|
}
|
|
10782
10718
|
//#endregion
|
|
10719
|
+
//#region src/system-reminder.ts
|
|
10720
|
+
/**
|
|
10721
|
+
* system-reminder:以 <system-reminder> 用户消息向主会话注入插件提醒,不进系统提示词。
|
|
10722
|
+
* - 进度提醒:OM 启用时提示模型边做边简述计划与进展。
|
|
10723
|
+
* - 完整消息定义提醒:OM 或 recall 启用时说明 `<history>` 块与 recall 共用的完整消息 index。
|
|
10724
|
+
* 每个 step 检查表层,被压缩遮蔽或文本过期时补发,保证模型请求中每种恒有一条。
|
|
10725
|
+
* 导出 PROGRESS_REMINDER_SOURCE_KIND / DEFINITION_REMINDER_SOURCE_KIND / 对应 source 类型 /
|
|
10726
|
+
* SystemReminder / PROGRESS_REMINDER / DEFINITION_REMINDER / systemReminderMessage /
|
|
10727
|
+
* activeSystemReminders / ensureSystemReminders。
|
|
10728
|
+
*/
|
|
10729
|
+
/** 进度提醒的 producer-owned source kind(区别于压缩日志消息的 plugin:dsh-plugin-om)。 */
|
|
10730
|
+
const PROGRESS_REMINDER_SOURCE_KIND = "plugin:dsh-plugin-om:progress";
|
|
10731
|
+
/** 完整消息定义提醒的 producer-owned source kind。 */
|
|
10732
|
+
const DEFINITION_REMINDER_SOURCE_KIND = "plugin:dsh-plugin-om:definition";
|
|
10733
|
+
/** 用 system-reminder 标签包裹提醒正文。 */
|
|
10734
|
+
function wrap(lines) {
|
|
10735
|
+
return [
|
|
10736
|
+
"<system-reminder>",
|
|
10737
|
+
...lines,
|
|
10738
|
+
"</system-reminder>"
|
|
10739
|
+
].join("\n");
|
|
10740
|
+
}
|
|
10741
|
+
/** 进度提醒。 */
|
|
10742
|
+
const PROGRESS_REMINDER = {
|
|
10743
|
+
kind: PROGRESS_REMINDER_SOURCE_KIND,
|
|
10744
|
+
text: wrap([
|
|
10745
|
+
"在工作过程中同步输出文本,简洁记录关键结论与后续规划。思考内容不计入记录。",
|
|
10746
|
+
"- 每个阶段性工作开始前记录一次,一个阶段通常是 1-5 个工具调用",
|
|
10747
|
+
"- 禁止连续 10 个以上工具调用而无记录",
|
|
10748
|
+
"- 记录后在同一回复中继续调用工具,不要停下等待",
|
|
10749
|
+
"- 最终答案仅总结结果,不能替代这些记录"
|
|
10750
|
+
])
|
|
10751
|
+
};
|
|
10752
|
+
/** 完整消息定义提醒。 */
|
|
10753
|
+
const DEFINITION_REMINDER = {
|
|
10754
|
+
kind: DEFINITION_REMINDER_SOURCE_KIND,
|
|
10755
|
+
text: wrap([COMPLETE_MESSAGE_DEFINITION])
|
|
10756
|
+
};
|
|
10757
|
+
/** 构造一条新的提醒消息。 */
|
|
10758
|
+
function systemReminderMessage(reminder) {
|
|
10759
|
+
return createUserMessage({
|
|
10760
|
+
content: [{
|
|
10761
|
+
type: "text",
|
|
10762
|
+
text: reminder.text
|
|
10763
|
+
}],
|
|
10764
|
+
source: {
|
|
10765
|
+
kind: reminder.kind,
|
|
10766
|
+
form: "instructions"
|
|
10767
|
+
}
|
|
10768
|
+
});
|
|
10769
|
+
}
|
|
10770
|
+
/** 按配置与当前表层是否有 history 块返回应注入的提醒,顺序固定:进度在前,定义在后。 */
|
|
10771
|
+
function activeSystemReminders(config, hasHistory) {
|
|
10772
|
+
const reminders = [];
|
|
10773
|
+
if (config.omEnabled) reminders.push(PROGRESS_REMINDER);
|
|
10774
|
+
if (config.recallEnabled || hasHistory) reminders.push(DEFINITION_REMINDER);
|
|
10775
|
+
return reminders;
|
|
10776
|
+
}
|
|
10777
|
+
/** 消息是否为指定提醒的当前文本。 */
|
|
10778
|
+
function isCurrent(reminder, source, content) {
|
|
10779
|
+
return source.kind === reminder.kind && content.length === 1 && content[0]?.type === "text" && content[0].text === reminder.text;
|
|
10780
|
+
}
|
|
10781
|
+
/**
|
|
10782
|
+
* 保证本 step 之后的消息列表中每种指定提醒各有一条当前文本:本 step 已带上或表层已有则跳过,
|
|
10783
|
+
* 否则按顺序追加到末尾。返回新数组,不修改入参。
|
|
10784
|
+
*/
|
|
10785
|
+
function ensureSystemReminders(session, messages, reminders) {
|
|
10786
|
+
const result = [...messages];
|
|
10787
|
+
if (reminders.length === 0) return result;
|
|
10788
|
+
const events = session.snapshotEvents();
|
|
10789
|
+
const surface = session.surface.nodes.flatMap((seq) => {
|
|
10790
|
+
const event = events[seq];
|
|
10791
|
+
return event?.type === "user/message" ? [event.data] : [];
|
|
10792
|
+
});
|
|
10793
|
+
for (const reminder of reminders) if (![...result, ...surface].some((message) => isCurrent(reminder, message.source, message.content))) result.push(systemReminderMessage(reminder));
|
|
10794
|
+
return result;
|
|
10795
|
+
}
|
|
10796
|
+
//#endregion
|
|
10783
10797
|
//#region src/index.ts
|
|
10784
10798
|
/** 插件名(Loader 识别入口的稳定标识)。 */
|
|
10785
10799
|
const name = "dsh-plugin-om";
|
|
@@ -10790,7 +10804,7 @@ const inject = [
|
|
|
10790
10804
|
"tokenMeter",
|
|
10791
10805
|
"sessions"
|
|
10792
10806
|
];
|
|
10793
|
-
/** 插件激活入口:解析配置、注册工具、接线 pre-step
|
|
10807
|
+
/** 插件激活入口:解析配置、注册工具、接线 pre-step 自动压缩与提醒补发。 */
|
|
10794
10808
|
function apply(ctx, config) {
|
|
10795
10809
|
const resolved = currentConfig(config);
|
|
10796
10810
|
const logger = makeLogger(ctx, () => currentConfig(config).debug);
|
|
@@ -10798,32 +10812,32 @@ function apply(ctx, config) {
|
|
|
10798
10812
|
const warnModel = (message) => ctx.logger.warn(`dsh-plugin-om: ${message}`);
|
|
10799
10813
|
const logModel = (message) => logger.info(message);
|
|
10800
10814
|
let disposeRecall;
|
|
10801
|
-
|
|
10802
|
-
let
|
|
10803
|
-
|
|
10804
|
-
/** 保持实际注册列表与当前配置一致;仅首次启用或更换目录时启动后台预热。 */
|
|
10815
|
+
/** 当前已注册 recall 对应的语义增强开关与模型目录。 */
|
|
10816
|
+
let registered;
|
|
10817
|
+
/** 保持注册的 recall 与当前配置一致;仅语义增强首次生效或更换目录时启动后台预热。 */
|
|
10805
10818
|
function syncTools() {
|
|
10806
10819
|
const next = currentConfig(config);
|
|
10807
|
-
|
|
10808
|
-
|
|
10820
|
+
const semantic = next.recallEnabled && next.semanticRecallEnabled;
|
|
10821
|
+
if (disposeRecall && (!next.recallEnabled || registered?.semantic !== semantic || semantic && registered.modelDir !== next.modelDir)) {
|
|
10809
10822
|
disposeRecall();
|
|
10810
10823
|
disposeRecall = void 0;
|
|
10824
|
+
registered = void 0;
|
|
10811
10825
|
}
|
|
10812
|
-
if (
|
|
10813
|
-
disposeSemantic();
|
|
10814
|
-
disposeSemantic = void 0;
|
|
10815
|
-
}
|
|
10816
|
-
if (next.semanticRecallEnabled && !disposeSemantic) {
|
|
10826
|
+
if (next.recallEnabled && !disposeRecall) {
|
|
10817
10827
|
const directory = next.modelDir;
|
|
10818
|
-
|
|
10828
|
+
disposeRecall = ctx.tools.register(buildRecallTool({
|
|
10819
10829
|
getPruner: () => ctx.get("toolResultPruner"),
|
|
10820
|
-
|
|
10821
|
-
|
|
10830
|
+
...semantic ? { semantic: {
|
|
10831
|
+
modelStatus: () => ensureModelReady(directory, warnModel, void 0, logModel),
|
|
10832
|
+
embedder: (texts) => getEmbedder(directory).then((embed) => embed(texts))
|
|
10833
|
+
} } : {}
|
|
10822
10834
|
}));
|
|
10835
|
+
registered = {
|
|
10836
|
+
semantic,
|
|
10837
|
+
modelDir: directory
|
|
10838
|
+
};
|
|
10839
|
+
if (semantic) ensureModelReady(directory, warnModel, void 0, logModel);
|
|
10823
10840
|
}
|
|
10824
|
-
if (next.semanticRecallEnabled && (!semanticEnabled || next.modelDir !== modelDir)) ensureModelReady(next.modelDir, warnModel, void 0, logModel);
|
|
10825
|
-
modelDir = next.modelDir;
|
|
10826
|
-
semanticEnabled = next.semanticRecallEnabled;
|
|
10827
10841
|
}
|
|
10828
10842
|
syncTools();
|
|
10829
10843
|
ctx.on("loader/volatile-update", () => syncTools());
|
|
@@ -10845,9 +10859,11 @@ function apply(ctx, config) {
|
|
|
10845
10859
|
return { kind: "reject" };
|
|
10846
10860
|
}
|
|
10847
10861
|
const decision = await next();
|
|
10848
|
-
|
|
10862
|
+
const hasHistory = hasHistoryBlock(agent.session);
|
|
10863
|
+
const reminders = activeSystemReminders(currentConfig(config), hasHistory);
|
|
10864
|
+
if (decision.kind === "enter" && !signal.aborted && reminders.length > 0 && isMainSession(agent.session)) return {
|
|
10849
10865
|
...decision,
|
|
10850
|
-
messages:
|
|
10866
|
+
messages: ensureSystemReminders(agent.session, decision.messages, reminders)
|
|
10851
10867
|
};
|
|
10852
10868
|
return decision;
|
|
10853
10869
|
});
|