@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/ledger.js CHANGED
@@ -10,6 +10,8 @@ import { join } from "node:path";
10
10
  export const LEDGER_DIR = "advisor";
11
11
  /** 账本文件名。 */
12
12
  export const LEDGER_FILE = "usage.jsonl";
13
+ /** 建议账本(跨会话汇总用,一行一条建议)。 */
14
+ export const ADVICE_FILE = "advice.jsonl";
13
15
  /** 滚动阈值:超过这个字节数就把旧文件改名(保留一份历史,不做无界增长)。 */
14
16
  export const LEDGER_MAX_BYTES = 2 * 1024 * 1024;
15
17
 
@@ -17,7 +19,7 @@ export const LEDGER_MAX_BYTES = 2 * 1024 * 1024;
17
19
  * @typedef {object} LedgerEntry
18
20
  * @property {string} at ISO 时间
19
21
  * @property {string} sessionId
20
- * @property {"tool"|"shadow"|"manual"} trigger
22
+ * @property {"tool"|"shadow"|"manual"|"post-answer"} trigger
21
23
  * @property {string} provider
22
24
  * @property {string} model
23
25
  * @property {string} effort
@@ -63,7 +65,10 @@ export function dayKey(date = new Date()) {
63
65
  * totals: () => { calls: number, inputTokens: number, outputTokens: number, costUsd: number, byTrigger: Record<string, number> },
64
66
  * recent: (limit?: number) => LedgerEntry[],
65
67
  * ready: () => Promise<void>,
68
+ * recordAdvice: (entry: any) => Promise<void>,
69
+ * adviceTotals: () => Promise<{ total: number, bySeverity: Record<string, number>, byModel: Record<string, number>, byDay: Record<string, number>, byConfidence: Record<string, number> }>,
66
70
  * path: string,
71
+ * advicePath: string,
67
72
  * }}
68
73
  */
