@kangyishuai/dsh-advisor 0.1.0 → 0.3.0

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
@@ -17,20 +17,31 @@ import { appendPluginRecord, pluginRecordOf } from "@deepseek-ai/dsh-session";
17
17
  import { Remote, RemoteError, TypertRemoteService } from "@deepseek-ai/dsh-typert-protocol";
18
18
  import { summarizeAdoption } from "./adoption.js";
19
19
  import { applyAnchorVerdict, buildIndex, verifyAnchors } from "./anchors.js";
20
+ import { checkPool, createBudgetPool } from "./budget.js";
20
21
  import { callAdvisor } from "./call.js";
22
+ import { checkAllowlist, effectivePrice } from "./catalog.js";
21
23
  import {
22
24
  checkBudget,
23
25
  estimateCostUsd,
24
26
  fingerprint,
27
+ immuneActive,
25
28
  isHollowAdvice,
26
29
  rememberFingerprint,
27
30
  } from "./guard.js";
28
31
  import { createLedger } from "./ledger.js";
29
32
  import { parseAdvice, summarizeAdvice, TOOL_DESCRIPTION } from "./prompt.js";
30
33
  import { pairingCheck, resolveRoute } from "./route.js";
31
- import { isConfigured, loadSettings, mergeSettings, saveSettings } from "./settings.js";
34
+ import {
35
+ isConfigured,
36
+ loadSettings,
37
+ mergeSettings,
38
+ saveSettings,
39
+ settingsPath,
40
+ } from "./settings.js";
32
41
  import { renderToolOutput, TOOL_NAME, TOOL_OUTPUT_SCHEMA, TOOL_PARAMETERS } from "./tool-schema.js";
42
+ import { buildTracePreview } from "./trace.js";
33
43
  import { buildTranscript } from "./transcript.js";
44
+ import { runEvidencePass } from "./twopass.js";
34
45
 
35
46
  /** plugin record 类型(必须匹配 ^plugin:[a-z0-9][a-z0-9._-]*(/[...])*$)。 */
36
47
  export const ADVICE_RECORD = "plugin:advisor/advice";
