dsh-plugin-om 0.0.46 → 0.0.48

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/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
- * 条目标签语义 + CDATA 约定 + toolcall 结构)始终保留;<user_message> / <sys> /
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");
@@ -7648,7 +7644,7 @@ function renderToolResultText(session, cm, pruner) {
7648
7644
  const message = toolResultMessageOf(session, cm, pruner);
7649
7645
  return message ? renderMessageText(message) : "";
7650
7646
  }
7651
- /** 渲染一条完整消息为「文本 + 图片」(recall / recall-semantic 输出用):
7647
+ /** 渲染一条完整消息为「文本 + 图片」(recall 输出用):
7652
7648
  * user/sys 取消息原文,assistant 取文本块,toolcall 为调用块 + 结果文本
7653
7649
  * (pruner 裁剪超大结果);同时收集该条完整消息携带的图片附件(含 tool-result 嵌套,
7654
7650
  * pruner 裁剪掉的图片不收集)。
@@ -9148,30 +9144,18 @@ async function runCompressionLoop(ctx, session, options) {
9148
9144
  }
9149
9145
  //#endregion
9150
9146
  //#region src/om-event.ts
9151
- /** om 信封 text 前缀:标识该 feedback/record 记录由本插件写入。 */
9152
- const OM_EVENT_PREFIX = "om:1:";
9153
- /**
9154
- * 解码一条会话事件为 om 私有事件:仅识别 feedback/record 中带 om 信封前缀的
9155
- * text;前缀缺失、JSON 非法、kind 未知或载荷字段缺失时返回 undefined。
9156
- */
9147
+ /** 解码一条会话事件为 om 私有事件:仅识别 plugin:dsh-plugin-om:*。 */
9157
9148
  function readOmEvent(event) {
9158
- if (event === void 0 || event === null || event.type !== "feedback/record") return void 0;
9159
- const text = event.data.text;
9160
- if (typeof text !== "string" || !text.startsWith("om:1:")) return void 0;
9161
- let envelope;
9162
- try {
9163
- envelope = JSON.parse(text.slice(5));
9164
- } catch {
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;
9149
+ if (event === void 0 || event === null) return void 0;
9150
+ const data = event.data;
9151
+ if (data === null || typeof data !== "object" || Array.isArray(data)) return void 0;
9152
+ const record = data;
9153
+ switch (event.type) {
9154
+ case "plugin:dsh-plugin-om:warning": {
9155
+ const { problem, message } = record;
9172
9156
  if (typeof problem !== "string" || typeof message !== "string") return void 0;
9173
9157
  return {
9174
- kind,
9158
+ kind: event.type,
9175
9159
  data: {
9176
9160
  problem,
9177
9161
  message
@@ -9179,20 +9163,20 @@ function readOmEvent(event) {
9179
9163
  seq: event.seq
9180
9164
  };
9181
9165
  }
9182
- case "om/observe-pending": {
9183
- const { triggerMessageIndex } = rest;
9166
+ case "plugin:dsh-plugin-om:observe-pending": {
9167
+ const { triggerMessageIndex } = record;
9184
9168
  if (typeof triggerMessageIndex !== "number" || !Number.isSafeInteger(triggerMessageIndex)) return void 0;
9185
9169
  return {
9186
- kind,
9170
+ kind: event.type,
9187
9171
  data: { triggerMessageIndex },
9188
9172
  seq: event.seq
9189
9173
  };
9190
9174
  }
9191
- case "om/observe-invalidate": {
9192
- const { pendingSeq } = rest;
9175
+ case "plugin:dsh-plugin-om:observe-invalidate": {
9176
+ const { pendingSeq } = record;
9193
9177
  if (typeof pendingSeq !== "number" || !Number.isSafeInteger(pendingSeq)) return void 0;
9194
9178
  return {
9195
- kind,
9179
+ kind: event.type,
9196
9180
  data: { pendingSeq },
9197
9181
  seq: event.seq
9198
9182
  };
@@ -9200,16 +9184,9 @@ function readOmEvent(event) {
9200
9184
  default: return;
9201
9185
  }
9202
9186
  }
9203
- /** 编码一条 om 私有事件为 feedback/record 的 text 信封。 */
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。 */
9187
+ /** 追加一条 om 私有事件(log-only,不进 surface),返回事件 seq。 */
9211
9188
  function appendOmEvent(session, kind, data) {
9212
- return session.append("feedback/record", { text: encodeOmEvent(kind, data) }).seq;
9189
+ return session.append(kind, data).seq;
9213
9190
  }
9214
9191
  function findOmEvents(session, kind) {
9215
9192
  const result = [];
@@ -9225,36 +9202,35 @@ function findOmEvents(session, kind) {
9225
9202
  * 降级报告:压缩流程中的挂载失败统一出口。
9226
9203
  * 导出 reportDegrade / DEGRADE_PROBLEMS / DegradedProblem。
9227
9204
  *
9228
- * - 挂载失败类问题(服务缺失、服务调用异常)始终 console.warn 到宿主进程外部输出,
9229
- * 并向会话日志追加 log-only 的 om 警告事件(借用 feedback/record 的 om 信封,
9230
- * 见 om-event.ts;客户端渲染为「功能降级」警告行);
9231
- * 同一会话同一问题只报告一次(按日志扫描去重,重启不重复)
9232
- * - 报告动作自身绝不抛错:追加失败只记日志,不阻塞压缩
9233
- * - 辅助函数的普通运行时报错(组装失败、请求头读取失败)不走本模块,仅记日志
9205
+ * 挂载失败类问题(服务缺失、服务调用异常)console.warn 到宿主进程外部输出,
9206
+ * 并向会话日志追加 log-only 的 plugin:dsh-plugin-om:warning 事件,
9207
+ * 客户端渲染为「功能降级」警告行。
9208
+ * 同一会话同一问题只报告一次(按日志扫描去重,重启不重复)。
9209
+ * 报告动作自身绝不抛错,追加失败只记日志,不阻塞压缩。
9210
+ * 辅助函数的普通运行时报错不走本模块,仅记日志。
9234
9211
  */
9235
- /** 各降级问题面向用户的简短说明(om/warning 信封载荷 message;客户端警告行直接展示)。 */
9212
+ /** 各降级问题面向用户的简短说明(plugin:dsh-plugin-om:warning 载荷 message;客户端警告行直接展示)。 */
9236
9213
  const DEGRADE_PROBLEMS = {
9237
9214
  "systemPrompt-missing": "系统提示词服务未挂载,上下文压力估算不扣除系统提示词 tokens(压缩触发会偏早)",
9238
9215
  "tokenMeter-unavailable": "token 计量服务异常,上下文压力估算降级(可能跳过压缩或按 0 计)",
9239
9216
  "reasoning-effort-unavailable": "配置的压缩思考等级不被压缩目标模型支持,压缩降级为模型默认思考等级"
9240
9217
  };
9241
9218
  /**
9242
- * 报告一次挂载失败类降级:console.warn 始终输出到宿主进程外部;同会话同问题首次
9243
- * 出现时,向会话日志追加 log-only om 警告事件(客户端渲染警告行,每会话最多
9244
- * 一次)并输出 logger.warn(避免每个 pre-step 重复刷日志)。
9245
- * 日志扫描/事件追加失败只记日志,绝不抛错、不阻塞压缩。
9219
+ * 报告一次挂载失败类降级:console.warn 输出到宿主进程外部;同会话同问题首次
9220
+ * 出现时,向会话日志追加 log-only plugin:dsh-plugin-om:warning 事件并输出 logger.warn。
9221
+ * 日志扫描/事件追加失败只记日志,不抛错、不阻塞压缩。
9246
9222
  */
9247
9223
  function reportDegrade(session, logger, problem) {
9248
9224
  const message = DEGRADE_PROBLEMS[problem];
9249
9225
  let first = true;
9250
9226
  try {
9251
- first = !findOmEvents(session, "om/warning").some((om) => om.data.problem === problem);
9227
+ first = !findOmEvents(session, "plugin:dsh-plugin-om:warning").some((om) => om.data.problem === problem);
9252
9228
  } catch {}
9253
9229
  if (!first) return;
9254
9230
  console.warn(`${PLUGIN_LABEL}: ${message}`);
9255
9231
  logger.warn(message);
9256
9232
  try {
9257
- appendOmEvent(session, "om/warning", {
9233
+ appendOmEvent(session, "plugin:dsh-plugin-om:warning", {
9258
9234
  problem,
9259
9235
  message
9260
9236
  });
@@ -9282,8 +9258,8 @@ function reportDegrade(session, logger, problem) {
9282
9258
  * tailMessageCount 时,把压缩边界至触发点的全部消息作为压缩视图替换为新 <history>
9283
9259
  * 块(旧块保留),等待期间的新消息成为下一轮未压缩尾部(延迟窗口内压力允许
9284
9260
  * 短暂超阈值);tailMessageCount=0 时触发当轮直接执行(不落待定标记)
9285
- * - 待定标记以 log-only om 信封事件(借用 feedback/record,kind 为 om/observe-pending /
9286
- * om/observe-invalidate,见 om-event.ts)持久化在会话日志中(重启后从日志恢复);
9261
+ * - 待定标记以 log-only 自定义会话事件(kind 为 plugin:dsh-plugin-om:observe-pending /
9262
+ * plugin:dsh-plugin-om:observe-invalidate,见 om-event.ts)持久化在会话日志中(重启后从日志恢复);
9287
9263
  * 压缩失败保留待定,下个 pre-step 直接重试执行
9288
9264
  * - 两级在 pre-step 阻塞串行执行(先反思后观察);仅主会话生效;omEnabled=false 关闭
9289
9265
  * - 压缩目标默认跟随会话路由;compressProvider + compressModel 成对配置时覆盖路由
@@ -9298,7 +9274,7 @@ function reportDegrade(session, logger, problem) {
9298
9274
  * - 提交走宿主 compaction/* 生命周期事件(start 带 phase → summary → 替换消息 → end),
9299
9275
  * 失败补 end(error,实际报错 + 诊断子会话 sessionId);替换消息 source 标记插件标识供 UI 认领
9300
9276
  * - 挂载失败类问题(systemPrompt/tokenMeter 服务异常)始终 console 到外部进程,并追加
9301
- * log-only om 警告事件(借用 feedback/record,客户端渲染功能降级警告行,每会话同一
9277
+ * log-only plugin:dsh-plugin-om:warning 事件(客户端渲染功能降级警告行,每会话同一
9302
9278
  * 问题至多一次);
9303
9279
  * 辅助估算的普通运行时报错仅记日志。降级与报错都不阻塞压缩(tokenMeter 压力数据
9304
9280
  * 缺失时本轮跳过观察)
@@ -9471,8 +9447,8 @@ function historySection(session) {
9471
9447
  };
9472
9448
  }
9473
9449
  /**
9474
- * 查找当前活跃的观察压缩待定标记:按日志顺序取最后一条 om/observe-pending 信封事件,
9475
- * 其后须无引用它的 om/observe-invalidate(已失效),且其后的压缩边界 seq 不大于标记
9450
+ * 查找当前活跃的观察压缩待定标记:按日志顺序取最后一条 plugin:dsh-plugin-om:observe-pending 事件,
9451
+ * 其后须无引用它的 plugin:dsh-plugin-om:observe-invalidate(已失效),且其后的压缩边界 seq 不大于标记
9476
9452
  * seq(边界后移说明标记期间已发生过压缩,标记过期——兜底「执行成功但失效标记未写出」
9477
9453
  * 的崩溃窗口)。无活跃标记返回 undefined。
9478
9454
  */
@@ -9482,24 +9458,24 @@ function findObservePending(session) {
9482
9458
  const event = session.snapshotEvents()[seq];
9483
9459
  if (!event) continue;
9484
9460
  const om = readOmEvent(event);
9485
- if (om?.kind === "om/observe-pending") pending = {
9461
+ if (om?.kind === "plugin:dsh-plugin-om:observe-pending") pending = {
9486
9462
  seq,
9487
9463
  triggerMessageIndex: om.data.triggerMessageIndex
9488
9464
  };
9489
- else if (om?.kind === "om/observe-invalidate" && pending !== void 0 && om.data.pendingSeq === pending.seq) pending = void 0;
9465
+ else if (om?.kind === "plugin:dsh-plugin-om:observe-invalidate" && pending !== void 0 && om.data.pendingSeq === pending.seq) pending = void 0;
9490
9466
  }
9491
9467
  if (pending === void 0) return void 0;
9492
9468
  const { boundarySeq } = historySection(session);
9493
9469
  if (boundarySeq !== void 0 && boundarySeq > pending.seq) return void 0;
9494
9470
  return pending;
9495
9471
  }
9496
- /** 追加观察压缩待定标记(log-only om 信封事件):记录触发点完整消息 index,返回事件 seq。 */
9472
+ /** 追加观察压缩待定标记(log-only 事件):记录触发点完整消息 index,返回事件 seq。 */
9497
9473
  function appendObservePending(session, triggerMessageIndex) {
9498
- return appendOmEvent(session, "om/observe-pending", { triggerMessageIndex });
9474
+ return appendOmEvent(session, "plugin:dsh-plugin-om:observe-pending", { triggerMessageIndex });
9499
9475
  }
9500
- /** 追加观察压缩待定失效标记(log-only om 信封事件):声明指定 pending 已失效,返回事件 seq。 */
9476
+ /** 追加观察压缩待定失效标记(log-only 事件):声明指定 pending 已失效,返回事件 seq。 */
9501
9477
  function appendObserveInvalidate(session, pendingSeq) {
9502
- return appendOmEvent(session, "om/observe-invalidate", { pendingSeq });
9478
+ return appendOmEvent(session, "plugin:dsh-plugin-om:observe-invalidate", { pendingSeq });
9503
9479
  }
9504
9480
  /** 当前打开中的 turn 号(最近 turn/start 且未被 turn/end 关闭);无则 null。 */
9505
9481
  function openTurnOf(session) {
@@ -9963,7 +9939,7 @@ async function maybeCompress(ctx, agent, config, signal) {
9963
9939
  //#endregion
9964
9940
  //#region src/model-download.ts
9965
9941
  /**
9966
- * 嵌入模型下载原语:recall-semantic 运行时按需下载与开发手动预下载(scripts/
9942
+ * 嵌入模型下载原语:recall 语义增强运行时按需下载与开发手动预下载(scripts/
9967
9943
  * download-model.mjs)共用。导出 EMBEDDING_MODEL_ID / ONNX_REL / MODEL_SMALL_FILES /
9968
9944
  * modelSourceUrl / modelTargetPath / needsDownload / downloadModel 及 DownloadResult /
9969
9945
  * ModelFetch 类型。
@@ -10043,7 +10019,7 @@ async function downloadModel(modelDir, { force = false, fetchImpl = fetch, log =
10043
10019
  //#endregion
10044
10020
  //#region src/embedding.ts
10045
10021
  /**
10046
- * 本地语义嵌入(recall-semantic 的向量引擎):Xenova/paraphrase-multilingual-MiniLM-L12-v2
10022
+ * 本地语义嵌入(recall 语义增强的向量引擎):Xenova/paraphrase-multilingual-MiniLM-L12-v2
10047
10023
  * 量化 ONNX,懒加载 + 批量推理 + cosine 相似度,模型缺失时按需后台下载。
10048
10024
  * 导出 BUNDLED_MODEL_DIR / EMBEDDING_MODEL_ID / resolveDshHome / sharedModelDir /
10049
10025
  * ensureModelSmallFiles / getEmbedder / resetEmbedder / ensureModelReady /
@@ -10259,7 +10235,7 @@ function resolveConfig(raw) {
10259
10235
  config.omEnabled = resolveBoolean(input.omEnabled, true);
10260
10236
  config.debug = resolveBoolean(input.debug, process.env.NODE_ENV !== "production");
10261
10237
  config.recallEnabled = resolveBoolean(input.recallEnabled, true);
10262
- config.semanticRecallEnabled = resolveBoolean(input.semanticRecallEnabled, true);
10238
+ config.semanticRecallEnabled = config.recallEnabled && resolveBoolean(input.semanticRecallEnabled, true);
10263
10239
  const modelDir = input.modelDir;
10264
10240
  if (typeof modelDir === "string" && modelDir.trim() !== "") config.modelDir = modelDir;
10265
10241
  config.compressProvider = resolveOptionalString(input.compressProvider);
@@ -10282,7 +10258,7 @@ function parametersFromZod(schema) {
10282
10258
  //#endregion
10283
10259
  //#region src/recall-output.ts
10284
10260
  /**
10285
- * recall / recall-semantic 共享输出契约:输出值为固定形态 { text, images }。
10261
+ * recall 输出契约:输出值为固定形态 { text, images }。
10286
10262
  * text 为完整消息的 XML 条目序列(形态见 recall-xml.ts,图片位置以 XML 注释标注),
10287
10263
  * images 为图片附件元数据(按 attachmentId 引用,不含字节)。
10288
10264
  * 导出 ImageRefValue / RecallOutputValue / RECALL_OUTPUT_SCHEMA / textOnly / imageNote /
@@ -10475,107 +10451,18 @@ function renderCompleteMessageXml(session, cm, options = {}) {
10475
10451
  };
10476
10452
  }
10477
10453
  //#endregion
10478
- //#region src/recall.ts
10479
- /**
10480
- * recall 工具:按完整消息 index 区间回看原始会话(含被压缩内容)。
10481
- * 导出 recallArgsSchema / RecallArgs / parseRecallArgs / buildRecallTool。
10482
- * 输出值为 { text, images }(契约见 recall-output.ts),text 为 XML 条目序列
10483
- * (形态见 recall-xml.ts);recall 自身不设输出上限,超大工具结果由 tool-result-pruner 裁剪。
10484
- */
10485
- /**
10486
- * recall 工具参数 schema:start 必填;end 与 offset 至少提供一个(同时给出时 end 优先)。
10487
- * 各字段描述经 .describe() 透传到 wire JSON Schema。
10488
- */
10489
- const recallArgsSchema = z.object({
10490
- start: z.number().describe("完整消息 index,基准边界,与 end 或 offset 配合指定区间;end 与 offset 至少提供一个(同时给出时 end 优先)。"),
10491
- end: z.number().optional().describe("与 offset 互斥,指定区间另一边界。"),
10492
- offset: z.number().optional().describe("与 end 互斥,相对 start 的步数(正向后、负向前)。")
10493
- }).refine((args) => args.end !== void 0 || args.offset !== void 0, { message: "end 与 offset 至少提供一个" });
10494
- /** 解析并校验 recall 调用参数:失败时抛出首个校验问题的可读消息(普通 Error,兼容 SDK 展示)。 */
10495
- function parseRecallArgs(raw) {
10496
- const result = recallArgsSchema.safeParse(raw);
10497
- if (!result.success) throw new Error(result.error.issues.map((issue) => `${issue.path.join(".") || "args"}: ${issue.message}`).join("; "));
10498
- return result.data;
10499
- }
10500
- /**
10501
- * 构建 recall 工具定义:按 start/end/offset 定位完整消息区间并渲染原始内容(标 index)。
10502
- * getPruner 返回 tool-result-pruner(可选),用于裁剪超大工具结果。
10503
- */
10504
- function buildRecallTool(getPruner) {
10505
- return {
10506
- name: "recall",
10507
- description: `在你需要查看历史消息时调用。${COMPLETE_MESSAGE_DEFINITION}此工具按 index 区间精确返回区间内全部完整消息的内容。`,
10508
- parameters: parametersFromZod(recallArgsSchema),
10509
- output: {
10510
- schema: RECALL_OUTPUT_SCHEMA,
10511
- render: (_args, value) => renderRecallOutput(value)
10512
- },
10513
- async execute(args, exec) {
10514
- const { start, end, offset } = parseRecallArgs(args);
10515
- const session = exec.agent?.session;
10516
- if (!session) return textOnly("会话异常");
10517
- if (!isMainSession(session)) return textOnly("recall 仅主会话可用");
10518
- const cms = indexCompleteMessages(session);
10519
- const startIndex = Number.isFinite(start) ? Math.floor(start) : 0;
10520
- if (startIndex < 0 || startIndex >= cms.length) return textOnly(`start ${start} 越界(完整消息共 ${cms.length} 条,index 范围 0..${cms.length - 1})`);
10521
- let endIndex;
10522
- if (end !== void 0) {
10523
- const e = Number.isFinite(end) ? Math.floor(end) : 0;
10524
- if (e < 0 || e >= cms.length) return textOnly(`end ${end} 越界(完整消息共 ${cms.length} 条,index 范围 0..${cms.length - 1})`);
10525
- endIndex = e;
10526
- } else {
10527
- const raw = offset ?? 0;
10528
- endIndex = startIndex + (Number.isFinite(raw) ? Math.floor(raw) : 0);
10529
- }
10530
- const lo = Math.max(0, Math.min(startIndex, endIndex));
10531
- const hi = Math.min(cms.length - 1, Math.max(startIndex, endIndex));
10532
- const pruner = getPruner?.();
10533
- const parts = [];
10534
- const images = [];
10535
- for (let i = lo; i <= hi; i += 1) {
10536
- const cm = cms[i];
10537
- if (!cm) continue;
10538
- try {
10539
- const rendered = renderCompleteMessageXml(session, cm, { pruner });
10540
- parts.push(rendered.xml);
10541
- images.push(...rendered.images);
10542
- } catch {}
10543
- }
10544
- if (parts.length === 0) return textOnly("指定区间没有完整消息");
10545
- return {
10546
- text: parts.join("\n"),
10547
- images
10548
- };
10549
- }
10550
- };
10551
- }
10552
- //#endregion
10553
10454
  //#region src/semantic-recall.ts
10554
10455
  /**
10555
- * recall-semantic 工具:按自然语言 query 对会话全部完整消息(含被压缩/遮蔽的)做
10456
+ * recall 语义增强的检索实现:按自然语言 query 对会话全部完整消息(含被压缩/遮蔽的)做
10556
10457
  * 语义检索,返回最匹配的完整消息与匹配说明。
10557
- * 导出 semanticRecallArgsSchema / SemanticRecallArgs / parseSemanticRecallArgs /
10558
- * resolveSemanticRange / tokenize / matchExplanation / buildSemanticRecallTool。
10458
+ * 导出 SemanticOptions / RangeArgs / resolveSemanticRange / tokenize / matchExplanation /
10459
+ * SEMANTIC_MODEL_NOT_READY_MESSAGE / semanticSearch。
10559
10460
  * 向量为本地 ONNX 嵌入(cosine 相似度);只匹配文本,纯图片消息不进候选池;
10560
10461
  * 区间缺省检索全部、区间不合法回退全量并在输出中告知;输出契约同 recall
10561
10462
  * ({ text, images },条目为 XML 形态见 recall-xml.ts,超大结果由 tool-result-pruner
10562
10463
  * 裁剪);候选池排除本次调用自身的 toolcall 完整消息(其渲染文本含 query 原文,
10563
- * 必居榜首);仅主会话可用。
10464
+ * 必居榜首)。工具入口与参数校验见 recall.ts。
10564
10465
  */
10565
- /** recall-semantic 工具参数 schema:query 必填;top_k 默认 3(1-10);区间参数均可选。 */
10566
- const semanticRecallArgsSchema = z.object({
10567
- query: z.string().describe("要找的内容的自然语言 query(中英文与代码术语皆可,如 \"修复 retry backoff 的逻辑\"),不能为空。"),
10568
- top_k: z.number().int().min(1).max(10).optional().describe("返回最匹配条数(1-10,默认 3)。"),
10569
- start: z.number().optional().describe("完整消息 index,基准边界,与 end/offset 配合指定搜索区间;缺省检索全部。"),
10570
- end: z.number().optional().describe("须与 start 配合,与 offset 互斥,指定搜索区间另一边界。"),
10571
- offset: z.number().optional().describe("须与 start 配合,与 end 互斥,相对 start 的步数(正向后、负向前)。")
10572
- }).refine((args) => args.query.trim().length > 0, { message: "query 不能为空" });
10573
- /** 解析并校验参数:失败时抛出可读错误(普通 Error 而非 ZodError)。 */
10574
- function parseSemanticRecallArgs(raw) {
10575
- const result = semanticRecallArgsSchema.safeParse(raw);
10576
- if (!result.success) throw new Error(result.error.issues.map((issue) => `${issue.path.join(".") || "args"}:${issue.message}`).join("; "));
10577
- return result.data;
10578
- }
10579
10466
  /**
10580
10467
  * 解析检索区间(完整消息 index,含端点)。
10581
10468
  * start 未提供 → 全量(fallback=false);start/end 越界或区间为空 → fallback=true
@@ -10642,85 +10529,194 @@ function matchExplanation(query, text, score) {
10642
10529
  }
10643
10530
  /** 模型未就绪时返回给模型的文案(下载完成后直接再次调用即可)。 */
10644
10531
  const SEMANTIC_MODEL_NOT_READY_MESSAGE = "语义检索暂不可用,本地向量模型尚未就绪。";
10645
- /** 构建 recall-semantic 工具定义(embedder/modelStatus 可注入,测试传替身;缺省用本地模型)。 */
10646
- function buildSemanticRecallTool(options) {
10647
- const getPruner = options?.getPruner ?? (() => void 0);
10532
+ /** 在会话完整消息中做语义检索,返回 TOP-K 命中条目。 */
10533
+ async function semanticSearch(input) {
10534
+ const { session, query, topK, start, end, offset, selfCallId, getPruner, options } = input;
10648
10535
  const embed = options?.embedder ?? ((texts) => getEmbedder().then((fn) => fn(texts)));
10536
+ if ((await options?.modelStatus?.() ?? "ready") !== "ready") return textOnly(SEMANTIC_MODEL_NOT_READY_MESSAGE);
10537
+ const cms = indexCompleteMessages(session);
10538
+ if (cms.length === 0) return textOnly("会话中没有可检索的消息");
10539
+ const range = resolveSemanticRange(cms.length, {
10540
+ start,
10541
+ end,
10542
+ offset
10543
+ });
10544
+ const candidates = [];
10545
+ for (let i = range.lo; i <= range.hi; i += 1) {
10546
+ const cm = cms[i];
10547
+ if (!cm) continue;
10548
+ if (selfCallId !== "" && cm.type === "toolcall" && cm.callId === selfCallId) continue;
10549
+ let text = "";
10550
+ try {
10551
+ text = renderCompleteMessage(session, cm);
10552
+ } catch {}
10553
+ if (text.trim().length > 0) candidates.push({
10554
+ cm,
10555
+ text
10556
+ });
10557
+ }
10558
+ if (candidates.length === 0) return textOnly("指定范围内没有可检索的消息");
10559
+ const [queryVec] = await embed([query]);
10560
+ if (!queryVec) return textOnly("语义检索失败:无法生成查询向量");
10561
+ const vectors = await embed(candidates.map((c) => c.text));
10562
+ const scored = candidates.map((c, i) => ({
10563
+ cm: c.cm,
10564
+ text: c.text,
10565
+ score: cosineSimilarity(queryVec, vectors[i] ?? /* @__PURE__ */ new Float32Array(0))
10566
+ }));
10567
+ scored.sort((a, b) => b.score - a.score);
10568
+ const limit = topK ?? 3;
10569
+ const hits = scored.slice(0, limit);
10570
+ const parts = [];
10571
+ const images = [];
10572
+ const rangeNote = range.fallback ? "指定区间不合法(start/end 越界等),已回退检索全部消息" : start === void 0 ? `检索全部消息(${candidates.length} 条可嵌入)` : `检索区间 [${range.lo}..${range.hi}](${candidates.length} 条可嵌入)`;
10573
+ parts.push(`<!-- ${xmlCommentText(`查询: ${query}`)} -->`);
10574
+ parts.push(`<!-- ${xmlCommentText(rangeNote)} -->`);
10575
+ parts.push(`<!-- ${xmlCommentText(`匹配 TOP-${hits.length}(共 ${scored.length} 条候选)`)} -->`);
10576
+ for (let i = 0; i < hits.length; i += 1) {
10577
+ const hit = hits[i];
10578
+ if (!hit) continue;
10579
+ const note = `<!-- ${xmlCommentText(`${i + 1}. ${matchExplanation(query, hit.text, hit.score)}`)} -->`;
10580
+ let xml;
10581
+ let hitImages = [];
10582
+ try {
10583
+ const pruner = getPruner();
10584
+ const rendered = renderCompleteMessageXml(session, hit.cm, {
10585
+ pruner,
10586
+ fallbackText: hit.text
10587
+ });
10588
+ xml = rendered.xml;
10589
+ hitImages = rendered.images;
10590
+ } catch {
10591
+ xml = hit.text;
10592
+ }
10593
+ parts.push(note);
10594
+ parts.push(xml);
10595
+ images.push(...hitImages);
10596
+ }
10649
10597
  return {
10650
- name: "recall-semantic",
10651
- description: `在你需要按语义检索历史消息时调用。${COMPLETE_MESSAGE_DEFINITION}此工具按自然语言含义检索最符合的完整消息,默认全量搜索,可指定区间。注意:只匹配文本。`,
10652
- parameters: parametersFromZod(semanticRecallArgsSchema),
10598
+ text: parts.join("\n"),
10599
+ images
10600
+ };
10601
+ }
10602
+ //#endregion
10603
+ //#region src/recall.ts
10604
+ /**
10605
+ * recall 工具:回看原始会话(含被压缩内容),语义增强启用时额外支持按含义检索。
10606
+ * 导出 recallArgsSchema / enhancedRecallArgsSchema / RecallArgs / parseRecallArgs / buildRecallTool。
10607
+ * - 区间模式:按完整消息 index 的 start/end/offset 精确返回区间内全部完整消息。
10608
+ * - 语义模式(仅增强启用且带 query):语义检索见 semantic-recall.ts。
10609
+ * 输出值为 { text, images }(契约见 recall-output.ts),text 为 XML 条目序列
10610
+ * (形态见 recall-xml.ts);recall 自身不设输出上限,超大工具结果由 tool-result-pruner 裁剪。
10611
+ */
10612
+ /**
10613
+ * 基础 recall 参数 schema:start 必填;end 与 offset 至少提供一个(同时给出时 end 优先)。
10614
+ * 各字段描述经 .describe() 透传到 wire JSON Schema。
10615
+ */
10616
+ const recallArgsSchema = z.object({
10617
+ start: z.number().describe("完整消息 index,基准边界,与 end 或 offset 配合指定区间;end 与 offset 至少提供一个(同时给出时 end 优先)。"),
10618
+ end: z.number().optional().describe("与 offset 互斥,指定区间另一边界。"),
10619
+ offset: z.number().optional().describe("与 end 互斥,相对 start 的步数(正向后、负向前)。")
10620
+ }).refine((args) => args.end !== void 0 || args.offset !== void 0, { message: "end 与 offset 至少提供一个" });
10621
+ /**
10622
+ * 语义增强 recall 参数 schema:带 query 走语义模式(区间可选,用于限定检索范围),
10623
+ * 不带 query 时与基础 schema 的校验一致。
10624
+ */
10625
+ const enhancedRecallArgsSchema = z.object({
10626
+ query: z.string().optional().describe("按含义检索的自然语言 query(中英文与代码术语皆可,如 \"修复 retry backoff 的逻辑\");提供时 start/end/offset 仅用于限定搜索区间,缺省检索全部。"),
10627
+ top_k: z.number().int().min(1).max(10).optional().describe("仅 query 模式:返回最匹配条数(1-10,默认 3)。"),
10628
+ start: z.number().optional().describe("完整消息 index,基准边界,与 end 或 offset 配合指定区间;未提供 query 时必填,且 end 与 offset 至少提供一个(同时给出时 end 优先)。"),
10629
+ end: z.number().optional().describe("与 offset 互斥,指定区间另一边界。"),
10630
+ offset: z.number().optional().describe("与 end 互斥,相对 start 的步数(正向后、负向前)。")
10631
+ }).superRefine((args, ctx) => {
10632
+ if (args.query !== void 0) {
10633
+ if (args.query.trim().length === 0) ctx.addIssue({
10634
+ code: "custom",
10635
+ path: ["query"],
10636
+ message: "query 不能为空"
10637
+ });
10638
+ return;
10639
+ }
10640
+ if (args.start === void 0) ctx.addIssue({
10641
+ code: "custom",
10642
+ path: ["start"],
10643
+ message: "未提供 query 时 start 必填"
10644
+ });
10645
+ else if (args.end === void 0 && args.offset === void 0) ctx.addIssue({
10646
+ code: "custom",
10647
+ path: ["end"],
10648
+ message: "end 与 offset 至少提供一个"
10649
+ });
10650
+ });
10651
+ /** 解析并校验 recall 调用参数(semantic 为语义增强是否启用):失败时抛出首个校验问题的可读消息。 */
10652
+ function parseRecallArgs(raw, semantic = false) {
10653
+ const result = (semantic ? enhancedRecallArgsSchema : recallArgsSchema).safeParse(raw);
10654
+ if (!result.success) throw new Error(result.error.issues.map((issue) => `${issue.path.join(".") || "args"}: ${issue.message}`).join("; "));
10655
+ return result.data;
10656
+ }
10657
+ /** 基础工具描述。 */
10658
+ const RECALL_DESCRIPTION = "在你需要查看历史消息时调用。此工具按 index 区间精确返回区间内全部完整消息的内容。";
10659
+ /** 语义增强启用时的工具描述。 */
10660
+ const ENHANCED_RECALL_DESCRIPTION = "在你需要查看历史消息时调用。两种用法:1) 给出 start 与 end 或 offset,按 index 区间精确返回区间内全部完整消息的内容;2) 给出 query,按自然语言含义检索最符合的完整消息,默认全量搜索,可用 start/end/offset 限定区间。注意:query 只匹配文本。";
10661
+ /**
10662
+ * 构建 recall 工具定义:按 start/end/offset 定位完整消息区间并渲染原始内容(标 index);
10663
+ * 传入 semantic 选项时额外支持 query 语义检索。
10664
+ */
10665
+ function buildRecallTool(options) {
10666
+ const getPruner = options?.getPruner;
10667
+ const semantic = options?.semantic;
10668
+ return {
10669
+ name: "recall",
10670
+ description: semantic ? ENHANCED_RECALL_DESCRIPTION : RECALL_DESCRIPTION,
10671
+ parameters: parametersFromZod(semantic ? enhancedRecallArgsSchema : recallArgsSchema),
10653
10672
  output: {
10654
10673
  schema: RECALL_OUTPUT_SCHEMA,
10655
10674
  render: (_args, value) => renderRecallOutput(value)
10656
10675
  },
10657
10676
  async execute(args, exec) {
10658
- const { query, top_k, start, end, offset } = parseSemanticRecallArgs(args);
10677
+ const { query, top_k, start, end, offset } = parseRecallArgs(args, semantic !== void 0);
10659
10678
  const session = exec.agent?.session;
10660
10679
  if (!session) return textOnly("会话异常");
10661
- if (!isMainSession(session)) return textOnly("recall-semantic 仅主会话可用");
10662
- if ((await options?.modelStatus?.() ?? "ready") !== "ready") return textOnly(SEMANTIC_MODEL_NOT_READY_MESSAGE);
10663
- const cms = indexCompleteMessages(session);
10664
- if (cms.length === 0) return textOnly("会话中没有可检索的消息");
10665
- const range = resolveSemanticRange(cms.length, {
10680
+ if (!isMainSession(session)) return textOnly("recall 仅主会话可用");
10681
+ if (query !== void 0) return semanticSearch({
10682
+ session,
10683
+ query,
10684
+ topK: top_k,
10666
10685
  start,
10667
10686
  end,
10668
- offset
10687
+ offset,
10688
+ selfCallId: String(exec.callId ?? ""),
10689
+ getPruner: () => getPruner?.(),
10690
+ options: semantic
10669
10691
  });
10670
- const selfCallId = String(exec.callId ?? "");
10671
- const candidates = [];
10672
- for (let i = range.lo; i <= range.hi; i += 1) {
10673
- const cm = cms[i];
10674
- if (!cm) continue;
10675
- if (selfCallId !== "" && cm.type === "toolcall" && cm.callId === selfCallId) continue;
10676
- let text = "";
10677
- try {
10678
- text = renderCompleteMessage(session, cm);
10679
- } catch {}
10680
- if (text.trim().length > 0) candidates.push({
10681
- cm,
10682
- text
10683
- });
10692
+ if (start === void 0) return textOnly("start 必填");
10693
+ const cms = indexCompleteMessages(session);
10694
+ const startIndex = Number.isFinite(start) ? Math.floor(start) : 0;
10695
+ if (startIndex < 0 || startIndex >= cms.length) return textOnly(`start ${start} 越界(完整消息共 ${cms.length} 条,index 范围 0..${cms.length - 1})`);
10696
+ let endIndex;
10697
+ if (end !== void 0) {
10698
+ const e = Number.isFinite(end) ? Math.floor(end) : 0;
10699
+ if (e < 0 || e >= cms.length) return textOnly(`end ${end} 越界(完整消息共 ${cms.length} 条,index 范围 0..${cms.length - 1})`);
10700
+ endIndex = e;
10701
+ } else {
10702
+ const raw = offset ?? 0;
10703
+ endIndex = startIndex + (Number.isFinite(raw) ? Math.floor(raw) : 0);
10684
10704
  }
10685
- if (candidates.length === 0) return textOnly("指定范围内没有可检索的消息");
10686
- const [queryVec] = await embed([query]);
10687
- if (!queryVec) return textOnly("语义检索失败:无法生成查询向量");
10688
- const vectors = await embed(candidates.map((c) => c.text));
10689
- const scored = candidates.map((c, i) => ({
10690
- cm: c.cm,
10691
- text: c.text,
10692
- score: cosineSimilarity(queryVec, vectors[i] ?? /* @__PURE__ */ new Float32Array(0))
10693
- }));
10694
- scored.sort((a, b) => b.score - a.score);
10695
- const limit = top_k ?? 3;
10696
- const hits = scored.slice(0, limit);
10705
+ const lo = Math.max(0, Math.min(startIndex, endIndex));
10706
+ const hi = Math.min(cms.length - 1, Math.max(startIndex, endIndex));
10707
+ const pruner = getPruner?.();
10697
10708
  const parts = [];
10698
10709
  const images = [];
10699
- const rangeNote = range.fallback ? "指定区间不合法(start/end 越界等),已回退检索全部消息" : start === void 0 ? `检索全部消息(${candidates.length} 条可嵌入)` : `检索区间 [${range.lo}..${range.hi}](${candidates.length} 条可嵌入)`;
10700
- parts.push(`<!-- ${xmlCommentText(`查询: ${query}`)} -->`);
10701
- parts.push(`<!-- ${xmlCommentText(rangeNote)} -->`);
10702
- parts.push(`<!-- ${xmlCommentText(`匹配 TOP-${hits.length}(共 ${scored.length} 条候选)`)} -->`);
10703
- for (let i = 0; i < hits.length; i += 1) {
10704
- const hit = hits[i];
10705
- if (!hit) continue;
10706
- const note = `<!-- ${xmlCommentText(`${i + 1}. ${matchExplanation(query, hit.text, hit.score)}`)} -->`;
10707
- let xml;
10708
- let hitImages = [];
10710
+ for (let i = lo; i <= hi; i += 1) {
10711
+ const cm = cms[i];
10712
+ if (!cm) continue;
10709
10713
  try {
10710
- const pruner = getPruner();
10711
- const rendered = renderCompleteMessageXml(session, hit.cm, {
10712
- pruner,
10713
- fallbackText: hit.text
10714
- });
10715
- xml = rendered.xml;
10716
- hitImages = rendered.images;
10717
- } catch {
10718
- xml = hit.text;
10719
- }
10720
- parts.push(note);
10721
- parts.push(xml);
10722
- images.push(...hitImages);
10714
+ const rendered = renderCompleteMessageXml(session, cm, { pruner });
10715
+ parts.push(rendered.xml);
10716
+ images.push(...rendered.images);
10717
+ } catch {}
10723
10718
  }
10719
+ if (parts.length === 0) return textOnly("指定区间没有完整消息");
10724
10720
  return {
10725
10721
  text: parts.join("\n"),
10726
10722
  images
@@ -10729,6 +10725,84 @@ function buildSemanticRecallTool(options) {
10729
10725
  };
10730
10726
  }
10731
10727
  //#endregion
10728
+ //#region src/system-reminder.ts
10729
+ /**
10730
+ * system-reminder:以 <system-reminder> 用户消息向主会话注入插件提醒,不进系统提示词。
10731
+ * - 进度提醒:OM 启用时提示模型边做边简述计划与进展。
10732
+ * - 完整消息定义提醒:OM 或 recall 启用时说明 `<history>` 块与 recall 共用的完整消息 index。
10733
+ * 每个 step 检查表层,被压缩遮蔽或文本过期时补发,保证模型请求中每种恒有一条。
10734
+ * 导出 PROGRESS_REMINDER_SOURCE_KIND / DEFINITION_REMINDER_SOURCE_KIND / 对应 source 类型 /
10735
+ * SystemReminder / PROGRESS_REMINDER / DEFINITION_REMINDER / systemReminderMessage /
10736
+ * activeSystemReminders / ensureSystemReminders。
10737
+ */
10738
+ /** 进度提醒的 producer-owned source kind(区别于压缩日志消息的 plugin:dsh-plugin-om)。 */
10739
+ const PROGRESS_REMINDER_SOURCE_KIND = "plugin:dsh-plugin-om:progress";
10740
+ /** 完整消息定义提醒的 producer-owned source kind。 */
10741
+ const DEFINITION_REMINDER_SOURCE_KIND = "plugin:dsh-plugin-om:definition";
10742
+ /** 用 system-reminder 标签包裹提醒正文。 */
10743
+ function wrap(lines) {
10744
+ return [
10745
+ "<system-reminder>",
10746
+ ...lines,
10747
+ "</system-reminder>"
10748
+ ].join("\n");
10749
+ }
10750
+ /** 进度提醒。 */
10751
+ const PROGRESS_REMINDER = {
10752
+ kind: PROGRESS_REMINDER_SOURCE_KIND,
10753
+ text: wrap([
10754
+ "Narrate your progress while you work, not only when the task is finished.",
10755
+ "- Before your first tool call on a task, state your plan in one or two sentences.",
10756
+ "- 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.",
10757
+ "- Do not narrate every individual tool call; one short note per chunk is enough.",
10758
+ "- Do not save all commentary for the final answer. The final answer summarizes outcomes."
10759
+ ])
10760
+ };
10761
+ /** 完整消息定义提醒。 */
10762
+ const DEFINITION_REMINDER = {
10763
+ kind: DEFINITION_REMINDER_SOURCE_KIND,
10764
+ text: wrap([COMPLETE_MESSAGE_DEFINITION])
10765
+ };
10766
+ /** 构造一条新的提醒消息。 */
10767
+ function systemReminderMessage(reminder) {
10768
+ return createUserMessage({
10769
+ content: [{
10770
+ type: "text",
10771
+ text: reminder.text
10772
+ }],
10773
+ source: {
10774
+ kind: reminder.kind,
10775
+ form: "instructions"
10776
+ }
10777
+ });
10778
+ }
10779
+ /** 按配置返回应注入的提醒,顺序固定:进度在前,定义在后。 */
10780
+ function activeSystemReminders(config) {
10781
+ const reminders = [];
10782
+ if (config.omEnabled) reminders.push(PROGRESS_REMINDER);
10783
+ if (config.omEnabled || config.recallEnabled) reminders.push(DEFINITION_REMINDER);
10784
+ return reminders;
10785
+ }
10786
+ /** 消息是否为指定提醒的当前文本。 */
10787
+ function isCurrent(reminder, source, content) {
10788
+ return source.kind === reminder.kind && content.length === 1 && content[0]?.type === "text" && content[0].text === reminder.text;
10789
+ }
10790
+ /**
10791
+ * 保证本 step 之后的消息列表中每种指定提醒各有一条当前文本:本 step 已带上或表层已有则跳过,
10792
+ * 否则按顺序追加到末尾。返回新数组,不修改入参。
10793
+ */
10794
+ function ensureSystemReminders(session, messages, reminders) {
10795
+ const result = [...messages];
10796
+ if (reminders.length === 0) return result;
10797
+ const events = session.snapshotEvents();
10798
+ const surface = session.surface.nodes.flatMap((seq) => {
10799
+ const event = events[seq];
10800
+ return event?.type === "user/message" ? [event.data] : [];
10801
+ });
10802
+ for (const reminder of reminders) if (![...result, ...surface].some((message) => isCurrent(reminder, message.source, message.content))) result.push(systemReminderMessage(reminder));
10803
+ return result;
10804
+ }
10805
+ //#endregion
10732
10806
  //#region src/index.ts
10733
10807
  /** 插件名(Loader 识别入口的稳定标识)。 */
10734
10808
  const name = "dsh-plugin-om";
@@ -10739,9 +10813,7 @@ const inject = [
10739
10813
  "tokenMeter",
10740
10814
  "sessions"
10741
10815
  ];
10742
- /** OM 主会话在任务推进中保留规划与结果节点。 */
10743
- const PROGRESS_PROMPT = "在任务推进的关键节点,简要输出后续规划,并在执行后说明对应结果;无需逐次播报工具调用。";
10744
- /** 插件激活入口:解析配置、注册工具、接线系统提示与 pre-step 自动压缩。 */
10816
+ /** 插件激活入口:解析配置、注册工具、接线 pre-step 自动压缩与提醒补发。 */
10745
10817
  function apply(ctx, config) {
10746
10818
  const resolved = currentConfig(config);
10747
10819
  const logger = makeLogger(ctx, () => currentConfig(config).debug);
@@ -10749,44 +10821,35 @@ function apply(ctx, config) {
10749
10821
  const warnModel = (message) => ctx.logger.warn(`dsh-plugin-om: ${message}`);
10750
10822
  const logModel = (message) => logger.info(message);
10751
10823
  let disposeRecall;
10752
- let disposeSemantic;
10753
- let modelDir = resolved.modelDir;
10754
- let semanticEnabled = false;
10755
- /** 保持实际注册列表与当前配置一致;仅首次启用或更换目录时启动后台预热。 */
10824
+ /** 当前已注册 recall 对应的语义增强开关与模型目录。 */
10825
+ let registered;
10826
+ /** 保持注册的 recall 与当前配置一致;仅语义增强首次生效或更换目录时启动后台预热。 */
10756
10827
  function syncTools() {
10757
10828
  const next = currentConfig(config);
10758
- if (next.recallEnabled && !disposeRecall) disposeRecall = ctx.tools.register(buildRecallTool(() => ctx.get("toolResultPruner")));
10759
- else if (!next.recallEnabled && disposeRecall) {
10829
+ const semantic = next.recallEnabled && next.semanticRecallEnabled;
10830
+ if (disposeRecall && (!next.recallEnabled || registered?.semantic !== semantic || semantic && registered.modelDir !== next.modelDir)) {
10760
10831
  disposeRecall();
10761
10832
  disposeRecall = void 0;
10833
+ registered = void 0;
10762
10834
  }
10763
- if (disposeSemantic && (!next.semanticRecallEnabled || next.modelDir !== modelDir)) {
10764
- disposeSemantic();
10765
- disposeSemantic = void 0;
10766
- }
10767
- if (next.semanticRecallEnabled && !disposeSemantic) {
10835
+ if (next.recallEnabled && !disposeRecall) {
10768
10836
  const directory = next.modelDir;
10769
- disposeSemantic = ctx.tools.register(buildSemanticRecallTool({
10837
+ disposeRecall = ctx.tools.register(buildRecallTool({
10770
10838
  getPruner: () => ctx.get("toolResultPruner"),
10771
- modelStatus: () => ensureModelReady(directory, warnModel, void 0, logModel),
10772
- embedder: (texts) => getEmbedder(directory).then((embed) => embed(texts))
10839
+ ...semantic ? { semantic: {
10840
+ modelStatus: () => ensureModelReady(directory, warnModel, void 0, logModel),
10841
+ embedder: (texts) => getEmbedder(directory).then((embed) => embed(texts))
10842
+ } } : {}
10773
10843
  }));
10844
+ registered = {
10845
+ semantic,
10846
+ modelDir: directory
10847
+ };
10848
+ if (semantic) ensureModelReady(directory, warnModel, void 0, logModel);
10774
10849
  }
10775
- if (next.semanticRecallEnabled && (!semanticEnabled || next.modelDir !== modelDir)) ensureModelReady(next.modelDir, warnModel, void 0, logModel);
10776
- modelDir = next.modelDir;
10777
- semanticEnabled = next.semanticRecallEnabled;
10778
10850
  }
10779
10851
  syncTools();
10780
10852
  ctx.on("loader/volatile-update", () => syncTools());
10781
- ctx.on("system-prompt/assemble", async (_assembly, context, next) => {
10782
- const assembly = await next();
10783
- if (currentConfig(config).omEnabled && context.agent && isMainSession(context.agent.session)) assembly.sections.push({
10784
- name: "dsh-plugin-om:progress",
10785
- text: PROGRESS_PROMPT,
10786
- interpolate: false
10787
- });
10788
- return assembly;
10789
- });
10790
10853
  ctx.on("agent/pre-step", async ({ agent, signal }, next) => {
10791
10854
  let outcome = { failed: false };
10792
10855
  try {
@@ -10804,7 +10867,13 @@ function apply(ctx, config) {
10804
10867
  logger.warn(`上下文压缩失败,拒绝本 step 中断当前 turn:${outcome.error}${diagnostic}`);
10805
10868
  return { kind: "reject" };
10806
10869
  }
10807
- return next();
10870
+ const decision = await next();
10871
+ const reminders = activeSystemReminders(currentConfig(config));
10872
+ if (decision.kind === "enter" && !signal.aborted && reminders.length > 0 && isMainSession(agent.session)) return {
10873
+ ...decision,
10874
+ messages: ensureSystemReminders(agent.session, decision.messages, reminders)
10875
+ };
10876
+ return decision;
10808
10877
  });
10809
10878
  }
10810
10879
  //#endregion