69
74
  export function createLedger(options) {
@@ -156,8 +161,11 @@ export function createLedger(options) {
156
161
  return current;
157
162
  };
158
163
 
164
+ const advicePath = join(dir, ADVICE_FILE);
165
+
159
166
  return {
160
167
  path,
168
+ advicePath,
161
169
 
162
170
  /**
163
171
  * 记录一次徵询(先落盘再更新内存;落盘失败不让调用失败)。
@@ -238,6 +246,63 @@ export function createLedger(options) {
238
246
  return recent.slice(0, Math.max(0, limit));
239
247
  },
240
248
 
249
+ /**
250
+ * 追加一条建议到跨会话账本(失败只告警,不影响徵询)。
251
+ * @param {any} entry
252
+ * @returns {Promise<void>}
253
+ */
254
+ async recordAdvice(entry) {
255
+ try {
256
+ await mkdir(dir, { recursive: true });
257
+ const line = `${JSON.stringify(entry)}\n`;
258
+ const existing = await readFile(advicePath, "utf8").catch(() => "");
259
+ await writeFile(advicePath, `${existing}${line}`, "utf8");
260
+ } catch (error) {
261
+ options.logger?.warn?.(`[advisor] 写建议账本失败:${String(error)}`);
262
+ }
263
+ },
264
+
265
+ /**
266
+ * 跨会话建议汇总(读整个 advice.jsonl;文件很小,一行一条)。
267
+ * @returns {Promise<{ total: number, bySeverity: Record<string, number>, byModel: Record<string, number>, byDay: Record<string, number>, byConfidence: Record<string, number> }>}
268
+ */
269
+ async adviceTotals() {
270
+ /** @type {Record<string, number>} */
271
+ const bySeverity = {};
272
+ /** @type {Record<string, number>} */
273
+ const byModel = {};
274
+ /** @type {Record<string, number>} */
275
+ const byDay = {};
276
+ /** @type {Record<string, number>} */
277
+ const byConfidence = {};
278
+ let total = 0;
279
+ try {
280
+ const text = await readFile(advicePath, "utf8");
281
+ for (const line of text.split("\n")) {
282
+ if (line.trim() === "") continue;
283
+ let entry;
284
+ try {
285
+ entry = JSON.parse(line);
286
+ } catch {
287
+ continue;
288
+ }
289
+ total += 1;
290
+ const severity = String(entry?.severity ?? "nit");
291
+ const model = String(entry?.model ?? "unknown");
292
+ const day = typeof entry?.at === "string" ? entry.at.slice(0, 10) : "unknown";
293
+ const confidence = String(entry?.confidence ?? "low");
294
+ bySeverity[severity] = (bySeverity[severity] ?? 0) + 1;
295
+ byModel[model] = (byModel[model] ?? 0) + 1;
296
+ byDay[day] = (byDay[day] ?? 0) + 1;
297
+ byConfidence[confidence] = (byConfidence[confidence] ?? 0) + 1;
298
+ }
299
+ } catch (error) {
300
+ const code = /** @type {any} */ (error)?.code;
301
+ if (code !== "ENOENT") options.logger?.warn?.(`[advisor] 读建议账本失败:${String(error)}`);
302
+ }
303
+ return { total, bySeverity, byModel, byDay, byConfidence };
304
+ },
305
+
241
306
  /** 首次读取时恢复「今日花费」与累计数(调用方不必 await,失败静默)。 */
242
307
  ready() {
243
308
  return ensureLoaded();
package/lib/prompt.js CHANGED
@@ -83,6 +83,25 @@ export const ADVISOR_SYSTEM_PROMPT = [
83
83
  "- Answer in the language the user is using in the transcript.",
84
84
  ].join("\n");
85
85
 
86
+ /**
87
+ * 按配置返回系统提示:开启「证据复核」时允许顾问请求读文件。
88
+ * @param {{ canRequestEvidence?: boolean }} [options]
89
+ * @returns {string}
90
+ */
91
+ export function advisorSystemPrompt(options = {}) {
92
+ if (options.canRequestEvidence !== true) return ADVISOR_SYSTEM_PROMPT;
93
+ return [
94
+ ADVISOR_SYSTEM_PROMPT,
95
+ "",
96
+ "You can and SHOULD request workspace evidence before finalizing whenever your advice depends on",
97
+ "what a file actually contains (a version, a config value, an implementation detail). Add a top-level field:",
98
+ `"needs": [{"kind":"file","ref":"relative/path"}]`,
99
+ "Only relative paths inside the session working directory are readable; at most 5 files, 64 KiB each.",
100
+ "You will then be called once more with those files quoted verbatim, and may revise your advice.",
101
+ "If you already have the text in the transcript, do not request it again.",
102
+ ].join("\n");
103
+ }
104
+
86
105
  /**
87
106
  * 每次调用新 mint 一个边界 nonce:让证据里引用的句子无法冒充分隔符。
88
107
  * @returns {string}
@@ -207,6 +226,7 @@ function normalizeEvidence(raw) {
207
226
  * @property {string[]} risks
208
227
  * @property {string[]} acceptance
209
228
  * @property {Array<{ kind: string, ref: string }>} evidence
229
+ * @property {Array<{ kind: string, ref: string }>} needs
210
230
  */
211
231
 
212
232
  /**
@@ -244,6 +264,7 @@ export function parseAdvice(raw) {
244
264
  risks: normalizeList(parsed.risks),
245
265
  acceptance: normalizeList(parsed.acceptance),
246
266
  evidence: normalizeEvidence(parsed.evidence),
267
+ needs: normalizeEvidence(parsed.needs),
247
268
  },
248
269
  };
249
270
  }
package/lib/route.js CHANGED
@@ -4,6 +4,8 @@
4
4
  // DSH 没有厂商那种「模型能力目录」,所以档位只能来自用户声明(settings.tiers)。
5
5
  // 拿不到档位时**不阻断**、也不假装通过:返回 kind:"unknown",由 UI 明示「未校验」。
6
6
 
7
+ import { effectiveRank } from "./catalog.js";
8
+
7
9
  /**
8
10
  * @typedef {{ provider: string, model: string, reasoningEffort?: string }} Route
9
11
  */
@@ -74,8 +76,9 @@ export function pairingCheck(input) {
74
76
  const { tiers, main, advisor } = input;
75
77
  const enforcement = input.enforcement === "block" ? "block" : "warn";
76
78
 
77
- const mainRank = tierOf(tiers, main);
78
- const advisorRank = tierOf(tiers, advisor);
79
+ // 用户声明的档位优先;没有声明时回落内置目录(catalog.js);都没有才算「未校验」。
80
+ const mainRank = effectiveRank(tiers, main);
81
+ const advisorRank = effectiveRank(tiers, advisor);
79
82
 
80
83
  if (mainRank === undefined || advisorRank === undefined) {
81
84
  return {