@@ -133,6 +144,7 @@ export class AdvisorService extends TypertRemoteService {
133
144
  this.logger = ctx?.logger ?? console;
134
145
  this.dataRoot = resolveDataRoot(this.config);
135
146
  this.ledger = createLedger({ home: this.dataRoot, logger: this.logger });
147
+ this.pool = createBudgetPool({ home: this.dataRoot, logger: this.logger });
136
148
  void this.ledger.ready();
137
149
  /** @type {{ at: number, value: any }} */
138
150
  this.settingsCache = { at: 0, value: null };
@@ -140,8 +152,10 @@ export class AdvisorService extends TypertRemoteService {
140
152
  this.turnOf = new Map();
141
153
  /** 在途徵询(cancel 用)。 @type {Map<string, AbortController>} */
142
154
  this.inflight = new Map();
143
- /** 去重表(shadow 投递用)。 @type {Map<string, number>} */
155
+ /** 去重表(被动投递用:shadow / post-answer)。 @type {Map<string, number>} */
144
156
  this.seen = new Map();
157
+ /** 每会话最近一次被动投递所在的回合(免疫窗口用)。 @type {Map<string, number>} */
158
+ this.lastDeliveryTurn = new Map();
145
159
  /** 最近一次结果(status / 工具卡 / 诊断)。 @type {any} */
146
160
  this.lastResult = null;
147
161
  /** 每会话已投递的建议条数(sessionCap 用)。 @type {Map<string, number>} */
@@ -207,6 +221,31 @@ export class AdvisorService extends TypertRemoteService {
207
221
  return undefined;
208
222
  }
209
223
 
224
+ /**
225
+ * 会话工作目录(取证阶段的读取根)。宿主服务优先,其次 header,最后进程 cwd。
226
+ * @param {any} session
227
+ * @returns {string}
228
+ */
229
+ sessionCwd(session) {
230
+ const sessionId = typeof session?.id === "string" ? session.id : "";
231
+ try {
232
+ const wd = serviceOf(this.ctx, "workingDirectory");
233
+ const value = wd?.get?.(sessionId) ?? wd?.current?.(sessionId) ?? wd?.path?.(sessionId);
234
+ if (typeof value === "string" && value !== "") return value;
235
+ } catch (_error) {
236
+ /* 退化到 header */
237
+ }
238
+ // 会话头里的 cwd 是权威的(日志第一行就有);再看 session 自身。
239
+ const header = session?.header ?? {};
240
+ for (const source of [header, session]) {
241
+ for (const key of ["cwd", "workingDirectory", "projectPath"]) {
242
+ const value = source?.[key];
243
+ if (typeof value === "string" && value !== "") return value;
244
+ }
245
+ }
246
+ return process.cwd();
247
+ }
248
+
210
249
  /**
211
250
  * 已注册的路由(含用户手写的 pi-ai 路由)。
212
251
  * @returns {Promise<Array<{ provider: string, displayName: string, source: "catalog"|"declared" }>>}
@@ -308,7 +347,7 @@ export class AdvisorService extends TypertRemoteService {
308
347
 
309
348
  /**
310
349
  * 跑一次顾问徵询。所有失败都返回结构化结果,绝不抛。
311
- * @param {{ session: any, trigger: "tool"|"shadow"|"manual", focus?: string, signal?: AbortSignal }} input
350
+ * @param {{ session: any, trigger: "tool"|"shadow"|"manual"|"post-answer", focus?: string, signal?: AbortSignal }} input
312
351
  * @returns {Promise<any>}
313
352
  */
314
353
  async runAdvisor(input) {
@@ -357,6 +396,29 @@ export class AdvisorService extends TypertRemoteService {
357
396
  });
358
397
  if (!pairing.allowed) return skip(`配对校验未通过:${pairing.message}`, "pairing_rejected");
359
398
 
399
+ const allow = checkAllowlist(settings.allowedModels, resolved.route);
400
+ if (!allow.allowed) return skip(`白名单拦截:${allow.reason}`, "not_allowed");
401
+
402
+ // 跨 provider 首次徵询需要显式确认(数据会离开本机去另一家)。
403
+ const mainProvider = typeof mainModel?.provider === "string" ? mainModel.provider : "";
404
+ if (mainProvider !== "" && mainProvider !== resolved.route.provider) {
405
+ const confirmed =
406
+ Array.isArray(settings.confirmedHosts) &&
407
+ settings.confirmedHosts.includes(resolved.route.provider);
408
+ if (!confirmed) {
409
+ return {
410
+ status: "skipped",
411
+ code: "needs_confirmation",
412
+ reason: `跨 provider 首次徵询需要确认:会话内容会发送到「${resolved.route.provider}」。运行 /advisor confirm 允许,或 /advisor preview 先看会发什么`,
413
+ advice: "",
414
+ severity: "nit",
415
+ risks: [],
416
+ acceptance: [],
417
+ evidence: [],
418
+ };
419
+ }
420
+ }
421
+
360
422
  const turn = this.turnOf.get(sessionId) ?? 0;
361
423
  const now = Date.now();
362
424
  const counters = this.ledger.counters(sessionId, now);
@@ -384,6 +446,29 @@ export class AdvisorService extends TypertRemoteService {
384
446
  };
385
447
  }
386
448
 
449
+ // 工作区级共享预算池(跨会话累计,按本地日滚动)与有效单价(用户声明 > 内置表 > 不算钱)。
450
+ const price = effectivePrice(settings, resolved.route.model);
451
+ const pool = await this.pool.read();
452
+ const poolCheck = checkPool(pool, settings);
453
+ if (!poolCheck.ok) {
454
+ const reason =
455
+ poolCheck.code === "workspace_calls"
456
+ ? `工作区今日调用已达上限(${poolCheck.used}/${poolCheck.limit})`
457
+ : `工作区今日预算已用完($${poolCheck.used.toFixed(4)}/$${poolCheck.limit})`;
458
+ if (sessionId !== "") this.lastSkip.set(sessionId, reason);
459
+ this.counters.skipped += 1;
460
+ return {
461
+ status: "skipped",
462
+ code: poolCheck.code,
463
+ reason,
464
+ advice: "",
465
+ severity: "nit",
466
+ risks: [],
467
+ acceptance: [],
468
+ evidence: [],
469
+ };
470
+ }
471
+
387
472
  // 上下文:包含工具调用与结果(这是与「只发文本」的关键区别)。
388
473
  const messages = typeof session?.deriveMessages === "function" ? session.deriveMessages() : [];
389
474
  const transcript = buildTranscript(messages, {
@@ -393,6 +478,9 @@ export class AdvisorService extends TypertRemoteService {
393
478
  });
394
479
  if (transcript.text.trim() === "") return skip("会话里还没有可发送的内容", "empty_transcript");
395
480
 
481
+ // 只存首尾预览;tracePrompt=off 时连预览都不落盘(requestChars 仍记)。
482
+ const trace = settings.tracePrompt === "preview" ? buildTracePreview(transcript.text) : null;
483
+
396
484
  const controller = new AbortController();
397
485
  if (sessionId !== "") this.inflight.set(sessionId, controller);
398
486
  const signal =
@@ -405,8 +493,8 @@ export class AdvisorService extends TypertRemoteService {
405
493
  const estimatedCost = estimateCostUsd({
406
494
  inputTokens: Math.ceil(transcript.text.length / 3),
407
495
  outputTokens: settings.maxTokens / 2,
408
- priceInputPerMTok: settings.priceInputPerMTok,
409
- priceOutputPerMTok: settings.priceOutputPerMTok,
496
+ priceInputPerMTok: price.input,
497
+ priceOutputPerMTok: price.output,
410
498
  });
411
499
 
412
500
  const started = Date.now();
@@ -417,6 +505,7 @@ export class AdvisorService extends TypertRemoteService {
417
505
  route: resolved.route,
418
506
  settings,
419
507
  transcript: transcript.text,
508
+ canRequestEvidence: settings.advisorTools === true,
420
509
  focus: input.focus,
421
510
  locale: this.localeName(),
422
511
  sessionId,
@@ -433,8 +522,8 @@ export class AdvisorService extends TypertRemoteService {
433
522
  ? estimateCostUsd({
434
523
  inputTokens: call.usage.inputTokens,
435
524
  outputTokens: call.usage.outputTokens,
436
- priceInputPerMTok: settings.priceInputPerMTok,
437
- priceOutputPerMTok: settings.priceOutputPerMTok,
525
+ priceInputPerMTok: price.input,
526
+ priceOutputPerMTok: price.output,
438
527
  })
439
528
  : 0;
440
529
 
@@ -484,6 +573,7 @@ export class AdvisorService extends TypertRemoteService {
484
573
  const parsed = parseAdvice(call.text ?? "");
485
574
  const usage = call.usage;
486
575
  this.ledger.noteCall(sessionId, { turn, costUsd, at: Date.now() });
576
+ void this.pool.add({ calls: 1, costUsd });
487
577
  this.counters.calls += 1;
488
578
 
489
579
  if (!parsed.ok) {
@@ -508,7 +598,41 @@ export class AdvisorService extends TypertRemoteService {
508
598
  return result;
509
599
  }
510
600
 
511
- const advice = parsed.advice;
601
+ let advice = parsed.advice;
602
+ let verification = null;
603
+ if (settings.advisorTools === true) {
604
+ const pass = await runEvidencePass({
605
+ advice,
606
+ root: this.sessionCwd(session),
607
+ settings: { advisorTools: true },
608
+ parseAdvice,
609
+ callSecond: async (block) =>
610
+ callAdvisor({
611
+ llm: this.llm(),
612
+ route: resolved.route,
613
+ settings,
614
+ transcript: transcript.text,
615
+ extra: block,
616
+ canRequestEvidence: false,
617
+ locale: this.localeName(),
618
+ sessionId,
619
+ signal,
620
+ logger: this.logger,
621
+ }),
622
+ });
623
+ advice = pass.advice;
624
+ verification = pass.verification;
625
+ if (pass.extraUsage !== null && call.usage !== undefined) {
626
+ call.usage = {
627
+ inputTokens: call.usage.inputTokens + pass.extraUsage.inputTokens,
628
+ outputTokens: call.usage.outputTokens + pass.extraUsage.outputTokens,
629
+ cacheReadTokens: call.usage.cacheReadTokens + pass.extraUsage.cacheReadTokens,
630
+ cacheWriteTokens: call.usage.cacheWriteTokens + pass.extraUsage.cacheWriteTokens,
631
+ reasoningTokens: call.usage.reasoningTokens + pass.extraUsage.reasoningTokens,
632
+ };
633
+ }
634
+ }
635
+
512
636
  const hollow = advice.verdict === "reviewed" && isHollowAdvice(advice.advice);
513
637
 
514
638
  // 证据锚点校验:顾问说「刚才那次失败/这个文件」时,回头核对它引用的东西是否真的存在。
@@ -521,6 +645,44 @@ export class AdvisorService extends TypertRemoteService {
521
645
  advice.severity = verdict.severity;
522
646
  advice.advice = verdict.advice;
523
647
 
648
+ // 被动投递(shadow / post-answer)才需要「别重复、别连着烦」;模型主动徵询永远放行。
649
+ const passive = trigger === "shadow" || trigger === "post-answer";
650
+ if (passive && advice.verdict === "reviewed" && !hollow) {
651
+ const fingerprintId = fingerprint(advice.advice);
652
+ const lastTurn = this.lastDeliveryTurn.get(sessionId);
653
+ if (
654
+ lastTurn !== undefined &&
655
+ immuneActive({
656
+ lastDeliveryTurn: lastTurn,
657
+ currentTurn: turn,
658
+ immuneTurns: settings.immuneTurns,
659
+ })
660
+ ) {
661
+ this.counters.skipped += 1;
662
+ if (sessionId !== "") this.lastSkip.set(sessionId, "免疫窗口内(上一条建议刚投递过)");
663
+ return {
664
+ ...baseResult,
665
+ status: "skipped",
666
+ code: "immune",
667
+ reason: `免疫窗口:上一条建议在第 ${lastTurn} 轮投递,${settings.immuneTurns} 轮内不再打扰`,
668
+ };
669
+ }
670
+ if (settings.dedupe === true) {
671
+ const remembered = rememberFingerprint(this.seen, fingerprintId, Date.now());
672
+ this.seen = remembered.table;
673
+ if (remembered.duplicate) {
674
+ this.counters.skipped += 1;
675
+ if (sessionId !== "") this.lastSkip.set(sessionId, "重复建议(24h 内说过)");
676
+ return {
677
+ ...baseResult,
678
+ status: "skipped",
679
+ code: "duplicate",
680
+ reason: "同一建议 24h 内已投递过",
681
+ };
682
+ }
683
+ }
684
+ }
685
+
524
686
  // 会话级投递上限:到顶后只放 blocker(长任务真出大事时仍然能说话)。
525
687
  const delivered = this.delivered.get(sessionId) ?? 0;
526
688
  if (
@@ -568,6 +730,7 @@ export class AdvisorService extends TypertRemoteService {
568
730
  risks: advice.risks,
569
731
  acceptance: advice.acceptance,
570
732
  evidence: advice.evidence,
733
+ ...(verification === null ? {} : { verification }),
571
734
  anchors: {
572
735
  checked: anchors.checks.length,
573
736
  verified: anchors.verified,
@@ -591,11 +754,30 @@ export class AdvisorService extends TypertRemoteService {
591
754
  model: result.model,
592
755
  usage: result.usage,
593
756
  trigger,
757
+ requestChars: transcript.text.length,
758
+ ...(trace === null
759
+ ? {}
760
+ : {
761
+ requestPreview: trace.preview,
762
+ requestPreviewTruncated: trace.truncated,
763
+ }),
594
764
  anchors: result.anchors,
765
+ ...(verification === null ? {} : { verification }),
595
766
  });
596
767
  } catch (error) {
597
768
  this.warn("cannot append advice record", error);
598
769
  }
770
+ void this.ledger.recordAdvice({
771
+ at: new Date().toISOString(),
772
+ sessionId,
773
+ adviceId,
774
+ turn,
775
+ severity: result.severity,
776
+ status: result.status,
777
+ model: result.model,
778
+ trigger,
779
+ anchors: result.anchors,
780
+ });
599
781
 
600
782
  await this.ledger.record({
601
783
  at: new Date().toISOString(),
@@ -615,6 +797,9 @@ export class AdvisorService extends TypertRemoteService {
615
797
  if (result.status === "reviewed" && settings.sessionCap > 0 && sessionId !== "") {
616
798
  this.delivered.set(sessionId, (this.delivered.get(sessionId) ?? 0) + 1);
617
799
  }
800
+ if (result.status === "reviewed" && passive && sessionId !== "") {
801
+ this.lastDeliveryTurn.set(sessionId, turn);
802
+ }
618
803
  if (trigger === "shadow") this.counters.shadow += 1;
619
804
  void estimatedCost;
620
805
  return result;
@@ -686,7 +871,9 @@ export class AdvisorService extends TypertRemoteService {
686
871
  const dispose = scope.commands.register({
687
872
  name: COMMAND_NAME,
688
873
  description: "Consult the advisor: status, choose a model, ask now, or turn it off",
689
- input: { hint: "[status|on|off|shadow|ask|cancel|report|doctor|<provider>/<model>]" },
874
+ input: {
875
+ hint: "[status|on|off|shadow|ask|cancel|report|doctor|confirm|preview|<provider>/<model>]",
876
+ },
690
877
  /** @param {{ agent: any, rawInput: string }} invocation */
691
878
  handler: (invocation) => this.handleCommand(invocation),
692
879
  });
@@ -758,6 +945,43 @@ export class AdvisorService extends TypertRemoteService {
758
945
  }
759
946
  return { kind: "success", text: "已取消本次顾问徵询。" };
760
947
  }
948
+ if (raw === "confirm") {
949
+ if (!isConfigured(settings)) return { kind: "error", text: "还没选顾问模型。" };
950
+ const list = Array.isArray(settings.confirmedHosts) ? settings.confirmedHosts : [];
951
+ const next = list.includes(settings.provider) ? list : [...list, settings.provider];
952
+ await this.writeSettings({ confirmedHosts: next });
953
+ return {
954
+ kind: "success",
955
+ text: `已允许把会话内容发送到「${settings.provider}」(可随时在设置里清空 confirmedHosts)。`,
956
+ };
957
+ }
958
+ if (raw === "preview") {
959
+ const preview = await this.previewText(session, settings);
960
+ return { kind: "success", text: preview };
961
+ }
962
+ if (raw === "report all") {
963
+ const totals = await this.ledger.adviceTotals();
964
+ if (totals.total === 0) return { kind: "success", text: "还没有任何建议记录。" };
965
+ /** @param {Record<string, number>} map */
966
+ const fmt = (map) =>
967
+ Object.entries(map)
968
+ .map(([key, value]) => `${key} ${value}`)
969
+ .join(" · ");
970
+ const days = Object.entries(totals.byDay)
971
+ .sort((a, b) => (a[0] < b[0] ? 1 : -1))
972
+ .slice(0, 7);
973
+ return {
974
+ kind: "success",
975
+ text: [
976
+ "顾问报告(跨会话)",
977
+ `累计 ${totals.total} 条建议`,
978
+ `严重度:${fmt(totals.bySeverity)}`,
979
+ `模型:${fmt(totals.byModel)}`,
980
+ `最近 7 天:${days.map(([day, count]) => `${day} ${count}`).join(" · ")}`,
981
+ `账本:${this.ledger.advicePath}`,
982
+ ].join("\n"),
983
+ };
984
+ }
761
985
  if (raw === "report") {
762
986
  return { kind: "success", text: await this.reportText(session) };
763
987
  }
@@ -776,7 +1000,7 @@ export class AdvisorService extends TypertRemoteService {
776
1000
  if (slash <= 0) {
777
1001
  return {
778
1002
  kind: "error",
779
- text: `无法识别的参数:${raw}。可用:status / on / off / shadow / ask / cancel / report / doctor / <provider>/<model>`,
1003
+ text: `无法识别的参数:${raw}。可用:status / on / off / shadow / ask / cancel / report / doctor / confirm / preview / <provider>/<model>`,
780
1004
  };
781
1005
  }
782
1006
  const provider = routePart.slice(0, slash);
@@ -853,6 +1077,50 @@ export class AdvisorService extends TypertRemoteService {
853
1077
  return { events: list, records };
854
1078
  }
855
1079
 
1080
+ /**
1081
+ * `/advisor preview`:**不发送**任何东西,只把「这一次会发出去什么」摊开。
1082
+ * @param {any} session
1083
+ * @param {any} settings
1084
+ * @returns {Promise<string>}
1085
+ */
1086
+ async previewText(session, settings) {
1087
+ if (session === undefined || session === null) return "当前没有会话。";
1088
+ const mainModel = this.mainModelOf(session);
1089
+ const resolved = resolveRoute({ settings, mainModel });
1090
+ if (resolved.route.provider === "" || resolved.route.model === "") return "还没配置顾问模型。";
1091
+ const messages = typeof session.deriveMessages === "function" ? session.deriveMessages() : [];
1092
+ const transcript = buildTranscript(messages, {
1093
+ scope: settings.privacyScope,
1094
+ redactSecrets: settings.redact,
1095
+ maxChars: settings.maxInputChars,
1096
+ });
1097
+ const price = effectivePrice(settings, resolved.route.model);
1098
+ const allow = checkAllowlist(settings.allowedModels, resolved.route);
1099
+ const pool = await this.pool.read();
1100
+ const crossProvider =
1101
+ typeof mainModel?.provider === "string" &&
1102
+ mainModel.provider !== "" &&
1103
+ mainModel.provider !== resolved.route.provider;
1104
+ const confirmed =
1105
+ Array.isArray(settings.confirmedHosts) &&
1106
+ settings.confirmedHosts.includes(resolved.route.provider);
1107
+ return [
1108
+ `目标:${resolved.route.provider}/${resolved.route.model}${resolved.route.reasoningEffort ? ` · 思考档 ${resolved.route.reasoningEffort}` : ""}`,
1109
+ `发送范围:${settings.privacyScope} · 脱敏 ${settings.redact ? "开" : "关"} · 上限 ${settings.maxInputChars} 字符`,
1110
+ `将发送:${transcript.text.length} 字符(约 ${Math.ceil(transcript.text.length / 3)} tokens)`,
1111
+ `上下文省略:${transcript.stats.contextOmitted} 字符(技能目录 / AGENTS.md 等宿主注入内容)`,
1112
+ `工具往来:${transcript.stats.toolCalls} 次调用 / ${transcript.stats.toolResults} 条结果 · 截断 ${transcript.stats.truncated} 处`,
1113
+ `脱敏命中:${transcript.stats.redactions.length === 0 ? "无" : transcript.stats.redactions.join(" / ")}`,
1114
+ `白名单:${allow.reason}`,
1115
+ `跨 provider:${crossProvider ? `是(需确认${confirmed ? ",已确认" : ",尚未确认 → /advisor confirm"})` : "否"}`,
1116
+ `单价:${price.source === "none" ? "未配置(只记 token)" : `输入 $${price.input}/M · 输出 $${price.output}/M(${price.source === "builtin" ? "内置参考价" : "用户设置"})`}`,
1117
+ `工作区今日:${pool.calls} 次(上限 ${settings.workspaceMaxCallsPerDay || "∞"})`,
1118
+ ``,
1119
+ `—— 正文前 400 字符 ——`,
1120
+ transcript.text.slice(0, 400),
1121
+ ].join("\n");
1122
+ }
1123
+
856
1124
  /**
857
1125
  * `/advisor report` 的正文:投递/采纳/锚点统计 + 最近几条。
858
1126
  * @param {any} session
@@ -907,21 +1175,36 @@ export class AdvisorService extends TypertRemoteService {
907
1175
  handleSessionEvent(session, event) {
908
1176
  const sessionId = typeof session?.id === "string" ? session.id : "";
909
1177
  if (sessionId !== "" && event?.type === "turn/start") {
910
- const next = (this.turnOf.get(sessionId) ?? 0) + 1;
1178
+ // 用事件里的**绝对回合号**,不要自己累计:会话可能早于插件加载就已有多个回合,
1179
+ // 累计值会和 turnTail 的 props.turn 对不上,顾问线就永远不显示(真机踩过)。
1180
+ const fromEvent = Number(event?.data?.turn);
1181
+ const next =
1182
+ Number.isSafeInteger(fromEvent) && fromEvent > 0
1183
+ ? fromEvent
1184
+ : (this.turnOf.get(sessionId) ?? 0) + 1;
911
1185
  this.turnOf.set(sessionId, next);
912
1186
  this.ledger.resetTurn(sessionId, next);
913
1187
  return;
914
1188
  }
915
1189
  if (event?.type !== "turn/end") return;
1190
+ const endTurn = Number(event?.data?.turn);
1191
+ if (sessionId !== "" && Number.isSafeInteger(endTurn) && endTurn > 0) {
1192
+ this.turnOf.set(sessionId, endTurn);
1193
+ }
916
1194
  if (event?.data?.reason?.kind !== "completed") return;
917
1195
  if (isSubagentSession(session)) return;
918
1196
  // 重要:不能在事件分发里同步写会话(重入保护),必须异步一拍。
919
1197
  void (async () => {
920
1198
  try {
921
1199
  const settings = await this.currentSettings();
922
- if (settings.mode !== "shadow") return;
923
- const result = await this.runAdvisor({ session, trigger: "shadow" });
924
- if (result.status === "reviewed") {
1200
+ const shadow = settings.mode === "shadow";
1201
+ const postAnswer = settings.mode === "advisory" && settings.postAnswer === "card";
1202
+ if (!shadow && !postAnswer) return;
1203
+ const result = await this.runAdvisor({
1204
+ session,
1205
+ trigger: shadow ? "shadow" : "post-answer",
1206
+ });
1207
+ if (shadow && result.status === "reviewed") {
925
1208
  const id = fingerprint(result.advice);
926
1209
  const remembered = rememberFingerprint(this.seen, id, Date.now());
927
1210
  this.seen = remembered.table;
@@ -1111,6 +1394,9 @@ export class AdvisorService extends TypertRemoteService {
1111
1394
  last: this.lastResult,
1112
1395
  lastSkip: sessionId === "" ? null : (this.lastSkip.get(sessionId) ?? null),
1113
1396
  ledgerPath: this.ledger.path,
1397
+ settingsPath: settingsPath(this.dataRoot),
1398
+ pool: await this.pool.read(),
1399
+ price: effectivePrice(settings, settings.model),
1114
1400
  dataRoot: this.dataRoot,
1115
1401
  commands: {
1116
1402
  on: "/advisor on",
@@ -1145,6 +1431,35 @@ export class AdvisorService extends TypertRemoteService {
1145
1431
  async updateSettings(request) {
1146
1432
  try {
1147
1433
  const patch = request?.patch ?? request ?? {};
1434
+ const current = await this.currentSettings();
1435
+ const nextEffort =
1436
+ typeof patch?.reasoningEffort === "string" ? patch.reasoningEffort.trim() : undefined;
1437
+ const nextProvider =
1438
+ typeof patch?.provider === "string" ? patch.provider.trim() : current.provider;
1439
+ const nextModel = typeof patch?.model === "string" ? patch.model.trim() : current.model;
1440
+ // 设置卡的 patch 也要复核思考档,否则会存下一个永远无法生效的组合。
1441
+ if (
1442
+ nextEffort !== undefined &&
1443
+ nextEffort !== "" &&
1444
+ nextProvider !== "" &&
1445
+ nextModel !== "" &&
1446
+ (nextProvider !== current.provider ||
1447
+ nextModel !== current.model ||
1448
+ nextEffort !== current.reasoningEffort)
1449
+ ) {
1450
+ const info = await this.resolveModel(nextProvider, nextModel);
1451
+ if (
1452
+ info !== null &&
1453
+ info.efforts.length > 0 &&
1454
+ !info.efforts.some((item) => item.id === nextEffort)
1455
+ ) {
1456
+ return {
1457
+ ok: false,
1458
+ code: "UNSUPPORTED_REASONING_EFFORT",
1459
+ message: `${nextProvider}/${nextModel} 不支持思考档「${nextEffort}」。可选:${info.efforts.map((item) => item.id).join(" / ")}`,
1460
+ };
1461
+ }
1462
+ }
1148
1463
  const saved = await this.writeSettings(patch);
1149
1464
  return { ok: true, settings: saved };
1150
1465
  } catch (error) {
@@ -1221,6 +1536,10 @@ export class AdvisorService extends TypertRemoteService {
1221
1536
  model: String(data?.model ?? ""),
1222
1537
  usage: String(data?.usage ?? ""),
1223
1538
  at: Number(data?.at ?? 0) || 0,
1539
+ trigger: String(data?.trigger ?? ""),
1540
+ requestChars: Number(data?.requestChars ?? 0) || 0,
1541
+ requestPreview: String(data?.requestPreview ?? ""),
1542
+ requestPreviewTruncated: data?.requestPreviewTruncated === true,
1224
1543
  anchors: data?.anchors ?? null,
1225
1544
  })),
1226
1545
  };
@@ -1229,6 +1548,26 @@ export class AdvisorService extends TypertRemoteService {
1229
1548
  }
1230
1549
  }
1231
1550
 
1551
+ /**
1552
+ * 预览这一次会发出去什么(不发送)。设置卡用。
1553
+ * @param {any} request
1554
+ * @returns {Promise<any>}
1555
+ */
1556
+ async preview(request) {
1557
+ try {
1558
+ const sessionId = typeof request?.sessionId === "string" ? request.sessionId : "";
1559
+ const sessions = serviceOf(this.ctx, "sessions");
1560
+ const session =
1561
+ serviceOf(this.ctx, "agents")?.get?.(sessionId)?.session ||
1562
+ sessions?.get?.(sessionId) ||
1563
+ sessions?.store?.get?.(sessionId);
1564
+ const settings = await this.currentSettings();
1565
+ return { ok: true, text: await this.previewText(session, settings), settings };
1566
+ } catch (error) {
1567
+ rethrowRemote(error);
1568
+ }
1569
+ }
1570
+
1232
1571
  /**
1233
1572
  * 采纳报告(Remote 版,供客户端以后直接渲染)。
1234
1573
  * @param {any} request
@@ -1426,4 +1765,5 @@ declareRemote(AdvisorService, "models");
1426
1765
  declareRemote(AdvisorService, "modelInfo");
1427
1766
  declareRemote(AdvisorService, "doctor");
1428
1767
  declareRemote(AdvisorService, "report");
1768
+ declareRemote(AdvisorService, "preview");
1429
1769
  declareRemote(AdvisorService, "advice");