@kangyishuai/dsh-next-step 0.3.1 → 0.4.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/events.js ADDED
@@ -0,0 +1,287 @@
1
+ // @ts-check
2
+ // 本地事件日志:`<dataRoot>/next-step/events.jsonl`,一行一个事件,append-only,2 MB 滚动。
3
+ //
4
+ // 为什么单独一个文件、不写进会话日志:
5
+ // - 会话日志是**对话的一部分**(会随 fork 复制、会被投影折叠、用户看得到);逐轮分析数据
6
+ // (闸门、耗时、token、曝光、结局)不是对话内容,混进去会污染 fork 并放大体积。
7
+ // - 落盘约定沿用 advisor 的 `decisions.jsonl`:一轮一行、append-only、超过上限改名保留一份历史。
8
+ //
9
+ // 隐私边界(硬性):**不写用户原文**。用户消息只留长度、延迟、与胶囊重合的具体对象个数;
10
+ // 胶囊文案(我们自己生成的 ≤20 字 × 1–2 条)要写,因为复盘按钮文案必须看它;
11
+ // 摘要/提问只写长度(全文在会话日志里)。
12
+ //
13
+ // 可靠性:所有写入都是「尽力而为」——失败只 warn 一次,绝不抛进回合流程。
14
+
15
+ import { createHash } from "node:crypto";
16
+ import { appendFile, mkdir, readFile, rename, stat } from "node:fs/promises";
17
+ import { join } from "node:path";
18
+
19
+ import { PROMPT_VERSION, SCHEME } from "./scheme.js";
20
+
21
+ /** 事件目录名(位于数据根下)。 */
22
+ export const EVENTS_DIR = "next-step";
23
+ /** 事件文件名。 */
24
+ export const EVENTS_FILE = "events.jsonl";
25
+ /** 滚动阈值:超过就改名 `.1`(旧的 `.1` 丢弃)。 */
26
+ export const EVENTS_MAX_BYTES = 2 * 1024 * 1024;
27
+ /** 事件结构版本。 */
28
+ export const EVENTS_VERSION = 1;
29
+
30
+ /**
31
+ * 事件目录。
32
+ * @param {string} home 数据根
33
+ * @returns {string}
34
+ */
35
+ export function eventsDirOf(home) {
36
+ return join(home, EVENTS_DIR);
37
+ }
38
+
39
+ /**
40
+ * 事件文件路径。
41
+ * @param {string} home 数据根
42
+ * @returns {string}
43
+ */
44
+ export function eventsPathOf(home) {
45
+ return join(eventsDirOf(home), EVENTS_FILE);
46
+ }
47
+
48
+ /**
49
+ * 会话 id → 稳定的 8 位短哈希(跨会话统计用,不必把完整 id 落盘)。
50
+ * @param {string} sessionId
51
+ * @returns {string}
52
+ */
53
+ export function sidOf(sessionId) {
54
+ const text = typeof sessionId === "string" ? sessionId : "";
55
+ if (text === "") return "unknown";
56
+ return createHash("sha256").update(text).digest("hex").slice(0, 8);
57
+ }
58
+
59
+ /**
60
+ * @param {{ at: number, sid: string, turn: number, tier: string, feat: { answerChars: number, toolCalls: number }, gate: string, cand?: any }} input
61
+ * @returns {any}
62
+ */
63
+ export function turnEvent(input) {
64
+ return {
65
+ t: "turn",
66
+ at: input.at,
67
+ sid: input.sid,
68
+ turn: input.turn,
69
+ tier: input.tier,
70
+ feat: { answerChars: input.feat.answerChars, toolCalls: input.feat.toolCalls },
71
+ gate: input.gate,
72
+ ...(input.cand === undefined ? {} : { cand: input.cand }),
73
+ };
74
+ }
75
+
76
+ /**
77
+ * @param {{ at: number, sid: string, turn: number, kind: "clicked" | "dismissed", index?: number, stance?: string, labelLen?: number, msSinceShown?: number }} input
78
+ * @returns {any}
79
+ */
80
+ export function actionEvent(input) {
81
+ return {
82
+ t: "action",
83
+ at: input.at,
84
+ sid: input.sid,
85
+ turn: input.turn,
86
+ kind: input.kind,
87
+ ...(input.index === undefined ? {} : { index: input.index }),
88
+ ...(input.stance === undefined ? {} : { stance: input.stance }),
89
+ ...(input.labelLen === undefined ? {} : { labelLen: input.labelLen }),
90
+ ...(input.msSinceShown === undefined ? {} : { msSinceShown: input.msSinceShown }),
91
+ };
92
+ }
93
+
94
+ /**
95
+ * @param {{ at: number, sid: string, turn: number, typed: boolean, delayMs: number, textChars: number, overlap: number }} input
96
+ * @returns {any}
97
+ */
98
+ export function followupEvent(input) {
99
+ return {
100
+ t: "followup",
101
+ at: input.at,
102
+ sid: input.sid,
103
+ turn: input.turn,
104
+ typed: input.typed,
105
+ delayMs: Math.max(0, Math.round(input.delayMs) || 0),
106
+ textChars: Math.max(0, Math.round(input.textChars) || 0),
107
+ overlap: Math.max(0, Math.round(input.overlap) || 0),
108
+ };
109
+ }
110
+
111
+ /**
112
+ * @param {{ at: number, sid: string, turn: number, visibleMs: number, ratio: number }} input
113
+ * @returns {any}
114
+ */
115
+ export function impressionEvent(input) {
116
+ return {
117
+ t: "impression",
118
+ at: input.at,
119
+ sid: input.sid,
120
+ turn: input.turn,
121
+ visibleMs: Math.max(0, Math.round(input.visibleMs) || 0),
122
+ // ratio < 0 表示宿主没有 IntersectionObserver:报表把它单列「未知」,不进曝光率分母
123
+ ratio: Number.isFinite(input.ratio) ? input.ratio : -1,
124
+ };
125
+ }
126
+
127
+ /**
128
+ * @param {{ at: number, sid: string, turn: number, found: boolean, value?: string }} input
129
+ * @returns {any}
130
+ */
131
+ export function promoteEvent(input) {
132
+ return {
133
+ t: "promote",
134
+ at: input.at,
135
+ sid: input.sid,
136
+ turn: input.turn,
137
+ found: input.found === true,
138
+ ...(input.value === undefined ? {} : { value: input.value }),
139
+ };
140
+ }
141
+
142
+ /**
143
+ * @param {{ at: number, sid: string, turn: number, kind: "schema" | "timeout" | "cancelled" | "llm" | "route", detail?: string }} input
144
+ * @returns {any}
145
+ */
146
+ export function errorEvent(input) {
147
+ const detail = typeof input.detail === "string" ? input.detail.slice(0, 200) : "";
148
+ return {
149
+ t: "error",
150
+ at: input.at,
151
+ sid: input.sid,
152
+ turn: input.turn,
153
+ kind: input.kind,
154
+ ...(detail === "" ? {} : { detail }),
155
+ };
156
+ }
157
+
158
+ /**
159
+ * @param {{ at: number, tier: string }} input
160
+ * @returns {any}
161
+ */
162
+ export function metaEvent(input) {
163
+ return { t: "meta", at: input.at, tier: input.tier, since: input.at };
164
+ }
165
+
166
+ /**
167
+ * 创建一个事件日志写入器。
168
+ *
169
+ * - 所有写入串行(内部 promise 链),避免滚动与追加交错;
170
+ * - 超过上限时把 `events.jsonl` 改名成 `events.jsonl.1`(旧 `.1` 被覆盖);
171
+ * - 任何失败只 warn 一次,返回 false,不抛错。
172
+ * @param {{ home: string, pkg?: string, logger?: { warn?: (message: string) => void }, now?: () => number }} options
173
+ * @returns {{
174
+ * path: string,
175
+ * append: (event: any) => Promise<boolean>,
176
+ * ensureMeta: (input: { tier: string }) => Promise<boolean>,
177
+ * stats: () => Promise<{ path: string, bytes: number, lines: number }>,
178
+ * }}
179
+ */
180
+ export function createEventLog({ home, pkg, logger, now }) {
181
+ const path = eventsPathOf(home);
182
+ const dir = eventsDirOf(home);
183
+ const clock = typeof now === "function" ? now : () => Date.now();
184
+ const packageVersion = typeof pkg === "string" ? pkg : "";
185
+ let chain = Promise.resolve();
186
+ let warned = false;
187
+ /** 统计缓存:避免每次设置页刷新都读整个文件。 */
188
+ let statsCache = { at: 0, bytes: 0, lines: 0 };
189
+
190
+ /**
191
+ * @param {string} message
192
+ * @param {unknown} [error]
193
+ * @returns {void}
194
+ */
195
+ function warnOnce(message, error) {
196
+ if (warned) return;
197
+ warned = true;
198
+ const detail = error instanceof Error ? `: ${error.message}` : "";
199
+ logger?.warn?.(`next-step: ${message}${detail}`);
200
+ }
201
+
202
+ /**
203
+ * @param {any} event
204
+ * @returns {Promise<boolean>}
205
+ */
206
+ async function write(event) {
207
+ const row = {
208
+ v: EVENTS_VERSION,
209
+ scheme: SCHEME,
210
+ pv: PROMPT_VERSION,
211
+ ...(packageVersion === "" ? {} : { pkg: packageVersion }),
212
+ ...event,
213
+ };
214
+ const line = `${JSON.stringify(row)}\n`;
215
+ try {
216
+ await mkdir(dir, { recursive: true });
217
+ const info = await stat(path).catch(() => null);
218
+ if (info !== null && info.size + line.length > EVENTS_MAX_BYTES) {
219
+ // 滚动:改名保留一份历史(旧的 .1 自然被覆盖)
220
+ await rename(path, `${path}.1`).catch(() => undefined);
221
+ }
222
+ await appendFile(path, line, "utf8");
223
+ statsCache.at = 0;
224
+ return true;
225
+ } catch (error) {
226
+ warnOnce("cannot write events log", error);
227
+ return false;
228
+ }
229
+ }
230
+
231
+ return {
232
+ path,
233
+ /**
234
+ * 追加一条事件(写入串行化)。
235
+ * @param {any} event
236
+ * @returns {Promise<boolean>}
237
+ */
238
+ append(event) {
239
+ const next = chain.then(() => write(event));
240
+ chain = next.then(
241
+ () => undefined,
242
+ () => undefined,
243
+ );
244
+ return next;
245
+ },
246
+ /**
247
+ * 首次运行时写一条 meta(记录采集起算点与当时档位)。已有事件时不写。
248
+ *
249
+ * 幂等性放在**串行链内部**判:并发调用时若在外面 stat,两次都会看到「空文件」,
250
+ * 于是写出两条 meta(桌面实测踩到:两个 diagnostics 并发就把起算点写了两遍)。
251
+ * @param {{ tier: string }} input
252
+ * @returns {Promise<boolean>}
253
+ */
254
+ ensureMeta(input) {
255
+ const run = async () => {
256
+ const info = await stat(path).catch(() => null);
257
+ if (info !== null && info.size > 0) return false;
258
+ return write(metaEvent({ at: clock(), tier: input.tier }));
259
+ };
260
+ const next = chain.then(run);
261
+ chain = next.then(
262
+ () => undefined,
263
+ () => undefined,
264
+ );
265
+ return next;
266
+ },
267
+ /**
268
+ * 文件体积与行数(设置页「回顾」块用;行数是近似值,1 s 内复用缓存)。
269
+ * @returns {Promise<{ path: string, bytes: number, lines: number }>}
270
+ */
271
+ async stats() {
272
+ const at = clock();
273
+ if (statsCache.at !== 0 && at - statsCache.at < 1000) {
274
+ return { path, bytes: statsCache.bytes, lines: statsCache.lines };
275
+ }
276
+ try {
277
+ const info = await stat(path);
278
+ const text = await readFile(path, "utf8");
279
+ const lines = text === "" ? 0 : text.split("\n").filter((row) => row !== "").length;
280
+ statsCache = { at, bytes: info.size, lines };
281
+ return { path, bytes: info.size, lines };
282
+ } catch (_error) {
283
+ return { path, bytes: 0, lines: 0 };
284
+ }
285
+ },
286
+ };
287
+ }
package/lib/gates.js CHANGED
@@ -4,16 +4,22 @@
4
4
  // 出错的时候不要打扰用户、回答太短没有上下文可依、用户已经在排队等回复。
