@kangyishuai/dsh-advisor 0.0.0-stage → 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.
@@ -0,0 +1,258 @@
1
+ // @ts-check
2
+ // 插件设置:落在 DSH 数据根下的一个 JSON 文件,host 每次徵询前重读(1s 缓存)。
3
+ // 单独成文件的理由与 next-step 相同:冒烟脚本改文件即可验证行为,不需要重启宿主。
4
+ // 数据根必须可注入(config.dataRoot > $DSH_HOME > ~/.dsh),见 docs/plugin-conventions.md §2。
5
+ import { mkdir, readFile, rename, writeFile } from "node:fs/promises";
6
+ import { join } from "node:path";
7
+
8
+ /** 设置文件名(位于数据根下)。 */
9
+ export const SETTINGS_FILE = "advisor.settings.json";
10
+
11
+ /** 三种模式:关闭 / 影子(只记账不回灌)/ 顾问(正常徵询)。 */
12
+ export const MODES = Object.freeze(/** @type {const} */ (["off", "shadow", "advisory"]));
13
+
14
+ /**
15
+ * 默认设置:**默认关闭**。一个会花钱、会把会话内容发出去的插件必须显式 opt-in。
16
+ * - provider/model 为空时永不发起调用(对齐 Claude「配置 advisor 才生效」)。
17
+ * - privacyScope 默认 summary:只发摘要,不发文件全文。
18
+ */
19
+ export const DEFAULT_SETTINGS = Object.freeze({
20
+ mode: "off",
21
+ provider: "",
22
+ model: "",
23
+ reasoningEffort: "",
24
+ maxTokens: 4096,
25
+ temperature: null,
26
+ maxCallsPerTurn: 1,
27
+ maxCallsPerSession: 32,
28
+ maxCallsPerHour: 12,
29
+ maxCostPerDayUsd: 0,
30
+ priceInputPerMTok: 0,
31
+ priceOutputPerMTok: 0,
32
+ privacyScope: "summary",
33
+ redact: true,
34
+ immuneTurns: 3,
35
+ dedupe: true,
36
+ sessionCap: 24,
37
+ tiers: Object.freeze({}),
38
+ allowedModels: Object.freeze([]),
39
+ confirmedHosts: Object.freeze([]),
40
+ pairingEnforcement: "warn",
41
+ workspaceMaxCallsPerDay: 200,
42
+ workspaceMaxCostPerDayUsd: 0,
43
+ postAnswer: "off",
44
+ advisorTools: false,
45
+ timeoutMs: 90000,
46
+ maxInputChars: 60000,
47
+ });
48
+
49
+ /** 数值字段的夹紧区间。`0` 在预算类字段里表示「不限」。 */
50
+ const LIMITS = Object.freeze({
51
+ maxTokens: [256, 32000],
52
+ maxCallsPerTurn: [0, 8],
53
+ maxCallsPerSession: [0, 1000],
54
+ maxCallsPerHour: [0, 500],
55
+ maxCostPerDayUsd: [0, 10000],
56
+ priceInputPerMTok: [0, 1000],
57
+ priceOutputPerMTok: [0, 1000],
58
+ immuneTurns: [0, 20],
59
+ sessionCap: [0, 200],
60
+ workspaceMaxCallsPerDay: [0, 100000],
61
+ workspaceMaxCostPerDayUsd: [0, 10000],
62
+ timeoutMs: [5000, 600000],
63
+ maxInputChars: [4000, 400000],
64
+ });
65
+
66
+ /** 字符串字段的最大长度,防止有人在设置里塞进一整段提示词。 */
67
+ const MAX_STRING = 300;
68
+
69
+ /**
70
+ * 数据根下的设置文件路径。
71
+ * @param {string} home 数据根(DSH_HOME 或 profile 数据目录)
72
+ * @returns {string}
73
+ */
74
+ export function settingsPath(home) {
75
+ return join(home, SETTINGS_FILE);
76
+ }
77
+
78
+ /**
79
+ * 把数字夹紧到区间并取整。
80
+ * @param {unknown} value
81
+ * @param {number} fallback
82
+ * @param {number} min
83
+ * @param {number} max
84
+ * @returns {number}
85
+ */
86
+ function clampNumber(value, fallback, min, max) {
87
+ const n = typeof value === "number" ? value : Number(value);
88
+ if (!Number.isFinite(n)) return fallback;
89
+ return Math.min(max, Math.max(min, Math.round(n)));
90
+ }
91
+
92
+ /**
93
+ * 夹紧一个可空的数字(`temperature` 用:`null` 表示「不传,让 adapter 决定」)。
94
+ * @param {unknown} value
95
+ * @param {number} min
96
+ * @param {number} max
97
+ * @returns {number|null}
98
+ */
99
+ function nullableNumber(value, min, max) {
100
+ if (value === null || value === undefined || value === "") return null;
101
+ const n = typeof value === "number" ? value : Number(value);
102
+ if (!Number.isFinite(n)) return null;
103
+ return Math.min(max, Math.max(min, n));
104
+ }
105
+
106
+ /**
107
+ * 规整档位表:只接受 `provider/model` → 正整数档位。非法项丢弃。
108
+ * @param {unknown} raw
109
+ * @returns {Record<string, number>}
110
+ */
111
+ export function normalizeTiers(raw) {
112
+ /** @type {Record<string, number>} */
113
+ const out = {};
114
+ if (raw === null || typeof raw !== "object") return out;
115
+ for (const [key, value] of Object.entries(/** @type {Record<string, unknown>} */ (raw))) {
116
+ const id = typeof key === "string" ? key.trim() : "";
117
+ if (id === "" || id.length > MAX_STRING) continue;
118
+ const rank = typeof value === "number" ? value : Number(value);
119
+ if (!Number.isFinite(rank) || rank < 0) continue;
120
+ out[id] = Math.round(rank);
121
+ }
122
+ return out;
123
+ }
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
+
145
+ /**
146
+ * 把任意输入规整成合法设置:未知键丢弃、类型不符回落默认、数字夹紧、字符串截断。
147
+ * @param {unknown} raw 文件内容或 RPC patch 合并后的值
148
+ * @returns {typeof DEFAULT_SETTINGS}
149
+ */
150
+ export function normalizeSettings(raw) {
151
+ const input = raw !== null && typeof raw === "object" ? /** @type {any} */ (raw) : {};
152
+ /** @type {any} */
153
+ const out = { ...DEFAULT_SETTINGS };
154
+
155
+ if (typeof input.mode === "string" && MODES.includes(input.mode)) out.mode = input.mode;
156
+
157
+ for (const key of ["provider", "model", "reasoningEffort"]) {
158
+ if (typeof input[key] === "string") out[key] = input[key].trim().slice(0, MAX_STRING);
159
+ }
160
+
161
+ if (
162
+ typeof input.privacyScope === "string" &&
163
+ ["full", "summary", "off"].includes(input.privacyScope)
164
+ ) {
165
+ out.privacyScope = input.privacyScope;
166
+ }
167
+ if (
168
+ typeof input.pairingEnforcement === "string" &&
169
+ ["warn", "block"].includes(input.pairingEnforcement)
170
+ ) {
171
+ out.pairingEnforcement = input.pairingEnforcement;
172
+ }
173
+ for (const key of ["redact", "dedupe"]) {
174
+ if (typeof input[key] === "boolean") out[key] = input[key];
175
+ }
176
+
177
+ for (const key of /** @type {(keyof typeof LIMITS)[]} */ (Object.keys(LIMITS))) {
178
+ const [min, max] = LIMITS[key];
179
+ out[key] = clampNumber(input[key], DEFAULT_SETTINGS[key], min, max);
180
+ }
181
+ out.temperature = nullableNumber(input.temperature, 0, 2);
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;
189
+
190
+ return out;
191
+ }
192
+
193
+ /**
194
+ * 覆盖合并:`patch` 里出现的键才改,其余保持当前值。
195
+ * @param {typeof DEFAULT_SETTINGS} current
196
+ * @param {unknown} patch
197
+ * @returns {typeof DEFAULT_SETTINGS}
198
+ */
199
+ export function mergeSettings(current, patch) {
200
+ const base = current !== null && typeof current === "object" ? current : DEFAULT_SETTINGS;
201
+ const input = patch !== null && typeof patch === "object" ? /** @type {any} */ (patch) : {};
202
+ /** @type {Record<string, unknown>} */
203
+ const merged = { ...base };
204
+ for (const key of Object.keys(DEFAULT_SETTINGS)) {
205
+ if (Object.hasOwn(input, key)) merged[key] = input[key];
206
+ }
207
+ return normalizeSettings(merged);
208
+ }
209
+
210
+ /**
211
+ * 读设置文件;不存在或损坏时返回默认值(绝不抛给调用方)。
212
+ * @param {{ home: string, logger?: DSH.Logger }} options
213
+ * @returns {Promise<typeof DEFAULT_SETTINGS>}
214
+ */
215
+ export async function loadSettings(options) {
216
+ const path = settingsPath(options.home);
217
+ try {
218
+ const text = await readFile(path, "utf8");
219
+ const parsed = JSON.parse(text);
220
+ return normalizeSettings(parsed);
221
+ } catch (error) {
222
+ const code = /** @type {any} */ (error)?.code;
223
+ if (code !== "ENOENT" && options.logger) {
224
+ options.logger.warn(`[advisor] 设置文件无法解析,已回落到默认值:${String(error)}`);
225
+ }
226
+ return normalizeSettings(DEFAULT_SETTINGS);
227
+ }
228
+ }
229
+
230
+ /**
231
+ * 原子写设置文件(先写临时文件再 rename),避免半截文件让后续读取回落默认值。
232
+ * @param {{ home: string, settings: typeof DEFAULT_SETTINGS }} options
233
+ * @returns {Promise<typeof DEFAULT_SETTINGS>}
234
+ */
235
+ export async function saveSettings(options) {
236
+ const next = normalizeSettings(options.settings);
237
+ const path = settingsPath(options.home);
238
+ const temp = `${path}.tmp`;
239
+ await mkdir(options.home, { recursive: true });
240
+ await writeFile(temp, `${JSON.stringify(next, null, 2)}\n`, "utf8");
241
+ await rename(temp, path);
242
+ return next;
243
+ }
244
+
245
+ /**
246
+ * 「已配置顾问」:provider 与 model 都非空。没配就永不发起调用。
247
+ * @param {typeof DEFAULT_SETTINGS} [settings]
248
+ * @returns {boolean}
249
+ */
250
+ export function isConfigured(settings) {
251
+ const s = settings ?? DEFAULT_SETTINGS;
252
+ return (
253
+ typeof s.provider === "string" &&
254
+ s.provider !== "" &&
255
+ typeof s.model === "string" &&
256
+ s.model !== ""
257
+ );
258
+ }
@@ -0,0 +1,153 @@
1
+ // @ts-check
2
+ // 工具定义里**与宿主无关**的部分:名字、参数 schema、输出 schema、渲染函数。
3
+ // 单独成文件的理由:`service.js` 要 import 宿主包(`@deepseek-ai/dsh-llm` 等),
4
+ // 单测里解析不到;把可测的部分拆出来,schema 的「只支持子集」约束才能被测试守住。
5
+ // 受支持的 JSON Schema 关键字是子集:type/oneOf/properties/required/additionalProperties/items/enum/const。
6
+ // **`minimum` / `maximum` 不支持**,传了会让 register() 静默失败(docs/runtime/0.2.2-rc.1.md §9.10)。
7
+
8
+ /** 工具名:与 Claude 的 advisor 工具同名。 */
9
+ export const TOOL_NAME = "advisor";
10
+
11
+ /** 工具参数:零必填参数(对齐原版「input 永远为空」),只留一个可选 focus。 */
12
+ export const TOOL_PARAMETERS = Object.freeze({
13
+ type: "object",
14
+ properties: Object.freeze({
15
+ focus: Object.freeze({
16
+ type: "string",
17
+ description:
18
+ "Optional: the specific doubt you want the advisor to settle, in one short sentence. Omit it to let the advisor read the transcript.",
19
+ }),
20
+ }),
21
+ additionalProperties: false,
22
+ });
23
+
24
+ /** 工具返回值 schema(宿主会用它校验 execute 的返回值)。 */
25
+ export const TOOL_OUTPUT_SCHEMA = Object.freeze({
26
+ type: "object",
27
+ properties: Object.freeze({
28
+ status: Object.freeze({
29
+ type: "string",
30
+ enum: Object.freeze(["reviewed", "declined", "unavailable", "skipped"]),
31
+ }),
32
+ severity: Object.freeze({ type: "string", enum: Object.freeze(["nit", "concern", "blocker"]) }),
33
+ advice: Object.freeze({ type: "string" }),
34
+ risks: Object.freeze({ type: "array", items: Object.freeze({ type: "string" }) }),
35
+ acceptance: Object.freeze({ type: "array", items: Object.freeze({ type: "string" }) }),
36
+ evidence: Object.freeze({
37
+ type: "array",
38
+ items: Object.freeze({
39
+ type: "object",
40
+ properties: Object.freeze({
41
+ kind: Object.freeze({ type: "string" }),
42
+ ref: Object.freeze({ type: "string" }),
43
+ }),
44
+ required: Object.freeze(["kind", "ref"]),
45
+ }),
46
+ }),
47
+ adviceId: Object.freeze({ type: "string" }),
48
+ anchors: Object.freeze({
49
+ type: "object",
50
+ properties: Object.freeze({
51
+ checked: Object.freeze({ type: "number" }),
52
+ verified: Object.freeze({ type: "number" }),
53
+ unverified: Object.freeze({ type: "number" }),
54
+ downgraded: Object.freeze({ type: "boolean" }),
55
+ }),
56
+ additionalProperties: true,
57
+ }),
58
+ reason: Object.freeze({ type: "string" }),
59
+ model: Object.freeze({ type: "string" }),
60
+ usage: Object.freeze({ type: "string" }),
61
+ }),
62
+ required: Object.freeze(["status"]),
63
+ additionalProperties: true,
64
+ });
65
+
66
+ /** 受支持的 schema 关键字白名单(测试与自检共用)。 */
67
+ export const SUPPORTED_SCHEMA_KEYWORDS = Object.freeze(
68
+ new Set([
69
+ "type",
70
+ "oneOf",
71
+ "properties",
72
+ "required",
73
+ "additionalProperties",
74
+ "items",
75
+ "enum",
76
+ "const",
77
+ "description",
78
+ "title",
79
+ ]),
80
+ );
81
+
82
+ /**
83
+ * 递归找出 schema 里不受支持的关键字。
84
+ * @param {unknown} schema
85
+ * @param {string} [path]
86
+ * @returns {string[]}
87
+ */
88
+ export function unsupportedSchemaKeywords(schema, path = "$") {
89
+ /** @type {string[]} */
90
+ const out = [];
91
+ if (schema === null || typeof schema !== "object") return out;
92
+ if (Array.isArray(schema)) {
93
+ schema.forEach((item, index) => {
94
+ out.push(...unsupportedSchemaKeywords(item, `${path}[${index}]`));
95
+ });
96
+ return out;
97
+ }
98
+ for (const [key, value] of Object.entries(/** @type {Record<string, unknown>} */ (schema))) {
99
+ if (!SUPPORTED_SCHEMA_KEYWORDS.has(key) && !(path === "$" && key === "$schema")) {
100
+ out.push(`${path}.${key}`);
101
+ }
102
+ if (key === "properties" && value !== null && typeof value === "object") {
103
+ for (const [name, child] of Object.entries(/** @type {Record<string, unknown>} */ (value))) {
104
+ out.push(...unsupportedSchemaKeywords(child, `${path}.properties.${name}`));
105
+ }
106
+ } else if (key === "items" || key === "oneOf") {
107
+ out.push(...unsupportedSchemaKeywords(value, `${path}.${key}`));
108
+ }
109
+ }
110
+ return out;
111
+ }
112
+
113
+ /**
114
+ * 工具卡渲染:把结果值转成文本块(**只给界面看**,模型拿到的是 JSON 值本身)。
115
+ * @param {unknown} _args
116
+ * @param {any} value
117
+ * @returns {any[]}
118
+ */
119
+ export function renderToolOutput(_args, value) {
120
+ const status = String(value?.status ?? "unavailable");
121
+ const model = String(value?.model ?? "");
122
+ const usage = String(value?.usage ?? "");
123
+ const tail = [model, usage].filter((item) => item !== "").join(" · ");
124
+
125
+ if (status === "reviewed") {
126
+ const risks =
127
+ Array.isArray(value?.risks) && value.risks.length > 0
128
+ ? `\n风险:${value.risks.join(";")}`
129
+ : "";
130
+ const acceptance =
131
+ Array.isArray(value?.acceptance) && value.acceptance.length > 0
132
+ ? `\n验收:${value.acceptance.join(";")}`
133
+ : "";
134
+ return [
135
+ {
136
+ type: "text",
137
+ text: `顾问已复核(${String(value?.severity ?? "nit")})\n${String(value?.advice ?? "")}${risks}${acceptance}\n${tail}`.trim(),
138
+ },
139
+ ];
140
+ }
141
+ if (status === "declined") {
142
+ return [{ type: "text", text: `顾问认为无需建议${tail === "" ? "" : `\n${tail}`}` }];
143
+ }
144
+ if (status === "skipped") {
145
+ return [{ type: "text", text: `顾问未徵询:${String(value?.reason ?? value?.code ?? "")}` }];
146
+ }
147
+ return [
148
+ {
149
+ type: "text",
150
+ text: `顾问不可用(${String(value?.code ?? "error")}):${String(value?.reason ?? "")}`,
151
+ },
152
+ ];
153
+ }
@@ -0,0 +1,220 @@
1
+ // @ts-check
2
+ // 把会话历史渲染成顾问能读的纯文本。
3
+ //
4
+ // 与 next-step 的 renderTranscript 的关键区别:**必须包含工具调用与工具结果**。
5
+ // Claude 的 advisor 拿到的是「含每次工具调用与结果」的完整对话;只发文本会丢掉一半信息。
6
+ // 本文件不 import 宿主包,方便单测直接喂假消息。
7
+ import { redact } from "./redact.js";
8
+
9
+ /** 我们自己的工具名:绝不喂回顾问(自观察排除)。 */
10
+ export const SELF_TOOL_NAMES = Object.freeze(new Set(["advisor"]));
11
+
12
+ /**
13
+ * 每个块的裁剪上限,按隐私档位取值(字符)。
14
+ * - off:只发人说的话,不发工具往来;
15
+ * - summary:工具参数与结果都摘要(默认);
16
+ * - full:工具结果放宽 5 倍。
17
+ */
18
+ export const SCOPE_LIMITS = Object.freeze({
19
+ off: Object.freeze({ toolArgs: 0, toolResult: 0, text: 1200, context: 0 }),
20
+ summary: Object.freeze({ toolArgs: 300, toolResult: 700, text: 2000, context: 300 }),
21
+ full: Object.freeze({ toolArgs: 1200, toolResult: 3500, text: 4000, context: 2000 }),
22
+ });
23
+
24
+ /**
25
+ * 真人输入 / 用户 RPC 之外的消息来源都算「宿主注入的上下文」(技能目录、AGENTS.md、
26
+ * 运行时事实、模型选择记录…)。它们动辄上万 token,整段发给顾问会让一次徵询贵得离谱,
27
+ * 而这些内容对「这次改动对不对」几乎没有增量信息 —— 默认只留一个带长度的标记。
28
+ * @param {any} message
29
+ * @returns {boolean}
30
+ */
31
+ export function isInjectedContext(message) {
32
+ if (message?.role !== "user") return false;
33
+ const kind = message?.source?.kind;
34
+ return kind !== undefined && kind !== "user" && kind !== "user-rpc";
35
+ }
36
+
37
+ /**
38
+ * 裁剪一段文本并留下可核对的痕迹。
39
+ * @param {string} text
40
+ * @param {number} limit 0 表示整段丢弃
41
+ * @returns {string}
42
+ */
43
+ export function clip(text, limit) {
44
+ const value = typeof text === "string" ? text : "";
45
+ if (limit <= 0) return "";
46
+ if (value.length <= limit) return value;
47
+ return `${value.slice(0, limit)}…(已截断,原长 ${value.length} 字符)`;
48
+ }
49
+
50
+ /**
51
+ * 取一条消息里所有文本块的纯文本(忽略 reasoning / 图片 / 文件)。
52
+ * @param {any} message
53
+ * @returns {string}
54
+ */
55
+ export function textOf(message) {
56
+ if (!message || !Array.isArray(message.content)) return "";
57
+ let out = "";
58
+ for (const block of message.content) {
59
+ if (block && block.type === "text" && typeof block.text === "string") out += block.text;
60
+ }
61
+ return out.trim();
62
+ }
63
+
64
+ /**
65
+ * 取 assistant 消息里的工具调用(name + 参数 + callId)。
66
+ * @param {any} message
67
+ * @returns {Array<{ id: string, name: string, args: string }>}
68
+ */
69
+ export function toolCallsOf(message) {
70
+ if (!message || !Array.isArray(message.content)) return [];
71
+ /** @type {Array<{ id: string, name: string, args: string }>} */
72
+ const out = [];
73
+ for (const block of message.content) {
74
+ if (block && block.type === "tool-call") {
75
+ out.push({
76
+ id: typeof block.id === "string" ? block.id : "",
77
+ name: typeof block.name === "string" ? block.name : "tool",
78
+ args: typeof block.arguments === "string" ? block.arguments : "",
79
+ });
80
+ }
81
+ }
82
+ return out;
83
+ }
84
+
85
+ /**
86
+ * 用户消息的「来源」标签:区分真人输入、插件注入的上下文、运行时事实。
87
+ * 顾问需要知道哪些是用户亲口说的,哪些是宿主塞进去的。
88
+ * @param {any} message
89
+ * @returns {string}
90
+ */
91
+ export function speakerOf(message) {
92
+ const role = message?.role;
93
+ const kind = message?.source?.kind;
94
+ if (role === "tool") return "工具结果";
95
+ if (role === "assistant") return "助手";
96
+ if (role === "user") {
97
+ if (kind === undefined || kind === "user" || kind === "user-rpc") return "用户";
98
+ return `上下文(${String(kind)})`;
99
+ }
100
+ return String(role ?? "未知");
101
+ }
102
+
103
+ /**
104
+ * @typedef {object} TranscriptOptions
105
+ * @property {"off"|"summary"|"full"} [scope]
106
+ * @property {boolean} [redactSecrets]
107
+ * @property {number} [maxChars] 总字符预算
108
+ */
109
+
110
+ /**
111
+ * 渲染会话历史。返回文本 + 统计(供工具卡与诊断显示「发了多少、截了多少」)。
112
+ * @param {any[]} messages `session.deriveMessages()` 的结果
113
+ * @param {TranscriptOptions} [options]
114
+ * @returns {{ text: string, stats: { messages: number, toolCalls: number, toolResults: number, contextOmitted: number, truncated: number, redactions: string[] } }}
115
+ */
116
+ export function buildTranscript(messages, options = {}) {
117
+ const scope = options.scope === "full" ? "full" : options.scope === "off" ? "off" : "summary";
118
+ const limits = SCOPE_LIMITS[scope];
119
+ const maxChars = Number.isFinite(options.maxChars) ? Number(options.maxChars) : 60000;
120
+ const shouldRedact = options.redactSecrets !== false;
121
+ /** 被排除的工具调用 id(顾问自己的调用):它们的结果也不能回喂。 */
122
+ const excludedCalls = new Set();
123
+ const toolFlowEnabled = limits.toolArgs > 0 || limits.toolResult > 0;
124
+
125
+ /** @type {string[]} */
126
+ const redactions = [];
127
+ /** @type {string[]} */
128
+ const blocks = [];
129
+ let messageCount = 0;
130
+ let toolCalls = 0;
131
+ let toolResults = 0;
132
+ let contextOmitted = 0;
133
+ let truncated = 0;
134
+
135
+ /**
136
+ * @param {string} raw
137
+ * @param {number} limit
138
+ * @param {boolean} [applyRedaction]
139
+ * @returns {string}
140
+ */
141
+ const prepare = (raw, limit, applyRedaction = true) => {
142
+ if (limit <= 0) return "";
143
+ let value = raw;
144
+ if (shouldRedact && applyRedaction) {
145
+ const result = redact(value);
146
+ value = result.text;
147
+ for (const hit of result.hits) if (!redactions.includes(hit)) redactions.push(hit);
148
+ }
149
+ const clipped = clip(value, limit);
150
+ if (clipped !== value) truncated += 1;
151
+ return clipped;
152
+ };
153
+
154
+ for (const message of Array.isArray(messages) ? messages : []) {
155
+ const role = message?.role;
156
+ if (role === "system" || role === "developer") continue;
157
+ messageCount += 1;
158
+
159
+ if (role === "tool") {
160
+ if (limits.toolResult <= 0) continue;
161
+ if (excludedCalls.has(String(message?.toolCallId ?? ""))) continue;
162
+ toolResults += 1;
163
+ const body = prepare(textOf(message), limits.toolResult);
164
+ if (body === "") continue;
165
+ const flag = message?.isError === true ? "(失败)" : "";
166
+ blocks.push(`[工具结果${flag}] ${body}`);
167
+ continue;
168
+ }
169
+
170
+ // 宿主注入的上下文:留长度标记,正文默认不发(见 isInjectedContext 的注释)。
171
+ if (isInjectedContext(message)) {
172
+ const raw = textOf(message);
173
+ if (raw === "") continue;
174
+ const kept = prepare(raw, limits.context);
175
+ contextOmitted += Math.max(0, raw.length - kept.length);
176
+ blocks.push(
177
+ `[上下文(${String(message?.source?.kind)})] ${kept === "" ? `已省略 ${raw.length} 字符` : kept}`,
178
+ );
179
+ continue;
180
+ }
181
+
182
+ const texts = prepare(textOf(message), limits.text);
183
+ if (texts !== "") blocks.push(`[${speakerOf(message)}] ${texts}`);
184
+
185
+ if (role === "assistant" && toolFlowEnabled) {
186
+ for (const call of toolCallsOf(message)) {
187
+ if (SELF_TOOL_NAMES.has(call.name)) {
188
+ if (call.id !== "") excludedCalls.add(call.id);
189
+ continue;
190
+ }
191
+ toolCalls += 1;
192
+ const args = prepare(call.args, limits.toolArgs);
193
+ blocks.push(`[工具调用] ${call.name}(${args})`);
194
+ }
195
+ }
196
+ }
197
+
198
+ let text = blocks.join("\n\n");
199
+ if (text.length > maxChars) {
200
+ // 保留开头(任务与约束)与结尾(最近的进展),中间折叠。
201
+ const headSize = Math.floor(maxChars * 0.3);
202
+ const tailSize = maxChars - headSize;
203
+ const head = text.slice(0, headSize);
204
+ const tail = text.slice(text.length - tailSize);
205
+ text = `${head}\n\n…(中间省略 ${text.length - maxChars} 字符)…\n\n${tail}`;
206
+ truncated += 1;
207
+ }
208
+
209
+ return {
210
+ text,
211
+ stats: {
212
+ messages: messageCount,
213
+ toolCalls,
214
+ toolResults,
215
+ contextOmitted,
216
+ truncated,
217
+ redactions,
218
+ },
219
+ };
220
+ }
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
+ }