dsh-plugin-om 0.0.50 → 0.0.52

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.
Files changed (48) hide show
  1. package/README.md +14 -6
  2. package/dist/client/OmCompactionCard.d.ts +12 -5
  3. package/dist/client/OmCompactionCard.d.ts.map +1 -1
  4. package/dist/client/OmRecompressMenu.d.ts +13 -0
  5. package/dist/client/OmRecompressMenu.d.ts.map +1 -0
  6. package/dist/client/definition.d.ts +2 -0
  7. package/dist/client/definition.d.ts.map +1 -1
  8. package/dist/client/index.d.ts.map +1 -1
  9. package/dist/client/locales.d.ts +13 -1
  10. package/dist/client/locales.d.ts.map +1 -1
  11. package/dist/client/recompress-inject.d.ts +9 -0
  12. package/dist/client/recompress-inject.d.ts.map +1 -0
  13. package/dist/client/recompress-run.d.ts +73 -0
  14. package/dist/client/recompress-run.d.ts.map +1 -0
  15. package/dist/client.js +426 -60
  16. package/dist/client.js.map +1 -1
  17. package/dist/compaction-log.d.ts +28 -4
  18. package/dist/compaction-log.d.ts.map +1 -1
  19. package/dist/compress-loop.d.ts +6 -0
  20. package/dist/compress-loop.d.ts.map +1 -1
  21. package/dist/compress-tools.d.ts +2 -2
  22. package/dist/compress-tools.d.ts.map +1 -1
  23. package/dist/compress-view.d.ts +6 -8
  24. package/dist/compress-view.d.ts.map +1 -1
  25. package/dist/compress.d.ts +7 -3
  26. package/dist/compress.d.ts.map +1 -1
  27. package/dist/constants.d.ts +3 -5
  28. package/dist/constants.d.ts.map +1 -1
  29. package/dist/format.d.ts +6 -0
  30. package/dist/format.d.ts.map +1 -0
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.mjs +354 -152
  33. package/dist/log-index.d.ts +2 -2
  34. package/dist/log-index.d.ts.map +1 -1
  35. package/dist/recall-xml.d.ts +0 -1
  36. package/dist/recall-xml.d.ts.map +1 -1
  37. package/dist/recall.d.ts.map +1 -1
  38. package/dist/recompress.d.ts +66 -0
  39. package/dist/recompress.d.ts.map +1 -0
  40. package/dist/system-reminder.d.ts +5 -14
  41. package/dist/system-reminder.d.ts.map +1 -1
  42. package/dist/types.d.ts +7 -12
  43. package/dist/types.d.ts.map +1 -1
  44. package/dist/utils.d.ts +3 -1
  45. package/dist/utils.d.ts.map +1 -1
  46. package/package.json +4 -1
  47. package/dist/client/format.d.ts +0 -6
  48. package/dist/client/format.d.ts.map +0 -1
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
1
  import { CompactionId } from "@deepseek-ai/dsh-compaction";
2
- import { BlockAssembler, createToolResultMessage, createUserMessage } from "@deepseek-ai/dsh-llm";
2
+ import { BlockAssembler, createAssistantMessage, createToolResultMessage, createUserMessage } from "@deepseek-ai/dsh-llm";
3
3
  import { scopeOf } from "@deepseek-ai/dsh-scope";
4
4
  import { SessionId, SessionSeq } from "@deepseek-ai/dsh-session";
5
5
  import { renderPrompt } from "@deepseek-ai/dsh-system-prompt";
@@ -15,6 +15,22 @@ import { AttachmentId } from "@deepseek-ai/dsh-attachment";
15
15
  //#region \0rolldown/runtime.js
16
16
  var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
17
17
  //#endregion
18
+ //#region src/format.ts
19
+ /**
20
+ * 紧凑数字格式化(压缩卡片、重压缩记录与压缩日志共用)。零依赖,服务端与浏览器均可引用。导出 formatCompactCount。
21
+ * <1k 原样;≥1k 用 k;≥1w(万)用 w;≥1M 用 M;保留 1 位小数并去掉末尾 .0。
22
+ */
23
+ function formatCompactCount(value) {
24
+ const trim = (n) => {
25
+ const text = String(Math.round(n * 10) / 10);
26
+ return text.endsWith(".0") ? text.slice(0, -2) : text;
27
+ };
28
+ if (value >= 1e6) return `${trim(value / 1e6)}M`;
29
+ if (value >= 1e4) return `${trim(value / 1e4)}w`;
30
+ if (value >= 1e3) return `${trim(value / 1e3)}k`;
31
+ return String(value);
32
+ }
33
+ //#endregion
18
34
  //#region src/constants.ts
19
35
  /** 插件标识:日志前缀与历史日志的 source.plugin 取值。 */
20
36
  const PLUGIN_LABEL = "dsh-plugin-om";
@@ -36,19 +52,22 @@ const HISTORY_TAG = "history";
36
52
  /** 压缩日志块开标签的 tip 属性(对 AI 的提醒:本块是历史压缩产物,不要复述)。 */
37
53
  const HISTORY_TIP = "当前块是历史消息的压缩产物,不要复述";
38
54
  /**
39
- * 「完整消息」定义(压缩提示词与主会话 system-reminder 共用)。
55
+ * 「完整消息」定义(压缩提示词、recall 工具描述与 <history> 块顶注释共用)。
40
56
  * 完整消息是摘要日志与 recall 共用的定位单位;首条 index 为 0,按会话顺序递增、全局稳定。
41
57
  */
42
- const COMPLETE_MESSAGE_DEFINITION = "`完整消息`指一条`用户消息`、`系统消息`、`模型输出文本`或`具有result的toolcall`;首条 index 为 0,按会话顺序递增。";
58
+ const COMPLETE_MESSAGE_DEFINITION = "`完整消息`指一条`用户消息`、`模型输出文本`或`具有result的toolcall`;首条 index 为 0,按会话顺序递增。";
43
59
  /**
44
60
  * 最终 <history> 块内文块首的格式说明注释(XML 注释)。通用部分(条目标签语义 +
45
- * CDATA 约定 + toolcall 结构)始终保留;<user_message> / <sys> /
61
+ * CDATA 约定 + toolcall 结构)始终保留;<user_message> /
46
62
  * <skill_content> / <ask-user-question> 的条目说明仅在块内存在对应条目时追加。
47
63
  */