5
5
  //
6
6
  // 抽成纯函数是为了能单测:service.js 依赖 @deepseek-ai/*,在单测环境里导入不了。
7
+ //
8
+ // v0.4 的两处口径调整(见 docs/adr/0013):
9
+ // - 预算闸只统计**出过的**卡(`shown`):它是"界面噪音阀门",不是"生成次数阀门";
10
+ // 被档位抑制的候选不占预算,否则严格档会把预算永远用不完、放松档位时又突然没了额度。
11
+ // - 短答闸不再只看最后一个回答的字数:工具密集型回合的收尾回答常常只有一句(「改好了」),
12
+ // 但上下文一点都不缺。判据改成「本轮回答总字数 < 80 **且** 本轮没有工具调用」。
7
13
 
8
- /** 回答短于这个字符数就不出卡:没有足够上下文,生成的建议必然是空话。 */
14
+ /** 回答短于这个字符数、且本轮没有任何工具调用,就不出卡:没有足够上下文,生成的建议必然是空话。 */
9
15
  export const MIN_ANSWER_CHARS = 80;
10
16
 
11
17
  /**
12
18
  * 判定这一轮是否应当跳过(不调用模型)。
13
19
  * @param {{
14
20
  * enabled: boolean, cardEnabled: boolean, pauseUntil: number, now: number,
15
- * queued: number, cardsForTurn: boolean, cardsInSession: number, maxCards: number,
16
- * endKind?: string, answerChars?: number,
21
+ * queued: number, cardsForTurn: boolean, shownCardsInSession: number, maxCards: number,
22
+ * endKind?: string, answerChars?: number, toolCalls?: number,
17
23
  * }} input
18
24
  * @returns {{ reason: string, detail: string } | null} 需要跳过时返回原因,否则 null
19
25
  */
