@kangyishuai/dsh-advisor 0.6.2 → 0.6.3

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/lib/service.js CHANGED
@@ -2,7 +2,7 @@
2
2
  // host 半:服务名 advisor。
3
3
  //
4
4
  // 职责:
5
- // 1) 注册 `advisor` 工具(主模型在关键时刻徵询第二模型,结果作为工具结果回到主模型);
5
+ // 1) 注册 `advisor` 工具(主模型在关键时刻征询第二模型,结果作为工具结果回到主模型);
6
6
  // 2) 注册 `/advisor` 命令(status / ask / cancel / doctor / on / off / <route>);
7
7
  // 3) 对客户端暴露代理 RPC(routes / models / modelInfo / candidates / setModel / state / doctor);
8
8
  // 4) shadow 模式:回合结束后跑一次顾问,只记账不回灌。
@@ -13,6 +13,7 @@
13
13
  // - `session/event` 监听器里**同步** append 会撞重入保护 ⇒ 一律异步一拍再写。
14
14
 
15
15
  import { randomBytes } from "node:crypto";
16
+ import { fileURLToPath } from "node:url";
16
17
  import { appendPluginRecord, pluginRecordOf } from "@deepseek-ai/dsh-session";
17
18
  import { Remote, RemoteError, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
18
19
  import { summarizeAdoption } from "./adoption.js";
@@ -20,6 +21,13 @@ import { applyAnchorVerdict, buildIndex, verifyAnchors } from "./anchors.js";
20
21
  import { checkPool, createBudgetPool } from "./budget.js";
21
22
  import { callAdvisor } from "./call.js";
22
23
  import { checkAllowlist, effectivePrice } from "./catalog.js";
24
+ import {
25
+ COMMAND_NAME,
26
+ commandReply,
27
+ effectiveLine,
28
+ effectiveStateOf,
29
+ formatStatusText,
30
+ } from "./command-text.js";
23
31
  import { createDecisionLog, createDecisionTracker } from "./decisions.js";
24
32
  import {
25
33
  checkBudget,
@@ -30,6 +38,7 @@ import {
30
38
  rememberFingerprint,
31
39
  } from "./guard.js";
32
40
  import { createLedger } from "./ledger.js";
41
+ import { FALLBACK, loadMessagesSync, pickLanguage } from "./messages.js";
33
42
  import { formatMoney, fromUsd } from "./money.js";
34
43
  import { parseAdvice, summarizeAdvice, TOOL_DESCRIPTION } from "./prompt.js";
35
44
  import { pairingCheck, resolveRoute } from "./route.js";
@@ -40,6 +49,7 @@ import {
40
49
  saveSettings,
41
50
  settingsPath,
42
51
  } from "./settings.js";
52
+ import { exposeSkip } from "./tool-result.js";
43
53
  import { renderToolOutput, TOOL_NAME, TOOL_OUTPUT_SCHEMA, TOOL_PARAMETERS } from "./tool-schema.js";
44
54
  import { buildTracePreview } from "./trace.js";
45
55
  import { buildTranscript } from "./transcript.js";
@@ -48,8 +58,8 @@ import { runEvidencePass } from "./twopass.js";
48
58
  /** plugin record 类型(必须匹配 ^plugin:[a-z0-9][a-z0-9._-]*(/[...])*$)。 */
49
59
  export const ADVICE_RECORD = "plugin:advisor/advice";
50
60
 
51
- /** 命令名:`/advisor`。 */
52
- export const COMMAND_NAME = "advisor";
61
+ /** 命令名:`/advisor`(定义在 command-text.js,这里重导出保持对外入口不变)。 */
62
+ export { COMMAND_NAME };
53
63
 
54
64
  /**
55
65
  * 与 session-rewind / next-step 相同的原因:运行时不支持装饰器语法,用命令式方式登记 Remote。
@@ -94,6 +104,15 @@ function joinHome() {
94
104
  return env === "" ? ".dsh" : `${env}/.dsh`;
95
105
  }
96
106
 
107
+ /**
108
+ * 包内 locale 目录:npm 包随 `files` 发布,安装路径里可能有空格,
109
+ * 所以用 `fileURLToPath(new URL(...))` 而不是手拼字符串。
110
+ * @returns {string}
111
+ */
112
+ function localeDirOf() {
113
+ return fileURLToPath(new URL("../locale/", import.meta.url));
114
+ }
115
+
97
116
  /**
98
117
  * 安全取宿主服务。
99
118
  * @param {any} ctx
@@ -115,6 +134,10 @@ function serviceOf(ctx, name) {
115
134
 
116
135
  /**
117
136
  * 子代理会话判定(shadow 只在顶层会话跑,避免多份顾问调用叠加)。
137
+ *
138
+ * 同一个判据也决定**决策日志的口径**(审计 AUD-ADV-08):子代理回合不写 decisions.jsonl,
139
+ * 所以 `pnpm advisor:review` 的征询率/采纳率是「主会话」口径,不能用来推断 fork/spawn
140
+ * 子代理里的征询行为。README 的决策日志一节写明了这一点。
118
141
  * @param {any} session
119
142
  * @returns {boolean}
120
143
  */
@@ -145,8 +168,23 @@ export class AdvisorService extends TypertRemoteService {
145
168
  this.config = config ?? {};
146
169
  this.logger = ctx?.logger ?? console;
147
170
  this.dataRoot = resolveDataRoot(this.config);
171
+ /**
172
+ * host 半可见文案:宿主的 `commands.register()` 只认注册时的字面量,
173
+ * 自己读 `locale/<lang>.json`(见 lib/messages.js 文件头的宿主事实)。
174
+ * 加载失败一律回落英文 FALLBACK,命令本身不能因为文案读不到而注册失败。
175
+ * @type {{ description: string, hint: string }}
176
+ */
177
+ this.messages = { ...FALLBACK };
178
+ try {
179
+ this.messages = {
180
+ ...FALLBACK,
181
+ ...loadMessagesSync(localeDirOf(), pickLanguage(this.config?.language)),
182
+ };
183
+ } catch (error) {
184
+ this.warn("cannot load advisor locale messages", error);
185
+ }
148
186
  this.ledger = createLedger({ home: this.dataRoot, logger: this.logger });
149
- // 决策日志:一个回合一行,回答「该徵询的时候有没有徵询」,与钱的账本分开。
187
+ // 决策日志:一个回合一行,回答「该征询的时候有没有征询」,与钱的账本分开。
150
188
  this.decisions = createDecisionLog({ home: this.dataRoot, logger: this.logger });
151
189
  // 回合跟踪器:事件 → 特征 → 决策行 → outcome 回填(逻辑在 decisions.js,可单测)。
152
190
  this.decisionTracker = createDecisionTracker({ log: this.decisions });
@@ -156,7 +194,7 @@ export class AdvisorService extends TypertRemoteService {
156
194
  this.settingsCache = { at: 0, value: null };
157
195
  /** 每会话回合序号(工具路径拿不到 turn,自己数)。 @type {Map<string, number>} */
158
196
  this.turnOf = new Map();
159
- /** 在途徵询(cancel 用)。 @type {Map<string, AbortController>} */
197
+ /** 在途征询(cancel 用)。 @type {Map<string, AbortController>} */
160
198
  this.inflight = new Map();
161
199
  /** 去重表(被动投递用:shadow / post-answer)。 @type {Map<string, number>} */
162
200
  this.seen = new Map();
@@ -166,7 +204,7 @@ export class AdvisorService extends TypertRemoteService {
166
204
  this.lastResult = null;
167
205
  /** 每会话已投递的建议条数(sessionCap 用)。 @type {Map<string, number>} */
168
206
  this.delivered = new Map();
169
- /** 每会话最近一次「为什么没徵询」。 @type {Map<string, string>} */
207
+ /** 每会话最近一次「为什么没征询」。 @type {Map<string, string>} */
170
208
  this.lastSkip = new Map();
171
209
  /** @type {{ calls: number, failures: number, skipped: number, shadow: number }} */
172
210
  this.counters = { calls: 0, failures: 0, skipped: 0, shadow: 0 };
@@ -349,10 +387,10 @@ export class AdvisorService extends TypertRemoteService {
349
387
  }
350
388
  }
351
389
 
352
- // ---- 核心:一次徵询 ----------------------------------------------------
390
+ // ---- 核心:一次征询 ----------------------------------------------------
353
391
 
354
392
  /**
355
- * 跑一次顾问徵询。所有失败都返回结构化结果,绝不抛。
393
+ * 跑一次顾问征询。所有失败都返回结构化结果,绝不抛。
356
394
  * @param {{ session: any, trigger: "tool"|"shadow"|"manual"|"post-answer", focus?: string, signal?: AbortSignal }} input
357
395
  * @returns {Promise<any>}
358
396
  */
@@ -361,14 +399,20 @@ export class AdvisorService extends TypertRemoteService {
361
399
  const settings = await this.currentSettings();
362
400
  const sessionId = typeof session?.id === "string" ? session.id : "";
363
401
 
364
- /** @param {string} reason @param {string} [code] */
402
+ /**
403
+ * 记一条内部跳过:`lastSkip` 留真实原因(状态面板/诊断用),
404
+ * 返回给调用方的 code/reason 走 {@link exposeSkip} —— 工具触发时内部开关状态
405
+ * 不进模型上下文(审计 USIM-U1-11)。
406
+ * @param {string} reason @param {string} [code]
407
+ */
365
408
  const skip = (reason, code = "skipped") => {
366
409
  if (sessionId !== "") this.lastSkip.set(sessionId, reason);
367
410
  this.counters.skipped += 1;
411
+ const exposed = exposeSkip({ trigger, code, reason });
368
412
  return {
369
413
  status: "skipped",
370
- code,
371
- reason,
414
+ code: exposed.code,
415
+ reason: exposed.reason,
372
416
  advice: "",
373
417
  severity: "nit",
374
418
  risks: [],
@@ -379,7 +423,7 @@ export class AdvisorService extends TypertRemoteService {
379
423
 
380
424
  if (settings.mode === "off") return skip("顾问已关闭(/advisor on 打开)", "disabled");
381
425
  if (!isConfigured(settings)) return skip("还没配置顾问模型(/advisor 选择)", "not_configured");
382
- // shadow 的语义是「只记账、不回灌」。模型主动徵询时同样不给建议,
426
+ // shadow 的语义是「只记账、不回灌」。模型主动征询时同样不给建议,
383
427
  // 否则它照样会把建议吃进上下文,shadow 就名不副实。
384
428
  if (trigger === "tool" && settings.mode === "shadow") {
385
429
  return skip(
@@ -405,7 +449,7 @@ export class AdvisorService extends TypertRemoteService {
405
449
  const allow = checkAllowlist(settings.allowedModels, resolved.route);
406
450
  if (!allow.allowed) return skip(`白名单拦截:${allow.reason}`, "not_allowed");
407
451
 
408
- // 跨 provider 首次徵询需要显式确认(数据会离开本机去另一家)。
452
+ // 跨 provider 首次征询需要显式确认(数据会离开本机去另一家)。
409
453
  const mainProvider = typeof mainModel?.provider === "string" ? mainModel.provider : "";
410
454
  if (mainProvider !== "" && mainProvider !== resolved.route.provider) {
411
455
  const confirmed =
@@ -415,7 +459,7 @@ export class AdvisorService extends TypertRemoteService {
415
459
  return {
416
460
  status: "skipped",
417
461
  code: "needs_confirmation",
418
- reason: `跨 provider 首次徵询需要确认:会话内容会发送到「${resolved.route.provider}」。运行 /advisor confirm 允许,或 /advisor preview 先看会发什么`,
462
+ reason: `跨 provider 首次征询需要确认:会话内容会发送到「${resolved.route.provider}」。运行 /advisor confirm 允许,或 /advisor preview 先看会发什么`,
419
463
  advice: "",
420
464
  severity: "nit",
421
465
  risks: [],
@@ -428,25 +472,55 @@ export class AdvisorService extends TypertRemoteService {
428
472
  const turn = this.turnOf.get(sessionId) ?? 0;
429
473
  const now = Date.now();
430
474
  const counters = this.ledger.counters(sessionId, now);
431
- const budget = checkBudget({ settings, counters, now });
475
+
476
+ // 上下文:包含工具调用与结果(这是与「只发文本」的关键区别)。
477
+ const messages = typeof session?.deriveMessages === "function" ? session.deriveMessages() : [];
478
+ const transcript = buildTranscript(messages, {
479
+ scope: settings.privacyScope,
480
+ redactSecrets: settings.redact,
481
+ maxChars: settings.maxInputChars,
482
+ });
483
+ if (transcript.text.trim() === "") return skip("会话里还没有可发送的内容", "empty_transcript");
484
+
485
+ // 有效单价(用户声明 > 内置表 > 不算钱)与本次**预计**花费:日预算与工作区池都用它做
486
+ // 「这笔会不会顶到」的预判,而不是等超了才拦(审计 AUD-ADV-11)。
487
+ const price = effectivePrice(settings, resolved.route.model);
488
+ const estimatedCost = estimateCostUsd({
489
+ inputTokens: Math.ceil(transcript.text.length / 3),
490
+ outputTokens: settings.maxTokens / 2,
491
+ priceInputPerMTok: price.input,
492
+ priceOutputPerMTok: price.output,
493
+ priceCacheReadPerMTok: price.cacheRead,
494
+ priceCacheWritePerMTok: price.cacheWrite,
495
+ });
496
+
497
+ /** 预算金额按设置币种显示;内部账本始终是 USD。 @param {number} usd @param {number} digits */
498
+ const money = (usd, digits) =>
499
+ formatMoney(fromUsd(usd, settings.currency, settings.usdToCny), settings.currency, digits);
500
+
501
+ const budget = checkBudget({ settings, counters, now, estimatedCostUsd: estimatedCost });
432
502
  if (!budget.ok) {
433
503
  this.counters.skipped += 1;
434
- /** @type {Record<string, string>} */
435
- const reasons = {
436
- turn_limit: `本回合已达上限(${budget.used}/${budget.limit})`,
437
- session_limit: `本会话已达上限(${budget.used}/${budget.limit})`,
438
- hour_limit: `本小时已达上限(${budget.used}/${budget.limit})`,
439
- day_budget: `今日预算已用完(${formatMoney(
440
- fromUsd(budget.used, settings.currency, settings.usdToCny),
441
- settings.currency,
442
- 4,
443
- )}/${formatMoney(
444
- fromUsd(budget.limit, settings.currency, settings.usdToCny),
445
- settings.currency,
446
- 2,
447
- )})`,
448
- };
449
- const reason = reasons[budget.code] ?? "预算不足";
504
+ // 拒绝可能来自「已花完」也可能是「这一笔会顶到」:后者报 used < limit,不能再说
505
+ // 「今日预算已用完」(复审 F4 —— 否则用户看到 $0.01/$0.10 会以为账本错了)。
506
+ /** @type {string} */
507
+ let reason;
508
+ if (budget.code === "day_budget") {
509
+ // 分开写是为了拿到 only-on-day_budget 的 estimatedCostUsd(钱花完了 vs 这一笔会顶到)。
510
+ reason =
511
+ budget.used >= budget.limit
512
+ ? `今日预算已用完(${money(budget.used, 4)}/${money(budget.limit, 2)})`
513
+ : `本次调用预计超出今日预算(已花 ${money(budget.used, 4)} / 上限 ${money(
514
+ budget.limit,
515
+ 2,
516
+ )} / 预计 ${money(budget.estimatedCostUsd, 4)}),已取消发送`;
517
+ } else if (budget.code === "turn_limit") {
518
+ reason = `本回合已达上限(${budget.used}/${budget.limit})`;
519
+ } else if (budget.code === "session_limit") {
520
+ reason = `本会话已达上限(${budget.used}/${budget.limit})`;
521
+ } else {
522
+ reason = `本小时已达上限(${budget.used}/${budget.limit})`;
523
+ }
450
524
  if (sessionId !== "") this.lastSkip.set(sessionId, reason);
451
525
  return {
452
526
  status: "skipped",
@@ -460,23 +534,22 @@ export class AdvisorService extends TypertRemoteService {
460
534
  };
461
535
  }
462
536
 
463
- // 工作区级共享预算池(跨会话累计,按本地日滚动)与有效单价(用户声明 > 内置表 > 不算钱)。
464
- const price = effectivePrice(settings, resolved.route.model);
537
+ // 工作区级共享预算池(跨会话累计,按本地日滚动;写入串行,见 budget.js)。
465
538
  const pool = await this.pool.read();
466
- const poolCheck = checkPool(pool, settings);
539
+ const poolCheck = checkPool(pool, settings, estimatedCost);
467
540
  if (!poolCheck.ok) {
468
541
  const reason =
469
542
  poolCheck.code === "workspace_calls"
470
543
  ? `工作区今日调用已达上限(${poolCheck.used}/${poolCheck.limit})`
471
- : `工作区今日预算已用完(${formatMoney(
472
- fromUsd(poolCheck.used, settings.currency, settings.usdToCny),
473
- settings.currency,
474
- 4,
475
- )}/${formatMoney(
476
- fromUsd(poolCheck.limit, settings.currency, settings.usdToCny),
477
- settings.currency,
478
- 2,
479
- )})`;
544
+ : poolCheck.used >= poolCheck.limit
545
+ ? `工作区今日预算已用完(${money(poolCheck.used, 4)}/${money(poolCheck.limit, 2)})`
546
+ : `本次调用预计超出工作区今日预算(已花 ${money(
547
+ poolCheck.used,
548
+ 4,
549
+ )} / 上限 ${money(poolCheck.limit, 2)} / 预计 ${money(
550
+ poolCheck.estimatedCostUsd,
551
+ 4,
552
+ )}),已取消发送`;
480
553
  if (sessionId !== "") this.lastSkip.set(sessionId, reason);
481
554
  this.counters.skipped += 1;
482
555
  return {
@@ -491,15 +564,6 @@ export class AdvisorService extends TypertRemoteService {
491
564
  };
492
565
  }
493
566
 
494
- // 上下文:包含工具调用与结果(这是与「只发文本」的关键区别)。
495
- const messages = typeof session?.deriveMessages === "function" ? session.deriveMessages() : [];
496
- const transcript = buildTranscript(messages, {
497
- scope: settings.privacyScope,
498
- redactSecrets: settings.redact,
499
- maxChars: settings.maxInputChars,
500
- });
501
- if (transcript.text.trim() === "") return skip("会话里还没有可发送的内容", "empty_transcript");
502
-
503
567
  // 只存首尾预览;tracePrompt=off 时连预览都不落盘(requestChars 仍记)。
504
568
  const trace = settings.tracePrompt === "preview" ? buildTracePreview(transcript.text) : null;
505
569
 
@@ -512,15 +576,6 @@ export class AdvisorService extends TypertRemoteService {
512
576
  ? AbortSignal.any([input.signal, controller.signal])
513
577
  : controller.signal;
514
578
 
515
- const estimatedCost = estimateCostUsd({
516
- inputTokens: Math.ceil(transcript.text.length / 3),
517
- outputTokens: settings.maxTokens / 2,
518
- priceInputPerMTok: price.input,
519
- priceOutputPerMTok: price.output,
520
- priceCacheReadPerMTok: price.cacheRead,
521
- priceCacheWritePerMTok: price.cacheWrite,
522
- });
523
-
524
579
  const started = Date.now();
525
580
  let call;
526
581
  try {
@@ -637,14 +692,16 @@ export class AdvisorService extends TypertRemoteService {
637
692
  let usage = call.usage;
638
693
 
639
694
  // 记一次调用(调用数与最终成本):两阶段取证的额外 usage 合并后再记,避免只记第一轮。
640
- const charge = () => {
695
+ // 预算池的 add 是读-改-写,必须 await:并发会话各自 fire-and-forget 会互相覆盖丢更新
696
+ // (审计 AUD-ADV-02)。
697
+ const charge = async () => {
641
698
  this.ledger.noteCall(sessionId, { turn, costUsd, at: Date.now() });
642
- void this.pool.add({ calls: 1, costUsd });
699
+ await this.pool.add({ calls: 1, costUsd });
643
700
  this.counters.calls += 1;
644
701
  };
645
702
 
646
703
  if (!parsed.ok) {
647
- charge();
704
+ await charge();
648
705
  const result = { ...baseResult, status: "unavailable", code: `advice_${parsed.reason}` };
649
706
  this.counters.failures += 1;
650
707
  this.lastResult = result;
@@ -707,7 +764,7 @@ export class AdvisorService extends TypertRemoteService {
707
764
  costUsd = costOf(usage);
708
765
  usageLine = usageLineOf(usage, costUsd, call.ms);
709
766
  baseResult.usage = usageLine;
710
- charge();
767
+ await charge();
711
768
 
712
769
  const hollow = advice.verdict === "reviewed" && isHollowAdvice(advice.advice);
713
770
 
@@ -721,7 +778,7 @@ export class AdvisorService extends TypertRemoteService {
721
778
  advice.severity = verdict.severity;
722
779
  advice.advice = verdict.advice;
723
780
 
724
- // 被动投递(shadow / post-answer)才需要「别重复、别连着烦」;模型主动徵询永远放行。
781
+ // 被动投递(shadow / post-answer)才需要「别重复、别连着烦」;模型主动征询永远放行。
725
782
  const passive = trigger === "shadow" || trigger === "post-answer";
726
783
  if (passive && advice.verdict === "reviewed" && !hollow) {
727
784
  const fingerprintId = fingerprint(advice.advice);
@@ -818,7 +875,7 @@ export class AdvisorService extends TypertRemoteService {
818
875
  };
819
876
  this.lastResult = result;
820
877
 
821
- // 决策日志:本回合确实徵询了,记下结果(回合结束时消费,用来算徵询率与采纳率)。
878
+ // 决策日志:本回合确实征询了,记下结果(回合结束时消费,用来算征询率与采纳率)。
822
879
  if (this.lastResult === result && result.status === "reviewed") {
823
880
  this.decisionTracker.noteAdvice(sessionId, {
824
881
  adviceId,
@@ -826,6 +883,8 @@ export class AdvisorService extends TypertRemoteService {
826
883
  trigger,
827
884
  costUsd,
828
885
  adviceText: result.advice,
886
+ // 证据 ref 也是可追踪信号:模型回头读了同一处,就算「照着建议做了」。
887
+ evidence: result.evidence,
829
888
  });
830
889
  }
831
890
 
@@ -890,7 +949,6 @@ export class AdvisorService extends TypertRemoteService {
890
949
  this.lastDeliveryTurn.set(sessionId, turn);
891
950
  }
892
951
  if (trigger === "shadow") this.counters.shadow += 1;
893
- void estimatedCost;
894
952
  return result;
895
953
  }
896
954
 
@@ -959,10 +1017,10 @@ export class AdvisorService extends TypertRemoteService {
959
1017
  scope.effect(() => {
960
1018
  const dispose = scope.commands.register({
961
1019
  name: COMMAND_NAME,
962
- description: "Consult the advisor: status, choose a model, ask now, or turn it off",
963
- input: {
964
- hint: "[status|on|off|shadow|ask|cancel|report|doctor|confirm|preview|<provider>/<model>]",
965
- },
1020
+ // 宿主逐字透传、不会翻译(docs/runtime/0.2.2-rc.5.md §8.1),
1021
+ // 所以文案来自包内 locale/*.json 的 host 段(lib/messages.js)。
1022
+ description: this.messages.description,
1023
+ input: { hint: this.messages.hint },
966
1024
  /** @param {{ agent: any, rawInput: string }} invocation */
967
1025
  handler: (invocation) => this.handleCommand(invocation),
968
1026
  });
@@ -985,72 +1043,71 @@ export class AdvisorService extends TypertRemoteService {
985
1043
  const session = invocation?.agent?.session;
986
1044
  const sessionId = typeof session?.id === "string" ? session.id : "";
987
1045
  const settings = await this.currentSettings();
1046
+ /**
1047
+ * 所有回执的第一行都是**原始命令行**(审计 USIM-U2-07):宿主的通用命令卡片只显示
1048
+ * 命令名(`advisor`)、不显示用户敲的子命令;单行 summary 还会被 CSS 省略号截断。
1049
+ * 所以文本本身必须自带「我敲了什么」,插件自己的命令卡片再把正文完整展开。
1050
+ * @param {"success" | "error"} kind
1051
+ * @param {string} text
1052
+ * @returns {{ kind: "success" | "error", text: string }}
1053
+ */
1054
+ const reply = (kind, text) => ({ kind, text: commandReply(raw, text) });
988
1055
 
989
1056
  if (raw === "" || raw === "status") {
990
- return { kind: "success", text: await this.statusText(settings, sessionId) };
1057
+ return reply("success", await this.statusText(settings, sessionId));
991
1058
  }
992
1059
  if (raw === "on") {
993
- const next = await this.writeSettings({
994
- mode: isConfigured(settings)
995
- ? "advisory"
996
- : settings.mode === "off"
997
- ? "advisory"
998
- : settings.mode,
999
- });
1000
- if (!isConfigured(next)) {
1001
- return {
1002
- kind: "error",
1003
- text: "还没有选顾问模型。用 /advisor 打开选择器,或 /advisor <provider>/<model> 直接指定。",
1004
- };
1060
+ // 没配模型时**不写 mode**:旧实现先把保存值改成 advisory 再报错,结果是设置页
1061
+ // 显示「模式:顾问」、实际生效是 off(审计 USIM-U2-08 的根因)。
1062
+ if (!isConfigured(settings)) {
1063
+ return reply(
1064
+ "error",
1065
+ "还没有选顾问模型。用 /advisor 打开选择器,或 /advisor <provider>/<model> 直接指定。",
1066
+ );
1005
1067
  }
1006
- return { kind: "success", text: `顾问已开启(${next.provider}/${next.model})。` };
1068
+ const next = await this.writeSettings({ mode: "advisory" });
1069
+ return reply("success", `顾问已开启(${next.provider}/${next.model})。`);
1007
1070
  }
1008
1071
  if (raw === "off") {
1009
1072
  await this.writeSettings({ mode: "off" });
1010
- return { kind: "success", text: "顾问已关闭(/advisor on 重新开启)。" };
1073
+ return reply("success", "顾问已关闭(/advisor on 重新开启)。");
1011
1074
  }
1012
1075
  if (raw === "shadow") {
1013
1076
  await this.writeSettings({ mode: "shadow" });
1014
- return {
1015
- kind: "success",
1016
- text: "已切到 shadow 模式:照常调用并记账,但不把建议回灌给模型。",
1017
- };
1077
+ return reply("success", "已切到 shadow 模式:照常调用并记账,但不把建议回灌给模型。");
1018
1078
  }
1019
1079
  if (raw === "ask") {
1020
- if (session === undefined) return { kind: "error", text: "当前没有会话。" };
1080
+ if (session === undefined) return reply("error", "当前没有会话。");
1021
1081
  const result = await this.runAdvisor({ session, trigger: "manual" });
1022
- return {
1023
- kind: result.status === "reviewed" ? "success" : "error",
1024
- text: this.describeResult(result),
1025
- };
1082
+ return reply(result.status === "reviewed" ? "success" : "error", this.describeResult(result));
1026
1083
  }
1027
1084
  if (raw === "cancel") {
1028
1085
  const controller = this.inflight.get(sessionId);
1029
- if (controller === undefined) return { kind: "error", text: "没有在途的顾问徵询。" };
1086
+ if (controller === undefined) return reply("error", "没有在途的顾问征询。");
1030
1087
  try {
1031
1088
  controller.abort(new Error("user cancelled"));
1032
1089
  } catch (_error) {
1033
1090
  /* 已中止 */
1034
1091
  }
1035
- return { kind: "success", text: "已取消本次顾问徵询。" };
1092
+ return reply("success", "已取消本次顾问征询。");
1036
1093
  }
1037
1094
  if (raw === "confirm") {
1038
- if (!isConfigured(settings)) return { kind: "error", text: "还没选顾问模型。" };
1095
+ if (!isConfigured(settings)) return reply("error", "还没选顾问模型。");
1039
1096
  const list = Array.isArray(settings.confirmedHosts) ? settings.confirmedHosts : [];
1040
1097
  const next = list.includes(settings.provider) ? list : [...list, settings.provider];
1041
1098
  await this.writeSettings({ confirmedHosts: next });
1042
- return {
1043
- kind: "success",
1044
- text: `已允许把会话内容发送到「${settings.provider}」(可随时在设置里清空 confirmedHosts)。`,
1045
- };
1099
+ return reply(
1100
+ "success",
1101
+ `已允许把会话内容发送到「${settings.provider}」(可随时在设置里清空 confirmedHosts)。`,
1102
+ );
1046
1103
  }
1047
1104
  if (raw === "preview") {
1048
1105
  const preview = await this.previewText(session, settings);
1049
- return { kind: "success", text: preview };
1106
+ return reply("success", preview);
1050
1107
  }
1051
1108
  if (raw === "report all") {
1052
1109
  const totals = await this.ledger.adviceTotals();
1053
- if (totals.total === 0) return { kind: "success", text: "还没有任何建议记录。" };
1110
+ if (totals.total === 0) return reply("success", "还没有任何建议记录。");
1054
1111
  /** @param {Record<string, number>} map */
1055
1112
  const fmt = (map) =>
1056
1113
  Object.entries(map)
@@ -1059,9 +1116,9 @@ export class AdvisorService extends TypertRemoteService {
1059
1116
  const days = Object.entries(totals.byDay)
1060
1117
  .sort((a, b) => (a[0] < b[0] ? 1 : -1))
1061
1118
  .slice(0, 7);
1062
- return {
1063
- kind: "success",
1064
- text: [
1119
+ return reply(
1120
+ "success",
1121
+ [
1065
1122
  "顾问报告(跨会话)",
1066
1123
  `累计 ${totals.total} 条建议`,
1067
1124
  `严重度:${fmt(totals.bySeverity)}`,
@@ -1069,17 +1126,17 @@ export class AdvisorService extends TypertRemoteService {
1069
1126
  `最近 7 天:${days.map(([day, count]) => `${day} ${count}`).join(" · ")}`,
1070
1127
  `账本:${this.ledger.advicePath}`,
1071
1128
  ].join("\n"),
1072
- };
1129
+ );
1073
1130
  }
1074
1131
  if (raw === "report") {
1075
- return { kind: "success", text: await this.reportText(session) };
1132
+ return reply("success", await this.reportText(session));
1076
1133
  }
1077
1134
  if (raw === "doctor") {
1078
1135
  const checks = await this.doctorChecks(sessionId);
1079
- return {
1080
- kind: "success",
1081
- text: checks.map((check) => `${iconOf(check.status)} ${check.message}`).join("\n"),
1082
- };
1136
+ return reply(
1137
+ "success",
1138
+ checks.map((check) => `${iconOf(check.status)} ${check.message}`).join("\n"),
1139
+ );
1083
1140
  }
1084
1141
 
1085
1142
  // <provider>/<model> [effort]
@@ -1087,20 +1144,20 @@ export class AdvisorService extends TypertRemoteService {
1087
1144
  const routePart = parts[0] ?? "";
1088
1145
  const slash = routePart.indexOf("/");
1089
1146
  if (slash <= 0) {
1090
- return {
1091
- kind: "error",
1092
- text: `无法识别的参数:${raw}。可用:status / on / off / shadow / ask / cancel / report / doctor / confirm / preview / <provider>/<model>`,
1093
- };
1147
+ return reply(
1148
+ "error",
1149
+ `无法识别的参数:${raw}。可用:status / on / off / shadow / ask / cancel / report / doctor / confirm / preview / <provider>/<model>`,
1150
+ );
1094
1151
  }
1095
1152
  const provider = routePart.slice(0, slash);
1096
1153
  const model = routePart.slice(slash + 1);
1097
1154
  const effort = parts[1] ?? "";
1098
1155
  const saved = await this.setModel({ provider, model, reasoningEffort: effort });
1099
- if (!saved.ok) return { kind: "error", text: saved.message };
1100
- return {
1101
- kind: "success",
1102
- text: `顾问已设为 ${provider}/${model}${effort === "" ? "" : ` · 思考档 ${effort}`}(下一次徵询生效)。`,
1103
- };
1156
+ if (!saved.ok) return reply("error", saved.message);
1157
+ return reply(
1158
+ "success",
1159
+ `顾问已设为 ${provider}/${model}${effort === "" ? "" : ` · 思考档 ${effort}`}(下一次征询生效)。`,
1160
+ );
1104
1161
  }
1105
1162
 
1106
1163
  /**
@@ -1114,17 +1171,9 @@ export class AdvisorService extends TypertRemoteService {
1114
1171
  const totals = this.ledger.totals();
1115
1172
  const last = this.lastResult;
1116
1173
  const skip = sessionId === "" ? undefined : this.lastSkip.get(sessionId);
1117
- const route = isConfigured(settings) ? `${settings.provider}/${settings.model}` : "(未配置)";
1118
- return [
1119
- `模式:${settings.mode}`,
1120
- `顾问:${route}${settings.reasoningEffort === "" ? "" : ` · 思考档 ${settings.reasoningEffort}`}`,
1121
- `本会话:${counters.sessionCalls} 次(本回合 ${counters.turnCalls}/${
1122
- settings.maxCallsPerTurn === 0 ? "∞" : settings.maxCallsPerTurn
1123
- },本会话上限 ${settings.maxCallsPerSession === 0 ? "∞" : settings.maxCallsPerSession})`,
1124
- `累计 token:${totals.inputTokens} in / ${totals.outputTokens} out(${totals.calls} 次)`,
1125
- `最近一次:${last === null ? "(还没有)" : `${last.status}${last.code && last.code !== "ok" ? ` · ${last.code}` : ""}${last.usage ? ` · ${last.usage}` : ""}`}`,
1126
- `最近跳过:${skip ?? "(无)"}`,
1127
- ].join("\n");
1174
+ // 多行 + 「生效」独立成行:保存的 mode 与真实生效状态分开说(审计 USIM-U2-08)。
1175
+ // 文案规则在 lib/command-text.js(纯函数,可单测)。
1176
+ return formatStatusText({ settings, counters, totals, last, skip });
1128
1177
  }
1129
1178
 
1130
1179
  /**
@@ -1140,7 +1189,7 @@ export class AdvisorService extends TypertRemoteService {
1140
1189
  return `${head}${risks}${acceptance}\n${result.usage}`;
1141
1190
  }
1142
1191
  if (result.status === "declined") return `顾问认为无需建议。\n${result.usage ?? ""}`.trim();
1143
- if (result.status === "skipped") return `未徵询:${result.reason}`;
1192
+ if (result.status === "skipped") return `未征询:${result.reason}`;
1144
1193
  return `顾问不可用(${result.code}):${result.reason}`;
1145
1194
  }
1146
1195
 
@@ -1244,7 +1293,7 @@ export class AdvisorService extends TypertRemoteService {
1244
1293
  if (session === undefined || session === null) return "当前没有会话。";
1245
1294
  const { events, records } = this.adviceRecords(session);
1246
1295
  if (records.length === 0) {
1247
- return "本会话还没有顾问记录。用 /advisor on 打开,或让模型在关键节点徵询。";
1296
+ return "本会话还没有顾问记录。用 /advisor on 打开,或让模型在关键节点征询。";
1248
1297
  }
1249
1298
  const summary = summarizeAdoption(events, records);
1250
1299
  const recent = summary.items
@@ -1257,7 +1306,11 @@ export class AdvisorService extends TypertRemoteService {
1257
1306
  const totals = this.ledger.totals();
1258
1307
  return [
1259
1308
  "顾问报告(本会话)",
1309
+ // 采纳率必须带分母:大部分建议没有可追踪信号,只说「采纳 0」会被读成「从没被采纳」。
1260
1310
  `投递 ${summary.total} 条 · 采纳 ${summary.adopted} · 未判定 ${summary.unknown}`,
1311
+ `可追踪 ${summary.traceable}/${summary.total} 条(${
1312
+ summary.traceableRate === null ? "—" : `${Math.round(summary.traceableRate * 100)}%`
1313
+ })—— 采纳率只在这部分建议上有意义`,
1261
1314
  `证据锚点:校验 ${summary.anchorsChecked} 条 / 对上 ${summary.anchorsVerified} 条`,
1262
1315
  `累计 token:${totals.inputTokens} in / ${totals.outputTokens} out(${totals.calls} 次调用,含其他会话)`,
1263
1316
  "最近:",
@@ -1288,7 +1341,7 @@ export class AdvisorService extends TypertRemoteService {
1288
1341
  */
1289
1342
  handleSessionEvent(session, event) {
1290
1343
  const sessionId = typeof session?.id === "string" ? session.id : "";
1291
- // ---- 决策日志:回合特征与 outcome 回填(与徵询逻辑无关,只做记录)----
1344
+ // ---- 决策日志:回合特征与 outcome 回填(与征询逻辑无关,只做记录)----
1292
1345
  if (sessionId !== "" && !isSubagentSession(session)) {
1293
1346
  this.decisionTracker.track(sessionId, event);
1294
1347
  }
@@ -1817,10 +1870,15 @@ export class AdvisorService extends TypertRemoteService {
1817
1870
  }
1818
1871
  }
1819
1872
 
1873
+ // 诊断也报**真实生效状态**:保存的 mode 是 advisory 但没配模型时,
1874
+ // 旧文案「当前模式 advisory」会让人以为已经开着(审计 USIM-U2-08)。
1875
+ const state = effectiveStateOf(settings);
1820
1876
  checks.push({
1821
1877
  id: "mode",
1822
- status: settings.mode === "off" ? "warn" : "pass",
1823
- message: settings.mode === "off" ? "当前模式是 off:不会徵询" : `当前模式 ${settings.mode}`,
1878
+ status: state.effective === "off" ? "warn" : "pass",
1879
+ message:
1880
+ `生效状态:${effectiveLine(state)}` +
1881
+ (state.reason === "unconfigured" ? `(保存的模式是 ${settings.mode})` : ""),
1824
1882
  });
1825
1883
 
1826
1884
  if (sessionId !== "") {