@kangyishuai/dsh-advisor 0.1.0 → 0.2.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,11 +17,14 @@ 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";
@@ -31,6 +34,7 @@ import { pairingCheck, resolveRoute } from "./route.js";
31
34
  import { isConfigured, loadSettings, mergeSettings, saveSettings } from "./settings.js";
32
35
  import { renderToolOutput, TOOL_NAME, TOOL_OUTPUT_SCHEMA, TOOL_PARAMETERS } from "./tool-schema.js";
33
36
  import { buildTranscript } from "./transcript.js";
37
+ import { runEvidencePass } from "./twopass.js";
34
38
 
35
39
  /** plugin record 类型(必须匹配 ^plugin:[a-z0-9][a-z0-9._-]*(/[...])*$)。 */
36
40
  export const ADVICE_RECORD = "plugin:advisor/advice";
@@ -133,6 +137,7 @@ export class AdvisorService extends TypertRemoteService {
133
137
  this.logger = ctx?.logger ?? console;
134
138
  this.dataRoot = resolveDataRoot(this.config);
135
139
  this.ledger = createLedger({ home: this.dataRoot, logger: this.logger });
140
+ this.pool = createBudgetPool({ home: this.dataRoot, logger: this.logger });
136
141
  void this.ledger.ready();
137
142
  /** @type {{ at: number, value: any }} */
138
143
  this.settingsCache = { at: 0, value: null };
@@ -140,8 +145,10 @@ export class AdvisorService extends TypertRemoteService {
140
145
  this.turnOf = new Map();
141
146
  /** 在途徵询(cancel 用)。 @type {Map<string, AbortController>} */
142
147
  this.inflight = new Map();
143
- /** 去重表(shadow 投递用)。 @type {Map<string, number>} */
148
+ /** 去重表(被动投递用:shadow / post-answer)。 @type {Map<string, number>} */
144
149
  this.seen = new Map();
150
+ /** 每会话最近一次被动投递所在的回合(免疫窗口用)。 @type {Map<string, number>} */
151
+ this.lastDeliveryTurn = new Map();
145
152
  /** 最近一次结果(status / 工具卡 / 诊断)。 @type {any} */
146
153
  this.lastResult = null;
147
154
  /** 每会话已投递的建议条数(sessionCap 用)。 @type {Map<string, number>} */
@@ -207,6 +214,31 @@ export class AdvisorService extends TypertRemoteService {
207
214
  return undefined;
208
215
  }
209
216
 
217
+ /**
218
+ * 会话工作目录(取证阶段的读取根)。宿主服务优先,其次 header,最后进程 cwd。
219
+ * @param {any} session
220
+ * @returns {string}
221
+ */
222
+ sessionCwd(session) {
223
+ const sessionId = typeof session?.id === "string" ? session.id : "";
224
+ try {
225
+ const wd = serviceOf(this.ctx, "workingDirectory");
226
+ const value = wd?.get?.(sessionId) ?? wd?.current?.(sessionId) ?? wd?.path?.(sessionId);
227
+ if (typeof value === "string" && value !== "") return value;
228
+ } catch (_error) {
229
+ /* 退化到 header */
230
+ }
231
+ // 会话头里的 cwd 是权威的(日志第一行就有);再看 session 自身。
232
+ const header = session?.header ?? {};
233
+ for (const source of [header, session]) {
234
+ for (const key of ["cwd", "workingDirectory", "projectPath"]) {
235
+ const value = source?.[key];
236
+ if (typeof value === "string" && value !== "") return value;
237
+ }
238
+ }
239
+ return process.cwd();
240
+ }
241
+
210
242
  /**
211
243
  * 已注册的路由(含用户手写的 pi-ai 路由)。
212
244
  * @returns {Promise<Array<{ provider: string, displayName: string, source: "catalog"|"declared" }>>}
@@ -308,7 +340,7 @@ export class AdvisorService extends TypertRemoteService {
308
340
 
309
341
  /**
310
342
  * 跑一次顾问徵询。所有失败都返回结构化结果,绝不抛。
311
- * @param {{ session: any, trigger: "tool"|"shadow"|"manual", focus?: string, signal?: AbortSignal }} input
343
+ * @param {{ session: any, trigger: "tool"|"shadow"|"manual"|"post-answer", focus?: string, signal?: AbortSignal }} input
312
344
  * @returns {Promise<any>}
313
345
  */
314
346
  async runAdvisor(input) {
@@ -357,6 +389,29 @@ export class AdvisorService extends TypertRemoteService {
357
389
  });
358
390
  if (!pairing.allowed) return skip(`配对校验未通过:${pairing.message}`, "pairing_rejected");
359
391
 
392
+ const allow = checkAllowlist(settings.allowedModels, resolved.route);
393
+ if (!allow.allowed) return skip(`白名单拦截:${allow.reason}`, "not_allowed");
394
+
395
+ // 跨 provider 首次徵询需要显式确认(数据会离开本机去另一家)。
396
+ const mainProvider = typeof mainModel?.provider === "string" ? mainModel.provider : "";
397
+ if (mainProvider !== "" && mainProvider !== resolved.route.provider) {
398
+ const confirmed =
399
+ Array.isArray(settings.confirmedHosts) &&
400
+ settings.confirmedHosts.includes(resolved.route.provider);
401
+ if (!confirmed) {
402
+ return {
403
+ status: "skipped",
404
+ code: "needs_confirmation",
405
+ reason: `跨 provider 首次徵询需要确认:会话内容会发送到「${resolved.route.provider}」。运行 /advisor confirm 允许,或 /advisor preview 先看会发什么`,
406
+ advice: "",
407
+ severity: "nit",
408
+ risks: [],
409
+ acceptance: [],
410
+ evidence: [],
411
+ };
412
+ }
413
+ }
414
+
360
415
  const turn = this.turnOf.get(sessionId) ?? 0;
361
416
  const now = Date.now();
362
417
  const counters = this.ledger.counters(sessionId, now);
@@ -384,6 +439,29 @@ export class AdvisorService extends TypertRemoteService {
384
439
  };
385
440
  }
386
441
 
442
+ // 工作区级共享预算池(跨会话累计,按本地日滚动)与有效单价(用户声明 > 内置表 > 不算钱)。
443
+ const price = effectivePrice(settings, resolved.route.model);
444
+ const pool = await this.pool.read();
445
+ const poolCheck = checkPool(pool, settings);
446
+ if (!poolCheck.ok) {
447
+ const reason =
448
+ poolCheck.code === "workspace_calls"
449
+ ? `工作区今日调用已达上限(${poolCheck.used}/${poolCheck.limit})`
450
+ : `工作区今日预算已用完($${poolCheck.used.toFixed(4)}/$${poolCheck.limit})`;
451
+ if (sessionId !== "") this.lastSkip.set(sessionId, reason);
452
+ this.counters.skipped += 1;
453
+ return {
454
+ status: "skipped",
455
+ code: poolCheck.code,
456
+ reason,
457
+ advice: "",
458
+ severity: "nit",
459
+ risks: [],
460
+ acceptance: [],
461
+ evidence: [],
462
+ };
463
+ }
464
+
387
465
  // 上下文:包含工具调用与结果(这是与「只发文本」的关键区别)。
388
466
  const messages = typeof session?.deriveMessages === "function" ? session.deriveMessages() : [];
389
467
  const transcript = buildTranscript(messages, {
@@ -405,8 +483,8 @@ export class AdvisorService extends TypertRemoteService {
405
483
  const estimatedCost = estimateCostUsd({
406
484
  inputTokens: Math.ceil(transcript.text.length / 3),
407
485
  outputTokens: settings.maxTokens / 2,
408
- priceInputPerMTok: settings.priceInputPerMTok,
409
- priceOutputPerMTok: settings.priceOutputPerMTok,
486
+ priceInputPerMTok: price.input,
487
+ priceOutputPerMTok: price.output,
410
488
  });
411
489
 
412
490
  const started = Date.now();
@@ -417,6 +495,7 @@ export class AdvisorService extends TypertRemoteService {
417
495
  route: resolved.route,
418
496
  settings,
419
497
  transcript: transcript.text,
498
+ canRequestEvidence: settings.advisorTools === true,
420
499
  focus: input.focus,
421
500
  locale: this.localeName(),
422
501
  sessionId,
@@ -433,8 +512,8 @@ export class AdvisorService extends TypertRemoteService {
433
512
  ? estimateCostUsd({
434
513
  inputTokens: call.usage.inputTokens,
435
514
  outputTokens: call.usage.outputTokens,
436
- priceInputPerMTok: settings.priceInputPerMTok,
437
- priceOutputPerMTok: settings.priceOutputPerMTok,
515
+ priceInputPerMTok: price.input,
516
+ priceOutputPerMTok: price.output,
438
517
  })
439
518
  : 0;
440
519
 
@@ -484,6 +563,7 @@ export class AdvisorService extends TypertRemoteService {
484
563
  const parsed = parseAdvice(call.text ?? "");
485
564
  const usage = call.usage;
486
565
  this.ledger.noteCall(sessionId, { turn, costUsd, at: Date.now() });
566
+ void this.pool.add({ calls: 1, costUsd });
487
567
  this.counters.calls += 1;
488
568
 
489
569
  if (!parsed.ok) {
@@ -508,7 +588,41 @@ export class AdvisorService extends TypertRemoteService {
508
588
  return result;
509
589
  }
510
590
 
511
- const advice = parsed.advice;
591
+ let advice = parsed.advice;
592
+ let verification = null;
593
+ if (settings.advisorTools === true) {
594
+ const pass = await runEvidencePass({
595
+ advice,
596
+ root: this.sessionCwd(session),
597
+ settings: { advisorTools: true },
598
+ parseAdvice,
599
+ callSecond: async (block) =>
600
+ callAdvisor({
601
+ llm: this.llm(),
602
+ route: resolved.route,
603
+ settings,
604
+ transcript: transcript.text,
605
+ extra: block,
606
+ canRequestEvidence: false,
607
+ locale: this.localeName(),
608
+ sessionId,
609
+ signal,
610
+ logger: this.logger,
611
+ }),
612
+ });
613
+ advice = pass.advice;
614
+ verification = pass.verification;
615
+ if (pass.extraUsage !== null && call.usage !== undefined) {
616
+ call.usage = {
617
+ inputTokens: call.usage.inputTokens + pass.extraUsage.inputTokens,
618
+ outputTokens: call.usage.outputTokens + pass.extraUsage.outputTokens,
619
+ cacheReadTokens: call.usage.cacheReadTokens + pass.extraUsage.cacheReadTokens,
620
+ cacheWriteTokens: call.usage.cacheWriteTokens + pass.extraUsage.cacheWriteTokens,
621
+ reasoningTokens: call.usage.reasoningTokens + pass.extraUsage.reasoningTokens,
622
+ };
623
+ }
624
+ }
625
+
512
626
  const hollow = advice.verdict === "reviewed" && isHollowAdvice(advice.advice);
513
627
 
514
628
  // 证据锚点校验:顾问说「刚才那次失败/这个文件」时,回头核对它引用的东西是否真的存在。
@@ -521,6 +635,44 @@ export class AdvisorService extends TypertRemoteService {
521
635
  advice.severity = verdict.severity;
522
636
  advice.advice = verdict.advice;
523
637
 
638
+ // 被动投递(shadow / post-answer)才需要「别重复、别连着烦」;模型主动徵询永远放行。
639
+ const passive = trigger === "shadow" || trigger === "post-answer";
640
+ if (passive && advice.verdict === "reviewed" && !hollow) {
641
+ const fingerprintId = fingerprint(advice.advice);
642
+ const lastTurn = this.lastDeliveryTurn.get(sessionId);
643
+ if (
644
+ lastTurn !== undefined &&
645
+ immuneActive({
646
+ lastDeliveryTurn: lastTurn,
647
+ currentTurn: turn,
648
+ immuneTurns: settings.immuneTurns,
649
+ })
650
+ ) {
651
+ this.counters.skipped += 1;
652
+ if (sessionId !== "") this.lastSkip.set(sessionId, "免疫窗口内(上一条建议刚投递过)");
653
+ return {
654
+ ...baseResult,
655
+ status: "skipped",
656
+ code: "immune",
657
+ reason: `免疫窗口:上一条建议在第 ${lastTurn} 轮投递,${settings.immuneTurns} 轮内不再打扰`,
658
+ };
659
+ }
660
+ if (settings.dedupe === true) {
661
+ const remembered = rememberFingerprint(this.seen, fingerprintId, Date.now());
662
+ this.seen = remembered.table;
663
+ if (remembered.duplicate) {
664
+ this.counters.skipped += 1;
665
+ if (sessionId !== "") this.lastSkip.set(sessionId, "重复建议(24h 内说过)");
666
+ return {
667
+ ...baseResult,
668
+ status: "skipped",
669
+ code: "duplicate",
670
+ reason: "同一建议 24h 内已投递过",
671
+ };
672
+ }
673
+ }
674
+ }
675
+
524
676
  // 会话级投递上限:到顶后只放 blocker(长任务真出大事时仍然能说话)。
525
677
  const delivered = this.delivered.get(sessionId) ?? 0;
526
678
  if (
@@ -568,6 +720,7 @@ export class AdvisorService extends TypertRemoteService {
568
720
  risks: advice.risks,
569
721
  acceptance: advice.acceptance,
570
722
  evidence: advice.evidence,
723
+ ...(verification === null ? {} : { verification }),
571
724
  anchors: {
572
725
  checked: anchors.checks.length,
573
726
  verified: anchors.verified,
@@ -592,10 +745,22 @@ export class AdvisorService extends TypertRemoteService {
592
745
  usage: result.usage,
593
746
  trigger,
594
747
  anchors: result.anchors,
748
+ ...(verification === null ? {} : { verification }),
595
749
  });
596
750
  } catch (error) {
597
751
  this.warn("cannot append advice record", error);
598
752
  }
753
+ void this.ledger.recordAdvice({
754
+ at: new Date().toISOString(),
755
+ sessionId,
756
+ adviceId,
757
+ turn,
758
+ severity: result.severity,
759
+ status: result.status,
760
+ model: result.model,
761
+ trigger,
762
+ anchors: result.anchors,
763
+ });
599
764
 
600
765
  await this.ledger.record({
601
766
  at: new Date().toISOString(),
@@ -615,6 +780,9 @@ export class AdvisorService extends TypertRemoteService {
615
780
  if (result.status === "reviewed" && settings.sessionCap > 0 && sessionId !== "") {
616
781
  this.delivered.set(sessionId, (this.delivered.get(sessionId) ?? 0) + 1);
617
782
  }
783
+ if (result.status === "reviewed" && passive && sessionId !== "") {
784
+ this.lastDeliveryTurn.set(sessionId, turn);
785
+ }
618
786
  if (trigger === "shadow") this.counters.shadow += 1;
619
787
  void estimatedCost;
620
788
  return result;
@@ -686,7 +854,9 @@ export class AdvisorService extends TypertRemoteService {
686
854
  const dispose = scope.commands.register({
687
855
  name: COMMAND_NAME,
688
856
  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>]" },
857
+ input: {
858
+ hint: "[status|on|off|shadow|ask|cancel|report|doctor|confirm|preview|<provider>/<model>]",
859
+ },
690
860
  /** @param {{ agent: any, rawInput: string }} invocation */
691
861
  handler: (invocation) => this.handleCommand(invocation),
692
862
  });
@@ -758,6 +928,43 @@ export class AdvisorService extends TypertRemoteService {
758
928
  }
759
929
  return { kind: "success", text: "已取消本次顾问徵询。" };
760
930
  }
931
+ if (raw === "confirm") {
932
+ if (!isConfigured(settings)) return { kind: "error", text: "还没选顾问模型。" };
933
+ const list = Array.isArray(settings.confirmedHosts) ? settings.confirmedHosts : [];
934
+ const next = list.includes(settings.provider) ? list : [...list, settings.provider];
935
+ await this.writeSettings({ confirmedHosts: next });
936
+ return {
937
+ kind: "success",
938
+ text: `已允许把会话内容发送到「${settings.provider}」(可随时在设置里清空 confirmedHosts)。`,
939
+ };
940
+ }
941
+ if (raw === "preview") {
942
+ const preview = await this.previewText(session, settings);
943
+ return { kind: "success", text: preview };
944
+ }
945
+ if (raw === "report all") {
946
+ const totals = await this.ledger.adviceTotals();
947
+ if (totals.total === 0) return { kind: "success", text: "还没有任何建议记录。" };
948
+ /** @param {Record<string, number>} map */
949
+ const fmt = (map) =>
950
+ Object.entries(map)
951
+ .map(([key, value]) => `${key} ${value}`)
952
+ .join(" · ");
953
+ const days = Object.entries(totals.byDay)
954
+ .sort((a, b) => (a[0] < b[0] ? 1 : -1))
955
+ .slice(0, 7);
956
+ return {
957
+ kind: "success",
958
+ text: [
959
+ "顾问报告(跨会话)",
960
+ `累计 ${totals.total} 条建议`,
961
+ `严重度:${fmt(totals.bySeverity)}`,
962
+ `模型:${fmt(totals.byModel)}`,
963
+ `最近 7 天:${days.map(([day, count]) => `${day} ${count}`).join(" · ")}`,
964
+ `账本:${this.ledger.advicePath}`,
965
+ ].join("\n"),
966
+ };
967
+ }
761
968
  if (raw === "report") {
762
969
  return { kind: "success", text: await this.reportText(session) };
763
970
  }
@@ -776,7 +983,7 @@ export class AdvisorService extends TypertRemoteService {
776
983
  if (slash <= 0) {
777
984
  return {
778
985
  kind: "error",
779
- text: `无法识别的参数:${raw}。可用:status / on / off / shadow / ask / cancel / report / doctor / <provider>/<model>`,
986
+ text: `无法识别的参数:${raw}。可用:status / on / off / shadow / ask / cancel / report / doctor / confirm / preview / <provider>/<model>`,
780
987
  };
781
988
  }
782
989
  const provider = routePart.slice(0, slash);
@@ -853,6 +1060,50 @@ export class AdvisorService extends TypertRemoteService {
853
1060
  return { events: list, records };
854
1061
  }
855
1062
 
1063
+ /**
1064
+ * `/advisor preview`:**不发送**任何东西,只把「这一次会发出去什么」摊开。
1065
+ * @param {any} session
1066
+ * @param {any} settings
1067
+ * @returns {Promise<string>}
1068
+ */
1069
+ async previewText(session, settings) {
1070
+ if (session === undefined || session === null) return "当前没有会话。";
1071
+ const mainModel = this.mainModelOf(session);
1072
+ const resolved = resolveRoute({ settings, mainModel });
1073
+ if (resolved.route.provider === "" || resolved.route.model === "") return "还没配置顾问模型。";
1074
+ const messages = typeof session.deriveMessages === "function" ? session.deriveMessages() : [];
1075
+ const transcript = buildTranscript(messages, {
1076
+ scope: settings.privacyScope,
1077
+ redactSecrets: settings.redact,
1078
+ maxChars: settings.maxInputChars,
1079
+ });
1080
+ const price = effectivePrice(settings, resolved.route.model);
1081
+ const allow = checkAllowlist(settings.allowedModels, resolved.route);
1082
+ const pool = await this.pool.read();
1083
+ const crossProvider =
1084
+ typeof mainModel?.provider === "string" &&
1085
+ mainModel.provider !== "" &&
1086
+ mainModel.provider !== resolved.route.provider;
1087
+ const confirmed =
1088
+ Array.isArray(settings.confirmedHosts) &&
1089
+ settings.confirmedHosts.includes(resolved.route.provider);
1090
+ return [
1091
+ `目标:${resolved.route.provider}/${resolved.route.model}${resolved.route.reasoningEffort ? ` · 思考档 ${resolved.route.reasoningEffort}` : ""}`,
1092
+ `发送范围:${settings.privacyScope} · 脱敏 ${settings.redact ? "开" : "关"} · 上限 ${settings.maxInputChars} 字符`,
1093
+ `将发送:${transcript.text.length} 字符(约 ${Math.ceil(transcript.text.length / 3)} tokens)`,
1094
+ `上下文省略:${transcript.stats.contextOmitted} 字符(技能目录 / AGENTS.md 等宿主注入内容)`,
1095
+ `工具往来:${transcript.stats.toolCalls} 次调用 / ${transcript.stats.toolResults} 条结果 · 截断 ${transcript.stats.truncated} 处`,
1096
+ `脱敏命中:${transcript.stats.redactions.length === 0 ? "无" : transcript.stats.redactions.join(" / ")}`,
1097
+ `白名单:${allow.reason}`,
1098
+ `跨 provider:${crossProvider ? `是(需确认${confirmed ? ",已确认" : ",尚未确认 → /advisor confirm"})` : "否"}`,
1099
+ `单价:${price.source === "none" ? "未配置(只记 token)" : `输入 $${price.input}/M · 输出 $${price.output}/M(${price.source === "builtin" ? "内置参考价" : "用户设置"})`}`,
1100
+ `工作区今日:${pool.calls} 次(上限 ${settings.workspaceMaxCallsPerDay || "∞"})`,
1101
+ ``,
1102
+ `—— 正文前 400 字符 ——`,
1103
+ transcript.text.slice(0, 400),
1104
+ ].join("\n");
1105
+ }
1106
+
856
1107
  /**
857
1108
  * `/advisor report` 的正文:投递/采纳/锚点统计 + 最近几条。
858
1109
  * @param {any} session
@@ -907,21 +1158,36 @@ export class AdvisorService extends TypertRemoteService {
907
1158
  handleSessionEvent(session, event) {
908
1159
  const sessionId = typeof session?.id === "string" ? session.id : "";
909
1160
  if (sessionId !== "" && event?.type === "turn/start") {
910
- const next = (this.turnOf.get(sessionId) ?? 0) + 1;
1161
+ // 用事件里的**绝对回合号**,不要自己累计:会话可能早于插件加载就已有多个回合,
1162
+ // 累计值会和 turnTail 的 props.turn 对不上,顾问线就永远不显示(真机踩过)。
1163
+ const fromEvent = Number(event?.data?.turn);
1164
+ const next =
1165
+ Number.isSafeInteger(fromEvent) && fromEvent > 0
1166
+ ? fromEvent
1167
+ : (this.turnOf.get(sessionId) ?? 0) + 1;
911
1168
  this.turnOf.set(sessionId, next);
912
1169
  this.ledger.resetTurn(sessionId, next);
913
1170
  return;
914
1171
  }
915
1172
  if (event?.type !== "turn/end") return;
1173
+ const endTurn = Number(event?.data?.turn);
1174
+ if (sessionId !== "" && Number.isSafeInteger(endTurn) && endTurn > 0) {
1175
+ this.turnOf.set(sessionId, endTurn);
1176
+ }
916
1177
  if (event?.data?.reason?.kind !== "completed") return;
917
1178
  if (isSubagentSession(session)) return;
918
1179
  // 重要:不能在事件分发里同步写会话(重入保护),必须异步一拍。
919
1180
  void (async () => {
920
1181
  try {
921
1182
  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") {
1183
+ const shadow = settings.mode === "shadow";
1184
+ const postAnswer = settings.mode === "advisory" && settings.postAnswer === "card";
1185
+ if (!shadow && !postAnswer) return;
1186
+ const result = await this.runAdvisor({
1187
+ session,
1188
+ trigger: shadow ? "shadow" : "post-answer",
1189
+ });
1190
+ if (shadow && result.status === "reviewed") {
925
1191
  const id = fingerprint(result.advice);
926
1192
  const remembered = rememberFingerprint(this.seen, id, Date.now());
927
1193
  this.seen = remembered.table;
@@ -1111,6 +1377,8 @@ export class AdvisorService extends TypertRemoteService {
1111
1377
  last: this.lastResult,
1112
1378
  lastSkip: sessionId === "" ? null : (this.lastSkip.get(sessionId) ?? null),
1113
1379
  ledgerPath: this.ledger.path,
1380
+ pool: await this.pool.read(),
1381
+ price: effectivePrice(settings, settings.model),
1114
1382
  dataRoot: this.dataRoot,
1115
1383
  commands: {
1116
1384
  on: "/advisor on",
@@ -1145,6 +1413,35 @@ export class AdvisorService extends TypertRemoteService {
1145
1413
  async updateSettings(request) {
1146
1414
  try {
1147
1415
  const patch = request?.patch ?? request ?? {};
1416
+ const current = await this.currentSettings();
1417
+ const nextEffort =
1418
+ typeof patch?.reasoningEffort === "string" ? patch.reasoningEffort.trim() : undefined;
1419
+ const nextProvider =
1420
+ typeof patch?.provider === "string" ? patch.provider.trim() : current.provider;
1421
+ const nextModel = typeof patch?.model === "string" ? patch.model.trim() : current.model;
1422
+ // 设置卡的 patch 也要复核思考档,否则会存下一个永远无法生效的组合。
1423
+ if (
1424
+ nextEffort !== undefined &&
1425
+ nextEffort !== "" &&
1426
+ nextProvider !== "" &&
1427
+ nextModel !== "" &&
1428
+ (nextProvider !== current.provider ||
1429
+ nextModel !== current.model ||
1430
+ nextEffort !== current.reasoningEffort)
1431
+ ) {
1432
+ const info = await this.resolveModel(nextProvider, nextModel);
1433
+ if (
1434
+ info !== null &&
1435
+ info.efforts.length > 0 &&
1436
+ !info.efforts.some((item) => item.id === nextEffort)
1437
+ ) {
1438
+ return {
1439
+ ok: false,
1440
+ code: "UNSUPPORTED_REASONING_EFFORT",
1441
+ message: `${nextProvider}/${nextModel} 不支持思考档「${nextEffort}」。可选:${info.efforts.map((item) => item.id).join(" / ")}`,
1442
+ };
1443
+ }
1444
+ }
1148
1445
  const saved = await this.writeSettings(patch);
1149
1446
  return { ok: true, settings: saved };
1150
1447
  } catch (error) {
@@ -1229,6 +1526,26 @@ export class AdvisorService extends TypertRemoteService {
1229
1526
  }
1230
1527
  }
1231
1528
 
1529
+ /**
1530
+ * 预览这一次会发出去什么(不发送)。设置卡用。
1531
+ * @param {any} request
1532
+ * @returns {Promise<any>}
1533
+ */
1534
+ async preview(request) {
1535
+ try {
1536
+ const sessionId = typeof request?.sessionId === "string" ? request.sessionId : "";
1537
+ const sessions = serviceOf(this.ctx, "sessions");
1538
+ const session =
1539
+ serviceOf(this.ctx, "agents")?.get?.(sessionId)?.session ||
1540
+ sessions?.get?.(sessionId) ||
1541
+ sessions?.store?.get?.(sessionId);
1542
+ const settings = await this.currentSettings();
1543
+ return { ok: true, text: await this.previewText(session, settings), settings };
1544
+ } catch (error) {
1545
+ rethrowRemote(error);
1546
+ }
1547
+ }
1548
+
1232
1549
  /**
1233
1550
  * 采纳报告(Remote 版,供客户端以后直接渲染)。
1234
1551
  * @param {any} request
@@ -1426,4 +1743,5 @@ declareRemote(AdvisorService, "models");
1426
1743
  declareRemote(AdvisorService, "modelInfo");
1427
1744
  declareRemote(AdvisorService, "doctor");
1428
1745
  declareRemote(AdvisorService, "report");
1746
+ declareRemote(AdvisorService, "preview");
1429
1747
  declareRemote(AdvisorService, "advice");
package/lib/settings.js CHANGED
@@ -35,7 +35,13 @@ export const DEFAULT_SETTINGS = Object.freeze({
35
35
  dedupe: true,
36
36
  sessionCap: 24,
37
37
  tiers: Object.freeze({}),
38
+ allowedModels: Object.freeze([]),
39
+ confirmedHosts: Object.freeze([]),
38
40
  pairingEnforcement: "warn",
41
+ workspaceMaxCallsPerDay: 200,
42
+ workspaceMaxCostPerDayUsd: 0,
43
+ postAnswer: "off",
44
+ advisorTools: false,
39
45
  timeoutMs: 90000,
40
46
  maxInputChars: 60000,
41
47
  });
@@ -51,6 +57,8 @@ const LIMITS = Object.freeze({
51
57
  priceOutputPerMTok: [0, 1000],
52
58
  immuneTurns: [0, 20],
53
59
  sessionCap: [0, 200],
60
+ workspaceMaxCallsPerDay: [0, 100000],
61
+ workspaceMaxCostPerDayUsd: [0, 10000],
54
62
  timeoutMs: [5000, 600000],
55
63
  maxInputChars: [4000, 400000],
56
64
  });
@@ -114,6 +122,26 @@ export function normalizeTiers(raw) {
114
122
  return out;
115
123
  }
116
124
 
125
+ /**
126
+ * 规整字符串数组:去空、去重、截断、限制条数。
127
+ * @param {unknown} raw
128
+ * @param {number} [max]
129
+ * @returns {string[]}
130
+ */
131
+ export function normalizeStringList(raw, max = 50) {
132
+ if (!Array.isArray(raw)) return [];
133
+ /** @type {string[]} */
134
+ const out = [];
135
+ for (const item of raw) {
136
+ if (typeof item !== "string") continue;
137
+ const value = item.trim().slice(0, MAX_STRING);
138
+ if (value === "" || out.includes(value)) continue;
139
+ out.push(value);
140
+ if (out.length >= max) break;
141
+ }
142
+ return out;
143
+ }
144
+
117
145
  /**
118
146
  * 把任意输入规整成合法设置:未知键丢弃、类型不符回落默认、数字夹紧、字符串截断。
119
147
  * @param {unknown} raw 文件内容或 RPC patch 合并后的值
@@ -152,6 +180,12 @@ export function normalizeSettings(raw) {
152
180
  }
153
181
  out.temperature = nullableNumber(input.temperature, 0, 2);
154
182
  out.tiers = normalizeTiers(input.tiers);
183
+ out.allowedModels = normalizeStringList(input.allowedModels);
184
+ out.confirmedHosts = normalizeStringList(input.confirmedHosts);
185
+ if (typeof input.postAnswer === "string" && ["off", "card"].includes(input.postAnswer)) {
186
+ out.postAnswer = input.postAnswer;
187
+ }
188
+ if (typeof input.advisorTools === "boolean") out.advisorTools = input.advisorTools;
155
189
 
156
190
  return out;
157
191
  }
package/lib/twopass.js ADDED
@@ -0,0 +1,60 @@
1
+ // @ts-check
2
+ // 两阶段取证的**编排**部分(与宿主解耦,便于单测)。
3
+ //
4
+ // 流程:第一轮建议带 `needs` → 在会话工作目录内取证 → 把证据回灌 → 第二轮复核。
5
+ // 任何一步失败都保留第一轮结论(绝不能因为取证失败而丢掉已经付费拿到的建议)。
6
+ import { buildVerificationBlock, collectEvidence } from "./verifier.js";
7
+
8
+ /**
9
+ * @typedef {object} EvidencePassResult
10
+ * @property {any} advice 最终采用的建议(可能是第二轮,也可能是第一轮)
11
+ * @property {any|null} verification 取证摘要;没触发取证时为 null
12
+ * @property {{ inputTokens: number, outputTokens: number, cacheReadTokens: number, cacheWriteTokens: number, reasoningTokens: number }|null} extraUsage 第二轮新增的 token
13
+ */
14
+
15
+ /**
16
+ * @param {object} input
17
+ * @param {any} input.advice 第一轮解析后的建议(需含 `needs`)
18
+ * @param {string} input.root 会话工作目录
19
+ * @param {{ advisorTools?: boolean, maxFiles?: number, maxBytes?: number }} [input.settings]
20
+ * @param {(block: string) => Promise<{ ok: boolean, text?: string, usage?: any }>} input.callSecond 发起第二轮调用
21
+ * @param {(raw: string) => { ok: boolean, advice?: any }} input.parseAdvice 重新解析
22
+ * @param {typeof collectEvidence} [input.collect] 取证实现(测试可注入)
23
+ * @returns {Promise<EvidencePassResult>}
24
+ */
25
+ export async function runEvidencePass(input) {
26
+ const { advice, root, callSecond, parseAdvice } = input;
27
+ const collect = input.collect ?? collectEvidence;
28
+ const needs = Array.isArray(advice?.needs) ? advice.needs : [];
29
+ if (needs.length === 0) {
30
+ return { advice, verification: null, extraUsage: null };
31
+ }
32
+
33
+ const evidence = await collect({
34
+ root,
35
+ needs,
36
+ maxFiles: Number.isFinite(input.settings?.maxFiles) ? Number(input.settings?.maxFiles) : 5,
37
+ maxBytes: Number.isFinite(input.settings?.maxBytes)
38
+ ? Number(input.settings?.maxBytes)
39
+ : undefined,
40
+ });
41
+ /** @type {{ requested: number, read: string[], refused: string[], pass2: boolean }} */
42
+ const verification = {
43
+ requested: needs.length,
44
+ read: evidence.sections.map((section) => section.ref),
45
+ refused: evidence.refused,
46
+ pass2: false,
47
+ };
48
+
49
+ const block = buildVerificationBlock(evidence);
50
+ if (block === "") return { advice, verification, extraUsage: null };
51
+
52
+ const second = await callSecond(block);
53
+ if (!second?.ok) return { advice, verification, extraUsage: null };
54
+
55
+ const reparsed = parseAdvice(second.text ?? "");
56
+ if (!reparsed?.ok) return { advice, verification, extraUsage: null };
57
+
58
+ verification.pass2 = true;
59
+ return { advice: reparsed.advice, verification, extraUsage: second.usage ?? null };
60
+ }