@@ -25,15 +31,30 @@ export function cheapSkipReason(input) {
25
31
  if (input.queued >= 2)
26
32
  return { reason: "queued", detail: "the user already has queued messages" };
27
33
  if (input.cardsForTurn) return { reason: "duplicate", detail: "this turn already has a card" };
28
- if (input.cardsInSession >= input.maxCards) {
34
+ if (input.shownCardsInSession >= input.maxCards) {
29
35
  return { reason: "budget", detail: "per-session card budget reached" };
30
36
  }
31
37
  // 上一轮报错/被中断:先让用户看错误、决定怎么修,别在错误旁边推销下一步。
32
38
  if (typeof input.endKind === "string" && input.endKind !== "completed") {
33
39
  return { reason: "turn-error", detail: `turn ended as ${input.endKind}` };
34
40
  }
35
- if (typeof input.answerChars === "number" && input.answerChars < MIN_ANSWER_CHARS) {
36
- return { reason: "short-answer", detail: `answer has ${input.answerChars} chars` };
41
+ if (isShortAnswerWithoutTools(input)) {
42
+ return {
43
+ reason: "short-answer",
44
+ detail: `answer has ${input.answerChars ?? 0} chars and no tool calls`,
45
+ };
37
46
  }
38
47
  return null;
39
48
  }
49
+
50
+ /**
51
+ * 短答闸的判据本身:没有工具调用、且本轮回答总字数不足。
52
+ * 单独导出是为了让 service 与单测用同一套口径(也便于将来在报表里解释这条闸的损益)。
53
+ * @param {{ answerChars?: number, toolCalls?: number }} input
54
+ * @returns {boolean}
55
+ */
56
+ export function isShortAnswerWithoutTools(input) {
57
+ const chars = typeof input.answerChars === "number" ? input.answerChars : 0;
58
+ const tools = typeof input.toolCalls === "number" ? input.toolCalls : 0;
59
+ return chars < MIN_ANSWER_CHARS && tools === 0;
60
+ }
package/lib/projection.js CHANGED
@@ -1,70 +1,24 @@
1
1
  // @ts-check
2
2
  // 会话投影:把插件记录折叠成客户端可读的视图。
3
3
  // 这是「状态属于会话数据」的落点——刷新、切会话、fork 后都能从日志重建。
4
+ //
5
+ // v0.4 起视图多一个 `reveals`(用户要求显示被档位抑制的候选),
6
+ // 校验与归一化搬到 ./card-data.js(纯函数,可单测);本文件只负责折叠事件。
4
7
  import { pluginRecordOf } from "@deepseek-ai/dsh-session";
5
8
 
6
- /** 卡片记录类型(一轮一张)。 */
7
- export const CARD_RECORD = "plugin:next-step/card";
8
- /** 决策记录类型(点了 / 关了)。 */
9
- export const DECISION_RECORD = "plugin:next-step/decision";
10
- /** 投影键,客户端用 useProjection(PROJECTION_KEY) 读。 */
11
- export const PROJECTION_KEY = "nextStep";
12
-
13
- /**
14
- * 一条 option 是否合法(label 既是按钮文案,也是点击后原样发出的用户消息;
15
- * v0.2 起不再有隐藏的 text 字段——旧记录里残留的 text 会被忽略)。
16
- * @param {any} option
17
- * @returns {boolean}
18
- */
19
- function isOption(option) {
20
- return (
21
- option !== null &&
22
- typeof option === "object" &&
23
- typeof option.stance === "string" &&
24
- option.stance.trim() !== "" &&
25
- typeof option.label === "string" &&
26
- option.label.trim() !== ""
27
- );
28
- }
9
+ import {
10
+ CARD_RECORD,
11
+ DECISION_RECORD,
12
+ isCardData,
13
+ isDecisionData,
14
+ isRevealData,
15
+ REVEAL_RECORD,
16
+ } from "./card-data.js";
29
17
 
30
- /**
31
- * 卡片记录是否合法;不合法就整条丢弃(宁可不显示,也不显示半张卡)。
32
- * @param {any} data
33
- * @returns {boolean}
34
- */
35
- export function isCardData(data) {
36
- return (
37
- data !== null &&
38
- typeof data === "object" &&
39
- Number.isSafeInteger(data.turn) &&
40
- typeof data.summary === "string" &&
41
- data.summary.trim() !== "" &&
42
- typeof data.question === "string" &&
43
- data.question.trim() !== "" &&
44
- Array.isArray(data.options) &&
45
- // 1–2 条:只给 1 条表示「下一步很明确」,不是残缺;3 条以上徒增选择成本。
46
- data.options.length >= 1 &&
47
- data.options.length <= 2 &&
48
- data.options.every(isOption) &&
49
- (data.options.length === 1 || data.options[0].stance !== data.options[1].stance) &&
50
- (data.nextPrompt === undefined || typeof data.nextPrompt === "string")
51
- );
52
- }
18
+ export { CARD_RECORD, DECISION_RECORD, REVEAL_RECORD };
53
19
 
54
- /**
55
- * 决策记录是否合法。
56
- * @param {any} data
57
- * @returns {boolean}
58
- */
59
- export function isDecisionData(data) {
60
- return (
61
- data !== null &&
62
- typeof data === "object" &&
63
- Number.isSafeInteger(data.turn) &&
64
- (data.phase === "sent" || data.phase === "dismissed") &&
65
- (data.phase !== "sent" || Number.isSafeInteger(data.index))
66
- );
67
- }
20
+ /** 投影键,客户端用 useProjection(PROJECTION_KEY) 读。 */
21
+ export const PROJECTION_KEY = "nextStep";
68
22
 
69
23
  /**
70
24
  * 最小 schema 桩:`SessionProjectionRegistry` 在**读取**时会无条件调用
@@ -76,15 +30,16 @@ export function isDecisionData(data) {
76
30
  const PASSTHROUGH_SCHEMA = Object.freeze({ parse: (/** @type {any} */ value) => value });
