@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.
@@ -0,0 +1,106 @@
1
+ // @ts-check
2
+ // 数据根下的两种写盘原语:**单行追加**与**整份原子替换**。
3
+ //
4
+ // 为什么单独一个模块(审计 AUD-ADV-01 / 02 / §4):
5
+ // - 盘上数据的正确性只取决于两件事:一次写要么完整、要么不发生;同一文件的写者要排队。
6
+ // `readFile` 后 `writeFile` 覆盖是最坏组合(既非原子、又把并发读到的旧内容写回去)。
7
+ // - btw 的 history/settings 与 advisor 的 budget/settings 各自实现过一版 temp+rename,
8
+ // 再复制第三次就会漂移,所以这里收敛成一份。
9
+ //
10
+ // 取舍:
11
+ // - 追加用 `appendFile`(POSIX O_APPEND,单行 <4 KiB 的写入不会被撕开);崩溃最多留下
12
+ // 最后一行半截,读取侧本来就跳过坏行。
13
+ // - 整份替换用「同目录唯一 tmp + rename」:rename 在同一文件系统内是原子的。
14
+ // - 进程内用 per-path 串行队列;跨进程没有锁(同一数据根只该有一个宿主进程,README 已写明)。
15
+
16
+ import { randomBytes } from "node:crypto";
17
+ import { appendFile, mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
18
+ import { dirname } from "node:path";
19
+
20
+ /** per-path 串行队列的尾巴(值总是已 settle 的 promise,不会把错误传下去)。 */
21
+ /** @type {Map<string, Promise<void>>} */
22
+ const TAILS = new Map();
23
+
24
+ /**
25
+ * 同一个 path 上的任务按提交顺序串行执行(进程内 single-flight)。
26
+ * 前一个任务失败不会阻塞后一个;失败会照常传回给各自的调用方。
27
+ * @template T
28
+ * @param {string} path
29
+ * @param {() => Promise<T>} task
30
+ * @returns {Promise<T>}
31
+ */
32
+ export function serializeByPath(path, task) {
33
+ const previous = TAILS.get(path) ?? Promise.resolve();
34
+ const run = previous.then(task, task);
35
+ /** @type {Promise<void>} */
36
+ const tail = run.then(
37
+ () => {},
38
+ () => {},
39
+ );
40
+ TAILS.set(path, tail);
41
+ void tail.then(() => {
42
+ if (TAILS.get(path) === tail) TAILS.delete(path);
43
+ });
44
+ return run;
45
+ }
46
+
47
+ /**
48
+ * 原子替换整份文件内容。
49
+ * @param {string} path
50
+ * @param {string} text
51
+ * @returns {Promise<void>}
52
+ */
53
+ export async function writeTextAtomic(path, text) {
54
+ await mkdir(dirname(path), { recursive: true });
55
+ const temp = `${path}.${process.pid}.${randomBytes(6).toString("hex")}.tmp`;
56
+ try {
57
+ await writeFile(temp, text, "utf8");
58
+ await rename(temp, path);
59
+ } catch (error) {
60
+ await rm(temp, { force: true }).catch(() => {});
61
+ throw error;
62
+ }
63
+ }
64
+
65
+ /**
66
+ * 追加一行 JSON(整份文件的写者排队,避免「读全文 + 覆盖」丢行)。
67
+ * @param {string} path
68
+ * @param {unknown} value
69
+ * @param {{ rotateBytes?: number, rotateTo?: string }} [options] 超过 rotateBytes 时先改名到 rotateTo(默认 `${path}.1`)
70
+ * @returns {Promise<void>}
71
+ */
72
+ export function appendJsonLine(path, value, options = {}) {
73
+ return serializeByPath(path, async () => {
74
+ await mkdir(dirname(path), { recursive: true });
75
+ const rotateBytes = Number(options.rotateBytes ?? 0) || 0;
76
+ if (rotateBytes > 0) {
77
+ const info = await stat(path).catch(() => undefined);
78
+ if (info !== undefined && info.size > rotateBytes) {
79
+ // 滚动失败(例如目标已存在且平台不允许覆盖)不该让本次记录丢掉:继续往旧文件追加。
80
+ await rename(path, options.rotateTo ?? `${path}.1`).catch(() => {});
81
+ }
82
+ }
83
+ await appendFile(path, `${JSON.stringify(value)}\n`, "utf8");
84
+ });
85
+ }
86
+
87
+ /**
88
+ * 读一份「一行一个 JSON」的文件;坏行跳过、文件不存在返回空数组。
89
+ * @param {string} path
90
+ * @returns {Promise<any[]>}
91
+ */
92
+ export async function readJsonLines(path) {
93
+ const text = await readFile(path, "utf8").catch(() => "");
94
+ /** @type {any[]} */
95
+ const out = [];
96
+ for (const line of text.split("\n")) {
97
+ if (line.trim() === "") continue;
98
+ try {
99
+ const parsed = JSON.parse(line);
100
+ if (parsed !== null && typeof parsed === "object") out.push(parsed);
101
+ } catch (_error) {
102
+ /* 跳过坏行:一行脏数据不该毁掉整份账本 */
103
+ }
104
+ }
105
+ return out;
106
+ }
package/lib/guard.js CHANGED
@@ -67,9 +67,9 @@ export function immuneActive(input) {
67
67
 
68
68
  /**
69
69
  * @typedef {object} BudgetCounters
70
- * @property {number} turnCalls 本回合已徵询次数
71
- * @property {number} sessionCalls 本会话已徵询次数
72
- * @property {number[]} hourStamps 最近一小时内的徵询时间戳(毫秒)
70
+ * @property {number} turnCalls 本回合已征询次数
71
+ * @property {number} sessionCalls 本会话已征询次数
72
+ * @property {number[]} hourStamps 最近一小时内的征询时间戳(毫秒)
73
73
  * @property {number} dayCostUsd 今日已花(美元,估算值)
74
74
  */
75
75
 
@@ -84,8 +84,13 @@ export function immuneActive(input) {
84
84
  /**
85
85
  * 四级预算检查。返回**第一个**不满足的条件(顺序固定,便于测试与文案稳定)。
86
86
  * 每个字段为 0 都表示「不限制」。
87
+ *
88
+ * 日预算的拒绝有两种成因:已花达到上限,或「已花 + 本次预估」会达到上限。返回里带上
89
+ * `estimatedCostUsd`,调用方才能给出不误导的文案(复审 F4)。
87
90
  * @param {BudgetInput} input
88
- * @returns {{ ok: true } | { ok: false, code: "turn_limit"|"session_limit"|"hour_limit"|"day_budget", limit: number, used: number }}
91
+ * @returns {{ ok: true }
92
+ * | { ok: false, code: "turn_limit"|"session_limit"|"hour_limit", limit: number, used: number }
93
+ * | { ok: false, code: "day_budget", limit: number, used: number, estimatedCostUsd: number }}
89
94
  */
90
95
  export function checkBudget(input) {
91
96
  const { settings, counters, now, estimatedCostUsd = 0 } = input;
@@ -114,13 +119,17 @@ export function checkBudget(input) {
114
119
  }
115
120
  }
116
121
  // 设置里的限额按 settings.currency 填写;比较前先换算成 USD。
122
+ // 边界口径与工作区池一致:**已达上限就拒绝**(`>=`),`estimatedCostUsd` 让「这一笔会顶到」
123
+ // 在发送前就被拦下(审计 AUD-ADV-11 / 12)。
117
124
  const maxCostUsd = toUsd(settings.maxCostPerDay, settings.currency, settings.usdToCny);
118
- if (maxCostUsd > 0 && counters.dayCostUsd + estimatedCostUsd > maxCostUsd) {
125
+ if (maxCostUsd > 0 && counters.dayCostUsd + estimatedCostUsd >= maxCostUsd) {
119
126
  return {
120
127
  ok: false,
121
128
  code: "day_budget",
122
129
  limit: maxCostUsd,
123
130
  used: counters.dayCostUsd,
131
+ // 拒绝可能只是「这一笔会顶到」,账上未必已花完 —— 带上预估供文案区分(复审 F4)。
132
+ estimatedCostUsd,
124
133
  };
125
134
  }
126
135
  return { ok: true };
package/lib/ledger.js CHANGED
@@ -2,10 +2,15 @@
2
2
  // 账本:宿主**不**给额外模型调用记 usage(只有主循环写 assistant/message 的 usage),
3
3
  // 所以顾问花了多少 token 必须由我们自己记账。这里同时是四级预算的计数器来源。
4
4
  //
5
- // 落盘:`<dataRoot>/advisor/usage.jsonl`,一次徵询一行;文件只追加,超过上限时滚动重命名。
6
- import { mkdir, readFile, rename, stat, writeFile } from "node:fs/promises";
5
+ // 落盘:`<dataRoot>/advisor/usage.jsonl`,一次征询一行;文件只追加,超过上限时滚动重命名。
6
+ // 追加走 `appendJsonLine`(O_APPEND + 进程内单写队列),不再「读全文 + 覆盖」——
7
+ // 后者既不是原子写,并发回合结束时还会互相覆盖丢行(审计 AUD-ADV-01)。
8
+ import { mkdir, readFile, stat } from "node:fs/promises";
7
9
  import { join } from "node:path";
8
10
 
11
+ import { dayKey, dayOfEntry } from "./day.js";
12
+ import { appendJsonLine } from "./fs-atomic.js";
13
+
9
14
  /** 账本目录名(位于数据根下)。 */
10
15
  export const LEDGER_DIR = "advisor";
11
16
  /** 账本文件名。 */
@@ -18,6 +23,7 @@ export const LEDGER_MAX_BYTES = 2 * 1024 * 1024;
18
23
  /**
19
24
  * @typedef {object} LedgerEntry
20
25
  * @property {string} at ISO 时间
26
+ * @property {string} [day] 本地日键 YYYY-MM-DD(写入时补;旧数据没有,读取时从 at 折算)
21
27
  * @property {string} sessionId
22
28
  * @property {"tool"|"shadow"|"manual"|"post-answer"} trigger
23
29
  * @property {string} provider
@@ -45,15 +51,13 @@ export const LEDGER_MAX_BYTES = 2 * 1024 * 1024;
45
51
  */
46
52
 
47
53
  /**
48
- * 本地日键,用于「每日预算」跨重启续算。
49
- * @param {Date} [date]
50
- * @returns {string}
54
+ * 一条新账本行补上本地日键;已有 `day` 的记录原样返回。
55
+ * @param {LedgerEntry} entry
56
+ * @returns {LedgerEntry}
51
57
  */
52
- export function dayKey(date = new Date()) {
53
- const year = date.getFullYear();
54
- const month = `${date.getMonth() + 1}`.padStart(2, "0");
55
- const day = `${date.getDate()}`.padStart(2, "0");
56
- return `${year}-${month}-${day}`;
58
+ function withDay(entry) {
59
+ const day = dayOfEntry(entry) || dayKey();
60
+ return day === entry.day ? entry : { ...entry, day };
57
61
  }
58
62
 
59
63
  /**
@@ -64,7 +68,6 @@ export function dayKey(date = new Date()) {
64
68
  * noteCall: (sessionId: string, input: { turn: number, costUsd: number, at: number }) => void,
65
69
  * resetTurn: (sessionId: string, turn: number) => void,
66
70
  * totals: () => { calls: number, inputTokens: number, outputTokens: number, cacheReadTokens: number, cacheWriteTokens: number, costUsd: number, byTrigger: Record<string, number> },
67
- * recent: (limit?: number) => LedgerEntry[],
68
71
  * ready: () => Promise<void>,
69
72
  * recordAdvice: (entry: any) => Promise<void>,
70
73
  * adviceTotals: () => Promise<{ total: number, bySeverity: Record<string, number>, byModel: Record<string, number>, byDay: Record<string, number>, byConfidence: Record<string, number> }>,
@@ -77,8 +80,6 @@ export function createLedger(options) {
77
80
  const path = join(dir, LEDGER_FILE);
78
81
  /** @type {Map<string, SessionCounters>} */
79
82
  const countersBySession = new Map();
80
- /** @type {LedgerEntry[]} */
81
- const recent = [];
82
83
  /** @type {{ calls: number, inputTokens: number, outputTokens: number, cacheReadTokens: number, cacheWriteTokens: number, costUsd: number, byTrigger: Record<string, number> }} */
83
84
  const totals = {
84
85
  calls: 0,
@@ -91,7 +92,40 @@ export function createLedger(options) {
91
92
  };
92
93
  let loaded = false;
93
94
 
94
- /** 读历史账本,恢复「今日花费」与累计数(只读尾部 2MB,避免大文件拖慢启动)。 */
95
+ /**
96
+ * 取某会话的计数器(惰性初始化;跨日自动清零当日花费)。
97
+ * @param {string} sessionId
98
+ * @param {number} [now]
99
+ * @returns {SessionCounters}
100
+ */
101
+ const counters = (sessionId, now = Date.now()) => {
102
+ const today = dayKey(new Date(now));
103
+ let current = countersBySession.get(sessionId);
104
+ if (current === undefined) {
105
+ current = {
106
+ turn: 0,
107
+ turnCalls: 0,
108
+ sessionCalls: 0,
109
+ hourStamps: [],
110
+ dayCostUsd: 0,
111
+ dayKey: today,
112
+ };
113
+ countersBySession.set(sessionId, current);
114
+ }
115
+ if (current.dayKey !== today) {
116
+ current.dayCostUsd = 0;
117
+ current.dayKey = today;
118
+ }
119
+ const hourAgo = now - 60 * 60 * 1000;
120
+ current.hourStamps = current.hourStamps.filter((at) => at > hourAgo);
121
+ return current;
122
+ };
123
+
124
+ /**
125
+ * 读历史账本,恢复累计数、**会话级调用数**、**最近一小时时间戳**与今日花费
126
+ * (只读尾部 2MB,避免大文件拖慢启动;更早的历史不参与这几级计数器)。
127
+ * 回合内计数(turnCalls)不恢复:它的生命周期就是一个回合,重启即新的回合。
128
+ */
95
129
  const ensureLoaded = async () => {
96
130
  if (loaded) return;
97
131
  loaded = true;
@@ -101,6 +135,7 @@ export function createLedger(options) {
101
135
  const text = await readFile(path, "utf8");
102
136
  const tail = start > 0 ? text.slice(text.lastIndexOf("\n", start) + 1) : text;
103
137
  const today = dayKey();
138
+ const hourAgo = Date.now() - 60 * 60 * 1000;
104
139
  for (const line of tail.split("\n")) {
105
140
  if (line.trim() === "") continue;
106
141
  /** @type {any} */
@@ -123,12 +158,9 @@ export function createLedger(options) {
123
158
  totals.costUsd += cost;
124
159
  const trigger = typeof entry.trigger === "string" ? entry.trigger : "tool";
125
160
  totals.byTrigger[trigger] = (totals.byTrigger[trigger] ?? 0) + 1;
126
- if (recent.length < 50) recent.push(entry);
127
161
  const sessionId = typeof entry.sessionId === "string" ? entry.sessionId : "";
128
162
  if (sessionId === "") continue;
129
- const day = typeof entry.at === "string" ? entry.at.slice(0, 10) : "";
130
- if (day !== today) continue;
131
- const counters = countersBySession.get(sessionId) ?? {
163
+ const current = countersBySession.get(sessionId) ?? {
132
164
  turn: 0,
133
165
  turnCalls: 0,
134
166
  sessionCalls: 0,
@@ -136,8 +168,13 @@ export function createLedger(options) {
136
168
  dayCostUsd: 0,
137
169
  dayKey: today,
138
170
  };
139
- counters.dayCostUsd += cost;
140
- countersBySession.set(sessionId, counters);
171
+ current.sessionCalls += 1;
172
+ const at = Date.parse(typeof entry.at === "string" ? entry.at : "");
173
+ if (Number.isFinite(at) && at > hourAgo) current.hourStamps.push(at);
174
+ // 日键优先用行里的 day(本地日),旧行回落到 at 的本地日期(审计 AUD-ADV-04)。
175
+ if (dayOfEntry(entry) === today) current.dayCostUsd += cost;
176
+ current.dayKey = today;
177
+ countersBySession.set(sessionId, current);
141
178
  }
142
179
  } catch (error) {
143
180
  const code = /** @type {any} */ (error)?.code;
@@ -145,35 +182,6 @@ export function createLedger(options) {
145
182
  }
146
183
  };
147
184
 
148
- /**
149
- * 取某会话的计数器(惰性初始化;跨日自动清零当日花费)。
150
- * @param {string} sessionId
151
- * @param {number} [now]
152
- * @returns {SessionCounters}
153
- */
154
- const counters = (sessionId, now = Date.now()) => {
155
- const today = dayKey(new Date(now));
156
- let current = countersBySession.get(sessionId);
157
- if (current === undefined) {
158
- current = {
159
- turn: 0,
160
- turnCalls: 0,
161
- sessionCalls: 0,
162
- hourStamps: [],
163
- dayCostUsd: 0,
164
- dayKey: today,
165
- };
166
- countersBySession.set(sessionId, current);
167
- }
168
- if (current.dayKey !== today) {
169
- current.dayCostUsd = 0;
170
- current.dayKey = today;
171
- }
172
- const hourAgo = now - 60 * 60 * 1000;
173
- current.hourStamps = current.hourStamps.filter((at) => at > hourAgo);
174
- return current;
175
- };
176
-
177
185
  const advicePath = join(dir, ADVICE_FILE);
178
186
 
179
187
  return {
@@ -181,13 +189,11 @@ export function createLedger(options) {
181
189
  advicePath,
182
190
 
183
191
  /**
184
- * 记录一次徵询(先落盘再更新内存;落盘失败不让调用失败)。
192
+ * 记录一次征询(先落盘再更新内存;落盘失败不让调用失败)。
185
193
  * @param {LedgerEntry} entry
186
194
  * @returns {Promise<void>}
187
195
  */
188
196
  async record(entry) {
189
- recent.unshift(entry);
190
- if (recent.length > 50) recent.pop();
191
197
  totals.calls += 1;
192
198
  totals.inputTokens += entry.inputTokens;
193
199
  totals.outputTokens += entry.outputTokens;
@@ -197,17 +203,10 @@ export function createLedger(options) {
197
203
  totals.byTrigger[entry.trigger] = (totals.byTrigger[entry.trigger] ?? 0) + 1;
198
204
 
199
205
  try {
200
- await mkdir(dir, { recursive: true });
201
- const info = await stat(path).catch(() => undefined);
202
- if (info && info.size > LEDGER_MAX_BYTES) {
203
- await rename(path, `${path}.1`).catch(() => undefined);
204
- }
205
- const line = `${JSON.stringify(entry)}\n`;
206
- const existing =
207
- info && info.size <= LEDGER_MAX_BYTES ? await readFile(path, "utf8").catch(() => "") : "";
208
- const next = `${existing}${line}`;
209
- // 一次性重写而不是 append:保证写入原子性(账本比吞吐重要)。
210
- await writeFile(path, next, "utf8");
206
+ await appendJsonLine(path, withDay(entry), {
207
+ rotateBytes: LEDGER_MAX_BYTES,
208
+ rotateTo: `${path}.1`,
209
+ });
211
210
  } catch (error) {
212
211
  options.logger?.warn?.(`[advisor] 写账本失败:${String(error)}`);
213
212
  }
@@ -253,25 +252,14 @@ export function createLedger(options) {
253
252
  },
254
253
 
255
254
  /**
256
- * 最近若干条(新→旧)。
257
- * @param {number} [limit]
258
- * @returns {LedgerEntry[]}
259
- */
260
- recent(limit = 10) {
261
- return recent.slice(0, Math.max(0, limit));
262
- },
263
-
264
- /**
265
- * 追加一条建议到跨会话账本(失败只告警,不影响徵询)。
255
+ * 追加一条建议到跨会话账本(失败只告警,不影响征询)。
266
256
  * @param {any} entry
267
257
  * @returns {Promise<void>}
268
258
  */
269
259
  async recordAdvice(entry) {
270
260
  try {
271
261
  await mkdir(dir, { recursive: true });
272
- const line = `${JSON.stringify(entry)}\n`;
273
- const existing = await readFile(advicePath, "utf8").catch(() => "");
274
- await writeFile(advicePath, `${existing}${line}`, "utf8");
262
+ await appendJsonLine(advicePath, withDay(entry));
275
263
  } catch (error) {
276
264
  options.logger?.warn?.(`[advisor] 写建议账本失败:${String(error)}`);
277
265
  }
@@ -304,7 +292,7 @@ export function createLedger(options) {
304
292
  total += 1;
305
293
  const severity = String(entry?.severity ?? "nit");
306
294
  const model = String(entry?.model ?? "unknown");
307
- const day = typeof entry?.at === "string" ? entry.at.slice(0, 10) : "unknown";
295
+ const day = dayOfEntry(entry) || "unknown";
308
296
  const confidence = String(entry?.confidence ?? "low");
309
297
  bySeverity[severity] = (bySeverity[severity] ?? 0) + 1;
310
298
  byModel[model] = (byModel[model] ?? 0) + 1;
@@ -0,0 +1,108 @@
1
+ // @ts-check
2
+ // 宿主半文案:从包内 `locale/<lang>.json` 的 `host.*` 段加载,摊平成平面键后使用。
3
+ //
4
+ // 为什么 host 半要自己读 JSON(docs/runtime/0.2.2-rc.5.md §8.1 实测):
5
+ // - 宿主**没有** locale 服务:`ctx.locale` 只在 client 半,`commands.register()` 的
6
+ // `description` / `input.hint` 由宿主逐字透传,不会翻译;
7
+ // - `locale/*.json` 在宿主眼里只是插件展示元数据(只读 `meta.title` / `meta.description`),
8
+ // 既不会注册成字典,也没有「嵌套 → 扁平」的归一化。
9
+ // 参考实现:btw 0.6.1(`packages/btw/lib/messages.js`,同一宿主结论)。
10
+ //
11
+ // 文件布局约定(`locale/zh.json` / `locale/en.json`):
12
+ // { "advisor": { ...client 字典(扁平点号键)... }, "host": { "command.description": ..., "command.hint": ... } }
13
+ // 两个段分开:client 的 locale-parity 测试只比对 `advisor` 段的键集,host 段由本模块测。
14
+ import { readFileSync } from "node:fs";
15
+ import { readFile } from "node:fs/promises";
16
+ import { join } from "node:path";
17
+
18
+ /**
19
+ * 缺翻译时的英文兜底(也是 `test/messages.test.js` 的键集事实来源)。
20
+ * 缺一不可:注册 `commands.register()` 拿到 `undefined` 会被宿主拒收。
21
+ * @type {Record<"description" | "hint", string>}
22
+ */
23
+ export const FALLBACK = Object.freeze({
24
+ description: "Consult the advisor: status, choose a model, ask now, or turn it off",
25
+ hint: "[status|on|off|shadow|ask|cancel|report|doctor|confirm|preview|<provider>/<model>]",
26
+ });
27
+
28
+ /**
29
+ * `locale/<lang>.json` 里 host 段 → 平面键(与 {@link FALLBACK} 一一对应)。
30
+ * @type {Record<"description" | "hint", string>}
31
+ */
32
+ export const HOST_KEYS = Object.freeze({
33
+ description: "host.command.description",
34
+ hint: "host.command.hint",
35
+ });
36
+
37
+ /**
38
+ * 把嵌套字典摊平成点号键(只保留字符串叶子)。
39
+ * @param {any} table
40
+ * @param {string} [prefix]
41
+ * @returns {Record<string, string>}
42
+ */
43
+ export function flattenMessages(table, prefix = "") {
44
+ /** @type {Record<string, string>} */
45
+ const out = {};
46
+ if (table === null || typeof table !== "object") return out;
47
+ for (const [key, value] of Object.entries(table)) {
48
+ const path = prefix === "" ? key : `${prefix}.${key}`;
49
+ if (typeof value === "string") out[path] = value;
50
+ else if (value !== null && typeof value === "object") {
51
+ Object.assign(out, flattenMessages(value, path));
52
+ }
53
+ }
54
+ return out;
55
+ }
56
+
57
+ /**
58
+ * 把 locale 文件的原始 JSON 映射成 host 半可用的平面字典。
59
+ * 兼容两种写法:带 `host` 段的嵌套结构(当前文件)与已经是平面键的字典。
60
+ * @param {any} raw
61
+ * @returns {Partial<Record<"description" | "hint", string>>}
62
+ */
63
+ export function mapMessages(raw) {
64
+ const flat = flattenMessages(raw);
65
+ /** @type {Partial<Record<"description" | "hint", string>>} */
66
+ const out = {};
67
+ for (const key of /** @type {Array<"description" | "hint">} */ (Object.keys(HOST_KEYS))) {
68
+ const value = flat[HOST_KEYS[key]] ?? flat[key];
69
+ if (typeof value === "string" && value.trim() !== "") out[key] = value;
70
+ }
71
+ return out;
72
+ }
73
+
74
+ /**
75
+ * 异步读取某语言的 host 文案。
76
+ * @param {string} localeDir
77
+ * @param {"en" | "zh"} language
78
+ * @returns {Promise<Partial<Record<"description" | "hint", string>>>}
79
+ */
80
+ export async function loadMessages(localeDir, language) {
81
+ const raw = await readFile(join(localeDir, `${language}.json`), "utf8");
82
+ return mapMessages(JSON.parse(raw));
83
+ }
84
+
85
+ /**
86
+ * 同步版本:host 半在注册 `/advisor` 命令**之前**就要拿到文案(宿主的 description
87
+ * 是注册时的字面量,之后不会再翻译),所以激活期同步读;locale 文件只有几 KB。
88
+ * @param {string} localeDir
89
+ * @param {"en" | "zh"} language
90
+ * @returns {Partial<Record<"description" | "hint", string>>}
91
+ */
92
+ export function loadMessagesSync(localeDir, language) {
93
+ const raw = readFileSync(join(localeDir, `${language}.json`), "utf8");
94
+ return mapMessages(JSON.parse(raw));
95
+ }
96
+
97
+ /**
98
+ * 选语言:显式配置(插件 config.language)优先,否则看系统语言是否中文。
99
+ * 与 btw 0.6.1 的判据一致:桌面版在中文环境里实测会走 zh(runtime §8.2)。
100
+ * @param {unknown} configured
101
+ * @param {Record<string, string | undefined>} [env]
102
+ * @returns {"en" | "zh"}
103
+ */
104
+ export function pickLanguage(configured, env = process.env) {
105
+ if (configured === "zh" || configured === "en") return configured;
106
+ const hint = `${env?.LANG ?? ""} ${env?.LC_ALL ?? ""} ${env?.LANGUAGE ?? ""}`;
107
+ return /zh|cn/i.test(hint) ? "zh" : "en";
108
+ }
package/lib/redact.js CHANGED
@@ -46,11 +46,24 @@ export const RULES = [
46
46
  pattern: /\b(Authorization\s*:\s*(?:Bearer|Basic|Token)\s+)[A-Za-z0-9._~+/=-]{8,}/giu,
47
47
  replacement: "$1***REDACTED***",
48
48
  },
49
- // KEY=value / KEY: value / --flag value 形态
49
+ // 裸 Bearer token(没有 Authorization 头前缀的形态,例如日志里的 "Bearer abc…")
50
+ {
51
+ id: "bearer-token",
52
+ pattern: /\b(Bearer\s+)[A-Za-z0-9._~+/=-]{16,}/giu,
53
+ replacement: "$1***REDACTED***",
54
+ },
55
+ // JWT(三段 base64url,`eyJ` 是 `{"` 的 base64 前缀)
56
+ {
57
+ id: "jwt",
58
+ pattern: /\beyJ[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\.[A-Za-z0-9_-]{6,}\b/gu,
59
+ replacement: "eyJ***REDACTED***",
60
+ },
61
+ // KEY=value / KEY: value 形态。键名**不区分大小写**:`api_key=`、`token:`、`apiKey:`、
62
+ // `password=` 这些常见小写/驼峰写法以前全漏(审计 AUD-ADV-13)。
50
63
  {
51
64
  id: "kv-assignment",
52
65
  pattern:
53
- /\b((?:[A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL|PRIVATE)[A-Z0-9_]*)\s*[=:]\s*)(?:"[^"\n]{6,}"|'[^'\n]{6,}'|[^\s,;]{6,})/gu,
66
+ /\b((?:[A-Z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL|PRIVATE)[A-Z0-9_]*)\s*[=:]\s*)(?:"[^"\n]{6,}"|'[^'\n]{6,}'|[^\s,;]{6,})/giu,
54
67
  replacement: "$1***REDACTED***",
55
68
  },
56
69
  // URL 里的凭据 user:pass@host