@kangyishuai/dsh-advisor 0.0.0-stage → 0.1.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/anchors.js ADDED
@@ -0,0 +1,140 @@
1
+ // @ts-check
2
+ // 证据锚点校验:顾问必须为它的判断指出「在对话里的哪一处」,我们回头核对那个 ref 是否真的存在。
3
+ //
4
+ // 动机(真机踩过):顾问会用「你刚才那次失败」「这个文件」这种模糊引用,甚至编一个不存在的
5
+ // call id。把 ref 拿去和会话里的工具调用 id / 消息 id / 路径对一遍,能立刻分出「有据」和「无据」。
6
+ //
7
+ // 纯函数,不 import 宿主包:输入是已经渲染好的 transcript 索引,输出是逐条校验结果。
8
+
9
+ /** 严重度降级链(校验失败时往下退一档,不直接归零)。 */
10
+ const DOWNGRADE = Object.freeze({ blocker: "concern", concern: "nit", nit: "nit" });
11
+
12
+ /**
13
+ * 从会话消息里建索引:工具调用 id、消息 id、出现过的路径。
14
+ * @param {any[]} messages `session.deriveMessages()` 的结果
15
+ * @returns {{ callIds: Set<string>, messageIds: Set<string>, paths: Set<string>, toolNames: Set<string> }}
16
+ */
17
+ export function buildIndex(messages) {
18
+ /** @type {Set<string>} */
19
+ const callIds = new Set();
20
+ /** @type {Set<string>} */
21
+ const messageIds = new Set();
22
+ /** @type {Set<string>} */
23
+ const paths = new Set();
24
+ /** @type {Set<string>} */
25
+ const toolNames = new Set();
26
+
27
+ for (const message of Array.isArray(messages) ? messages : []) {
28
+ if (typeof message?.id === "string" && message.id !== "") messageIds.add(message.id);
29
+ if (typeof message?.toolCallId === "string" && message.toolCallId !== "") {
30
+ callIds.add(message.toolCallId);
31
+ }
32
+ for (const block of Array.isArray(message?.content) ? message.content : []) {
33
+ if (block?.type === "tool-call") {
34
+ if (typeof block.id === "string" && block.id !== "") callIds.add(block.id);
35
+ if (typeof block.name === "string" && block.name !== "") toolNames.add(block.name);
36
+ }
37
+ if (block?.type === "text" && typeof block.text === "string") {
38
+ for (const path of extractPaths(block.text)) paths.add(path);
39
+ }
40
+ }
41
+ }
42
+ return { callIds, messageIds, paths, toolNames };
43
+ }
44
+
45
+ /**
46
+ * 从一段文本里抽路径(尽量保守:只认带分隔符的、带扩展名的、或 ./ 开头的)。
47
+ * @param {string} text
48
+ * @returns {string[]}
49
+ */
50
+ export function extractPaths(text) {
51
+ const out = [];
52
+ const pattern = /(?:\.{0,2}\/)?(?:[\w.@-]+\/)+[\w.@-]+\.[A-Za-z0-9]{1,12}\b/gu;
53
+ for (const match of String(text ?? "").matchAll(pattern)) {
54
+ const value = match[0].replace(/^\.\//u, "");
55
+ if (value.length <= 200) out.push(value);
56
+ }
57
+ return out;
58
+ }
59
+
60
+ /**
61
+ * @typedef {object} AnchorCheck
62
+ * @property {string} kind
63
+ * @property {string} ref
64
+ * @property {boolean} verified
65
+ * @property {string} reason
66
+ */
67
+
68
+ /**
69
+ * 逐条校验锚点。
70
+ *
71
+ * 判定:
72
+ * - `tool_result` / `tool_call`:ref 必须是会话里出现过的工具调用 id;
73
+ * - `message`:ref 必须是会话里出现过的消息 id;
74
+ * - `file` / `path`:ref 必须出现在 transcript 的文本里(去重后按 basename 或后缀匹配);
75
+ * - 其它 kind:只能按「ref 是否在 transcript 文本中出现」宽松校验。
76
+ *
77
+ * @param {Array<{ kind: string, ref: string }>} evidence
78
+ * @param {ReturnType<typeof buildIndex>} index
79
+ * @param {string} [transcriptText]
80
+ * @returns {{ checks: AnchorCheck[], verified: number, unverified: number }}
81
+ */
82
+ export function verifyAnchors(evidence, index, transcriptText = "") {
83
+ /** @type {AnchorCheck[]} */
84
+ const checks = [];
85
+ const haystack = typeof transcriptText === "string" ? transcriptText : "";
86
+
87
+ for (const anchor of Array.isArray(evidence) ? evidence : []) {
88
+ const kind = String(anchor?.kind ?? "").toLowerCase();
89
+ const ref = String(anchor?.ref ?? "").trim();
90
+ if (ref === "") continue;
91
+
92
+ /** @type {boolean} */
93
+ let verified = false;
94
+ /** @type {string} */
95
+ let reason = "";
96
+
97
+ if (kind === "tool_result" || kind === "tool_call" || kind === "tool") {
98
+ verified = index.callIds.has(ref);
99
+ reason = verified ? "工具调用 id 存在" : "会话里没有这个工具调用 id";
100
+ } else if (kind === "message") {
101
+ verified = index.messageIds.has(ref);
102
+ reason = verified ? "消息 id 存在" : "会话里没有这个消息 id";
103
+ } else if (kind === "file" || kind === "path") {
104
+ const normalized = ref.replace(/^\.\//u, "");
105
+ const byExact = index.paths.has(normalized);
106
+ const base = normalized.split("/").pop() ?? normalized;
107
+ const byBase = [...index.paths].some(
108
+ (path) => path === normalized || path.endsWith(`/${base}`),
109
+ );
110
+ verified = byExact || byBase || haystack.includes(normalized);
111
+ reason = verified ? "路径在对话里出现过" : "对话里没有这个路径";
112
+ } else {
113
+ verified = haystack.includes(ref);
114
+ reason = verified ? "对话文本里出现过该引用" : "对话文本里没有该引用";
115
+ }
116
+
117
+ checks.push({ kind: kind || "unknown", ref, verified, reason });
118
+ }
119
+
120
+ const verified = checks.filter((check) => check.verified).length;
121
+ return { checks, verified, unverified: checks.length - verified };
122
+ }
123
+
124
+ /**
125
+ * 根据锚点校验结果调整严重度:**一个锚点都没对上**(且有锚点)时降一档,并在建议末尾追加一句提示。
126
+ * 没有提供锚点时不动(顾问可能只是没引用;这由提示词去管,不该由守卫惩罚)。
127
+ * @param {{ severity: "nit"|"concern"|"blocker", advice: string }} advice
128
+ * @param {{ checks: AnchorCheck[], verified: number, unverified: number }} result
129
+ * @returns {{ severity: "nit"|"concern"|"blocker", advice: string, downgraded: boolean }}
130
+ */
131
+ export function applyAnchorVerdict(advice, result) {
132
+ if (result.checks.length === 0 || result.verified > 0) {
133
+ return { severity: advice.severity, advice: advice.advice, downgraded: false };
134
+ }
135
+ const severity = /** @type {"nit"|"concern"|"blocker"} */ (
136
+ DOWNGRADE[/** @type {"nit"|"concern"|"blocker"} */ (advice.severity)] ?? "nit"
137
+ );
138
+ const note = `(证据锚点未对上:${result.checks.length} 条引用在对话里都找不到,严重度已降为 ${severity})`;
139
+ return { severity, advice: `${advice.advice}\n${note}`, downgraded: true };
140
+ }
package/lib/call.js ADDED
@@ -0,0 +1,215 @@
1
+ // @ts-check
2
+ // 一次顾问调用:prepareCall → stream → 聚合文本 / usage / 错误分类。
3
+ // 这是整个插件唯一会花钱的地方,所有失败都必须变成**结构化结果**,绝不向上抛。
4
+ import { BlockAssembler } from "@deepseek-ai/dsh-llm";
5
+ import { ADVISOR_SYSTEM_PROMPT, buildAdvisorInput, mintNonce } from "./prompt.js";
6
+
7
+ /** 额外调用统一打这个 purpose:也是递归防护的判据(监听器按它跳过自己)。 */
8
+ export const PURPOSE = "advisor";
9
+
10
+ /**
11
+ * 把 SDK 抛出的错误归类成稳定的 code(供工具结果与 UI 文案使用)。
12
+ * @param {unknown} error
13
+ * @returns {string}
14
+ */
15
+ export function classifyError(error) {
16
+ const anyError = /** @type {any} */ (error);
17
+ const code = typeof anyError?.code === "string" ? anyError.code : "";
18
+ const name = typeof anyError?.name === "string" ? anyError.name : "";
19
+ const message = typeof anyError?.message === "string" ? anyError.message : String(error ?? "");
20
+
21
+ if (name === "AbortError" || code === "ABORT_ERR" || /abort/iu.test(message)) return "aborted";
22
+ if (code !== "") return code;
23
+ if (/credential|api[ _-]?key|unauthorized|401/iu.test(message)) return "MISSING_CREDENTIAL";
24
+ if (/rate.?limit|429|too many requests/iu.test(message)) return "rate_limited";
25
+ if (/overload|529|503/iu.test(message)) return "overloaded";
26
+ if (/context|too long|too many tokens|prompt_too_long/iu.test(message)) return "prompt_too_long";
27
+ if (/timeout|timed out/iu.test(message)) return "timeout";
28
+ return "error";
29
+ }
30
+
31
+ /**
32
+ * @typedef {object} CallInput
33
+ * @property {any} llm 宿主 llm 服务
34
+ * @property {{ provider: string, model: string, reasoningEffort?: string }} route
35
+ * @property {{ maxTokens: number, temperature: number|null, timeoutMs: number }} settings
36
+ * @property {string} transcript
37
+ * @property {string} [focus]
38
+ * @property {string} [locale]
39
+ * @property {string} sessionId
40
+ * @property {AbortSignal} [signal]
41
+ * @property {DSH.Logger} [logger]
42
+ */
43
+
44
+ /**
45
+ * @typedef {object} CallResult
46
+ * @property {boolean} ok
47
+ * @property {string} [text] 顾问原始输出
48
+ * @property {{ inputTokens: number, outputTokens: number, cacheReadTokens: number, cacheWriteTokens: number, reasoningTokens: number }} [usage]
49
+ * @property {number} ms 耗时
50
+ * @property {string} [code]
51
+ * @property {string} [message]
52
+ * @property {string} model 实际使用的模型 id
53
+ * @property {string} effort 实际使用的思考档(空串表示默认)
54
+ */
55
+
56
+ /**
57
+ * 走一次顾问补全。**任何异常都不抛**,统一返回 `{ ok:false, code, message }`。
58
+ * @param {CallInput} input
59
+ * @returns {Promise<CallResult>}
60
+ */
61
+ export async function callAdvisor(input) {
62
+ const { llm, route, settings, transcript, sessionId } = input;
63
+ const startedAt = Date.now();
64
+ const model = route.model;
65
+ const effort = typeof route.reasoningEffort === "string" ? route.reasoningEffort : "";
66
+
67
+ if (!llm || typeof llm.prepareCall !== "function") {
68
+ return {
69
+ ok: false,
70
+ code: "llm_unavailable",
71
+ message: "宿主没有提供 llm.prepareCall",
72
+ ms: 0,
73
+ model,
74
+ effort,
75
+ };
76
+ }
77
+
78
+ const nonce = mintNonce();
79
+ const userText = buildAdvisorInput({
80
+ transcript,
81
+ nonce,
82
+ focus: input.focus,
83
+ locale: input.locale,
84
+ });
85
+ const messages = /** @type {any} */ ([
86
+ { role: "user", content: [{ type: "text", text: userText }] },
87
+ ]);
88
+
89
+ // 超时与用户中断合并:任一触发都中止(绝不留下孤儿请求继续烧 token)。
90
+ const timeoutSignal = AbortSignal.timeout(settings.timeoutMs);
91
+ const signals = [input.signal, timeoutSignal].filter(Boolean);
92
+ const signal =
93
+ signals.length > 1 && typeof AbortSignal.any === "function"
94
+ ? AbortSignal.any(/** @type {AbortSignal[]} */ (signals))
95
+ : /** @type {AbortSignal|undefined} */ (signals[0]);
96
+
97
+ /**
98
+ * @param {string} effortOverride 传空串表示「这次不带思考档」
99
+ * @returns {Promise<CallResult>}
100
+ */
101
+ const run = async (effortOverride) => {
102
+ const useEffort = effortOverride !== "" ? effortOverride : effort;
103
+ const callConfig = {
104
+ provider: route.provider,
105
+ model: route.model,
106
+ maxTokens: settings.maxTokens,
107
+ ...(settings.temperature === null || settings.temperature === undefined
108
+ ? {}
109
+ : { temperature: settings.temperature }),
110
+ };
111
+ const prepared = await llm.prepareCall(
112
+ callConfig,
113
+ signal,
114
+ (/** @type {any} */ controls, /** @type {any} */ modelInfo) => {
115
+ /** @type {any} */
116
+ const next = { ...controls };
117
+ if (effortOverride === "") {
118
+ // 显式要求「不要思考档」:不要 materialize 默认值。
119
+ return next;
120
+ }
121
+ if (useEffort !== "") next.reasoningEffort = useEffort;
122
+ else if (typeof modelInfo?.reasoning?.defaultEffort === "string") {
123
+ next.reasoningEffort = modelInfo.reasoning.defaultEffort;
124
+ }
125
+ return next;
126
+ },
127
+ );
128
+
129
+ const assembler = new BlockAssembler();
130
+ /** @type {any} */
131
+ let usage;
132
+ /** @type {any} */
133
+ let finish;
134
+ for await (const chunk of prepared.stream({
135
+ ...prepared.config,
136
+ messages,
137
+ system: ADVISOR_SYSTEM_PROMPT,
138
+ sessionId,
139
+ purpose: PURPOSE,
140
+ ...(signal === undefined ? {} : { signal }),
141
+ })) {
142
+ if (chunk?.type === "usage") usage = chunk.usage;
143
+ if (chunk?.type === "finish") finish = chunk.reason;
144
+ assembler.push(chunk);
145
+ }
146
+
147
+ const settled = assembler.finish;
148
+ if (settled?.kind === "error") {
149
+ const failure = settled.failure;
150
+ return {
151
+ ok: false,
152
+ code: classifyError(failure),
153
+ message: `顾问调用失败:${failure?.message ?? "unknown"}`,
154
+ ms: Date.now() - startedAt,
155
+ model,
156
+ effort: useEffort,
157
+ };
158
+ }
159
+ if (settled?.kind === "aborted" || finish?.kind === "aborted") {
160
+ return {
161
+ ok: false,
162
+ code: "aborted",
163
+ message: "顾问调用被中止",
164
+ ms: Date.now() - startedAt,
165
+ model,
166
+ effort: useEffort,
167
+ };
168
+ }
169
+
170
+ let text = "";
171
+ for (const block of assembler.blocks()) {
172
+ if (block?.type === "text" && typeof block.text === "string") text += block.text;
173
+ }
174
+
175
+ const normalizedUsage = {
176
+ inputTokens: Number(usage?.inputTokens ?? 0) || 0,
177
+ outputTokens: Number(usage?.outputTokens ?? 0) || 0,
178
+ cacheReadTokens: Number(usage?.cacheReadTokens ?? 0) || 0,
179
+ cacheWriteTokens: Number(usage?.cacheWriteTokens ?? 0) || 0,
180
+ reasoningTokens: Number(usage?.reasoningTokens ?? 0) || 0,
181
+ };
182
+
183
+ return {
184
+ ok: true,
185
+ text,
186
+ usage: normalizedUsage,
187
+ ms: Date.now() - startedAt,
188
+ model,
189
+ effort: useEffort,
190
+ };
191
+ };
192
+
193
+ try {
194
+ try {
195
+ return await run(effort);
196
+ } catch (error) {
197
+ const code = classifyError(error);
198
+ // 模型不支持这个思考档:去掉思考档重试**一次**(不无限重试)。
199
+ if (code === "UNSUPPORTED_REASONING_EFFORT" || code === "INVALID_MODEL_REASONING") {
200
+ input.logger?.warn?.(`[advisor] 模型不支持思考档 ${effort || "(默认)"},已降级重试`);
201
+ return await run("");
202
+ }
203
+ throw error;
204
+ }
205
+ } catch (error) {
206
+ return {
207
+ ok: false,
208
+ code: classifyError(error),
209
+ message: error instanceof Error ? error.message : String(error),
210
+ ms: Date.now() - startedAt,
211
+ model,
212
+ effort,
213
+ };
214
+ }
215
+ }