77
31
 
78
32
  /**
79
- * 投影定义。`cards` / `decisions` 以 `String(turn)` 为键。
33
+ * 投影定义。`cards` / `decisions` / `reveals` 都以 `String(turn)` 为键。
80
34
  * @returns {any}
81
35
  */
82
36
  export function nextStepProjection() {
83
37
  return {
84
38
  key: PROJECTION_KEY,
85
- stateVersion: 1,
39
+ // v2:视图新增 reveals(客户端对缺失的 reveals 做了容错,缓存失效也不会白屏)
40
+ stateVersion: 2,
86
41
  stateSchema: PASSTHROUGH_SCHEMA,
87
- init: () => ({ view: { cards: {}, decisions: {} } }),
42
+ init: () => ({ view: { cards: {}, decisions: {}, reveals: {} } }),
88
43
  /**
89
44
  * @param {any} state
90
45
  * @param {any} event
@@ -93,28 +48,32 @@ export function nextStepProjection() {
93
48
  apply: (state, event) => {
94
49
  const record = pluginRecordOf(event);
95
50
  if (record === undefined) return state;
51
+ const view = state.view;
96
52
  if (record.type === CARD_RECORD) {
97
53
  if (!isCardData(record.data)) return state;
98
54
  const key = String(record.data.turn);
99
- if (state.view.cards[key] !== undefined) return state;
55
+ if (view.cards[key] !== undefined) return state;
100
56
  return {
101
57
  ...state,
102
- view: {
103
- ...state.view,
104
- cards: { ...state.view.cards, [key]: record.data },
105
- },
58
+ view: { ...view, cards: { ...view.cards, [key]: record.data } },
106
59
  };
107
60
  }
108
61
  if (record.type === DECISION_RECORD) {
109
62
  if (!isDecisionData(record.data)) return state;
110
63
  const key = String(record.data.turn);
111
- if (state.view.decisions[key] !== undefined) return state;
64
+ if (view.decisions[key] !== undefined) return state;
65
+ return {
66
+ ...state,
67
+ view: { ...view, decisions: { ...view.decisions, [key]: record.data } },
68
+ };
69
+ }
70
+ if (record.type === REVEAL_RECORD) {
71
+ if (!isRevealData(record.data)) return state;
72
+ const key = String(record.data.turn);
73
+ if (view.reveals[key] === true) return state;
112
74
  return {
113
75
  ...state,
114
- view: {
115
- ...state.view,
116
- decisions: { ...state.view.decisions, [key]: record.data },
117
- },
76
+ view: { ...view, reveals: { ...view.reveals, [key]: true } },
118
77
  };
119
78
  }
120
79
  return state;