48
64
  function historyFormatNote(sections = {}) {
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子元素(调用参数与工具返回内容)"];
65
+ const parts = [
66
+ COMPLETE_MESSAGE_DEFINITION,
67
+ "<TAG index=\"N\">表示单条完整消息,<TAG start=\"A\" end=\"B\"> 表示多条连续消息,start/end 是首尾完整消息的 index;消息块的内容是用CDATA包裹的纯文本",
68
+ "<assistant type=\"toolcall\" tool-name=\"T\" callId=\"C\" index=\"N\"> 表示工具调用,内含 <tool-args> 与 <tool-result> 两个CDATA子元素(调用参数与工具返回内容)"
69
+ ];
50
70
  if (sections.user) parts.push("<user_message index=\"N\"> 表示用户消息原文");
51
- if (sections.sys) parts.push("<sys type=\"KIND\" index=\"N\"> 表示被压缩的系统消息,块中为空");
52
71
  if (sections.skill) parts.push("<skill_content name=\"S\" index=\"N\"> 表示未压缩的原始 skill");
53
72
  if (sections.askUserQuestion) parts.push("<ask-user-question index=\"N\"> 表示向用户提问,CDATA 内为逐题成对的 q:(提问)与 a:(用户回答)行,未作答的题记为 a:(未回答)");
54
73
  return `<!-- ${parts.join(";")} -->`;
@@ -123,6 +142,14 @@ function textCharCount(message) {
123
142
  else if (block.type === "tool-result") total += blocksToText(block.content).length;
124
143
  return total;
125
144
  }
145
+ /** 一组表层事件 seq 派生消息的字符数之和(OM 卡片「原始字符」口径)。 */
146
+ function seqsCharCount(session, seqs) {
147
+ const events = session.snapshotEvents();
148
+ return seqs.reduce((total, seq) => {
149
+ const event = events[seq];
150
+ return total + textCharCount(event ? session.deriveEventMessage(event) : null);
151
+ }, 0);
152
+ }
126
153
  /** 面向 recall 的完整消息呈现:text 原样;tool-call 展开(参数=代码);tool-result 取文本。 */
127
154
  function renderMessageText(message) {
128
155
  if (!message || !Array.isArray(message.content)) return "";
@@ -186,9 +213,23 @@ function phaseLabel(phase) {
186
213
  if (phase === "reflect") return "反思";
187
214
  return "压缩";
188
215
  }
189
- /** 压缩会话记录 label:成功为会话记录、失败为失败日志,均含压缩阶段与轮数。 */
190
- function compressionRecordLabel(phase, rounds, success) {
191
- return `OM 压缩${success ? "会话记录" : "失败日志"}(${phaseLabel(phase)} · ${rounds} 轮)`;
216
+ /**
217
+ * 压缩会话记录 label:成功为会话记录、失败为失败日志,均含压缩阶段与轮数;
218
+ * 换模型重压缩传入 retryTarget,label 末尾追加「重压缩 provider/model」以区分。
219
+ */
220
+ function compressionRecordLabel(phase, rounds, success, retryTarget) {
221
+ const retry = retryTarget === void 0 ? "" : ` · 重压缩 ${retryTarget.provider}/${retryTarget.model}`;
222
+ return `OM 压缩${success ? "会话记录" : "失败日志"}(${phaseLabel(phase)} · ${rounds} 轮${retry})`;
223
+ }
224
+ /** 生成模型信息:压缩模型、思考等级、原始消息与压缩产物的字符数(k 单位)。 */
225
+ function compressionInfo(info) {
226
+ const effort = info.reasoningEffort ?? "默认思考等级";
227
+ const result = info.resultChars === void 0 ? "无(压缩失败)" : `${formatCompactCount(info.resultChars)} 字符`;
228
+ return {
229
+ text: `压缩使用模型 ${info.target.provider}/${info.target.model}(${effort}),原始消息 ${formatCompactCount(info.originalChars)} 字符,压缩产物 ${result}`,
230
+ provider: info.target.provider,
231
+ model: info.target.model
232
+ };
192
233
  }
193
234
  /**
194
235
  * 构造一个 seed 事件信封:seq 由调用方按顺序传入,surface 事件附 surfaceOp:'append'。
@@ -213,7 +254,7 @@ function seedEvent(type, seq, time, data, surfaceOp) {
213
254
  * 时间全程单调不减;轮次数组短于 assistant 数时(流错误注入的部分 assistant)回落上一
214
255
  * 轮结束时刻与循环结束时刻。
215
256
  */
216
- function buildCompressionSeed(messages, stats, label) {
257
+ function buildCompressionSeed(messages, stats, label, info) {
217
258
  const seed = [];
218
259
  const push = (type, time, data, surfaceOp) => {
219
260
  seed.push(seedEvent(type, seed.length, time, data, surfaceOp));
@@ -305,6 +346,32 @@ function buildCompressionSeed(messages, stats, label) {
305
346
  }, "append");
306
347
  else push("user/message", at(step === 0 ? stats.startedAt : stepTime), message, "append");
307
348
  closeStep();
349
+ if (info !== void 0) {
350
+ step += 1;
351
+ push("step/start", at(stats.completedAt), {
352
+ turn: 1,
353
+ step
354
+ });
355
+ push("assistant/message", at(stats.completedAt), {
356
+ turn: 1,
357
+ step,
358
+ message: createAssistantMessage({
359
+ content: [{
360
+ type: "text",
361
+ text: info.text
362
+ }],
363
+ source: {
364
+ provider: info.provider,
365
+ model: info.model
366
+ }
367
+ }),
368
+ stream: []
369
+ }, "append");
370
+ push("step/end", at(stats.completedAt), {
371
+ turn: 1,
372
+ step
373
+ });
374
+ }
308
375
  push("turn/end", at(stats.completedAt), {
309
376
  turn: 1,
310
377
  reason: { kind: "completed" }
@@ -315,7 +382,7 @@ function buildCompressionSeed(messages, stats, label) {
315
382
  * 把一次压缩工具循环的完整会话消息组落盘为子会话:以重建时间线的 seed 事件经
316
383
  * ctx.sessions.create 构造子会话(header origin 'subagent'、parentSession 指向主会话、
317
384
  * delegationDepth = 父 + 1、cwd 继承主会话;首事件 one-shot descriptor,provider
318
- * om-compaction-log,label 含压缩阶段与轮数),flush 持久化,在父会话登记
385
+ * om-compaction-log,label 含压缩阶段与轮数;info 存在时尾部追加一条模型文本),flush 持久化,在父会话登记
319
386
  * subagent/catalog,返回子会话 id。成功与失败均调用;落盘自身绝不抛错,任何失败仅
320
387
  * logger.warn 并返回 undefined。
321
388
  */
@@ -323,8 +390,8 @@ async function recordCompressionSession(ctx, parentSession, options) {
323
390
  const logger = makeLogger(ctx, options.debug);
324
391
  try {
325
392
  const header = parentSession.header;
326
- const label = compressionRecordLabel(options.phase, options.stats.rounds.length, options.success);
327
- const seed = buildCompressionSeed(options.messages, options.stats, label);
393
+ const label = compressionRecordLabel(options.phase, options.stats.rounds.length, options.success, options.retryTarget);
394
+ const seed = buildCompressionSeed(options.messages, options.stats, label, options.info);
328
395
  const child = ctx.sessions.create(SessionId(`om-compaction-log-${uuid()}`), {
329
396
  seed,
330
397
  meta: {
@@ -7491,15 +7558,15 @@ var import_lib = (/* @__PURE__ */ __commonJSMin(((exports) => {
7491
7558
  })))();
7492
7559
  /**
7493
7560
  * 会话日志索引:完整消息索引与渲染。
7494
- * 导出 indexCompleteMessages(完整消息四类折叠索引,recall 与摘要共用同一套编号)、
7561
+ * 导出 indexCompleteMessages(完整消息三类折叠索引,recall 与摘要共用同一套编号)、
7495
7562
  * indexMessages / surfaceIndexOf / messageIdOfEvent(消息级定位辅助)、
7496
7563
  * collectImageRefs / toolCallBlockOf / toolResultMessageOf / renderToolResultText /
7497
7564
  * renderCompleteMessageParts /
7498
7565
  * renderCompleteMessage(完整消息渲染与图片附件收集)。事件日志仅追加(被遮蔽的事件仍可读,
7499
7566
  * recall 依赖此性质)。
7500
7567
  *
7501
- * 完整消息分四类:user(用户消息)、sys(系统消息,压缩日志中以 <sys> 空块表示)、
7502
- * assistant(模型输出文本)、toolcall(单个工具调用及其结果,result 按 callId 匹配并入)。
7568
+ * 完整消息分三类:user(用户消息)、assistant(模型输出文本)、
7569
+ * toolcall(单个工具调用及其结果,result 按 callId 匹配并入)。系统消息不占位。
7503
7570
  * index 从 0 起、按日志顺序递增、只追加不重排(压缩后旧摘要条目引用的 index 仍然有效)。
7504
7571
  */
7505
7572
  /** 查找 seq 在表层节点序列中的下标(不在则返回 -1)。 */
@@ -7508,7 +7575,7 @@ function surfaceIndexOf(nodes, seq) {
7508
7575
  return -1;
7509
7576
  }
7510
7577
  /**
7511
- * 完整消息索引:按日志顺序把消息事件折叠为完整消息序列(四类,见文件头)。
7578
+ * 完整消息索引:按日志顺序把消息事件折叠为完整消息序列(三类,见文件头)。
7512
7579
  * 工具调用结果按 source.callId 匹配其 tool-call 并入该条;未匹配的 result 独立成条(防御)。
7513
7580
  * 本插件自产消息不占位;压缩在 agent/pre-step 触发(call-result 完备),不存在未闭合调用。
7514
7581
  */
@@ -7527,12 +7594,6 @@ function indexCompleteMessages(session) {
7527
7594
  type: "user",
7528
7595
  seqs: [seq]
7529
7596
  });
7530
- else cms.push({
7531
- index: cms.length,
7532
- type: "sys",
7533
- seqs: [seq],
7534
- ...source?.kind === void 0 ? {} : { kind: source.kind }
7535
- });
7536
7597
  } else if (event.type === "assistant/message") {
7537
7598
  const message = event.data.message;
7538
7599
  if (!message || !Array.isArray(message.content)) continue;
@@ -7632,13 +7693,13 @@ function renderToolResultText(session, cm, pruner) {
7632
7693
  return message ? renderMessageText(message) : "";
7633
7694
  }
7634
7695
  /** 渲染一条完整消息为「文本 + 图片」(recall 输出用):
7635
- * user/sys 取消息原文,assistant 取文本块,toolcall 为调用块 + 结果文本
7696
+ * user 取消息原文,assistant 取文本块,toolcall 为调用块 + 结果文本
7636
7697
  * (pruner 裁剪超大结果);同时收集该条完整消息携带的图片附件(含 tool-result 嵌套,
7637
7698
  * pruner 裁剪掉的图片不收集)。
7638
7699
  */
7639
7700
  function renderCompleteMessageParts(session, cm, pruner) {
7640
7701
  const images = [];
7641
- if (cm.type === "user" || cm.type === "sys") {
7702
+ if (cm.type === "user") {
7642
7703
  const seq = cm.seqs[0];
7643
7704
  const event = seq === void 0 ? void 0 : session.snapshotEvents()[seq];
7644
7705
  const message = event ? session.deriveEventMessage(event) : null;
@@ -7820,7 +7881,7 @@ function askUserQuestionText(ask) {
7820
7881
  }
7821
7882
  /**
7822
7883
  * 观察视图:被压缩区间(表层 seq 集合)内的完整消息投影为条目——
7823
- * user → 原文(图片等非文本块为注释)、sys → 空条目(手动加载的 skill 为 skill 条目)、
7884
+ * user → 原文(图片等非文本块为注释)、
7824
7885
  * assistant/toolcall → 原文渲染,reasoning 作为参考条目置于其所属 assistant 条目之前(每条 assistant 消息输出一次;
7825
7886
  * skipReasoning 时省略)。
7826
7887
  * 要求区间为区间内完整消息的首尾 index。
@@ -7841,33 +7902,6 @@ function buildObserveView(session, seqs, options = {}) {
7841
7902
  const emittedReasoning = /* @__PURE__ */ new Set();
7842
7903
  for (const cm of indexCompleteMessages(session)) {
7843
7904
  if (!cm.seqs.every((seq) => shadowed.has(seq))) continue;
7844
- if (cm.type === "sys") {
7845
- const seq = cm.seqs[0];
7846
- const event = seq === void 0 ? void 0 : session.snapshotEvents()[seq];
7847
- const source = event?.type === "user/message" ? event.data.source : void 0;
7848
- if (cm.kind === "skill-invocation" && source?.kind === "skill-invocation" && typeof source.name === "string") {
7849
- const text = renderCompleteMessage(session, cm);
7850
- if (text.trim() !== "") {
7851
- entries.push({
7852
- kind: "assistant",
7853
- lo: cm.index,
7854
- hi: cm.index,
7855
- text,
7856
- toolName: SKILL_TOOL_NAME,
7857
- skillName: source.name
7858
- });
7859
- continue;
7860
- }
7861
- }
7862
- entries.push({
7863
- kind: "sys",
7864
- lo: cm.index,
7865
- hi: cm.index,
7866
- text: "",
7867
- ...cm.kind === void 0 ? {} : { sysKind: cm.kind }
7868
- });
7869
- continue;
7870
- }
7871
7905
  if (cm.type === "user") {
7872
7906
  const parts = userEntryParts(session, cm);
7873
7907
  if (parts === null) continue;
@@ -8022,9 +8056,9 @@ function askUserQuestionSections(text) {
8022
8056
  };
8023
8057
  }
8024
8058
  /**
8025
- * 解析一个已有 <history> 块的内条目(反思视图):user_message / sys / assistant
8059
+ * 解析一个已有 <history> 块的内条目(反思视图):user_message / assistant
8026
8060
  * (index 单条或 start/end 区间)/ skill_content(name 属性 + index 定位)/
8027
- * ask-user-question(index 定位)/ reasoning。
8061
+ * ask-user-question(index 定位)/ reasoning;其余标签(含旧版 sys)一律忽略。
8028
8062
  * 整块无法解析或根非 <history> 时降级为单条不可定位的历史遗留条目(text 为块内文原文,
8029
8063
  * 构建最终块时原样保留)。
8030
8064
  */
@@ -8058,18 +8092,6 @@ function parseBlockEntries(blockText, blockSeq) {
8058
8092
  text,
8059
8093
  blockSeq
8060
8094
  });
8061
- } else if (el.nodeName === "sys") {
8062
- const index = intAttr(el, "index");
8063
- if (index === void 0) continue;
8064
- const type = el.getAttribute("type");
8065
- entries.push({
8066
- kind: "sys",
8067
- lo: index,
8068
- hi: index,
8069
- text: "",
8070
- ...type === null ? {} : { sysKind: type },
8071
- blockSeq
8072
- });
8073
8095
  } else if (el.nodeName === "assistant") {
8074
8096
  const index = intAttr(el, "index");
8075
8097
  if (index !== void 0) {
@@ -8176,7 +8198,7 @@ function buildReflectView(blocks, options = {}) {
8176
8198
  }
8177
8199
  /**
8178
8200
  * 把一个视图条目构建为 XML 元素(正文统一以 CDATA 包裹,逐字原样;user 条目的注释
8179
- * 输出为 XML 注释节点;sys 条目为无正文的空元素,自闭合输出)。getHistory 输出与
8201
+ * 输出为 XML 注释节点)。getHistory 输出与
8180
8202
  * 最终 <history> 块共用。
8181
8203
  */
8182
8204
  function entryToElement(doc, entry) {
@@ -8187,12 +8209,6 @@ function entryToElement(doc, entry) {
8187
8209
  for (const note of entry.notes ?? []) el.appendChild(doc.createComment(note));
8188
8210
  return el;
8189
8211
  }
8190
- if (entry.kind === "sys") {
8191
- const el = doc.createElement("sys");
8192
- el.setAttribute("type", entry.sysKind ?? "");
8193
- if (entry.lo !== void 0) el.setAttribute("index", String(entry.lo));
8194
- return el;
8195
- }
8196
8212
  if (entry.kind === "reasoning") {
8197
8213
  const el = doc.createElement("reasoning");
8198
8214
  appendCdataText(doc, el, entry.text);
@@ -8491,10 +8507,6 @@ var CompressionState = class CompressionState {
8491
8507
  text: `${CompressionState.spanLabel(lo, hi)} 覆盖用户消息(index ${entry.lo}),用户消息不可压缩`,
8492
8508
  isError: true
8493
8509
  };
8494
- if (entry.kind === "sys") return {
8495
- text: `${CompressionState.spanLabel(lo, hi)} 覆盖系统消息(index ${entry.lo}),系统消息不可压缩`,
8496
- isError: true
8497
- };
8498
8510
  if (entry.kind === "assistant" && !(entry.lo >= lo && entry.hi <= hi)) return {
8499
8511
  text: `${CompressionState.spanLabel(lo, hi)} 与 assistant 条目 [${entry.lo}..${entry.hi}] 部分重叠,需完整包含或不相交`,
8500
8512
  isError: true
@@ -8627,7 +8639,7 @@ var CompressionState = class CompressionState {
8627
8639
  unprocessedAskIndices() {
8628
8640
  return this.view.entries.flatMap((entry) => entry.ask !== void 0 && entry.lo !== void 0 && !this.coveredBy(entry) && !this.rewrittenAsks.has(entry.lo) ? [entry.lo] : []);
8629
8641
  }
8630
- /** completeCompression:所有原始合法 ask 已压缩或重写后标记完成。 */
8642
+ /** completeCompression:所有原始合法 ask 已压缩或重写后标记完成;result 为最终 <history> 块。 */
8631
8643
  complete() {
8632
8644
  const pending = this.unprocessedAskIndices();
8633
8645
  if (pending.length > 0) return {
@@ -8636,12 +8648,12 @@ var CompressionState = class CompressionState {
8636
8648
  };
8637
8649
  this._completed = true;
8638
8650
  return {
8639
- text: "压缩完成",
8651
+ text: this.buildFinalBlock(),
8640
8652
  isError: false
8641
8653
  };
8642
8654
  }
8643
8655
  /**
8644
- * 构建最终 <history> 块:按 index 顺序合并视图条目与替换记录——user / sys 条目
8656
+ * 构建最终 <history> 块:按 index 顺序合并视图条目与替换记录——user 条目
8645
8657
  * 原样、被替换区间生成 <assistant index|start end> 摘要条目(content 以 CDATA 包裹嵌入)、
8646
8658
  * 未替换普通与历史条目原样保留,原始 ask 使用重写后的 q/a;reasoning 不进产物。
8647
8659
  * 块首按最终条目动态生成格式说明注释,开标签携带 tip 属性。
@@ -8691,7 +8703,6 @@ var CompressionState = class CompressionState {
8691
8703
  flushReplacementsBefore(void 0);
8692
8704
  const note = historyFormatNote({
8693
8705
  user: this.view.entries.some((e) => e.kind === "user"),
8694
- sys: this.view.entries.some((e) => e.kind === "sys"),
8695
8706
  skill: this.view.entries.some((e) => e.kind === "assistant" && e.toolName === "skill" && !coveredBy(e)),
8696
8707
  askUserQuestion: this.view.entries.some((e) => isAskEntry(e) && !coveredBy(e))
8697
8708
  });
@@ -8769,7 +8780,7 @@ const COMPRESSION_TOOL_SCHEMAS = [
8769
8780
  },
8770
8781
  {
8771
8782
  name: "compressHistory",
8772
- description: "把 index 单条或 start..end 连续区间的 assistant 类条目(模型输出文本、工具调用)替换为 content 摘要。index 与 start/end 二选一,start 与 end 成对提供且 start==end 等同 index。区间不得覆盖用户消息或系统消息,不得与已有替换区间部分重叠(完全包含则覆盖)。用户消息与系统消息保持原样,无需处理。",
8783
+ description: "把 index 单条或 start..end 连续区间的 assistant 类条目(模型输出文本、工具调用)替换为 content 摘要。index 与 start/end 二选一,start 与 end 成对提供且 start==end 等同 index。区间不得覆盖用户消息,不得与已有替换区间部分重叠(完全包含则覆盖)。用户消息保持原样,无需处理。",
8773
8784
  parameters: {
8774
8785
  type: "object",
8775
8786
  properties: {
@@ -8891,17 +8902,17 @@ function buildCompressionPrompt(skipReasoning) {
8891
8902
  "",
8892
8903
  "【工具】",
8893
8904
  "- getHistory(option?: {start?, end?}):查看压缩区间内的历史条目。start/end 缺省为要求区间的第一个/最后一个完整消息 index,必须在要求区间内。返回压缩视图:已压缩内容以摘要条目呈现,区间切入已压缩块时返回整块,不带 <history> 包裹。",
8894
- "- compressHistory(option?: {index?, start?, end?, content}):把 index 单条或 start..end 连续区间的 assistant 类条目替换为 content 摘要(纯文本,不要包含 CDATA 包裹,插件自动包裹)。index 与 start/end 二选一,start==end 等同 index。区间不得覆盖用户消息或系统消息;与已有替换区间部分重叠会被拒绝,完全包含则覆盖。",
8905
+ "- compressHistory(option?: {index?, start?, end?, content}):把 index 单条或 start..end 连续区间的 assistant 类条目替换为 content 摘要(纯文本,不要包含 CDATA 包裹,插件自动包裹)。index 与 start/end 二选一,start==end 等同 index。区间不得覆盖用户消息;与已有替换区间部分重叠会被拒绝,完全包含则覆盖。",
8895
8906
  "- completeCompression():全部压缩完成后调用,立即结束。",
8896
8907
  "",
8897
8908
  "【压缩要求】",
8898
- "- 先用 getHistory 查看区间内容,再划分模块分批压缩;用户消息与系统消息不可压缩、保持原样,无需处理。",
8909
+ "- 先用 getHistory 查看区间内容,再划分模块分批压缩;用户消息不可压缩、保持原样,无需处理。",
8899
8910
  ...skipReasoning ? [] : ["- <reasoning> 仅作压缩参考,不进产物。"],
8900
8911
  "- 将具有关联性的 assistant 消息按内在逻辑连贯性划分为连续模块,聚合为区间压缩(start..end)",
8901
8912
  "- 单条重要的完整消息以 index 单独压缩",
8902
8913
  "- 压缩后的 assistant 消息内,应当描述**行为逻辑**,强调关键的**结论、产出和任务**;涉及到的具体文件保留完整路径",
8903
8914
  "- 摘要粒度越往后越细:靠近末尾(最近)的消息保留更多细节,开头(较早)的消息简写。",
8904
- "- <history> 条目正文以 CDATA 包裹(空的 <sys> 条目为自闭合空元素,无正文),CDATA 内为逐字原样内容。",
8915
+ "- <history> 条目正文以 CDATA 包裹,CDATA 内为逐字原样内容。",
8905
8916
  "- 工具调用条目为 <assistant index=\"N\" type=\"toolcall\" tool-name=\"…\" callId=\"…\">,内含 <tool-args>(调用参数 JSON)与 <tool-result>(工具返回内容)两个 CDATA 子元素。",
8906
8917
  "- 加载的 skill 以 <skill_content name=\"…\" index=\"N\"> 条目呈现,内含 <skill_resources> 与 <skill_instructions> 两段,内文为加载的 skill 内容,属于关键信息。仅在你明确判断该 skill 与后续任务无关时,压缩它;如果该 skill 与后续任务相关,或者你无法判断,不要压缩,**保持原文**。",
8907
8918
  "- 已有 <history> 块中的 ask_user_question 以 <ask-user-question index=\"N\"> 呈现,CDATA 内为逐题成对的 q:(问题文本)与 a:(用户回答)行,未作答的题记为 a:(未回答)。这些提问已经处理;仅在明确判断与后续任务无关时压缩,否则保持原样。原始提问按本会话的专用处理规则执行。",
@@ -8930,6 +8941,10 @@ const ASK_COMPRESSION_PROMPT = [
8930
8941
  ].join("\n");
8931
8942
  /** 模型输出纯文本(无工具调用)时追加的提醒消息文本。 */
8932
8943
  const COMPRESSION_NUDGE_TEXT = "请通过工具执行压缩:用 getHistory 查看区间条目,用 compressHistory 压缩 assistant 条目,完成后调用 completeCompression。不要输出与工具调用无关的文本。";
8944
+ /** 视图原始消息字符数估算:非 reasoning 条目之和;工具调用条目的 text 已含参数与结果,不重复计入。 */
8945
+ function viewCharCount(view) {
8946
+ return view.entries.reduce((total, entry) => entry.kind === "reasoning" ? total : total + entry.text.length, 0);
8947
+ }
8933
8948
  /** 构造插件自产 user 消息(压缩指令/提醒;source 为插件自有 kind)。 */
8934
8949
  function makePluginUserMessage(text) {
8935
8950
  return createUserMessage({
@@ -9009,12 +9024,19 @@ async function runCompressionLoop(ctx, session, options) {
9009
9024
  rounds: roundStats
9010
9025
  };
9011
9026
  };
9012
- const recordSessionId = async (success, stats) => recordCompressionSession(ctx, session, {
9027
+ const recordSessionId = async (success, stats, resultChars) => recordCompressionSession(ctx, session, {
9013
9028
  phase: options.phase,
9014
9029
  messages,
9015
9030
  stats,
9016
9031
  success,
9017
- debug: options.debug
9032
+ debug: options.debug,
9033
+ info: compressionInfo({
9034
+ target: options.target,
9035
+ originalChars: options.originalChars ?? viewCharCount(options.view),
9036
+ ...options.reasoningEffort === void 0 ? {} : { reasoningEffort: options.reasoningEffort },
9037
+ ...resultChars === void 0 ? {} : { resultChars }
9038
+ }),
9039
+ ...options.retryTarget === void 0 ? {} : { retryTarget: options.retryTarget }
9018
9040
  });
9019
9041
  const failWith = async (error, aborted) => {
9020
9042
  const stats = buildStats();
@@ -9116,7 +9138,7 @@ async function runCompressionLoop(ctx, session, options) {
9116
9138
  if (state.replacementCount === 0 && state.rewriteCount === 0) logger.warn("压缩完成但未执行任何压缩替换(空提交)");
9117
9139
  logger.info(`压缩循环完成(${rounds} 轮,${state.replacementCount} 次压缩替换,${state.rewriteCount} 条提问重写,输出 ${text.length} 字符)`);
9118
9140
  const stats = buildStats();
9119
- const id = await recordSessionId(true, stats);
9141
+ const id = await recordSessionId(true, stats, text.length);
9120
9142
  return {
9121
9143
  ok: true,
9122
9144
  text,
@@ -9250,7 +9272,7 @@ function reportDegrade(session, logger, problem) {
9250
9272
  /**
9251
9273
  * 两级自动压缩(观察/反思)与 compaction 生命周期提交。
9252
9274
  * 导出 estimateTextTokens / isPairBalancedAfter / computeCompressRange / historySection /
9253
- * hasHistoryBlock / findObservePending / reflectPass / observePass / maybeCompress。
9275
+ * historyTextOf / findObservePending / reflectPass / observePass / maybeCompress。
9254
9276
  *
9255
9277
  * - 摘要生成走工具驱动的压缩循环(compress-loop.ts runCompressionLoop):首条 user
9256
9278
  * 消息仅含压缩指令与 start/end 区间,模型经 getHistory / compressHistory /
@@ -9452,11 +9474,6 @@ function historySection(session) {
9452
9474
  boundarySeq
9453
9475
  };
9454
9476
  }
9455
- /** 表层是否存在合法 <history> 压缩日志块。 */
9456
- function hasHistoryBlock(session) {
9457
- for (const seq of session.surface.nodes) if (historyTextOf(session.snapshotEvents()[seq]) !== void 0) return true;
9458
- return false;
9459
- }
9460
9477
  /**
9461
9478
  * 查找当前活跃的观察压缩待定标记:按日志顺序取最后一条 om/observe-pending 信封事件,
9462
9479
  * 其后须无引用它的 om/observe-invalidate(已失效),且其后的压缩边界 seq 不大于标记
@@ -9620,6 +9637,7 @@ async function reflectPass(ctx, agent, config, target, signal, reasoningEffort)
9620
9637
  }
9621
9638
  const summaryResult = await runPassLoop(ctx, session, lifecycle, {
9622
9639
  view,
9640
+ originalChars: shadowedCharCount,
9623
9641
  phase: "reflect",
9624
9642
  taskText: buildCompressionTaskText("reflect", view.minIndex, view.maxIndex),
9625
9643
  target,
@@ -9822,6 +9840,7 @@ async function observePass(ctx, agent, config, waitCount, target, signal, reason
9822
9840
  clearPending();
9823
9841
  return { failed: false };
9824
9842
  }
9843
+ const shadowedCharCount = seqsCharCount(session, replaceSeqs);
9825
9844
  const view = buildObserveView(session, replaceSeqs, { skipReasoning: config.compressSkipReasoning });
9826
9845
  if (view.minIndex === void 0 || view.maxIndex === void 0) {
9827
9846
  logger.step("观察:区间内无可定位条目,清除待定标记视为完成");
@@ -9843,6 +9862,7 @@ async function observePass(ctx, agent, config, waitCount, target, signal, reason
9843
9862
  }
9844
9863
  const summaryResult = await runPassLoop(ctx, session, lifecycle, {
9845
9864
  view,
9865
+ originalChars: shadowedCharCount,
9846
9866
  phase: "observe",
9847
9867
  taskText: buildCompressionTaskText("observe", view.minIndex, view.maxIndex),
9848
9868
  target,
@@ -9872,11 +9892,6 @@ async function observePass(ctx, agent, config, waitCount, target, signal, reason
9872
9892
  }
9873
9893
  return total + tokens;
9874
9894
  }, 0);
9875
- const shadowedCharCount = replaceSeqs.reduce((total, seq) => {
9876
- const event = session.snapshotEvents()[seq];
9877
- const message = event ? session.deriveEventMessage(event) : null;
9878
- return total + (message ? textCharCount(message) : 0);
9879
- }, 0);
9880
9895
  try {
9881
9896
  logger.step("观察提交:追加 compaction/summary(影子价格认领)");
9882
9897
  const summarySeq = appendCompactionSummary(session, {
@@ -10406,19 +10421,11 @@ function toolcallElement(doc, session, cm, pruner, images) {
10406
10421
  appendImageComments(doc, el, images);
10407
10422
  return el;
10408
10423
  }
10409
- /** 按完整消息类别构建元素(user / sys / assistant 文本条目复用 parts 渲染)。 */
10424
+ /** 按完整消息类别构建元素(user / assistant 文本条目复用 parts 渲染)。 */
10410
10425
  function buildElement(doc, session, cm, pruner, images) {
10411
10426
  if (cm.type === "toolcall") return toolcallElement(doc, session, cm, pruner, images);
10412
10427
  const parts = renderCompleteMessageParts(session, cm, pruner);
10413
10428
  images.push(...parts.images);
10414
- if (cm.type === "sys") {
10415
- const el = doc.createElement("sys");
10416
- el.setAttribute("index", String(cm.index));
10417
- if (cm.kind !== void 0) el.setAttribute("type", cm.kind);
10418
- appendBodyText(doc, el, parts.text);
10419
- appendImageComments(doc, el, parts.images);
10420
- return el;
10421
- }
10422
10429
  const el = doc.createElement(cm.type === "user" ? "user_message" : "assistant");
10423
10430
  el.setAttribute("index", String(cm.index));
10424
10431
  if (cm.type === "assistant") el.setAttribute("type", "text");
@@ -10428,12 +10435,6 @@ function buildElement(doc, session, cm, pruner, images) {
10428
10435
  }
10429
10436
  /** 主渲染失败时的回退元素:按完整消息类别输出最简形态,正文为回退文本。 */
10430
10437
  function fallbackElement(doc, cm, text) {
10431
- if (cm.type === "sys") {
10432
- const el = doc.createElement("sys");
10433
- el.setAttribute("index", String(cm.index));
10434
- if (cm.kind !== void 0) el.setAttribute("type", cm.kind);
10435
- return el;
10436
- }
10437
10438
  const el = doc.createElement(cm.type === "user" ? "user_message" : "assistant");
10438
10439
  el.setAttribute("index", String(cm.index));
10439
10440
  if (cm.type !== "user") el.setAttribute("type", cm.type === "toolcall" ? "toolcall" : "text");
@@ -10666,9 +10667,9 @@ function parseRecallArgs(raw, semantic = false) {
10666
10667
  return result.data;
10667
10668
  }
10668
10669
  /** 基础工具描述。 */
10669
- const RECALL_DESCRIPTION = "在你需要查看历史消息时调用。此工具按 index 区间精确返回区间内全部完整消息的内容。";
10670
+ const RECALL_DESCRIPTION = `在你需要查看历史消息时调用。${COMPLETE_MESSAGE_DEFINITION}此工具按 index 区间精确返回区间内全部完整消息的内容。`;
10670
10671
  /** 语义增强启用时的工具描述。 */
10671
- const ENHANCED_RECALL_DESCRIPTION = "在你需要查看历史消息时调用。两种用法:1) 给出 start 与 end 或 offset,按 index 区间精确返回区间内全部完整消息的内容;2) 给出 query,按自然语言含义检索最符合的完整消息,默认全量搜索,可用 start/end/offset 限定区间。注意:query 只匹配文本。";
10672
+ const ENHANCED_RECALL_DESCRIPTION = `在你需要查看历史消息时调用。${COMPLETE_MESSAGE_DEFINITION}两种用法:1) 给出 start 与 end 或 offset,按 index 区间精确返回区间内全部完整消息的内容;2) 给出 query,按自然语言含义检索最符合的完整消息,默认全量搜索,可用 start/end/offset 限定区间。注意:query 只匹配文本。`;
10672
10673
  /**
10673
10674
  * 构建 recall 工具定义:按 start/end/offset 定位完整消息区间并渲染原始内容(标 index);
10674
10675
  * 传入 semantic 选项时额外支持 query 语义检索。
@@ -10736,20 +10737,192 @@ function buildRecallTool(options) {
10736
10737
  };
10737
10738
  }
10738
10739
  //#endregion
10740
+ //#region src/recompress.ts
10741
+ /** 命令行用法提示。 */
10742
+ const USAGE = "用法:/om-recompress <compactionId> <provider> <model> [思考等级]";
10743
+ /** 解析命令行:compactionId provider model [reasoningEffort],空白分隔。 */
10744
+ function parseRecompressInput(rawInput) {
10745
+ const parts = rawInput.trim().split(/\s+/).filter((part) => part !== "");
10746
+ const [compactionId, provider, model, reasoningEffort] = parts;
10747
+ if (compactionId === void 0 || provider === void 0 || model === void 0 || parts.length > 4) return {
10748
+ ok: false,
10749
+ error: USAGE
10750
+ };
10751
+ return {
10752
+ ok: true,
10753
+ request: {
10754
+ compactionId,
10755
+ provider,
10756
+ model,
10757
+ ...reasoningEffort === void 0 ? {} : { reasoningEffort }
10758
+ }
10759
+ };
10760
+ }
10761
+ /** 正在重压缩的会话 id(同一会话同时仅一次)。 */
10762
+ const running = /* @__PURE__ */ new Set();
10763
+ /** 按 compactionId 收集 start/summary/end 载荷。 */
10764
+ function findLifecycle(session, compactionId) {
10765
+ const lifecycle = {
10766
+ phase: void 0,
10767
+ summary: void 0,
10768
+ end: void 0
10769
+ };
10770
+ for (const event of session.snapshotEvents()) if (event.type === "compaction/start") {
10771
+ const data = event.data;
10772
+ if (String(data.compactionId) === compactionId) lifecycle.phase = data.phase;
10773
+ } else if (event.type === "compaction/summary") {
10774
+ const data = event.data;
10775
+ if (String(data.compactionId) === compactionId) lifecycle.summary = data;
10776
+ } else if (event.type === "compaction/end") {
10777
+ const data = event.data;
10778
+ if (String(data.compactionId) === compactionId) lifecycle.end = data;
10779
+ }
10780
+ return lifecycle;
10781
+ }
10782
+ /** 重建被压缩内容的视图;不可重建时返回错误。 */
10783
+ function rebuildView(session, phase, shadowedSeqs, skipReasoning) {
10784
+ if (phase === "reflect") return buildReflectView(shadowedSeqs.flatMap((seq) => {
10785
+ const text = historyTextOf(session.snapshotEvents()[seq]);
10786
+ return text === void 0 ? [] : [{
10787
+ text,
10788
+ seq
10789
+ }];
10790
+ }), { skipReasoning });
10791
+ return buildObserveView(session, shadowedSeqs, { skipReasoning });
10792
+ }
10793
+ /**
10794
+ * 对已成功的 compaction 用目标模型重压缩一次。校验失败、压缩循环失败均以
10795
+ * { ok: false } 返回,不抛错;会话本身不被修改(见文件头说明)。
10796
+ */
10797
+ async function recompress(ctx, agent, config, request, signal) {
10798
+ const session = agent.session;
10799
+ if (!isMainSession(session)) return {
10800
+ ok: false,
10801
+ error: "重压缩仅支持主会话"
10802
+ };
10803
+ const lifecycle = findLifecycle(session, request.compactionId);
10804
+ if (lifecycle.phase === void 0 && lifecycle.summary === void 0) return {
10805
+ ok: false,
10806
+ error: `未找到压缩 ${request.compactionId}`
10807
+ };
10808
+ const summary = lifecycle.summary;
10809
+ if (summary === void 0 || lifecycle.end === void 0 || lifecycle.end.error !== void 0) return {
10810
+ ok: false,
10811
+ error: `压缩 ${request.compactionId} 未成功完成,无法重压缩`
10812
+ };
10813
+ const shadowedSeqs = (summary.shadowedSeqs ?? []).map(Number);
10814
+ if (shadowedSeqs.length === 0) return {
10815
+ ok: false,
10816
+ error: `压缩 ${request.compactionId} 缺少 shadowedSeqs,无法重放`
10817
+ };
10818
+ const firstEvent = session.snapshotEvents()[shadowedSeqs[0] ?? -1];
10819
+ const phase = lifecycle.phase ?? (historyTextOf(firstEvent) === void 0 ? "observe" : "reflect");
10820
+ const view = rebuildView(session, phase, shadowedSeqs, config.compressSkipReasoning);
10821
+ if (typeof view === "string") return {
10822
+ ok: false,
10823
+ error: view
10824
+ };
10825
+ if (view.minIndex === void 0 || view.maxIndex === void 0) return {
10826
+ ok: false,
10827
+ error: `压缩 ${request.compactionId} 的原内容无可定位条目`
10828
+ };
10829
+ if (signal?.aborted === true) return {
10830
+ ok: false,
10831
+ error: COMPACTION_ABORTED_ERROR
10832
+ };
10833
+ if (running.has(session.id)) return {
10834
+ ok: false,
10835
+ error: "该会话已有重压缩进行中"
10836
+ };
10837
+ const target = {
10838
+ provider: request.provider,
10839
+ model: request.model
10840
+ };
10841
+ const logger = makeLogger(ctx, config.debug);
10842
+ running.add(session.id);
10843
+ try {
10844
+ logger.step(`重压缩:${request.compactionId}(${phase})→ ${target.provider}/${target.model}${request.reasoningEffort === void 0 ? "" : ` · ${request.reasoningEffort}`}`);
10845
+ const originalChars = summary.shadowedCharCount ?? (phase === "observe" ? seqsCharCount(session, shadowedSeqs) : viewCharCount(view));
10846
+ const outcome = await runCompressionLoop(ctx, session, {
10847
+ view,
10848
+ originalChars,
10849
+ phase,
10850
+ taskText: buildCompressionTaskText(phase, view.minIndex, view.maxIndex),
10851
+ target,
10852
+ maxTokens: config.compressMaxTokens,
10853
+ rateLimitWaitMs: config.rateLimitWaitMs,
10854
+ skipReasoning: config.compressSkipReasoning,
10855
+ debug: config.debug,
10856
+ retryTarget: target,
10857
+ ...request.reasoningEffort === void 0 ? {} : { reasoningEffort: request.reasoningEffort },
10858
+ ...signal === void 0 ? {} : { signal }
10859
+ });
10860
+ if (!outcome.ok) return {
10861
+ ok: false,
10862
+ error: outcome.error,
10863
+ ...outcome.recordSessionId === void 0 ? {} : { recordSessionId: outcome.recordSessionId }
10864
+ };
10865
+ return {
10866
+ ok: true,
10867
+ text: outcome.text,
10868
+ phase,
10869
+ rounds: outcome.rounds,
10870
+ originalChars,
10871
+ newChars: outcome.text.length,
10872
+ durationMs: outcome.stats.durationMs,
10873
+ ...outcome.recordSessionId === void 0 ? {} : { recordSessionId: outcome.recordSessionId }
10874
+ };
10875
+ } finally {
10876
+ running.delete(session.id);
10877
+ }
10878
+ }
10879
+ /** 重压缩命令名(压缩卡片按钮经宿主命令通道调用)。 */
10880
+ const RECOMPRESS_COMMAND_NAME = "om-recompress";
10881
+ /** 毫秒耗时的简短文本。 */
10882
+ function secondsText(durationMs) {
10883
+ return `${(durationMs / 1e3).toFixed(1)}s`;
10884
+ }
10885
+ /** 渲染命令结果文本:成功为「模型(等级),原始消息 → 产物,耗时」,失败给出原因。 */
10886
+ function describeResult(request, result) {
10887
+ const label = `${request.provider}/${request.model}(${request.reasoningEffort ?? "默认"})`;
10888
+ if (!result.ok) return `重压缩失败 ${label}:${result.error}`;
10889
+ return `重压缩完成 ${label},${formatCompactCount(result.originalChars)} → ${formatCompactCount(result.newChars)},${secondsText(result.durationMs)}`;
10890
+ }
10891
+ /** 构造 /om-recompress 命令定义;配置按调用时刻读取。 */
10892
+ function buildRecompressCommand(ctx, getConfig) {
10893
+ return {
10894
+ name: RECOMPRESS_COMMAND_NAME,
10895
+ description: "由压缩卡片调用:用另一模型重新压缩一次已完成的压缩",
10896
+ input: { hint: "<compactionId> <provider> <model> [思考等级]" },
10897
+ handler: async ({ agent, rawInput, signal }) => {
10898
+ const parsed = parseRecompressInput(rawInput);
10899
+ if (!parsed.ok) return {
10900
+ kind: "error",
10901
+ text: parsed.error
10902
+ };
10903
+ const result = await recompress(ctx, agent, getConfig(), parsed.request, signal);
10904
+ const text = describeResult(parsed.request, result);
10905
+ return result.ok ? {
10906
+ kind: "success",
10907
+ text
10908
+ } : {
10909
+ kind: "error",
10910
+ text
10911
+ };
10912
+ }
10913
+ };
10914
+ }
10915
+ //#endregion
10739
10916
  //#region src/system-reminder.ts
10740
10917
  /**
10741
- * system-reminder:以 <system-reminder> 用户消息向主会话注入插件提醒,不进系统提示词。
10742
- * - 进度提醒:OM 启用时提示模型边做边简述计划与进展。
10743
- * - 完整消息定义提醒:OM 或 recall 启用时说明 `<history>` 块与 recall 共用的完整消息 index。
10744
- * 每个 step 检查表层,被压缩遮蔽或文本过期时补发,保证模型请求中每种恒有一条。
10745
- * 导出 PROGRESS_REMINDER_SOURCE_KIND / DEFINITION_REMINDER_SOURCE_KIND / 对应 source 类型 /
10746
- * SystemReminder / PROGRESS_REMINDER / DEFINITION_REMINDER / systemReminderMessage /
10747
- * activeSystemReminders / ensureSystemReminders。
10918
+ * system-reminder:以 <system-reminder> 用户消息向主会话注入进度提醒,不进系统提示词。
10919
+ * 进度提醒:表层缺少同 kind 消息时补发,或无记录活动累计至少 4 个已结束 step、超过 10 次工具调用时重发。
10920
+ * 每个 step 检查表层;真实用户消息、非空模型 text 与进度提醒重置活动窗口。
10921
+ * 导出 PROGRESS_REMINDER_SOURCE_KIND / ProgressReminderSource / SystemReminder /
10922
+ * PROGRESS_REMINDER / systemReminderMessage / activeSystemReminders / ensureSystemReminders。
10748
10923
  */
10749
10924
  /** 进度提醒的 producer-owned source kind(区别于压缩日志消息的 plugin:dsh-plugin-om)。 */
10750
10925
  const PROGRESS_REMINDER_SOURCE_KIND = "plugin:dsh-plugin-om:progress";
10751
- /** 完整消息定义提醒的 producer-owned source kind。 */
10752
- const DEFINITION_REMINDER_SOURCE_KIND = "plugin:dsh-plugin-om:definition";
10753
10926
  /** 用 system-reminder 标签包裹提醒正文。 */
10754
10927
  function wrap(lines) {
10755
10928
  return [
@@ -10762,18 +10935,13 @@ function wrap(lines) {
10762
10935
  const PROGRESS_REMINDER = {
10763
10936
  kind: PROGRESS_REMINDER_SOURCE_KIND,
10764
10937
  text: wrap([
10765
- "在工作过程中同步输出文本,简洁记录关键结论与后续规划。思考内容不计入记录。",
10766
- "- 每个阶段性工作开始前记录一次,一个阶段通常是 1-5 个工具调用",
10767
- "- 禁止连续 10 个以上工具调用而无记录",
10768
- "- 记录后在同一回复中继续调用工具,不要停下等待",
10769
- "- 最终答案仅总结结果,不能替代这些记录"
10938
+ "在本会话中,你应当持续输出文本,记录最近几步的成果:",
10939
+ "- 1-2句话即可,概括为主,不必覆盖所有细节",
10940
+ "- 承上启下,突出要点,例如“读 f1,发现 L1 关联了 f2-L2,读 f2”,“m1 完成,按计划开始 m2”",
10941
+ "- 记录后继续完成任务,不要等待确认",
10942
+ "- 记录仅是中间产物,最终输出需要另行构建"
10770
10943
  ])
10771
10944
  };
10772
- /** 完整消息定义提醒。 */
10773
- const DEFINITION_REMINDER = {
10774
- kind: DEFINITION_REMINDER_SOURCE_KIND,
10775
- text: wrap([COMPLETE_MESSAGE_DEFINITION])
10776
- };
10777
10945
  /** 构造一条新的提醒消息。 */
10778
10946
  function systemReminderMessage(reminder) {
10779
10947
  return createUserMessage({
@@ -10787,20 +10955,44 @@ function systemReminderMessage(reminder) {
10787
10955
  }
10788
10956
  });
10789
10957
  }
10790
- /** 按配置与当前表层是否有 history 块返回应注入的提醒,顺序固定:进度在前,定义在后。 */
10791
- function activeSystemReminders(config, hasHistory) {
10792
- const reminders = [];
10793
- if (config.omEnabled) reminders.push(PROGRESS_REMINDER);
10794
- if (config.recallEnabled || hasHistory) reminders.push(DEFINITION_REMINDER);
10795
- return reminders;
10796
- }
10797
- /** 消息是否为指定提醒的当前文本。 */
10798
- function isCurrent(reminder, source, content) {
10799
- return source.kind === reminder.kind && content.length === 1 && content[0]?.type === "text" && content[0].text === reminder.text;
10958
+ /** 按配置返回应注入的提醒:omEnabled 时为进度提醒。 */
10959
+ function activeSystemReminders(config) {
10960
+ return config.omEnabled ? [PROGRESS_REMINDER] : [];
10961
+ }
10962
+ /** 进度提醒在表层缺失,或静默窗口达到 4 个已结束 step 且超过 10 次调用时补发。 */
10963
+ function progressReminderTrigger(surface, events, messages) {
10964
+ if (messages.some((message) => message.source.kind === "plugin:dsh-plugin-om:progress")) return void 0;
10965
+ if (!surface.some((event) => event.type === "user/message" && event.data.source.kind === "plugin:dsh-plugin-om:progress")) return "missing";
10966
+ if (messages.some((message) => message.source.kind === "user")) return void 0;
10967
+ const ended = /* @__PURE__ */ new Set();
10968
+ for (const event of events) if (event.type === "step/end") ended.add(`${event.data.turn}:${event.data.step}`);
10969
+ const steps = /* @__PURE__ */ new Set();
10970
+ let toolCalls = 0;
10971
+ let textStep;
10972
+ for (const event of surface) if (event.type === "user/message") {
10973
+ const kind = event.data.source.kind;
10974
+ if (kind === "user" || kind === "plugin:dsh-plugin-om:progress") {
10975
+ steps.clear();
10976
+ toolCalls = 0;
10977
+ textStep = void 0;
10978
+ }
10979
+ } else if (event.type === "assistant/message") {
10980
+ const { turn, step, message } = event.data;
10981
+ const key = `${turn}:${step}`;
10982
+ if (message.content.some((block) => block.type === "text" && block.text.trim() !== "")) {
10983
+ steps.clear();
10984
+ toolCalls = 0;
10985
+ textStep = key;
10986
+ } else if (key !== textStep && ended.has(key)) {
10987
+ steps.add(key);
10988
+ toolCalls += message.content.filter((block) => block.type === "tool-call").length;
10989
+ }
10990
+ }
10991
+ return steps.size >= 4 && toolCalls > 10 ? "activity" : void 0;
10800
10992
  }
10801
10993
  /**
10802
- * 保证本 step 之后的消息列表中每种指定提醒各有一条当前文本:本 step 已带上或表层已有则跳过,
10803
- * 否则按顺序追加到末尾。返回新数组,不修改入参。
10994
+ * 按表层与待输入消息补发提醒,追加到末尾且不修改入参。
10995
+ * 进度提醒按 kind 去重并检测活动窗口,活动达标时追加立刻记录要求。
10804
10996
  */
10805
10997
  function ensureSystemReminders(session, messages, reminders) {
10806
10998
  const result = [...messages];
@@ -10808,9 +11000,17 @@ function ensureSystemReminders(session, messages, reminders) {
10808
11000
  const events = session.snapshotEvents();
10809
11001
  const surface = session.surface.nodes.flatMap((seq) => {
10810
11002
  const event = events[seq];
10811
- return event?.type === "user/message" ? [event.data] : [];
11003
+ return event === void 0 ? [] : [event];
10812
11004
  });
10813
- for (const reminder of reminders) if (![...result, ...surface].some((message) => isCurrent(reminder, message.source, message.content))) result.push(systemReminderMessage(reminder));
11005
+ for (const reminder of reminders) {
11006
+ const trigger = progressReminderTrigger(surface, events, result);
11007
+ if (trigger === void 0) continue;
11008
+ const progress = trigger === "activity" ? {
11009
+ ...reminder,
11010
+ text: reminder.text.replace("\n</system-reminder>", "\n你应当*立刻*输出一条记录\n</system-reminder>")
11011
+ } : reminder;
11012
+ result.push(systemReminderMessage(progress));
11013
+ }
10814
11014
  return result;
10815
11015
  }
10816
11016
  //#endregion
@@ -10861,6 +11061,9 @@ function apply(ctx, config) {
10861
11061
  }
10862
11062
  syncTools();
10863
11063
  ctx.on("loader/volatile-update", () => syncTools());
11064
+ ctx.inject(["commands"], (inner) => {
11065
+ inner.effect(() => inner.commands.register(buildRecompressCommand(ctx, () => currentConfig(config))), "dsh-plugin-om: recompress command");
11066
+ });
10864
11067
  ctx.on("agent/pre-step", async ({ agent, signal }, next) => {
10865
11068
  let outcome = { failed: false };
10866
11069
  try {
@@ -10879,8 +11082,7 @@ function apply(ctx, config) {
10879
11082
  return { kind: "reject" };
10880
11083
  }
10881
11084
  const decision = await next();
10882
- const hasHistory = hasHistoryBlock(agent.session);
10883
- const reminders = activeSystemReminders(currentConfig(config), hasHistory);
11085
+ const reminders = activeSystemReminders(currentConfig(config));
10884
11086
  if (decision.kind === "enter" && !signal.aborted && reminders.length > 0 && isMainSession(agent.session)) return {
10885
11087
  ...decision,
10886
11088
  messages: ensureSystemReminders(agent.session, decision.messages, reminders)