@kangyishuai/dsh-advisor 0.6.1 → 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/README.md +94 -72
- package/README.zh-CN.md +107 -79
- package/lib/abort-reason.js +29 -0
- package/lib/adoption.js +12 -3
- package/lib/budget.js +36 -33
- package/lib/call.js +45 -11
- package/lib/client.js +381 -80
- package/lib/command-text.js +125 -0
- package/lib/day.js +44 -0
- package/lib/deadline.js +94 -0
- package/lib/decisions.js +162 -75
- package/lib/fs-atomic.js +106 -0
- package/lib/guard.js +14 -5
- package/lib/ledger.js +65 -77
- package/lib/messages.js +108 -0
- package/lib/redact.js +15 -2
- package/lib/service.js +197 -139
- package/lib/settings.js +2 -2
- package/lib/tool-result.js +46 -0
- package/lib/tool-schema.js +4 -2
- package/lib/transcript.js +1 -1
- package/locale/en.json +17 -1
- package/locale/zh.json +24 -8
- package/package.json +1 -1
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// `/advisor` 命令输出的文案规则(纯函数,单测可直接导入)。
|
|
3
|
+
//
|
|
4
|
+
// 为什么单独成文件:service.js 一开头就 import 宿主包(`@deepseek-ai/dsh-session` 等),
|
|
5
|
+
// 单测环境解析不到,命令文案就只能靠人肉回归。审计 USIM-U2-07 / USIM-U2-08 的修复
|
|
6
|
+
// 全部落在这几个字符串规则上,所以抽出来测。
|
|
7
|
+
//
|
|
8
|
+
// 两条宿主事实(docs/runtime/0.2.2-rc.5.md §5.2 / 本地 `app.asar` 内的
|
|
9
|
+
// `dsh-client-ui-chat/src/client/chat/GenericCommandCard.tsx`):
|
|
10
|
+
// 1. 通用命令卡片只显示 `node.name`(= `advisor`),**不显示用户敲的子命令**;
|
|
11
|
+
// 单行 summary 会被 CSS 省略号截断,多行正文要点开卡片第二层折叠才看得见。
|
|
12
|
+
// 2. 命令节点被宿主 Chat 的分组逻辑放进可折叠的 process 块(标题固定是「已完成分析」),
|
|
13
|
+
// 插件没有办法把节点移出分组。所以插件自己的命令卡片必须把「原始命令行 + 多行正文」
|
|
14
|
+
// 一次给全,并且回执(shell.overlay)不依赖分组是否展开。
|
|
15
|
+
|
|
16
|
+
/** 命令名(注册与回显共用一处,避免两处漂移)。 */
|
|
17
|
+
export const COMMAND_NAME = "advisor";
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* 把用户实际敲的参数拼回命令行。宿主的 `command/run.args` 是 `rawInput` 原文
|
|
21
|
+
* (含分隔空白),这里统一 trim 后只留一个空格。
|
|
22
|
+
* @param {unknown} rawInput
|
|
23
|
+
* @returns {string} 形如 `/advisor status`
|
|
24
|
+
*/
|
|
25
|
+
export function commandEcho(rawInput) {
|
|
26
|
+
const raw = typeof rawInput === "string" ? rawInput.trim() : "";
|
|
27
|
+
return raw === "" ? `/${COMMAND_NAME}` : `/${COMMAND_NAME} ${raw}`;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* 命令回执文本:第一行永远是原始命令行,正文原样保留(不做折行/截断)。
|
|
32
|
+
* 这样即使只看 `command/done.data.text`(会话日志、宿主的通用卡片、冒烟脚本),
|
|
33
|
+
* 也能知道用户执行了哪条命令。
|
|
34
|
+
* @param {unknown} rawInput
|
|
35
|
+
* @param {unknown} text
|
|
36
|
+
* @returns {string}
|
|
37
|
+
*/
|
|
38
|
+
export function commandReply(rawInput, text) {
|
|
39
|
+
const echo = commandEcho(rawInput);
|
|
40
|
+
const body = typeof text === "string" ? text.trim() : "";
|
|
41
|
+
return body === "" ? echo : `${echo}\n${body}`;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* 保存态 → 真实生效态。
|
|
46
|
+
*
|
|
47
|
+
* 与宿主 `runAdvisor` 的判据保持一致(service.js 里先判 mode、再判是否配置了模型):
|
|
48
|
+
* - `mode === "off"` → 关闭,原因是模式;
|
|
49
|
+
* - 没有 provider/model → 关闭,原因是未选择模型(即使保存的 mode 是 advisory);
|
|
50
|
+
* - `mode === "shadow"` → 影子:照常调用并记账,但建议不回灌给模型;
|
|
51
|
+
* - 其余 → 正常生效。
|
|
52
|
+
* @param {any} settings
|
|
53
|
+
* @returns {{ effective: "on" | "shadow" | "off", reason: "mode" | "unconfigured" | null }}
|
|
54
|
+
*/
|
|
55
|
+
export function effectiveStateOf(settings) {
|
|
56
|
+
const mode = settings?.mode === "advisory" || settings?.mode === "shadow" ? settings.mode : "off";
|
|
57
|
+
const provider = typeof settings?.provider === "string" ? settings.provider.trim() : "";
|
|
58
|
+
const model = typeof settings?.model === "string" ? settings.model.trim() : "";
|
|
59
|
+
const configured = provider !== "" && model !== "";
|
|
60
|
+
if (mode === "off") return { effective: "off", reason: "mode" };
|
|
61
|
+
if (!configured) return { effective: "off", reason: "unconfigured" };
|
|
62
|
+
if (mode === "shadow") return { effective: "shadow", reason: null };
|
|
63
|
+
return { effective: "on", reason: null };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* 生效状态的一行中文(`/advisor status` 与设置页共用同一套判据)。
|
|
68
|
+
* @param {{ effective: "on" | "shadow" | "off", reason: "mode" | "unconfigured" | null }} state
|
|
69
|
+
* @returns {string}
|
|
70
|
+
*/
|
|
71
|
+
export function effectiveLine(state) {
|
|
72
|
+
if (state.effective === "on") return "已生效:会征询顾问";
|
|
73
|
+
if (state.effective === "shadow") return "影子模式:只记账,不回灌建议";
|
|
74
|
+
return state.reason === "unconfigured" ? "已关闭:未选择顾问模型" : "已关闭:模式为 off";
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* `/advisor status` 的正文(不含第一行命令回显,由 {@link commandReply} 加)。
|
|
79
|
+
* 拆成纯函数:多行结构、生效状态与路由的措辞都是审计点。
|
|
80
|
+
* @param {{
|
|
81
|
+
* settings: any,
|
|
82
|
+
* counters?: { sessionCalls?: number, turnCalls?: number } | null,
|
|
83
|
+
* totals?: { inputTokens?: number, outputTokens?: number, calls?: number } | null,
|
|
84
|
+
* last?: any,
|
|
85
|
+
* skip?: string | undefined | null,
|
|
86
|
+
* }} input
|
|
87
|
+
* @returns {string}
|
|
88
|
+
*/
|
|
89
|
+
export function formatStatusText(input) {
|
|
90
|
+
const settings = input.settings ?? {};
|
|
91
|
+
const counters = input.counters ?? {};
|
|
92
|
+
const totals = input.totals ?? {};
|
|
93
|
+
const state = effectiveStateOf(settings);
|
|
94
|
+
const provider = typeof settings.provider === "string" ? settings.provider : "";
|
|
95
|
+
const model = typeof settings.model === "string" ? settings.model : "";
|
|
96
|
+
const configured = provider !== "" && model !== "";
|
|
97
|
+
const route = configured ? `${provider}/${model}` : "(未配置)";
|
|
98
|
+
const effort = typeof settings.reasoningEffort === "string" ? settings.reasoningEffort : "";
|
|
99
|
+
const last = input.last ?? null;
|
|
100
|
+
const lastText =
|
|
101
|
+
last === null || typeof last !== "object"
|
|
102
|
+
? "(还没有)"
|
|
103
|
+
: `${String(last.status ?? "")}${
|
|
104
|
+
typeof last.code === "string" && last.code !== "" && last.code !== "ok"
|
|
105
|
+
? ` · ${last.code}`
|
|
106
|
+
: ""
|
|
107
|
+
}${typeof last.usage === "string" && last.usage !== "" ? ` · ${last.usage}` : ""}`;
|
|
108
|
+
const maxTurn = Number(settings.maxCallsPerTurn) > 0 ? String(settings.maxCallsPerTurn) : "∞";
|
|
109
|
+
const maxSession =
|
|
110
|
+
Number(settings.maxCallsPerSession) > 0 ? String(settings.maxCallsPerSession) : "∞";
|
|
111
|
+
const skip = typeof input.skip === "string" && input.skip !== "" ? input.skip : "(无)";
|
|
112
|
+
return [
|
|
113
|
+
`模式:${typeof settings.mode === "string" && settings.mode !== "" ? settings.mode : "off"}`,
|
|
114
|
+
`生效:${effectiveLine(state)}`,
|
|
115
|
+
`顾问:${route}${effort === "" ? "" : ` · 思考档 ${effort}`}`,
|
|
116
|
+
`本会话:${Number(counters.sessionCalls ?? 0)} 次(本回合 ${Number(
|
|
117
|
+
counters.turnCalls ?? 0,
|
|
118
|
+
)}/${maxTurn},本会话上限 ${maxSession})`,
|
|
119
|
+
`累计 token:${Number(totals.inputTokens ?? 0)} in / ${Number(
|
|
120
|
+
totals.outputTokens ?? 0,
|
|
121
|
+
)} out(${Number(totals.calls ?? 0)} 次)`,
|
|
122
|
+
`最近一次:${lastText}`,
|
|
123
|
+
`最近跳过:${skip}`,
|
|
124
|
+
].join("\n");
|
|
125
|
+
}
|
package/lib/day.js
ADDED
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// 「本地日键」只在这里实现一份。
|
|
3
|
+
//
|
|
4
|
+
// 审计 AUD-ADV-04:账本原来用 `new Date().toISOString()`(UTC)写入、却拿本地日键比较,
|
|
5
|
+
// UTC+8 下每天 0–8 点的花费会被算到前一天 → 重启后当日已花被低估。现在账本行自带 `day`
|
|
6
|
+
// 字段(写入时按本地日算),读取时优先用它;旧行没有 `day` 时按 `at` 的**本地日期**折算。
|
|
7
|
+
|
|
8
|
+
/** 账本行里稳定日键的形状。 */
|
|
9
|
+
const DAY_PATTERN = /^\d{4}-\d{2}-\d{2}$/u;
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* 本地日键 YYYY-MM-DD。
|
|
13
|
+
* @param {Date} [date]
|
|
14
|
+
* @returns {string}
|
|
15
|
+
*/
|
|
16
|
+
export function dayKey(date = new Date()) {
|
|
17
|
+
const year = date.getFullYear();
|
|
18
|
+
const month = `${date.getMonth() + 1}`.padStart(2, "0");
|
|
19
|
+
const day = `${date.getDate()}`.padStart(2, "0");
|
|
20
|
+
return `${year}-${month}-${day}`;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* 把 ISO 时间之类的时间值换算成本地日键;无法解析时返回空串(由调用方决定怎么兜底)。
|
|
25
|
+
* @param {unknown} value
|
|
26
|
+
* @returns {string}
|
|
27
|
+
*/
|
|
28
|
+
export function dayKeyOf(value) {
|
|
29
|
+
if (value instanceof Date) return Number.isNaN(value.getTime()) ? "" : dayKey(value);
|
|
30
|
+
if (typeof value !== "string" || value.trim() === "") return "";
|
|
31
|
+
const date = new Date(value);
|
|
32
|
+
return Number.isNaN(date.getTime()) ? "" : dayKey(date);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* 一条账本/建议记录属于哪个本地日:`day` 字段优先(新数据),否则从 `at` 折算(旧数据)。
|
|
37
|
+
* @param {{ day?: unknown, at?: unknown }} [entry]
|
|
38
|
+
* @returns {string}
|
|
39
|
+
*/
|
|
40
|
+
export function dayOfEntry(entry) {
|
|
41
|
+
const stored = entry?.day;
|
|
42
|
+
if (typeof stored === "string" && DAY_PATTERN.test(stored)) return stored;
|
|
43
|
+
return dayKeyOf(entry?.at);
|
|
44
|
+
}
|
package/lib/deadline.js
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// @ts-check
|
|
2
|
+
// 硬超时:`timeoutMs` 必须由**插件侧**主动中止请求,而不是依赖宿主流稍后自己收尾。
|
|
3
|
+
//
|
|
4
|
+
// 为什么单独一个模块(审计 AUD-ADV-03):
|
|
5
|
+
// - 原来的实现把 `AbortSignal.timeout()` 传给宿主,但只在流**自己**收尾成 aborted 时才判超时。
|
|
6
|
+
// 真实数据里有 6 次调用超过配置的 90s 仍以 `reviewed` 计费(94.6–155.1s),说明「信号发了、
|
|
7
|
+
// 流没停」时旧逻辑毫无作用。这里把「到点」变成一个可等待的事件:到点就中止请求并提前返回,
|
|
8
|
+
// 插件侧不再把这次调用记为成功(账本记 costUsd 0),残余风险写进 README。
|
|
9
|
+
// - `call.js` 会 import `@deepseek-ai/dsh-llm`(测试环境没有宿主包),所以时间语义放在这里,
|
|
10
|
+
// 用真实计时器单测;call.js 只做接线。
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* @typedef {object} Deadline
|
|
14
|
+
* @property {AbortSignal} signal 传给宿主请求/流的合并信号(超时与外部取消都会触发)
|
|
15
|
+
* @property {() => boolean} timedOut 是否是「配置的超时」触发
|
|
16
|
+
* @property {() => boolean} cancelled 是否是「外部取消」触发(用户 / 回合取消)
|
|
17
|
+
* @property {() => void} dispose 清理定时器与监听(幂等)
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* 建一个硬超时。外部 signal 会被转发进内部 controller,宿主只需要看一个信号。
|
|
22
|
+
* @param {{ timeoutMs: number, external?: AbortSignal }} input
|
|
23
|
+
* @returns {Deadline}
|
|
24
|
+
*/
|
|
25
|
+
export function createDeadline(input) {
|
|
26
|
+
const timeoutMs = Number(input?.timeoutMs);
|
|
27
|
+
const external = input?.external;
|
|
28
|
+
const controller = new AbortController();
|
|
29
|
+
let timedOut = false;
|
|
30
|
+
let disposed = false;
|
|
31
|
+
const timer = setTimeout(
|
|
32
|
+
() => {
|
|
33
|
+
timedOut = true;
|
|
34
|
+
controller.abort();
|
|
35
|
+
},
|
|
36
|
+
Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : 0,
|
|
37
|
+
);
|
|
38
|
+
// 不让一个「只等超时」的定时器把进程/测试拖住。
|
|
39
|
+
timer.unref?.();
|
|
40
|
+
|
|
41
|
+
/** @type {() => void} */
|
|
42
|
+
const onExternalAbort = () => {
|
|
43
|
+
controller.abort();
|
|
44
|
+
};
|
|
45
|
+
if (external !== undefined) {
|
|
46
|
+
if (external.aborted) controller.abort();
|
|
47
|
+
else external.addEventListener("abort", onExternalAbort, { once: true });
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
return {
|
|
51
|
+
signal: controller.signal,
|
|
52
|
+
timedOut: () => timedOut,
|
|
53
|
+
cancelled: () => external?.aborted === true && !timedOut,
|
|
54
|
+
dispose() {
|
|
55
|
+
if (disposed) return;
|
|
56
|
+
disposed = true;
|
|
57
|
+
clearTimeout(timer);
|
|
58
|
+
external?.removeEventListener("abort", onExternalAbort);
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* 干活与超时赛跑:超时/取消先到就提前返回,不等一个可能永远不结束的流。
|
|
65
|
+
* @template T
|
|
66
|
+
* @param {Promise<T>} work
|
|
67
|
+
* @param {Deadline} deadline
|
|
68
|
+
* @returns {Promise<{ kind: "settled", value: T } | { kind: "timeout" } | { kind: "aborted" } | { kind: "error", error: unknown }>}
|
|
69
|
+
*/
|
|
70
|
+
export function raceWithDeadline(work, deadline) {
|
|
71
|
+
return new Promise((resolve) => {
|
|
72
|
+
let settled = false;
|
|
73
|
+
/** @param {{ kind: "settled", value: T } | { kind: "timeout" } | { kind: "aborted" } | { kind: "error", error: unknown }} outcome */
|
|
74
|
+
const finish = (outcome) => {
|
|
75
|
+
if (settled) return;
|
|
76
|
+
settled = true;
|
|
77
|
+
deadline.signal.removeEventListener("abort", onAbort);
|
|
78
|
+
// 一次 race 只对应一次调用:结算后到点也不再有意义,顺手清掉定时器。
|
|
79
|
+
deadline.dispose();
|
|
80
|
+
resolve(outcome);
|
|
81
|
+
};
|
|
82
|
+
const onAbort = () => finish(deadline.timedOut() ? { kind: "timeout" } : { kind: "aborted" });
|
|
83
|
+
if (deadline.signal.aborted) {
|
|
84
|
+
onAbort();
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
deadline.signal.addEventListener("abort", onAbort, { once: true });
|
|
88
|
+
// 两个分支都挂上处理函数:超时胜出后迟到的 rejection 也不会变成 unhandled rejection。
|
|
89
|
+
Promise.resolve(work).then(
|
|
90
|
+
(value) => finish({ kind: "settled", value }),
|
|
91
|
+
(error) => finish({ kind: "error", error }),
|
|
92
|
+
);
|
|
93
|
+
});
|
|
94
|
+
}
|
package/lib/decisions.js
CHANGED
|
@@ -1,17 +1,19 @@
|
|
|
1
1
|
// @ts-check
|
|
2
|
-
//
|
|
2
|
+
// 决策日志:记录**每个回合**「有没有征询、为什么没征询、征询后用户怎么反应」。
|
|
3
3
|
//
|
|
4
|
-
// 为什么单独一个文件而不是并进 usage.jsonl:用途不同。usage
|
|
5
|
-
// 有 token 与成本);decisions
|
|
6
|
-
//
|
|
4
|
+
// 为什么单独一个文件而不是并进 usage.jsonl:用途不同。usage 是**钱的账本**(一次征询一行,
|
|
5
|
+
// 有 token 与成本);decisions 是**策略的证据**(一个回合一行,没有征询的回合也要记),
|
|
6
|
+
// 用来事后回答「该征询的时候有没有征询」。两件事混在一起会让两边都难查。
|
|
7
7
|
//
|
|
8
|
-
// 落盘:`<dataRoot>/advisor/decisions.jsonl
|
|
9
|
-
|
|
8
|
+
// 落盘:`<dataRoot>/advisor/decisions.jsonl`。新行用单行 O_APPEND 追加(按文件串行写队列,
|
|
9
|
+
// 并发回合不会互相覆盖);outcome 回填是「读-改-写整份」,但走唯一 tmp + rename 的原子重写,
|
|
10
|
+
// 并与追加共用同一个队列(审计 AUD-ADV-01)。超过上限(2 MiB)时滚动重命名保留一份历史。
|
|
10
11
|
import { join } from "node:path";
|
|
11
12
|
|
|
12
13
|
import { signalsOf } from "./adoption.js";
|
|
14
|
+
import { appendJsonLine, readJsonLines, serializeByPath, writeTextAtomic } from "./fs-atomic.js";
|
|
13
15
|
import { LEDGER_DIR } from "./ledger.js";
|
|
14
|
-
import { textOf, toolCallsOf } from "./transcript.js";
|
|
16
|
+
import { isInjectedContext, textOf, toolCallsOf } from "./transcript.js";
|
|
15
17
|
|
|
16
18
|
/** 决策日志文件名(与 usage.jsonl / advice.jsonl 同目录)。 */
|
|
17
19
|
export const DECISIONS_FILE = "decisions.jsonl";
|
|
@@ -19,7 +21,7 @@ export const DECISIONS_FILE = "decisions.jsonl";
|
|
|
19
21
|
export const DECISIONS_MAX_BYTES = 2 * 1024 * 1024;
|
|
20
22
|
|
|
21
23
|
/**
|
|
22
|
-
*
|
|
24
|
+
* 没征询时的原因码。**从主模型视角分类**,而不是按内部函数名:
|
|
23
25
|
* 复盘时要回答的是「这一回合本该问吗」,所以分桶要能对应到「机会成本」。
|
|
24
26
|
* @typedef {"skipped-disabled"|"skipped-not-configured"|"skipped-no-route"|"skipped-empty"|"skipped-budget"|"skipped-limit"|"skipped-immune"|"skipped-duplicate"|"skipped-needs-confirmation"|"skipped-not-requested"|"skipped-aborted"|"skipped-blocked"|"skipped-other"} SkipCode
|
|
25
27
|
*/
|
|
@@ -57,7 +59,7 @@ export function classifySkip(reason) {
|
|
|
57
59
|
}
|
|
58
60
|
|
|
59
61
|
/**
|
|
60
|
-
*
|
|
62
|
+
* 回合特征:用来给「该不该征询」分桶的、可用不变量化的东西。
|
|
61
63
|
* @param {{ answerChars?: number, toolCalls?: number, hadError?: boolean }} input
|
|
62
64
|
* @returns {{ answerChars: number, toolCalls: number, hadError: boolean, longAnswer: boolean, usedTools: boolean }}
|
|
63
65
|
*/
|
|
@@ -97,7 +99,7 @@ export function buildDecision(input) {
|
|
|
97
99
|
turn: input.turn,
|
|
98
100
|
endKind,
|
|
99
101
|
consulted,
|
|
100
|
-
//
|
|
102
|
+
// 没征询时给出原因码,复盘时先看这一列。
|
|
101
103
|
skipCode: consulted ? null : (endKindCode ?? classifySkip(input.skipReason)),
|
|
102
104
|
skipReason: consulted ? null : (input.skipReason ?? ""),
|
|
103
105
|
...turnFeatures(input.features ?? {}),
|
|
@@ -111,9 +113,10 @@ export function buildDecision(input) {
|
|
|
111
113
|
}
|
|
112
114
|
|
|
113
115
|
/**
|
|
114
|
-
*
|
|
116
|
+
* 判定上一回合建议的下场。**本函数只处理「下一条真人用户消息」这一种反应**:
|
|
115
117
|
* 建议里出现过的可追踪信号(路径、反引号命令、证据 ref)命中就算 accepted,
|
|
116
|
-
* 用户发了别的内容算 user-typed-other
|
|
118
|
+
* 用户发了别的内容算 user-typed-other。`"no-action"` 不由本函数产出——
|
|
119
|
+
* 它由回合跟踪器在「下个回合结束时仍没有任何真人反应」时回填(见 createDecisionTracker)。
|
|
117
120
|
* @param {{ adviceText?: string, signals?: string[] }} advice
|
|
118
121
|
* @param {string} nextUserText 下一回合用户输入
|
|
119
122
|
* @returns {"accepted"|"user-typed-other"}
|
|
@@ -130,6 +133,23 @@ export function outcomeOf(advice, nextUserText) {
|
|
|
130
133
|
return "user-typed-other";
|
|
131
134
|
}
|
|
132
135
|
|
|
136
|
+
/**
|
|
137
|
+
* 在一段(已序列化的)事件载荷里找建议信号。
|
|
138
|
+
* 与 `attributeAdoption` 的 `JSON.stringify(event.data)` 口径一致:工具参数、助手文本里
|
|
139
|
+
* 出现建议提到的路径/命令/证据 ref,就算「主模型照着做了」(审计 AUD-ADV-07)。
|
|
140
|
+
* @param {string} payload
|
|
141
|
+
* @param {string[]} signals
|
|
142
|
+
* @returns {string|null} 命中的信号;没有则 null
|
|
143
|
+
*/
|
|
144
|
+
export function matchSignalIn(payload, signals) {
|
|
145
|
+
const text = typeof payload === "string" ? payload : "";
|
|
146
|
+
if (text === "") return null;
|
|
147
|
+
for (const signal of Array.isArray(signals) ? signals : []) {
|
|
148
|
+
if (typeof signal === "string" && signal.length >= 3 && text.includes(signal)) return signal;
|
|
149
|
+
}
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
|
|
133
153
|
/** 分桶键:把回合特征压成有限几个桶,复盘时直接出交叉表。 */
|
|
134
154
|
/** @param {any} record @returns {string} */
|
|
135
155
|
export function bucketOf(record) {
|
|
@@ -186,7 +206,7 @@ export function summarize(records) {
|
|
|
186
206
|
} else {
|
|
187
207
|
const code = typeof record.skipCode === "string" ? record.skipCode : "skipped-other";
|
|
188
208
|
skipCodes[code] = (skipCodes[code] ?? 0) + 1;
|
|
189
|
-
//
|
|
209
|
+
// 疑似漏征询:这一回合有工具、回答也不短,却没有征询。
|
|
190
210
|
if (record.usedTools === true && record.longAnswer === true && record.hadError !== true) {
|
|
191
211
|
missed.push(record);
|
|
192
212
|
}
|
|
@@ -195,6 +215,7 @@ export function summarize(records) {
|
|
|
195
215
|
}
|
|
196
216
|
|
|
197
217
|
const turns = list.length;
|
|
218
|
+
const resolvedOutcomes = accepted + ignored + noAction;
|
|
198
219
|
return {
|
|
199
220
|
turns,
|
|
200
221
|
consulted,
|
|
@@ -202,8 +223,12 @@ export function summarize(records) {
|
|
|
202
223
|
accepted,
|
|
203
224
|
ignored,
|
|
204
225
|
noAction,
|
|
205
|
-
//
|
|
226
|
+
// 采纳率只对「已经出结果」的征询算,未回填的不进分母;但覆盖率要单独报,
|
|
227
|
+
// 否则分母很小时「采纳率 0%」会被读成「建议从没被采纳」(审计 AUD-ADV-07)。
|
|
206
228
|
acceptRate: accepted + ignored === 0 ? null : accepted / (accepted + ignored),
|
|
229
|
+
resolvedOutcomes,
|
|
230
|
+
pendingOutcomes: Math.max(0, consulted - resolvedOutcomes),
|
|
231
|
+
outcomeCoverage: consulted === 0 ? null : resolvedOutcomes / consulted,
|
|
207
232
|
skipCodes,
|
|
208
233
|
buckets: [...buckets.entries()]
|
|
209
234
|
.map(([bucket, value]) => ({ bucket, ...value }))
|
|
@@ -219,20 +244,8 @@ export function summarize(records) {
|
|
|
219
244
|
* @param {string} path
|
|
220
245
|
* @returns {Promise<any[]>}
|
|
221
246
|
*/
|
|
222
|
-
export
|
|
223
|
-
|
|
224
|
-
/** @type {any[]} */
|
|
225
|
-
const out = [];
|
|
226
|
-
for (const line of text.split("\n")) {
|
|
227
|
-
if (line.trim() === "") continue;
|
|
228
|
-
try {
|
|
229
|
-
const parsed = JSON.parse(line);
|
|
230
|
-
if (parsed && typeof parsed === "object") out.push(parsed);
|
|
231
|
-
} catch (_error) {
|
|
232
|
-
/* 跳过坏行 */
|
|
233
|
-
}
|
|
234
|
-
}
|
|
235
|
-
return out;
|
|
247
|
+
export function readDecisions(path) {
|
|
248
|
+
return readJsonLines(path);
|
|
236
249
|
}
|
|
237
250
|
|
|
238
251
|
/**
|
|
@@ -243,63 +256,98 @@ export function createDecisionLog(options) {
|
|
|
243
256
|
const dir = join(options.home, LEDGER_DIR);
|
|
244
257
|
const path = join(dir, DECISIONS_FILE);
|
|
245
258
|
|
|
259
|
+
// 进行中的写操作计数 + `flush()`:调用方(尤其是测试)可以**确定性地**等到落盘,
|
|
260
|
+
// 不必用 `setTimeout` 猜时序(接线测试曾因此偶发红)。`track()` 里的回填是 fire-and-forget,
|
|
261
|
+
// 但 `backfillOutcome` 在被调用的同步段就会登记 inflight,所以 flush 不会漏掉它们。
|
|
262
|
+
let inflight = 0;
|
|
263
|
+
/** @type {Array<() => void>} */
|
|
264
|
+
const waiters = [];
|
|
265
|
+
/** @template T @param {() => Promise<T>} task @returns {Promise<T>} */
|
|
266
|
+
const trackWrite = async (task) => {
|
|
267
|
+
inflight += 1;
|
|
268
|
+
try {
|
|
269
|
+
return await task();
|
|
270
|
+
} finally {
|
|
271
|
+
inflight -= 1;
|
|
272
|
+
if (inflight === 0) {
|
|
273
|
+
for (const resolve of waiters.splice(0)) resolve();
|
|
274
|
+
}
|
|
275
|
+
}
|
|
276
|
+
};
|
|
277
|
+
|
|
246
278
|
return {
|
|
247
279
|
path,
|
|
248
280
|
|
|
249
281
|
/**
|
|
250
|
-
*
|
|
282
|
+
* 等到当前所有写操作(追加 / 回填)落盘。没有在途写时立即 resolve。
|
|
283
|
+
* @returns {Promise<void>}
|
|
284
|
+
*/
|
|
285
|
+
flush() {
|
|
286
|
+
if (inflight === 0) return Promise.resolve();
|
|
287
|
+
return new Promise((resolve) => {
|
|
288
|
+
waiters.push(resolve);
|
|
289
|
+
});
|
|
290
|
+
},
|
|
291
|
+
|
|
292
|
+
/**
|
|
293
|
+
* 追加一行(O_APPEND 单写 + 进程内单写队列;不再读全文再覆盖,审计 AUD-ADV-01)。
|
|
251
294
|
* @param {any} record
|
|
252
295
|
* @returns {Promise<void>}
|
|
253
296
|
*/
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
297
|
+
append(record) {
|
|
298
|
+
return trackWrite(async () => {
|
|
299
|
+
try {
|
|
300
|
+
await appendJsonLine(path, record, {
|
|
301
|
+
rotateBytes: DECISIONS_MAX_BYTES,
|
|
302
|
+
rotateTo: `${path}.1`,
|
|
303
|
+
});
|
|
304
|
+
} catch (error) {
|
|
305
|
+
options.logger?.warn?.(`[advisor] 写决策日志失败:${String(error)}`);
|
|
260
306
|
}
|
|
261
|
-
|
|
262
|
-
info && info.size <= DECISIONS_MAX_BYTES
|
|
263
|
-
? await readFile(path, "utf8").catch(() => "")
|
|
264
|
-
: "";
|
|
265
|
-
await writeFile(path, `${existing}${JSON.stringify(record)}\n`, "utf8");
|
|
266
|
-
} catch (error) {
|
|
267
|
-
options.logger?.warn?.(`[advisor] 写决策日志失败:${String(error)}`);
|
|
268
|
-
}
|
|
307
|
+
});
|
|
269
308
|
},
|
|
270
309
|
|
|
271
310
|
/**
|
|
272
311
|
* 回填上一回合的 outcome(改最后一条匹配记录)。
|
|
273
|
-
*
|
|
312
|
+
*
|
|
313
|
+
* 为什么这里仍是「读-改-写整份」而不是追加补丁行:`decisions.jsonl` 同时被
|
|
314
|
+
* `pnpm advisor:review` 按「一行一条决策」直接读,补丁行会被它当成一个回合计入统计。
|
|
315
|
+
* 重写只发生在回填(每次征询最多一次),且与 append 共用同一个 per-path 队列 +
|
|
316
|
+
* 唯一 tmp + rename,所以既不会丢追加,也不会留下半截文件。
|
|
274
317
|
* @param {string} sessionId
|
|
275
318
|
* @param {number} turn
|
|
276
319
|
* @param {string} outcome
|
|
320
|
+
* @param {string} [why] 归因依据(tool-call / assistant-message / user-message / no-follow-up)
|
|
277
321
|
* @returns {Promise<boolean>} 是否真的改到了
|
|
278
322
|
*/
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
323
|
+
backfillOutcome(sessionId, turn, outcome, why = "") {
|
|
324
|
+
return trackWrite(async () => {
|
|
325
|
+
try {
|
|
326
|
+
return await serializeByPath(path, async () => {
|
|
327
|
+
const records = await readDecisions(path);
|
|
328
|
+
let changed = false;
|
|
329
|
+
for (let index = records.length - 1; index >= 0; index -= 1) {
|
|
330
|
+
const record = records[index];
|
|
331
|
+
if (record?.sessionId === sessionId && record?.turn === turn) {
|
|
332
|
+
if (record.outcome === outcome && (record.outcomeWhy ?? "") === why) return true;
|
|
333
|
+
record.outcome = outcome;
|
|
334
|
+
record.outcomeWhy = why;
|
|
335
|
+
changed = true;
|
|
336
|
+
break;
|
|
337
|
+
}
|
|
338
|
+
}
|
|
339
|
+
if (!changed) return false;
|
|
340
|
+
await writeTextAtomic(
|
|
341
|
+
path,
|
|
342
|
+
`${records.map((item) => JSON.stringify(item)).join("\n")}\n`,
|
|
343
|
+
);
|
|
344
|
+
return true;
|
|
345
|
+
});
|
|
346
|
+
} catch (error) {
|
|
347
|
+
options.logger?.warn?.(`[advisor] 回填决策日志失败:${String(error)}`);
|
|
348
|
+
return false;
|
|
291
349
|
}
|
|
292
|
-
|
|
293
|
-
await writeFile(
|
|
294
|
-
path,
|
|
295
|
-
`${records.map((item) => JSON.stringify(item)).join("\n")}\n`,
|
|
296
|
-
"utf8",
|
|
297
|
-
);
|
|
298
|
-
return true;
|
|
299
|
-
} catch (error) {
|
|
300
|
-
options.logger?.warn?.(`[advisor] 回填决策日志失败:${String(error)}`);
|
|
301
|
-
return false;
|
|
302
|
-
}
|
|
350
|
+
});
|
|
303
351
|
},
|
|
304
352
|
};
|
|
305
353
|
}
|
|
@@ -307,6 +355,19 @@ export function createDecisionLog(options) {
|
|
|
307
355
|
/**
|
|
308
356
|
* 回合跟踪器:把「事件 → 回合特征 → 决策行 → outcome 回填」这条链路从 service 里拆出来,
|
|
309
357
|
* 这样它可以脱离宿主包单独测试(service.js 依赖 @deepseek-ai/*,在单测环境里导入不了)。
|
|
358
|
+
*
|
|
359
|
+
* outcome 的三条路径(审计 AUD-ADV-07 / 09):
|
|
360
|
+
* - accepted:后续**助手消息**或**工具调用参数**里出现建议信号,或下一条**真人**用户消息
|
|
361
|
+
* 复述了信号。这是**启发式、无置信度区分**:路径 / 反引号命令 / 证据 ref 一视同仁,
|
|
362
|
+
* 模型顺手复述同一条命令也可能被算成 accepted;若 `tools/execute` 的 `data` 含工具
|
|
363
|
+
* 结果全文,读到的内容也可能被当成命中(`event.data` 形状待真机核实,复审 F6)。
|
|
364
|
+
* - user-typed-other:下一条真人用户消息没有命中任何信号;
|
|
365
|
+
* - no-action:下个回合结束时仍没有任何真人反应(目标自动继续等)。**会话结束时不会
|
|
366
|
+
* flush**:没有后续回合的 pending 会一直保持未回填,覆盖率里体现为 pending。
|
|
367
|
+
* 宿主注入的 `user/message`(time-context / goal / runtime-context)不是用户反应,直接忽略。
|
|
368
|
+
* post-answer / shadow 的建议在 `turn/end` 之后异步产生,`noteAdvice` 晚于该回合的
|
|
369
|
+
* `finishTurn` → 记到**下一回合**的决策行、pending 也在下一回合才设置(复审 F7,既有错位,
|
|
370
|
+
* 本批只记录不改;见 docs/testing/advisor.md)。
|
|
310
371
|
* @param {{ log: ReturnType<typeof createDecisionLog>, now?: () => number }} options
|
|
311
372
|
*/
|
|
312
373
|
export function createDecisionTracker(options) {
|
|
@@ -318,6 +379,23 @@ export function createDecisionTracker(options) {
|
|
|
318
379
|
/** @type {Map<string, { turn: number, signals: string[] }>} */
|
|
319
380
|
const pending = new Map();
|
|
320
381
|
|
|
382
|
+
/**
|
|
383
|
+
* 后续事件里出现建议信号 → 回填 accepted。
|
|
384
|
+
* @param {string} sessionId
|
|
385
|
+
* @param {any} event
|
|
386
|
+
* @param {string} why assistant-message | tool-call
|
|
387
|
+
* @returns {{ turn: number, outcome: string } | null}
|
|
388
|
+
*/
|
|
389
|
+
const claimFromEvent = (sessionId, event, why) => {
|
|
390
|
+
const waiting = pending.get(sessionId);
|
|
391
|
+
if (waiting === undefined) return null;
|
|
392
|
+
const hit = matchSignalIn(JSON.stringify(event?.data ?? ""), waiting.signals);
|
|
393
|
+
if (hit === null) return null;
|
|
394
|
+
pending.delete(sessionId);
|
|
395
|
+
void log.backfillOutcome(sessionId, waiting.turn, "accepted", why);
|
|
396
|
+
return { turn: waiting.turn, outcome: "accepted" };
|
|
397
|
+
};
|
|
398
|
+
|
|
321
399
|
return {
|
|
322
400
|
/**
|
|
323
401
|
* 回合开始:重置本回合统计。
|
|
@@ -329,7 +407,7 @@ export function createDecisionTracker(options) {
|
|
|
329
407
|
},
|
|
330
408
|
|
|
331
409
|
/**
|
|
332
|
-
*
|
|
410
|
+
* 本回合确实征询过时调用(由 runAdvisor 写入)。
|
|
333
411
|
* @param {string} sessionId
|
|
334
412
|
* @param {any} value
|
|
335
413
|
*/
|
|
@@ -338,7 +416,7 @@ export function createDecisionTracker(options) {
|
|
|
338
416
|
},
|
|
339
417
|
|
|
340
418
|
/**
|
|
341
|
-
*
|
|
419
|
+
* 累计事件特征;并在后续事件里找建议信号回填 accepted。
|
|
342
420
|
* @param {string} sessionId
|
|
343
421
|
* @param {any} event
|
|
344
422
|
* @returns {{ backfilled: { turn: number, outcome: string } | null }}
|
|
@@ -352,12 +430,12 @@ export function createDecisionTracker(options) {
|
|
|
352
430
|
current.answerChars += textOf(message).length;
|
|
353
431
|
current.toolCalls += toolCallsOf(message).length;
|
|
354
432
|
}
|
|
355
|
-
return { backfilled:
|
|
433
|
+
return { backfilled: claimFromEvent(sessionId, event, "assistant-message") };
|
|
356
434
|
}
|
|
357
435
|
if (type === "tools/execute") {
|
|
358
436
|
const current = stats.get(sessionId);
|
|
359
437
|
if (current) current.toolCalls += 1;
|
|
360
|
-
return { backfilled:
|
|
438
|
+
return { backfilled: claimFromEvent(sessionId, event, "tool-call") };
|
|
361
439
|
}
|
|
362
440
|
if (type === "agent/error" || type === "agent/request-error") {
|
|
363
441
|
const current = stats.get(sessionId);
|
|
@@ -366,13 +444,16 @@ export function createDecisionTracker(options) {
|
|
|
366
444
|
}
|
|
367
445
|
if (type !== "user/message") return { backfilled: null };
|
|
368
446
|
|
|
447
|
+
const message = event?.data?.message ?? event?.data;
|
|
448
|
+
// 注入的上下文不是真人反应:既不能算 accepted,也不能算 user-typed-other。
|
|
449
|
+
if (isInjectedContext(message)) return { backfilled: null };
|
|
369
450
|
const waiting = pending.get(sessionId);
|
|
370
|
-
if (
|
|
371
|
-
const text = textOf(
|
|
451
|
+
if (waiting === undefined) return { backfilled: null };
|
|
452
|
+
const text = textOf(message);
|
|
372
453
|
if (text === "") return { backfilled: null };
|
|
373
454
|
pending.delete(sessionId);
|
|
374
455
|
const outcome = outcomeOf({ signals: waiting.signals }, text);
|
|
375
|
-
void log.backfillOutcome(sessionId, waiting.turn, outcome);
|
|
456
|
+
void log.backfillOutcome(sessionId, waiting.turn, outcome, "user-message");
|
|
376
457
|
return { backfilled: { turn: waiting.turn, outcome } };
|
|
377
458
|
},
|
|
378
459
|
|
|
@@ -409,10 +490,16 @@ export function createDecisionTracker(options) {
|
|
|
409
490
|
? "回合被阻塞"
|
|
410
491
|
: (input.skipReason ?? input.fallbackReason),
|
|
411
492
|
});
|
|
493
|
+
// 上一回合的建议等到这个回合结束都没有真人反应 → no-action(该分支以前不可达)。
|
|
494
|
+
const stale = pending.get(input.sessionId);
|
|
495
|
+
if (stale !== undefined) {
|
|
496
|
+
pending.delete(input.sessionId);
|
|
497
|
+
await log.backfillOutcome(input.sessionId, stale.turn, "no-action", "no-follow-up");
|
|
498
|
+
}
|
|
412
499
|
if (record.consulted && usedAdvice?.adviceText) {
|
|
413
500
|
pending.set(input.sessionId, {
|
|
414
501
|
turn,
|
|
415
|
-
signals: signalsOf({ advice: usedAdvice.adviceText }),
|
|
502
|
+
signals: signalsOf({ advice: usedAdvice.adviceText, evidence: usedAdvice.evidence }),
|
|
416
503
|
});
|
|
417
504
|
}
|
|
418
505
|
await log.append(record);
|