dsh-plugin-om 0.0.45 → 0.0.47

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
@@ -4,12 +4,12 @@ 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";
6
6
  import { SUBAGENT_DESCRIPTOR_VERSION } from "@deepseek-ai/dsh-subagent";
7
+ import { z } from "zod";
7
8
  import Schema from "@deepseek-ai/schemastery";
8
9
  import { copyFileSync, existsSync, mkdirSync, renameSync, rmSync, statSync, writeFileSync } from "node:fs";
9
10
  import { homedir } from "node:os";
10
11
  import path from "node:path";
11
12
  import { fileURLToPath } from "node:url";
12
- import { z } from "zod";
13
13
  import { toJSONSchema } from "zod/v4/core";
14
14
  import { AttachmentId } from "@deepseek-ai/dsh-attachment";
15
15
  //#region \0rolldown/runtime.js
@@ -60,8 +60,8 @@ function historyFormatNote(sections = {}) {
60
60
  /** skill 工具名:toolcall 条目的工具名为该值时视为 skill 加载,<history> 块中以 <skill_content> 元素呈现。 */
61
61
  const SKILL_TOOL_NAME = "skill";
62
62
  /**
63
- * ask_user_question 工具名:toolcall 条目的工具名为该值时视为向用户的提问,
64
- * <history> 块中以 <ask-user-question> 元素呈现,压缩时与 skill 一样要求二次确认。
63
+ * 提问工具名:成功且问题与答案完整配对时视为合法 ask,失败调用按普通 toolcall 处理。
64
+ * 合法 ask 直接压缩需二次确认;未直接压缩的原始 ask 重写后以 q/a 形式保留。
65
65
  */
66
66
  const ASK_USER_QUESTION_TOOL_NAME = "ask_user_question";
67
67
  /**
@@ -7766,96 +7766,74 @@ function skillNameOf(session, cm) {
7766
7766
  }
7767
7767
  return "";
7768
7768
  }
7769
- /** 未作答的题在条目正文中的回答段。 */
7769
+ /** 未作答题目的呈现文本。 */
7770
7770
  const ASK_UNANSWERED_TEXT = "(未回答)";
7771
- /**
7772
- * 从 ask_user_question 调用参数 JSON 提取提问项:questions 数组逐项取 id 与
7773
- * question 字段(字符串元素原样、无 id),保持参数序。参数缺失、非法或解析不出
7774
- * 问题文本时返回空数组。
7775
- */
7776
- function askQuestionItems(args) {
7777
- if (args === void 0 || args.trim() === "") return [];
7778
- let parsed;
7779
- try {
7780
- parsed = JSON.parse(args);
7781
- } catch {
7782
- return [];
7783
- }
7784
- if (!isRecord(parsed) || !Array.isArray(parsed.questions)) return [];
7785
- const items = [];
7786
- for (const q of parsed.questions) if (typeof q === "string" && q.trim() !== "") items.push({ text: q });
7787
- else if (isRecord(q) && typeof q.question === "string" && q.question.trim() !== "") {
7788
- const id = typeof q.id === "string" && q.id !== "" ? q.id : void 0;
7789
- items.push(id === void 0 ? { text: q.question } : {
7790
- id,
7791
- text: q.question
7792
- });
7793
- }
7794
- return items;
7795
- }
7796
- /**
7797
- * 从 ask_user_question 工具返回文本提取回答项:返回为 JSON 且含 answers 数组时,
7798
- * 逐项取 id 与所选内容(selected 逐项拼接、custom 追加在后)。
7799
- * 返回不是可解析的 answers JSON 时返回 null(调用方回退为返回原文呈现)。
7800
- */
7801
- function askAnswerItems(result) {
7802
- let parsed;
7771
+ /** 提问参数的完整结构;非法项使整次调用回退。 */
7772
+ const askQuestionsSchema = z.object({ questions: z.array(z.object({
7773
+ id: z.string().refine((id) => id.trim() !== ""),
7774
+ question: z.string().refine((question) => question.trim() !== ""),
7775
+ options: z.array(z.object({
7776
+ label: z.string(),
7777
+ description: z.string().optional()
7778
+ })).optional()
7779
+ })).min(1) });
7780
+ /** 回答结果的完整结构;等待和失败状态不是合法问答。 */
7781
+ const askAnswersSchema = z.object({
7782
+ pending: z.literal(false).optional(),
7783
+ aborted: z.literal(false).optional(),
7784
+ isError: z.literal(false).optional(),
7785
+ error: z.never().optional(),
7786
+ answers: z.array(z.object({
7787
+ id: z.string().refine((id) => id.trim() !== ""),
7788
+ selected: z.array(z.string()),
7789
+ custom: z.string().optional()
7790
+ }))
7791
+ });
7792
+ /** 校验配对成功的原始 ask,按题序保存问题、选项和回答。 */
7793
+ function askUserQuestionData(session, cm) {
7794
+ const call = toolCallBlockOf(session, cm);
7795
+ const resultMessage = toolResultMessageOf(session, cm);
7796
+ if (!call || !resultMessage) return null;
7797
+ const resultSeq = cm.seqs[1];
7798
+ const resultEvent = resultSeq === void 0 ? void 0 : session.snapshotEvents()[resultSeq];
7799
+ if (resultEvent?.type !== "tool/result" || resultEvent.data.error !== void 0) return null;
7800
+ if (resultMessage.role === "tool" && (resultMessage.isError || resultMessage.toolCallId !== cm.callId)) return null;
7801
+ if (resultMessage.content.some((block) => {
7802
+ const legacy = block;
7803
+ return legacy.type === "tool-result" && legacy.isError === true;
7804
+ })) return null;
7805
+ const args = toolArgsJson(call.arguments);
7806
+ const result = renderMessageText(resultMessage);
7803
7807
  try {
7804
- parsed = JSON.parse(result);
7808
+ const questions = askQuestionsSchema.safeParse(JSON.parse(args));
7809
+ const answers = askAnswersSchema.safeParse(JSON.parse(result));
7810
+ if (!questions.success || !answers.success) return null;
7811
+ const ids = new Set(questions.data.questions.map((question) => question.id));
7812
+ const answerMap = new Map(answers.data.answers.map((answer) => [answer.id, answer]));
7813
+ if (ids.size !== questions.data.questions.length || answerMap.size !== answers.data.answers.length || answerMap.size !== ids.size || [...answerMap.keys()].some((id) => !ids.has(id))) return null;
7814
+ return { questions: questions.data.questions.map((question) => {
7815
+ const answer = answerMap.get(question.id);
7816
+ const text = answer ? [...answer.selected, ...answer.custom ? [answer.custom] : []].join(", ") : "";
7817
+ return {
7818
+ question: question.question,
7819
+ options: (question.options ?? []).map((option) => ({
7820
+ label: option.label,
7821
+ ...option.description === void 0 ? {} : { description: option.description }
7822
+ })),
7823
+ answer: text === "" ? ASK_UNANSWERED_TEXT : text
7824
+ };
7825
+ }) };
7805
7826
  } catch {
7806
7827
  return null;
7807
7828
  }
7808
- if (!isRecord(parsed) || !Array.isArray(parsed.answers)) return null;
7809
- const items = [];
7810
- for (const a of parsed.answers) {
7811
- if (!isRecord(a)) continue;
7812
- const selected = Array.isArray(a.selected) ? a.selected.filter((s) => typeof s === "string") : [];
7813
- const custom = typeof a.custom === "string" && a.custom !== "" ? [a.custom] : [];
7814
- const id = typeof a.id === "string" && a.id !== "" ? a.id : void 0;
7815
- const text = [...selected, ...custom].join(", ");
7816
- items.push(id === void 0 ? { text } : {
7817
- id,
7818
- text
7819
- });
7820
- }
7821
- return items;
7822
7829
  }
7823
- /**
7824
- * ask_user_question 条目正文行:回答可解析时按题输出 q:(问题文本)与 a:(用户回答)
7825
- * 成对的行——按 id 配对,未作答的题记为 a:(未回答),匹配不到问题的回答单独成行;
7826
- * 回答不可解析时逐行输出问题、末尾单行输出返回原文。
7827
- */
7828
- function askUserQuestionLines(questions, answers, result) {
7829
- if (answers === null) {
7830
- const lines = questions.map((q) => `q:${q.text}`);
7831
- if (result.trim() !== "") lines.push(`a:${result}`);
7832
- return lines;
7833
- }
7834
- const lines = [];
7835
- const paired = /* @__PURE__ */ new Set();
7836
- for (const q of questions) {
7837
- const index = q.id === void 0 ? -1 : answers.findIndex((a, i) => !paired.has(i) && a.id === q.id);
7838
- if (index >= 0) paired.add(index);
7839
- const answer = index >= 0 ? answers[index]?.text ?? "" : "";
7840
- lines.push(`q:${q.text} a:${answer === "" ? ASK_UNANSWERED_TEXT : answer}`);
7841
- }
7842
- answers.forEach((a, i) => {
7843
- if (!paired.has(i) && a.text !== "") lines.push(`a:${a.text}`);
7844
- });
7845
- return lines;
7846
- }
7847
- /**
7848
- * ask_user_question 条目正文:构造为原生 <ask-user-question> 包裹形态,内文见
7849
- * askUserQuestionLines。问题与回答均取不到内容时返回 null(调用方回退为通用完整消息呈现)。
7850
- */
7851
- function askUserQuestionText(session, cm) {
7852
- const call = toolCallBlockOf(session, cm);
7853
- const args = call === void 0 ? void 0 : toolArgsJson(call.arguments);
7854
- const resultMessage = toolResultMessageOf(session, cm);
7855
- const result = resultMessage && Array.isArray(resultMessage.content) ? renderMessageText(resultMessage) : "";
7856
- const lines = askUserQuestionLines(askQuestionItems(args), result.trim() === "" ? [] : askAnswerItems(result), result);
7857
- if (lines.length === 0) return null;
7858
- return `<ask-user-question>${lines.join("\n")}</ask-user-question>`;
7830
+ /** 观察 ask 正文:保留多行原文,每题按 q/options/a 呈现。 */
7831
+ function askUserQuestionText(ask) {
7832
+ return `<ask-user-question>${ask.questions.flatMap((question) => [
7833
+ `q:${question.question}`,
7834
+ ...question.options.map((option, index) => `o${index + 1}:${option.label}${option.description ? ` — ${option.description}` : ""}`),
7835
+ `a:${question.answer}`
7836
+ ]).join("\n")}</ask-user-question>`;
7859
7837
  }
7860
7838
  /**
7861
7839
  * 观察视图:被压缩区间(表层 seq 集合)内的完整消息投影为条目——
@@ -7934,9 +7912,9 @@ function buildObserveView(session, seqs, options = {}) {
7934
7912
  }
7935
7913
  const toolName = cm.type === "toolcall" ? toolCallNameOf(session, cm) : void 0;
7936
7914
  const isSkill = toolName === SKILL_TOOL_NAME;
7937
- const isAsk = toolName === ASK_USER_QUESTION_TOOL_NAME;
7938
- const askText = isAsk ? askUserQuestionText(session, cm) : void 0;
7939
- const text = isSkill ? renderToolResultText(session, cm) : isAsk ? askText ?? renderCompleteMessage(session, cm) : renderCompleteMessage(session, cm);
7915
+ const ask = toolName === "ask_user_question" ? askUserQuestionData(session, cm) : null;
7916
+ const isAsk = ask !== null;
7917
+ const text = isSkill ? renderToolResultText(session, cm) : ask !== null ? askUserQuestionText(ask) : renderCompleteMessage(session, cm);
7940
7918
  if (text.trim() === "") continue;
7941
7919
  const skillName = isSkill ? skillNameOf(session, cm) : void 0;
7942
7920
  let toolArgs;
@@ -7956,7 +7934,8 @@ function buildObserveView(session, seqs, options = {}) {
7956
7934
  ...skillName === void 0 ? {} : { skillName },
7957
7935
  ...cm.callId === void 0 || toolArgs === void 0 ? {} : { callId: cm.callId },
7958
7936
  ...toolArgs === void 0 ? {} : { toolArgs },
7959
- ...toolResult === void 0 ? {} : { toolResult }
7937
+ ...toolResult === void 0 ? {} : { toolResult },
7938
+ ...ask === null ? {} : { ask }
7960
7939
  });
7961
7940
  }
7962
7941
  return {
@@ -8252,6 +8231,12 @@ function entryToElement(doc, entry) {
8252
8231
  }
8253
8232
  return el;
8254
8233
  }
8234
+ if (entry.kind === "assistant" && entry.ask !== void 0) {
8235
+ const el = doc.createElement("ask-user-question");
8236
+ if (entry.lo !== void 0 && entry.lo === entry.hi) el.setAttribute("index", String(entry.lo));
8237
+ appendCdataText(doc, el, askUserQuestionInner(askUserQuestionText(entry.ask)) ?? "");
8238
+ return el;
8239
+ }
8255
8240
  if (entry.kind === "assistant" && entry.toolName === "ask_user_question") {
8256
8241
  const inner = askUserQuestionInner(entry.text);
8257
8242
  if (inner !== void 0) {
@@ -8317,11 +8302,22 @@ function renderEntriesXml(entries) {
8317
8302
  }
8318
8303
  //#endregion
8319
8304
  //#region src/compress-tools.ts
8305
+ /** 判定 JSON 对象,不接受数组或 null。 */
8306
+ function isJsonRecord(value) {
8307
+ return value !== null && typeof value === "object" && !Array.isArray(value);
8308
+ }
8309
+ /** 合法原始 ask 或已处理的历史 ask;普通失败 toolcall 不包含在内。 */
8310
+ function isAskEntry(entry) {
8311
+ return entry.kind === "assistant" && (entry.ask !== void 0 || entry.toolName === "ask_user_question" && entry.toolArgs === void 0);
8312
+ }
8320
8313
  /** 压缩会话的工具状态:视图 + 替换记录 + 二次确认标记(skill / ask_user_question)+ 完成标记。 */
8321
8314
  var CompressionState = class CompressionState {
8322
8315
  view;
8323
8316
  replacements = [];
8324
8317
  challengedSkills = /* @__PURE__ */ new Set();
8318
+ viewedAsks = /* @__PURE__ */ new Set();
8319
+ undeliveredAsks = /* @__PURE__ */ new Set();
8320
+ rewrittenAsks = /* @__PURE__ */ new Map();
8325
8321
  _completed = false;
8326
8322
  /**
8327
8323
  * @param view 压缩视图(观察或反思),工具校验与最终块构建的数据源。
@@ -8329,11 +8325,19 @@ var CompressionState = class CompressionState {
8329
8325
  constructor(view) {
8330
8326
  this.view = view;
8331
8327
  }
8332
- /** 已成功应用的替换次数(0 表示空提交)。 */
8328
+ /** 已成功应用的普通摘要替换区间数,不包含 ask 重写。 */
8333
8329
  get replacementCount() {
8334
8330
  return this.replacements.length;
8335
8331
  }
8336
- /** 是否已调用 completeCompression。 */
8332
+ /** 本次视图是否存在原始合法 ask,整个循环内保持稳定。 */
8333
+ get hasPendingAsks() {
8334
+ return this.view.entries.some((entry) => entry.ask !== void 0);
8335
+ }
8336
+ /** 已成功重写且最终未被直接压缩覆盖的 ask 数量。 */
8337
+ get rewriteCount() {
8338
+ return this.view.entries.filter((entry) => entry.ask !== void 0 && entry.lo !== void 0 && this.rewrittenAsks.has(entry.lo) && !this.coveredBy(entry)).length;
8339
+ }
8340
+ /** 是否已成功调用 completeCompression。 */
8337
8341
  get completed() {
8338
8342
  return this._completed;
8339
8343
  }
@@ -8342,7 +8346,7 @@ var CompressionState = class CompressionState {
8342
8346
  * 未知工具名或参数非法 JSON 返回错误结果,不抛出。
8343
8347
  */
8344
8348
  executeCall(name, rawArgs) {
8345
- if (name === "getHistory" || name === "compressHistory" || name === "completeCompression") {
8349
+ if (name === "getHistory" || name === "compressHistory" || name === "completeCompression" || name === "rewriteAskUserQuestion") {
8346
8350
  let args;
8347
8351
  if (typeof rawArgs === "string" && rawArgs.trim() === "") args = {};
8348
8352
  else try {
@@ -8353,16 +8357,26 @@ var CompressionState = class CompressionState {
8353
8357
  isError: true
8354
8358
  };
8355
8359
  }
8360
+ if (name === "rewriteAskUserQuestion" && this.hasPendingAsks) return this.rewriteAskUserQuestion(args);
8361
+ if (name === "rewriteAskUserQuestion") return {
8362
+ text: "本次视图没有待处理的原始 ask",
8363
+ isError: true
8364
+ };
8356
8365
  const record = args ?? {};
8357
8366
  if (name === "getHistory") return this.getHistory(record);
8358
8367
  if (name === "compressHistory") return this.compressHistory(record);
8359
8368
  return this.complete();
8360
8369
  }
8361
8370
  return {
8362
- text: `未知工具 ${name}(可用:getHistory / compressHistory / completeCompression)`,
8371
+ text: `未知工具 ${name}(可用:getHistory / compressHistory${this.hasPendingAsks ? " / rewriteAskUserQuestion" : ""} / completeCompression)`,
8363
8372
  isError: true
8364
8373
  };
8365
8374
  }
8375
+ /** 下一模型请求已携带成功的 getHistory 结果,允许使用其选项重写。 */
8376
+ markHistoryDelivered() {
8377
+ for (const index of this.undeliveredAsks) this.viewedAsks.add(index);
8378
+ this.undeliveredAsks.clear();
8379
+ }
8366
8380
  /** 解析可选数值参数(缺省 undefined;非有限数返回 NaN)。 */
8367
8381
  optionalNumber(value) {
8368
8382
  if (value === void 0 || value === null) return void 0;
@@ -8412,8 +8426,10 @@ var CompressionState = class CompressionState {
8412
8426
  text: `区间 [${start}..${end}] 没有条目`,
8413
8427
  isError: false
8414
8428
  };
8429
+ const text = `<!-- 完整消息区间 [${start}..${end}],共 ${selected.length} 条 -->\n${renderEntriesXml(selected)}`;
8430
+ for (const entry of selected) if (entry.ask !== void 0 && entry.lo !== void 0) this.undeliveredAsks.add(entry.lo);
8415
8431
  return {
8416
- text: `<!-- 完整消息区间 [${start}..${end}],共 ${selected.length} 条 -->\n${renderEntriesXml(selected)}`,
8432
+ text,
8417
8433
  isError: false
8418
8434
  };
8419
8435
  }
@@ -8514,7 +8530,7 @@ var CompressionState = class CompressionState {
8514
8530
  let challengedTool;
8515
8531
  for (const entry of this.view.entries) {
8516
8532
  if (entry.kind !== "assistant") continue;
8517
- if (entry.toolName !== "skill" && entry.toolName !== "ask_user_question") continue;
8533
+ if (entry.toolName !== "skill" && !isAskEntry(entry)) continue;
8518
8534
  if (entry.lo === void 0 || entry.lo < lo || entry.lo > hi) continue;
8519
8535
  if (!this.challengedSkills.has(entry.lo)) {
8520
8536
  unchallenged.push(entry.lo);
@@ -8523,10 +8539,13 @@ var CompressionState = class CompressionState {
8523
8539
  }
8524
8540
  if (unchallenged.length > 0) {
8525
8541
  for (const index of unchallenged) this.challengedSkills.add(index);
8526
- if (challengedTool === "ask_user_question") return {
8527
- text: `${CompressionState.spanLabel(lo, hi)} 包含 ask_user_question 向用户的提问(完整消息 index ${unchallenged.join("、")})。请重新思考该提问是否确定与后续任务无关:确定不相关时再次调用 compressHistory 压缩该区间;不确定或相关时不要压缩该区间,保持原样即可`,
8528
- isError: true
8529
- };
8542
+ if (challengedTool === "ask_user_question") {
8543
+ const rawAsk = this.view.entries.some((entry) => entry.ask !== void 0 && entry.lo !== void 0 && unchallenged.includes(entry.lo));
8544
+ return {
8545
+ text: `${CompressionState.spanLabel(lo, hi)} 包含 ask_user_question 向用户的提问(完整消息 index ${unchallenged.join("、")})。请重新思考该提问是否确定与后续任务无关:确定不相关时再次调用 compressHistory 压缩该区间;不确定或相关时不要压缩该区间,${rawAsk ? "请先查看,再调用 rewriteAskUserQuestion 重写后保留" : "保持原样即可"}`,
8546
+ isError: true
8547
+ };
8548
+ }
8530
8549
  return {
8531
8550
  text: `${CompressionState.spanLabel(lo, hi)} 包含 skill 加载(完整消息 index ${unchallenged.join("、")})。请重新思考该 skill 是否确定与后续任务无关:确定不相关时再次调用 compressHistory 压缩该区间;不确定或相关时不要压缩该区间,保持原样即可`,
8532
8551
  isError: true
@@ -8547,8 +8566,91 @@ var CompressionState = class CompressionState {
8547
8566
  isError: false
8548
8567
  };
8549
8568
  }
8550
- /** completeCompression:标记压缩完成(调用后压缩会话立即停止)。 */
8569
+ /** 条目是否已被成功直接压缩完全覆盖。 */
8570
+ coveredBy(entry) {
8571
+ return entry.lo !== void 0 && entry.hi !== void 0 && this.replacements.some((rep) => entry.lo !== void 0 && entry.hi !== void 0 && entry.lo >= rep.lo && entry.hi <= rep.hi);
8572
+ }
8573
+ /** 重写已查看、尚未压缩覆盖的原始 ask,一次提交全部题。 */
8574
+ rewriteAskUserQuestion(args) {
8575
+ if (!isJsonRecord(args) || Object.keys(args).some((key) => key !== "index" && key !== "qa")) return {
8576
+ text: "重写参数必须是仅含 index 与 qa 的对象",
8577
+ isError: true
8578
+ };
8579
+ const { index, qa } = args;
8580
+ if (typeof index !== "number" || !Number.isSafeInteger(index) || index < 0) return {
8581
+ text: "index 必须是非负整数",
8582
+ isError: true
8583
+ };
8584
+ const entry = this.view.entries.find((item) => item.kind === "assistant" && item.lo === index && item.hi === index && item.ask !== void 0);
8585
+ if (entry?.ask === void 0) return {
8586
+ text: `index ${index} 不是本次视图中的合法原始 ask`,
8587
+ isError: true
8588
+ };
8589
+ if (this.coveredBy(entry)) return {
8590
+ text: `index ${index} 已被 compressHistory 覆盖,不能重写`,
8591
+ isError: true
8592
+ };
8593
+ if (!this.viewedAsks.has(index)) return {
8594
+ text: `请先用 getHistory 查看 index ${index} 的问题、选项和回答,收到返回结果后的下一轮再重写,不要在同轮提交`,
8595
+ isError: true
8596
+ };
8597
+ if (!Array.isArray(qa) || qa.length !== entry.ask.questions.length) return {
8598
+ text: `qa 必须包含 index ${index} 的全部 ${entry.ask.questions.length} 题`,
8599
+ isError: true
8600
+ };
8601
+ const rewritten = [];
8602
+ const ordinals = /* @__PURE__ */ new Set();
8603
+ for (const item of qa) {
8604
+ if (!isJsonRecord(item) || Object.keys(item).some((key) => ![
8605
+ "ordinal",
8606
+ "q",
8607
+ "a"
8608
+ ].includes(key))) return {
8609
+ text: "每题只能包含 ordinal、q、a,不要提交 options 或其他字段",
8610
+ isError: true
8611
+ };
8612
+ const { ordinal, q, a } = item;
8613
+ if (typeof ordinal !== "number" || !Number.isInteger(ordinal) || ordinal < 1 || ordinal > qa.length || ordinals.has(ordinal)) return {
8614
+ text: `ordinal 必须覆盖 1..${qa.length} 的全部题序且不能重复`,
8615
+ isError: true
8616
+ };
8617
+ if (typeof q !== "string" || q.trim() === "" || typeof a !== "string" || a.trim() === "") return {
8618
+ text: "q 与 a 必须是非空纯文本;未回答的题明确写 (未回答)",
8619
+ isError: true
8620
+ };
8621
+ if (q.includes("<![CDATA[") || a.includes("<![CDATA[")) return {
8622
+ text: "q 与 a 不要包含 CDATA 包裹,插件会自动添加",
8623
+ isError: true
8624
+ };
8625
+ if (/^\s*o\d+\s*[::]/m.test(q) || /^\s*o\d+\s*[::]/m.test(a)) return {
8626
+ text: "q 与 a 不要包含 oN: 选项列表行;请将回答中的选项引用展开为自足表述",
8627
+ isError: true
8628
+ };
8629
+ ordinals.add(ordinal);
8630
+ rewritten.push({
8631
+ ordinal,
8632
+ q,
8633
+ a
8634
+ });
8635
+ }
8636
+ rewritten.sort((a, b) => a.ordinal - b.ordinal);
8637
+ this.rewrittenAsks.set(index, rewritten);
8638
+ return {
8639
+ text: `已重写完整消息 index ${index} 的 ${rewritten.length} 题`,
8640
+ isError: false
8641
+ };
8642
+ }
8643
+ /** 尚未直接压缩或重写的原始 ask index。 */
8644
+ unprocessedAskIndices() {
8645
+ return this.view.entries.flatMap((entry) => entry.ask !== void 0 && entry.lo !== void 0 && !this.coveredBy(entry) && !this.rewrittenAsks.has(entry.lo) ? [entry.lo] : []);
8646
+ }
8647
+ /** completeCompression:所有原始合法 ask 已压缩或重写后标记完成。 */
8551
8648
  complete() {
8649
+ const pending = this.unprocessedAskIndices();
8650
+ if (pending.length > 0) return {
8651
+ text: `尚未处理原始 ask(index ${pending.join("、")}):请直接压缩,或先查看再调用 rewriteAskUserQuestion 重写后保留`,
8652
+ isError: true
8653
+ };
8552
8654
  this._completed = true;
8553
8655
  return {
8554
8656
  text: "压缩完成",
@@ -8558,15 +8660,16 @@ var CompressionState = class CompressionState {
8558
8660
  /**
8559
8661
  * 构建最终 <history> 块:按 index 顺序合并视图条目与替换记录——user / sys 条目
8560
8662
  * 原样、被替换区间生成 <assistant index|start end> 摘要条目(content 以 CDATA 包裹嵌入)、
8561
- * 未替换 assistant 条目原样保留、reasoning 不进产物;块首为按产物内实际条目动态
8562
- * 生成的格式说明注释(user_message / sys / skill_content / ask-user-question 条目说明
8563
- * 仅在对应条目存在时包含),开标签携带 tip 属性。产物为合法 XML,无需校验。
8663
+ * 未替换普通与历史条目原样保留,原始 ask 使用重写后的 q/a;reasoning 不进产物。
8664
+ * 块首按最终条目动态生成格式说明注释,开标签携带 tip 属性。
8564
8665
  */
8565
8666
  buildFinalBlock() {
8667
+ const pending = this.unprocessedAskIndices();
8668
+ if (pending.length > 0) throw new Error(`原始 ask 尚未处理:index ${pending.join("、")}`);
8566
8669
  const doc = new import_lib.DOMParser({ onError: () => {} }).parseFromString(`<${HISTORY_TAG} />`, "text/xml");
8567
8670
  const root = doc.documentElement;
8568
8671
  if (!root) return "";
8569
- const coveredBy = (entry) => entry.lo !== void 0 && entry.hi !== void 0 && this.replacements.some((rep) => entry.lo !== void 0 && entry.hi !== void 0 && entry.lo >= rep.lo && entry.hi <= rep.hi);
8672
+ const coveredBy = (entry) => this.coveredBy(entry);
8570
8673
  const reps = [...this.replacements].sort((a, b) => a.lo - b.lo);
8571
8674
  let nextRep = 0;
8572
8675
  const emitReplacement = (rep) => {
@@ -8592,21 +8695,77 @@ var CompressionState = class CompressionState {
8592
8695
  if (entry.kind === "reasoning") continue;
8593
8696
  if (coveredBy(entry)) continue;
8594
8697
  flushReplacementsBefore(entry.lo);
8595
- root.appendChild(entryToElement(doc, entry));
8698
+ const qa = entry.lo === void 0 ? void 0 : this.rewrittenAsks.get(entry.lo);
8699
+ const output = entry.ask !== void 0 && qa !== void 0 && entry.lo !== void 0 ? {
8700
+ kind: "assistant",
8701
+ lo: entry.lo,
8702
+ hi: entry.lo,
8703
+ toolName: ASK_USER_QUESTION_TOOL_NAME,
8704
+ text: `<ask-user-question>${qa.map((item) => `q:${item.q}\na:${item.a}`).join("\n")}</ask-user-question>`
8705
+ } : entry;
8706
+ root.appendChild(entryToElement(doc, output));
8596
8707
  }
8597
8708
  flushReplacementsBefore(void 0);
8598
8709
  const note = historyFormatNote({
8599
8710
  user: this.view.entries.some((e) => e.kind === "user"),
8600
8711
  sys: this.view.entries.some((e) => e.kind === "sys"),
8601
8712
  skill: this.view.entries.some((e) => e.kind === "assistant" && e.toolName === "skill" && !coveredBy(e)),
8602
- askUserQuestion: this.view.entries.some((e) => e.kind === "assistant" && e.toolName === "ask_user_question" && !coveredBy(e))
8713
+ askUserQuestion: this.view.entries.some((e) => isAskEntry(e) && !coveredBy(e))
8603
8714
  });
8604
8715
  const serializer = new import_lib.XMLSerializer();
8605
8716
  const inner = Array.from(root.childNodes).map((node) => serializer.serializeToString(node)).join("\n");
8606
8717
  return `<${HISTORY_TAG} tip="${HISTORY_TIP}">\n${note}\n${inner}\n</${HISTORY_TAG}>`;
8607
8718
  }
8608
8719
  };
8609
- /** 压缩会话工具的 wire 定义(GenerateOptions.tools)。 */
8720
+ /** 仅含原始合法 ask 的压缩会话使用的重写工具。 */
8721
+ const REWRITE_ASK_TOOL_SCHEMA = {
8722
+ name: "rewriteAskUserQuestion",
8723
+ description: "重写已用 getHistory 查看且未被 compressHistory 覆盖的原始 ask。按原题序提交全部 q/a,忠实精炼问题与回答,展开选项引用,未回答的题明确写 (未回答)。保留 ask 的产物只含 q/a,不提交 options 或 CDATA 包裹。",
8724
+ parameters: {
8725
+ type: "object",
8726
+ properties: {
8727
+ index: {
8728
+ type: "integer",
8729
+ minimum: 0,
8730
+ description: "原始合法 ask 的完整消息 index"
8731
+ },
8732
+ qa: {
8733
+ type: "array",
8734
+ minItems: 1,
8735
+ description: "该调用内全部题的重写结果,保留题数和原题序",
8736
+ items: {
8737
+ type: "object",
8738
+ properties: {
8739
+ ordinal: {
8740
+ type: "integer",
8741
+ minimum: 1,
8742
+ description: "原始题序,从 1 开始"
8743
+ },
8744
+ q: {
8745
+ type: "string",
8746
+ minLength: 1,
8747
+ description: "忠实精炼后的问题纯文本"
8748
+ },
8749
+ a: {
8750
+ type: "string",
8751
+ minLength: 1,
8752
+ description: "自足的回答纯文本,保留用户条件和决定;未回答写 (未回答)"
8753
+ }
8754
+ },
8755
+ required: [
8756
+ "ordinal",
8757
+ "q",
8758
+ "a"
8759
+ ],
8760
+ additionalProperties: false
8761
+ }
8762
+ }
8763
+ },
8764
+ required: ["index", "qa"],
8765
+ additionalProperties: false
8766
+ }
8767
+ };
8768
+ /** 压缩会话基础工具的 wire 定义(GenerateOptions.tools)。 */
8610
8769
  const COMPRESSION_TOOL_SCHEMAS = [
8611
8770
  {
8612
8771
  name: "getHistory",
@@ -8653,7 +8812,7 @@ const COMPRESSION_TOOL_SCHEMAS = [
8653
8812
  },
8654
8813
  {
8655
8814
  name: "completeCompression",
8656
- description: "全部压缩完成后调用,立即结束压缩会话。未压缩的条目将原样保留,允许不压缩任何内容直接完成。",
8815
+ description: "处理完成后调用,成功时立即结束压缩会话。原始合法 ask 必须已成功压缩,或先查看并重写后保留;其他未压缩条目原样保留。无待处理的原始 ask 时允许直接完成。",
8657
8816
  parameters: {
8658
8817
  type: "object",
8659
8818
  properties: {}
@@ -8718,15 +8877,15 @@ async function gateRateLimit(waitMs, signal) {
8718
8877
  //#region src/compress-loop.ts
8719
8878
  /**
8720
8879
  * 工具驱动的压缩循环:以新会话方式直连 ctx.llm.stream(),模型通过 getHistory /
8721
- * compressHistory / completeCompression 三个工具完成压缩,替代直出 <history> 块。
8880
+ * compressHistory / completeCompression 完成压缩,存在原始合法提问时加入重写工具。
8722
8881
  * 导出 runCompressionLoop / buildCompressionPrompt / buildCompressionTaskText /
8723
- * CompressionLoopOptions / CompressionOutcome / CompressionStats / COMPRESSION_NUDGE_TEXT。
8882
+ * ASK_COMPRESSION_PROMPT / CompressionLoopOptions / CompressionOutcome / CompressionStats / COMPRESSION_NUDGE_TEXT。
8724
8883
  *
8725
8884
  * - 首条 user 消息仅含压缩指令与 start/end 区间(buildCompressionTaskText),不含
8726
8885
  * 历史消息内容;共享压缩提示词作为 system
8727
8886
  * - 每轮请求携带压缩工具 schemas(purpose='compaction',maxTokens 沿用配置);流经
8728
8887
  * BlockAssembler 组装为 assistant 消息,工具执行结果以 tool-result 消息回填
8729
- * - completeCompression 调用后立即停止(同轮后续工具调用不再执行),最终 <history>
8888
+ * - completeCompression 校验通过后立即停止(同轮后续工具调用不再执行),最终 <history>
8730
8889
  * 块由 CompressionState 构建,全程无需整块校验
8731
8890
  * - 模型输出纯文本(无工具调用)时追加提醒消息继续,连续 2 轮仍无工具调用判失败
8732
8891
  * - 429 限流走全局限流等待门(gateRateLimit / noteRateLimit);其余请求级错误依赖
@@ -8762,8 +8921,8 @@ function buildCompressionPrompt(skipReasoning) {
8762
8921
  "- <history> 条目正文以 CDATA 包裹(空的 <sys> 条目为自闭合空元素,无正文),CDATA 内为逐字原样内容。",
8763
8922
  "- 工具调用条目为 <assistant index=\"N\" type=\"toolcall\" tool-name=\"…\" callId=\"…\">,内含 <tool-args>(调用参数 JSON)与 <tool-result>(工具返回内容)两个 CDATA 子元素。",
8764
8923
  "- 加载的 skill 以 <skill_content name=\"…\" index=\"N\"> 条目呈现,内含 <skill_resources> 与 <skill_instructions> 两段,内文为加载的 skill 内容,属于关键信息。仅在你明确判断该 skill 与后续任务无关时,压缩它;如果该 skill 与后续任务相关,或者你无法判断,不要压缩,**保持原文**。",
8765
- "- ask_user_question 工具调用(向用户的提问)以 <ask-user-question index=\"N\"> 条目呈现,CDATA 内为逐题成对的 q:(问题文本)与 a:(用户回答)行,未作答的题记为 a:(未回答),属于关键信息。仅在你明确判断该提问与后续任务无关时,压缩它;如果该提问与后续任务相关,或者你无法判断,不要压缩,**保持原文**。",
8766
- "- 未压缩的条目将原样保留;宁可保留也不要强行压缩不确定的内容。",
8924
+ "- 已有 <history> 块中的 ask_user_question 以 <ask-user-question index=\"N\"> 呈现,CDATA 内为逐题成对的 q:(问题文本)与 a:(用户回答)行,未作答的题记为 a:(未回答)。这些提问已经处理;仅在明确判断与后续任务无关时压缩,否则保持原样。原始提问按本会话的专用处理规则执行。",
8925
+ "- 除原始提问外,未压缩的条目将原样保留;宁可保留也不要强行压缩不确定的内容。",
8767
8926
  "- 全部完成后调用 completeCompression 结束;不要输出与工具调用无关的文本。"
8768
8927
  ].join("\n");
8769
8928
  }
@@ -8774,6 +8933,18 @@ function buildCompressionTaskText(phase, start, end) {
8774
8933
  if (phase === "reflect") return `合并压缩全部 <history> 块,完整消息区间 [${start}..${end}]:用 getHistory 查看已有块条目,用 compressHistory 重新压缩合并 assistant 条目,完成后调用 completeCompression。`;
8775
8934
  return `压缩完整消息区间 [${start}..${end}]:用 getHistory 查看条目,用 compressHistory 分批压缩 assistant 条目,完成后调用 completeCompression。`;
8776
8935
  }
8936
+ /** 原始合法 ask 的处理约束,只在视图含待处理原始提问时注入。 */
8937
+ const ASK_COMPRESSION_PROMPT = [
8938
+ "【原始提问处理】",
8939
+ "- 原始合法 ask_user_question 在 getHistory 中以 <ask-user-question index=\"N\"> 展示,每题为 q:问题、o1:选项一、o2:选项二等及 a:回答;选项包含 label 与 description,无选项题省略 oN 行。",
8940
+ "- 每个原始提问必须二选一:直接用 compressHistory 压成普通 assistant 摘要;或者保留 ask 标签并用 rewriteAskUserQuestion 重写 q/a。不能原样跳过。",
8941
+ "- 直接压缩:仅在明确判断该提问与后续任务无关时执行;首次覆盖会被阻止一次,重新思考后再次调用才执行。不确定或相关时走保留重写路径。",
8942
+ "- 保留重写:先用 getHistory 查看该提问及全部选项,收到返回结果后的下一轮再调用 rewriteAskUserQuestion({index, qa:[{ordinal:1,q:\"问题\",a:\"回答\"},...]}),不要与查看同轮提交;ordinal 从 1 开始,按原题序提交全部题,不增删、不重复。",
8943
+ "- q/a 均可忠实精炼,保留语境与用户真实意图。将回答中对选项的编号、标签等引用展开为自足表述;产物仅有 q:/a:,不能保留 oN 选项列表或 options 字段。",
8944
+ "- 空答案明确为 (未回答),不得补造用户决定。仅提交纯文本 q/a,不自行拼接 XML 或 CDATA 包裹。",
8945
+ "- 允许切换路径;最终成功的直接压缩覆盖优先,已覆盖的 ask 不能再次重写。history 块中的 ask 已处理,不需重写。",
8946
+ "- completeCompression 仅在每个原始合法 ask 已成功直接压缩或重写后完成;若返回待处理 index,请处理后再次调用。"
8947
+ ].join("\n");
8777
8948
  /** 模型输出纯文本(无工具调用)时追加的提醒消息文本。 */
8778
8949
  const COMPRESSION_NUDGE_TEXT = "请通过工具执行压缩:用 getHistory 查看区间条目,用 compressHistory 压缩 assistant 条目,完成后调用 completeCompression。不要输出与工具调用无关的文本。";
8779
8950
  /** 构造插件自产 user 消息(压缩指令/提醒;source 为插件自有 kind)。 */
@@ -8837,6 +9008,8 @@ function isRateLimitFailure(message, status) {
8837
9008
  async function runCompressionLoop(ctx, session, options) {
8838
9009
  const logger = makeLogger(ctx, options.debug);
8839
9010
  const state = new CompressionState(options.view);
9011
+ const tools = state.hasPendingAsks ? [...COMPRESSION_TOOL_SCHEMAS, REWRITE_ASK_TOOL_SCHEMA] : COMPRESSION_TOOL_SCHEMAS;
9012
+ const system = [buildCompressionPrompt(options.skipReasoning), ...state.hasPendingAsks ? [ASK_COMPRESSION_PROMPT] : []].join("\n\n");
8840
9013
  const messages = [makePluginUserMessage(options.taskText)];
8841
9014
  let rounds = 0;
8842
9015
  let nudges = 0;
@@ -8891,11 +9064,12 @@ async function runCompressionLoop(ctx, session, options) {
8891
9064
  sessionId: session.id,
8892
9065
  purpose: "compaction",
8893
9066
  ...options.signal === void 0 ? {} : { signal: options.signal },
8894
- system: buildCompressionPrompt(options.skipReasoning),
9067
+ system,
8895
9068
  messages: [...messages],
8896
- tools: COMPRESSION_TOOL_SCHEMAS
9069
+ tools
8897
9070
  };
8898
9071
  const assembler = new BlockAssembler();
9072
+ state.markHistoryDelivered();
8899
9073
  try {
8900
9074
  for await (const chunk of ctx.llm.stream(requestOptions)) assembler.push(chunk);
8901
9075
  } catch (error) {
@@ -8950,19 +9124,15 @@ async function runCompressionLoop(ctx, session, options) {
8950
9124
  continue;
8951
9125
  }
8952
9126
  nudges = 0;
8953
- let completed = false;
8954
9127
  for (const call of calls) {
8955
- if (call.name === "completeCompression") {
8956
- messages.push(toolResultOf(call, state.complete()));
8957
- completed = true;
8958
- break;
8959
- }
8960
9128
  messages.push(toolResultOf(call, state.executeCall(call.name, call.arguments)));
9129
+ if (state.completed) break;
8961
9130
  }
8962
- if (completed) {
9131
+ if (state.completed) {
9132
+ if (options.signal?.aborted) return await failWith(COMPACTION_ABORTED_ERROR, true);
8963
9133
  const text = state.buildFinalBlock();
8964
- if (state.replacementCount === 0) logger.warn("压缩完成但未执行任何压缩替换(空提交)");
8965
- logger.info(`压缩循环完成(${rounds} 轮,${state.replacementCount} 次压缩替换,输出 ${text.length} 字符)`);
9134
+ if (state.replacementCount === 0 && state.rewriteCount === 0) logger.warn("压缩完成但未执行任何压缩替换(空提交)");
9135
+ logger.info(`压缩循环完成(${rounds} 轮,${state.replacementCount} 次压缩替换,${state.rewriteCount} 条提问重写,输出 ${text.length} 字符)`);
8966
9136
  const stats = buildStats();
8967
9137
  const id = await recordSessionId(true, stats);
8968
9138
  return {
@@ -10098,6 +10268,57 @@ function resolveConfig(raw) {
10098
10268
  return Object.freeze(config);
10099
10269
  }
10100
10270
  //#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
10101
10322
  //#region src/json-schema.ts
10102
10323
  /**
10103
10324
  * zod schema → 工具 wire 参数 JSON Schema 的转换工具。导出 parametersFromZod。
@@ -10569,7 +10790,7 @@ const inject = [
10569
10790
  "tokenMeter",
10570
10791
  "sessions"
10571
10792
  ];
10572
- /** 插件激活入口:解析配置、注册工具、接线 pre-step 自动压缩。 */
10793
+ /** 插件激活入口:解析配置、注册工具、接线 pre-step 自动压缩与进度提醒。 */
10573
10794
  function apply(ctx, config) {
10574
10795
  const resolved = currentConfig(config);
10575
10796
  const logger = makeLogger(ctx, () => currentConfig(config).debug);
@@ -10623,7 +10844,12 @@ function apply(ctx, config) {
10623
10844
  logger.warn(`上下文压缩失败,拒绝本 step 中断当前 turn:${outcome.error}${diagnostic}`);
10624
10845
  return { kind: "reject" };
10625
10846
  }
10626
- return next();
10847
+ const decision = await next();
10848
+ if (decision.kind === "enter" && !signal.aborted && currentConfig(config).omEnabled && isMainSession(agent.session)) return {
10849
+ ...decision,
10850
+ messages: ensureProgressReminder(agent.session, decision.messages)
10851
+ };
10852
+ return decision;
10627
10853
  });
10628
10854
  }
10629
10855
  //#endregion