dsh-selection-annotations 0.0.0-stage → 2.1.1

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.
Files changed (48) hide show
  1. package/CHANGELOG.md +171 -0
  2. package/LICENSE +21 -0
  3. package/README.md +161 -3
  4. package/README.zh-CN.md +161 -0
  5. package/client.js +11136 -0
  6. package/cordis.patch.yml +3 -0
  7. package/icon.svg +7 -0
  8. package/lib/annotations-db.js +1157 -0
  9. package/lib/index.js +1304 -0
  10. package/locale/en.json +6 -0
  11. package/locale/zh.json +6 -0
  12. package/package.json +76 -6
  13. package/scripts/build.mjs +37 -0
  14. package/scripts/check-build.mjs +10 -0
  15. package/src/core/annotation-clipboard.js +93 -0
  16. package/src/core/annotation-utils.js +27 -0
  17. package/src/core/cards.js +502 -0
  18. package/src/core/config.js +91 -0
  19. package/src/core/constants.js +34 -0
  20. package/src/core/draft-codec.js +77 -0
  21. package/src/core/draft-store.js +85 -0
  22. package/src/core/hidden-payload.js +73 -0
  23. package/src/core/image-codec.js +111 -0
  24. package/src/core/jump-icon.js +25 -0
  25. package/src/core/locale.js +59 -0
  26. package/src/core/log.js +19 -0
  27. package/src/core/markdown.js +80 -0
  28. package/src/core/messages.js +311 -0
  29. package/src/core/note-tone.js +77 -0
  30. package/src/core/panel-render.js +315 -0
  31. package/src/core/payload.js +191 -0
  32. package/src/core/preview-bridge.js +216 -0
  33. package/src/core/remote-sync.js +206 -0
  34. package/src/core/scroll-trace.js +177 -0
  35. package/src/core/sent-store.js +148 -0
  36. package/src/core/session.js +60 -0
  37. package/src/core/settings.js +168 -0
  38. package/src/core/side-tab-state.js +30 -0
  39. package/src/core/source-capture.js +530 -0
  40. package/src/core/source-locate.js +220 -0
  41. package/src/core/source-resolve.js +89 -0
  42. package/src/core/styles.js +590 -0
  43. package/src/core/turn-anchor.js +54 -0
  44. package/src/core/util.js +55 -0
  45. package/src/core/uuid.js +23 -0
  46. package/src/core/web-picker.js +426 -0
  47. package/src/entry.js +22 -0
  48. package/src/plugin.js +8706 -0
package/lib/index.js ADDED
@@ -0,0 +1,1304 @@
1
+ /**
2
+ * dsh-selection-annotations — 宿主半边(Node / Cordis)。
3
+ *
4
+ * 职责只有一件事:让「批注数据块」作为**用户指令**进入模型请求,同时留一条可回看的记录。
5
+ *
6
+ * 客户端半边把批注集合包成一份 JSON 附件随用户消息提交,于是那条用户消息的 content
7
+ * 形如 `[{type:'text'}, {type:'file'}]` —— 正文与批注块本来就是两个独立 content 块。
8
+ *
9
+ * 但 `file` 块进入模型时只会被投影成一行路径句柄(`dsh-llm` 的 `fileHandleText`),模型
10
+ * 得自己 `read` 一次才看得到内容。所以这里在 `agent/pre-step`(官方 waterfall seam,
11
+ * `dsh-session-reference` 的 recall 用的就是它)做三件事:
12
+ *
13
+ * 1. 把该 `file` 块从消息里摘掉(附件本身不再进入请求);
14
+ * 2. 把批注 JSON 作为额外的 text 块追加到原用户消息末尾,并保留 `source.kind: 'user'`;
15
+ * 3. 另发一条 `source.kind: 'selection-annotations'` 的独立消息,正文是同一份 JSON,只作记录。
16
+ *
17
+ * 两条通道各管一头:自动审查(@deepseek-ai/dsh-experimental-auto-review)只把
18
+ * `source.kind === 'user'` 的文本认作 user-instruction,其余 source 一律按 fact 处理;
19
+ * fact 只能确认事实,不能授权中等风险操作 —— 并入正文的那份负责授权。独立那条让上下文
20
+ * 里始终留着一份可回看的批注记录,不参与授权。两条消息共用同一次认领:附件只读一次,
21
+ * 同一条用户消息也只合并出一条,记录不会因为重复的 pre-step 再多出一份。
22
+ *
23
+ * 为让回合结束检查认得出这两条消息,并入的那条在 source 上写 `annotation: { version, count }`
24
+ * 标记,独立那条的 source.kind 是 'selection-annotations'(工具行据此显示
25
+ * 「上下文注入 · selection-annotations」);旧会话里写下的消息仍是 'annotation',认领时两种都收。
26
+ * v4 会话格式只要求 source.kind 非空且不是 'plugin',额外字段原样保留。
27
+ *
28
+ * 认领依据是**内容**而不是文件名:读出来的 JSON 必须带 `kind: 'dsh-selection-annotations'`。
29
+ * 文件名只用于快速预筛,`name` 变了也能正常工作。
30
+ *
31
+ * 本文件刻意不 import 任何 `@deepseek-ai/*` 包:请求期消息只需要 role/content/source,
32
+ * 自带等价实现即可,避免跨版本包解析问题。
33
+ */
34
+ import { randomUUID } from 'node:crypto'
35
+ import { appendFile, mkdir, readFile, writeFile } from 'node:fs/promises'
36
+ import { dirname } from 'node:path'
37
+ import { URL } from 'node:url'
38
+ import { REPLY_VERDICTS, createAnnotationsDb, scrollTraceFile } from './annotations-db.js'
39
+
40
+ /** 客户端给批注负载起的文件名 —— 只是预筛,不参与认领判定。 */
41
+ const ANNOTATION_FILE = '批注.json'
42
+
43
+ /** 与客户端半边共用的负载类型标记(写进 JSON 的 `kind` 字段)。 */
44
+ const PAYLOAD_KIND = 'dsh-selection-annotations'
45
+
46
+ /** 独立记录消息在 source 上写的 kind;工具行显示「上下文注入 · selection-annotations」。*/
47
+ const ANNOTATION_SOURCE_KIND = 'selection-annotations'
48
+
49
+ /** 旧版本写下的 source.kind;老会话里的消息不改写,认领时两种都收。*/
50
+ const LEGACY_ANNOTATION_SOURCE_KIND = 'annotation'
51
+
52
+ /** 单个附件读取上限的默认值,避免异常大文件拖垮这一步。 */
53
+ const DEFAULT_MAX_PAYLOAD_BYTES = 512 * 1024
54
+
55
+ /** 合并进用户消息的批注负载版本与文本边界;边界同时给客户端规则做隐藏锚点。 */
56
+ const ANNOTATION_SOURCE_VERSION = 1
57
+ const ANNOTATION_TEXT_PREFIX = '\n\n'
58
+
59
+ /** 常驻系统说明的段名与正文:让「必须逐条提交」跟着每一轮请求,而不是只藏在批注 JSON 里。 */
60
+ const REPLY_SECTION_NAME = 'selection-annotations:replies'
61
+ const REPLY_SECTION_TEXT =
62
+ '收到批注数据块(kind 为 dsh-selection-annotations 的消息)时,必须逐条答复:' +
63
+ '在结束这一轮之前调用 annotation_replies 工具,replies 的每一项用 annotations[].uuid 指定要答复的批注;' +
64
+ 'uuid 是唯一定位依据,不要用序号或轮次代替。' +
65
+ 'verdict 取 accepted / partial / rejected / needs_info,reason 写清判定理由。' +
66
+ '正文只写整体说明或需要澄清的问题,不要只在正文里复述逐条内容。' +
67
+ '当前环境没有 annotation_replies 工具时,在正文里说明原因,不要静默跳过。'
68
+
69
+ /** 回合结束检查保留多少个会话的瞬时状态。 */
70
+ const TURN_STATE_LIMIT = 100
71
+
72
+ /** 会话记录的落盘路由前缀;后面接会话 id。老接口,返回整份老形状快照。 */
73
+ const STORE_ROUTE = '/selection-annotations/session'
74
+
75
+ /** 单条批注的路由前缀;后面接条目 uuid(PATCH 写答复、DELETE 删除)。 */
76
+ const ENTRY_ROUTE = '/selection-annotations/entry'
77
+
78
+ /** 批次的路由前缀;后面接 batch_uuid(PATCH 回填 turn / anchor_key)。 */
79
+ const BATCH_ROUTE = '/selection-annotations/batch'
80
+
81
+ /** 滚动追踪的调试路由:客户端批量送来源标记,这里追加到明文日志,供人事后读。 */
82
+ const TRACE_ROUTE = '/selection-annotations/debug/trace'
83
+
84
+ /** 追踪请求体上限:一批最多 500 行,256KB 足够;再大直接 413。 */
85
+ const TRACE_MAX_BODY_BYTES = 256 * 1024
86
+
87
+ /** 日志只留最近这么多行,超出就重写文件保留尾部。 */
88
+ const TRACE_MAX_LINES = 2000
89
+
90
+ /** 会话 id 白名单:只允许规范形状,避免路径穿越。 */
91
+ const STORE_SAFE_ID = /^session-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/
92
+
93
+ /** 单个会话记录的上限;客户端已经按 3.5 MB 裁剪,这里留出余量。 */
94
+ const STORE_MAX_BYTES = 8 * 1024 * 1024
95
+
96
+ /** 台账库:懒打开的进程内单例(首次访问时才建目录、开库)。 */
97
+ let annotationsDb
98
+ function annotationStore() {
99
+ if (annotationsDb === undefined) annotationsDb = createAnnotationsDb()
100
+ return annotationsDb
101
+ }
102
+
103
+ export const name = 'selection-annotations'
104
+
105
+ // 这里刻意**不**声明 `export const Config`:schema 需要 `@deepseek-ai/schemastery`,
106
+ // 而本插件是以 `link:` 装进 profile 的 —— 模块解析按插件的真实路径(工作区)进行,
107
+ // 工作区没有 node_modules,`@deepseek-ai/*` 一律解析不到,静态导入会让整个宿主半边
108
+ // 加载失败(fiberPhase 停在 null,功能静默消失)。
109
+ // `apply(ctx, config)` 仍然照常收到 entry 的 config,所以需要在 profile patch 里写
110
+ // `config: { maxPayloadBytes: … }` 依然生效,只是没有可投影的 JSON Schema。
111
+
112
+ /** 不声明 inject:缺少附件服务时本插件仍应加载,只是退化为不做任何改写。 */
113
+ export function apply(ctx, config) {
114
+ const maxPayloadBytes = normalizeMaxBytes(config?.maxPayloadBytes)
115
+
116
+ // 会话记录的落盘通道:只有带 Web 服务器的宿主才注册;其它宿主安静跳过。
117
+ registerSessionStore(ctx)
118
+
119
+ // 逐条答复工具:模型用工具调用提交结构化答复,事件本身随会话持久化。
120
+ registerReplyTool(ctx)
121
+
122
+ // 规则不能只随批注数据进来:常驻说明负责「每轮都在」,回合结束检查负责「漏了有人管」。
123
+ registerReplyInstruction(ctx)
124
+ registerReplyWatchdog(ctx)
125
+
126
+ ctx.on(
127
+ 'agent/pre-step',
128
+ async ({ signal }, next) => {
129
+ const decision = await next()
130
+ if (decision === undefined || decision === null || decision.kind !== 'enter') return decision
131
+ if (!Array.isArray(decision.messages)) return decision
132
+
133
+ const messages = []
134
+ // 本次认领到的负载,等批注正文合并完再统一补独立记录:两条通道共用这一次认领。
135
+ const produced = []
136
+ let changed = false
137
+
138
+ for (const message of decision.messages) {
139
+ const content = Array.isArray(message?.content) ? message.content : []
140
+ const candidates = content.filter(isAnnotationBlock)
141
+
142
+ // 只处理用户自己提交的消息;合并后的消息仍带 source.kind 'user',不会被再次处理
143
+ // (附件块已经被摘掉,第二轮也不再有候选)。
144
+ if (candidates.length === 0 || message?.source?.kind !== 'user') {
145
+ messages.push(message)
146
+ continue
147
+ }
148
+
149
+ const { claimed, payloads } = await collectAnnotationBlocks(ctx, candidates, signal, maxPayloadBytes)
150
+ if (claimed.length === 0) {
151
+ messages.push(message)
152
+ continue
153
+ }
154
+
155
+ const kept = content.filter((block) => !claimed.includes(block))
156
+ changed = true
157
+
158
+ const payload = mergePayloads(payloads)
159
+ if (payload === undefined) {
160
+ // 认领了却合并不出负载:至少把附件块摘掉,避免模型只看到一行路径句柄。
161
+ if (kept.length > 0) messages.push({ ...message, content: kept })
162
+ continue
163
+ }
164
+ // 模型看到的每一条批注都把 uuid 与引文一起记下,供答复时按引文归位。
165
+ rememberAnnotationQuotes(payload)
166
+
167
+ // 批注 JSON 以 text 块并入原消息,source 保持 kind:'user',自动审查因此把整段
168
+ // 文本当作本轮用户指令;模型收到的仍然只有这一条消息。
169
+ messages.push({
170
+ ...message,
171
+ content: [
172
+ ...kept,
173
+ { type: 'text', text: ANNOTATION_TEXT_PREFIX + JSON.stringify(payload, null, 2) },
174
+ ],
175
+ source: {
176
+ ...message.source,
177
+ annotation: {
178
+ version: ANNOTATION_SOURCE_VERSION,
179
+ count: payload.annotations.length,
180
+ },
181
+ },
182
+ })
183
+
184
+ // 第二条通道:同一份负载另发一条独立记录,只作上下文里的回看。
185
+ produced.push(payload)
186
+ }
187
+
188
+ if (!changed) return decision
189
+
190
+ for (const payload of produced) {
191
+ // 上一轮的输出如果又被送回这一步(请求重试、宿主回放),记录已经在批里,不再补第二条。
192
+ if (hasAnnotationRecord(messages, annotationRecordText(payload))) continue
193
+ messages.push(createAnnotationRecord(payload))
194
+ }
195
+
196
+ return { ...decision, messages }
197
+ },
198
+ { prepend: true },
199
+ )
200
+ }
201
+
202
+ /* --------------------------------------------------------- 独立批注记录通道 */
203
+
204
+ /**
205
+ * 独立记录那条消息的正文。
206
+ *
207
+ * 与并入原消息的那份是同一份 JSON,只是不带 ANNOTATION_TEXT_PREFIX 的前导空行 ——
208
+ * 旧实现(014316c^)就是这么写的,保持形状不变,客户端按 `kind` 认它并折叠成占位符。
209
+ */
210
+ function annotationRecordText(payload) {
211
+ return JSON.stringify(payload, null, 2)
212
+ }
213
+
214
+ /**
215
+ * 合成「独立批注记录」消息:只作上下文记录,不参与授权。
216
+ *
217
+ * source.kind 固定为 'selection-annotations'(旧消息是 'annotation'),自动审查据此按 fact 处理,
218
+ * 不会把它当成用户指令;version/count 沿用旧实现的字段形状,不额外添加字段。
219
+ */
220
+ function createAnnotationRecord(payload) {
221
+ return {
222
+ id: randomUUID(),
223
+ role: 'user',
224
+ content: [{ type: 'text', text: annotationRecordText(payload) }],
225
+ source: {
226
+ kind: ANNOTATION_SOURCE_KIND,
227
+ version: ANNOTATION_SOURCE_VERSION,
228
+ count: payload.annotations.length,
229
+ },
230
+ }
231
+ }
232
+
233
+ /**
234
+ * 批里是否已经有一条内容相同的独立记录。
235
+ *
236
+ * pre-step 的输出会以 user/message 落进会话日志;同一批消息若被重复送进这一步,
237
+ * 上一轮的记录会原样出现在 decision.messages 里。按正文比对即可认出它,不必再合成一条。
238
+ */
239
+ function hasAnnotationRecord(messages, text) {
240
+ return messages.some(
241
+ (message) =>
242
+ (message?.source?.kind === ANNOTATION_SOURCE_KIND ||
243
+ message?.source?.kind === LEGACY_ANNOTATION_SOURCE_KIND) &&
244
+ Array.isArray(message.content) &&
245
+ message.content.length === 1 &&
246
+ message.content[0]?.type === 'text' &&
247
+ message.content[0].text === text,
248
+ )
249
+ }
250
+
251
+ /**
252
+ * 注册常驻系统说明。
253
+ *
254
+ * 批注的处置规则此前只写在批注 JSON 的 `instruction` 字段里,而它是一条普通的用户消息:
255
+ * 长对话被压缩后可能消失,模型也容易把「数据里的要求」当成数据。这里把它提升为系统提示段,
256
+ * 每轮请求都会带上;没有 systemPrompt 服务的宿主安静跳过。
257
+ */
258
+ function registerReplyInstruction(ctx) {
259
+ const mount = (scope) => {
260
+ let prompt
261
+ try {
262
+ prompt = scope.systemPrompt ?? (typeof scope.get === 'function' ? scope.get('systemPrompt') : undefined)
263
+ } catch {
264
+ prompt = undefined
265
+ }
266
+ if (prompt === undefined || prompt === null || typeof prompt.section !== 'function') return
267
+
268
+ let order = 9900
269
+ try {
270
+ if (typeof prompt.getSectionOrder === 'function') order = prompt.getSectionOrder('STRUCTURED_OUTPUT')
271
+ } catch {
272
+ /* 旧宿主没有命名序位:退回 STRUCTURED_OUTPUT 的数值 */
273
+ }
274
+ if (!Number.isFinite(order)) order = 9900
275
+
276
+ try {
277
+ // section 返回的清理函数绑定在注入作用域上,作用域销毁时自动移除。
278
+ prompt.section({ name: REPLY_SECTION_NAME, order, text: REPLY_SECTION_TEXT })
279
+ } catch (error) {
280
+ console.error('[selection-annotations] 注册常驻批注说明失败:', error)
281
+ }
282
+ }
283
+
284
+ try {
285
+ if (typeof ctx.inject === 'function') {
286
+ ctx.inject(['systemPrompt'], mount)
287
+ return
288
+ }
289
+ } catch {
290
+ /* 落到直接注册 */
291
+ }
292
+ mount(ctx)
293
+ }
294
+
295
+ /**
296
+ * 最近送达模型的数据块里的条目:uuid → quote。
297
+ *
298
+ * 答复工具只带 uuid;一旦客户端重建批次、宿主回填过另一套编号,模型手里的 uuid 就可能
299
+ * 在库里查不到。引文是这条批注唯一还留在数据块里的身份信息,先记下来,答复时用它归位。
300
+ * uuid 全局唯一,所以不必按会话分桶;上限只防长时间运行的无界增长。
301
+ */
302
+ const annotationQuotes = new Map()
303
+ const ANNOTATION_QUOTE_LIMIT = 2000
304
+
305
+ function rememberAnnotationQuotes(payload) {
306
+ const annotations = Array.isArray(payload?.annotations) ? payload.annotations : []
307
+ for (const annotation of annotations) {
308
+ const uuid = typeof annotation?.uuid === 'string' && annotation.uuid !== '' ? annotation.uuid : undefined
309
+ const quote = typeof annotation?.quote === 'string' && annotation.quote !== '' ? annotation.quote : undefined
310
+ if (uuid === undefined || quote === undefined) continue
311
+ // 重新插入让它排到队尾,热条目不会先被淘汰。
312
+ annotationQuotes.delete(uuid)
313
+ annotationQuotes.set(uuid, quote)
314
+ }
315
+ while (annotationQuotes.size > ANNOTATION_QUOTE_LIMIT) {
316
+ const oldest = annotationQuotes.keys().next().value
317
+ if (oldest === undefined) break
318
+ annotationQuotes.delete(oldest)
319
+ }
320
+ }
321
+
322
+ function quoteOfAnnotation(uuid) {
323
+ if (typeof uuid !== 'string' || uuid === '') return undefined
324
+ const exact = annotationQuotes.get(uuid)
325
+ if (exact !== undefined) return exact
326
+
327
+ // 答复里的编号偶尔不是库里那串:模型抄写时截断或改掉尾部(实测有过 35 位对 36 位)。
328
+ // uuid 是随机生成的,两条不同批注共有一段 28 位前缀的概率可以忽略,所以按公共前缀
329
+ // 认一次;只有唯一命中才认,认不出就交给「编号不存在」。
330
+ if (uuid.length < 28) return undefined
331
+ let found
332
+ for (const [key, quote] of annotationQuotes) {
333
+ if (key.length < 28) continue
334
+ const shorter = Math.min(key.length, uuid.length)
335
+ let same = 0
336
+ while (same < shorter && key[same] === uuid[same]) same += 1
337
+ if (same < 28) continue
338
+ if (found !== undefined && found !== quote) return undefined
339
+ found = quote
340
+ }
341
+ return found
342
+ }
343
+
344
+ /** 每个会话的回合状态:批注在哪一轮送达、哪一轮提交了答复、哪一轮已提醒过。 */
345
+ const turnStates = new Map()
346
+
347
+ function stateForSession(sessionId) {
348
+ let state = turnStates.get(sessionId)
349
+ if (state !== undefined) return state
350
+ state = { turn: 0, annotationTurn: 0, repliedTurn: 0, steeredTurn: 0 }
351
+ turnStates.set(sessionId, state)
352
+ if (turnStates.size > TURN_STATE_LIMIT) {
353
+ const oldest = turnStates.keys().next().value
354
+ if (oldest !== undefined) turnStates.delete(oldest)
355
+ }
356
+ return state
357
+ }
358
+
359
+ /**
360
+ * 这条消息是不是「带着批注进来」的用户消息。
361
+ *
362
+ * 两条通道各有一种认法:并入正文的那条 source.kind 仍是 'user',靠 source.annotation
363
+ * 标记区分;独立记录那条 source.kind 是 'selection-annotations'(旧消息为 'annotation',
364
+ * 两种都认)。标记在会话格式 v4 里只是额外字段,会被原样保留。
365
+ */
366
+ function isAnnotationCarryingMessage(message) {
367
+ const source = message?.source
368
+ if (source === null || typeof source !== 'object') return false
369
+ if (source.kind === ANNOTATION_SOURCE_KIND || source.kind === LEGACY_ANNOTATION_SOURCE_KIND) return true
370
+ const annotation = source.annotation
371
+ return (
372
+ source.kind === 'user' &&
373
+ annotation !== null &&
374
+ typeof annotation === 'object' &&
375
+ annotation.version === ANNOTATION_SOURCE_VERSION
376
+ )
377
+ }
378
+
379
+ /**
380
+ * 回合结束检查:这一轮收到了批注、却没有调用 annotation_replies,就在同一轮补一条提醒。
381
+ *
382
+ * 与 genui 的围栏纠正使用同一个接缝:在 agent/turn-stopping 里调 agent.steer,消息进入
383
+ * 下一步的收件箱,回合不会就此结束。每个回合最多提醒一次,避免模型持续不调用时反复追问。
384
+ */
385
+ function registerReplyWatchdog(ctx) {
386
+ ctx.on('session/event', (session, event) => {
387
+ const sessionId = session?.id
388
+ if (typeof sessionId !== 'string' || sessionId === '') return
389
+ const state = stateForSession(sessionId)
390
+ const type = event?.type
391
+ const data = event?.data
392
+ if (type === 'turn/start' && Number.isSafeInteger(data?.turn)) state.turn = data.turn
393
+ if (type === 'user/message' && isAnnotationCarryingMessage(data)) state.annotationTurn = state.turn
394
+ if (type === 'tool/call' && data?.name === 'annotation_replies') {
395
+ state.repliedTurn = Number.isSafeInteger(data?.turn) ? data.turn : state.turn
396
+ }
397
+ if (type === 'user/message' && data?.source?.kind === 'dsh-rewind') {
398
+ try {
399
+ recordRewind(sessionId, data?.turn)
400
+ } catch (error) {
401
+ console.error('[selection-annotations] 回退标记写入失败:', error)
402
+ }
403
+ }
404
+ if (isBotPromptEvent(event)) rememberBotSession(sessionId)
405
+ })
406
+
407
+ ctx.on('agent/turn-stopping', ({ agent, turn, signal }) => {
408
+ if (signal?.aborted === true) return
409
+ // 子代理不处理用户批注,避免为内部回合补提醒。
410
+ if (agent?.session?.header?.parentSession !== undefined) return
411
+ // DS Bot 的会话在回合收尾时要交付这条回复;此时 steer 会把提醒并进同一条答复,
412
+ // 让 Bot 多出一段不该出现的正文,所以 Bot 会话不补提醒(系统说明仍然生效)。
413
+ if (isBotSession(agent?.session)) return
414
+ const sessionId = agent?.session?.id
415
+ if (typeof sessionId !== 'string' || sessionId === '') return
416
+ const state = turnStates.get(sessionId)
417
+ if (state === undefined) return
418
+ if (state.annotationTurn !== turn || state.repliedTurn === turn || state.steeredTurn === turn) return
419
+ state.steeredTurn = turn
420
+ try {
421
+ agent.steer(createReminderMessage())
422
+ } catch (error) {
423
+ console.error('[selection-annotations] 批注答复提醒发送失败:', error)
424
+ }
425
+ })
426
+ }
427
+
428
+ /** DS Bot 的系统说明里才有的固定标记;只用来识别会话归属,不读取用户的聊天内容。 */
429
+ const BOT_PROMPT_MARKERS = ['How your Bot team works', 'Group chat']
430
+
431
+ /** 会话 id -> 是否 DS Bot 会话。会话的 system/message 不变,识别一次即可。 */
432
+ const botSessions = new Map()
433
+
434
+ function rememberBotSession(sessionId) {
435
+ if (botSessions.has(sessionId)) return
436
+ botSessions.set(sessionId, true)
437
+ if (botSessions.size > TURN_STATE_LIMIT) {
438
+ const oldest = botSessions.keys().next().value
439
+ if (oldest !== undefined) botSessions.delete(oldest)
440
+ }
441
+ }
442
+
443
+ function textOfContent(content) {
444
+ if (!Array.isArray(content)) return ''
445
+ let text = ''
446
+ for (const block of content) {
447
+ if (block?.type === 'text' && typeof block.text === 'string') text += block.text
448
+ }
449
+ return text
450
+ }
451
+
452
+ function isBotPromptEvent(event) {
453
+ if (event?.type !== 'system/message') return false
454
+ if (event?.data?.message?.source?.kind !== 'system-prompt') return false
455
+ const text = textOfContent(event.data.message.content)
456
+ return BOT_PROMPT_MARKERS.some((marker) => text.includes(marker))
457
+ }
458
+
459
+ /** 会话日志里有过 DS Bot 的系统说明,就认作 Bot 会话;日志不可读时按普通会话处理。 */
460
+ function isBotSession(session) {
461
+ const sessionId = session?.id
462
+ if (typeof sessionId !== 'string' || sessionId === '') return false
463
+ if (botSessions.has(sessionId)) return true
464
+ const log = session?.log
465
+ if (!Array.isArray(log)) return false
466
+ for (const event of log) {
467
+ if (isBotPromptEvent(event)) {
468
+ rememberBotSession(sessionId)
469
+ return true
470
+ }
471
+ }
472
+ return false
473
+ }
474
+
475
+ /** 提醒消息:以插件通知的身份插入,不伪装成用户原话。 */
476
+ function createReminderMessage() {
477
+ return {
478
+ id: randomUUID(),
479
+ role: 'user',
480
+ content: [
481
+ {
482
+ type: 'text',
483
+ text:
484
+ '你还没有提交这批批注的逐条答复。请先调用 annotation_replies 工具提交 replies' +
485
+ '(用数据块里每条批注的 uuid 对应要答复的条目),再结束这一轮;正文不必重复逐条内容。',
486
+ },
487
+ ],
488
+ // v4 会话格式只接受「生产者自己的」source kind:v3 的 kind:'plugin' 会被拒绝,
489
+ // 插件消息必须写成 plugin:<插件名>(与 genui 的围栏纠正消息同一个形状)。
490
+ source: { kind: 'plugin:dsh-selection-annotations', form: 'notice', summary: '批注答复提醒' },
491
+ }
492
+ }
493
+
494
+ /**
495
+ * 该 content 块是不是候选批注负载。
496
+ * 只做便宜的预筛(类型 + 文件名后缀),真正的认领在 {@link parsePayload} 里按内容判定。
497
+ */
498
+ function isAnnotationBlock(block) {
499
+ if (block === null || typeof block !== 'object' || block.type !== 'file') return false
500
+ const attachment = block.attachment
501
+ if (attachment === null || typeof attachment !== 'object') return false
502
+ if (typeof attachment.name !== 'string') return false
503
+ return attachment.name === ANNOTATION_FILE || attachment.name.toLowerCase().endsWith('.json')
504
+ }
505
+
506
+ /**
507
+ * 逐个读取候选附件,只认领内容确实是本插件负载的那些。
508
+ * 任何读取或解析失败都降级为「不认领」,绝不中断这一轮。
509
+ * @returns 认领的块(按原顺序)与解析出来的负载。
510
+ */
511
+ async function collectAnnotationBlocks(ctx, blocks, signal, maxPayloadBytes) {
512
+ const claimed = []
513
+ const payloads = []
514
+ for (const block of blocks) {
515
+ if (signal?.aborted === true) break
516
+ const text = await readAttachmentText(ctx, block.attachment, maxPayloadBytes)
517
+ const payload = parsePayload(text)
518
+ if (payload === undefined) continue
519
+ claimed.push(block)
520
+ payloads.push(payload)
521
+ }
522
+ return { claimed, payloads }
523
+ }
524
+
525
+ /** 认领的唯一依据:能解析成对象、`kind` 对得上、`annotations` 是数组。 */
526
+ function parsePayload(text) {
527
+ if (typeof text !== 'string' || text.trim() === '') return undefined
528
+ let parsed
529
+ try {
530
+ parsed = JSON.parse(text)
531
+ } catch {
532
+ return undefined
533
+ }
534
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) return undefined
535
+ if (parsed.kind !== PAYLOAD_KIND) return undefined
536
+ if (!Array.isArray(parsed.annotations)) return undefined
537
+ return parsed
538
+ }
539
+
540
+ /**
541
+ * 合并多份负载为一份数据块,并把 `index` 重新编号成 1..N。
542
+ * 单份时原样返回,保留客户端写好的 `instruction` 等字段。
543
+ */
544
+ function mergePayloads(payloads) {
545
+ if (payloads.length === 0) return undefined
546
+ if (payloads.length === 1) return payloads[0]
547
+ // 先把内容完全相同的副本去掉:运行时可能把已经发出的附件 restore 回输入态,
548
+ // 于是同一条消息上会挂两份一模一样的批注块 —— 那会让模型把同一批批注回复两遍。
549
+ const seen = new Set()
550
+ const unique = []
551
+ for (const payload of payloads) {
552
+ const key = JSON.stringify(payload.annotations ?? [])
553
+ if (seen.has(key)) continue
554
+ seen.add(key)
555
+ unique.push(payload)
556
+ }
557
+ if (unique.length === 1) return unique[0]
558
+ const annotations = unique
559
+ .flatMap((payload) => payload.annotations)
560
+ .map((item, index) => ({ ...item, index: index + 1 }))
561
+ return { ...unique[0], count: annotations.length, annotations }
562
+ }
563
+
564
+ /** 配置兜底:非法值回落到默认上限,而不是让这一步失败。 */
565
+ function normalizeMaxBytes(value) {
566
+ return Number.isSafeInteger(value) && value >= 1024 ? value : DEFAULT_MAX_PAYLOAD_BYTES
567
+ }
568
+
569
+ /** 优先走附件服务的流式读取,退化到宿主路径直接读文件。 */
570
+ async function readAttachmentText(ctx, ref, maxPayloadBytes = DEFAULT_MAX_PAYLOAD_BYTES) {
571
+ let attachments
572
+ try {
573
+ attachments = ctx.get('attachments')
574
+ } catch {
575
+ attachments = undefined
576
+ }
577
+ if (attachments === undefined || attachments === null) return undefined
578
+
579
+ if (typeof attachments.readFileStream === 'function') {
580
+ try {
581
+ const chunks = []
582
+ let total = 0
583
+ for await (const chunk of attachments.readFileStream(ref)) {
584
+ const bytes = Buffer.from(chunk)
585
+ // 超限视为无效负载(不认领),而不是截断半份数据丢给模型。
586
+ if (total + bytes.length > maxPayloadBytes) return undefined
587
+ total += bytes.length
588
+ chunks.push(bytes)
589
+ }
590
+ return Buffer.concat(chunks).toString('utf8')
591
+ } catch {
592
+ /* 落到宿主路径读取 */
593
+ }
594
+ }
595
+
596
+ if (typeof attachments.fileHostPath === 'function') {
597
+ try {
598
+ return await readFile(attachments.fileHostPath(ref), 'utf8')
599
+ } catch {
600
+ return undefined
601
+ }
602
+ }
603
+
604
+ return undefined
605
+ }
606
+
607
+ /* ------------------------------------------------------- 会话记录的落盘通道 */
608
+
609
+ /**
610
+ * 批注台账的路由:数据落在一个 SQLite 库里(`$DSH_HOME/selection-annotations/annotations.db`)。
611
+ *
612
+ * 为什么要落盘:客户端的 localStorage 只在这一个客户端里有效,换到 web 端或清掉站点数据
613
+ * 就什么都没有。批注和会话一样属于「本机数据」,应该跟着 DSH_HOME 走。
614
+ *
615
+ * 两个前缀路由:
616
+ * `STORE_ROUTE` 老接口,整份快照读写(客户端现在仍按老形状用);
617
+ * `ENTRY_ROUTE` 按条写入,PATCH 写答复、DELETE 删一条。
618
+ * 同一个会话下还有 `POST /session/<id>/batch` 新建一批。没有 Web 服务器的宿主安静跳过。
619
+ */
620
+ function registerSessionStore(ctx) {
621
+ /** 在拿到 webServer 的作用域里注册路由。 */
622
+ const mount = (scope) => {
623
+ let server
624
+ try {
625
+ server = scope.webServer ?? (typeof scope.get === 'function' ? scope.get('webServer') : undefined)
626
+ } catch {
627
+ server = undefined
628
+ }
629
+ if (server === undefined || server === null || typeof server.register !== 'function') return
630
+ const routes = [
631
+ {
632
+ kind: 'prefix',
633
+ path: STORE_ROUTE,
634
+ handler: (req, res) => handleSessionStore(req, res),
635
+ },
636
+ {
637
+ kind: 'prefix',
638
+ path: ENTRY_ROUTE,
639
+ handler: (req, res) => handleEntryStore(req, res),
640
+ },
641
+ {
642
+ kind: 'prefix',
643
+ path: BATCH_ROUTE,
644
+ handler: (req, res) => handleBatchStore(req, res),
645
+ },
646
+ {
647
+ kind: 'prefix',
648
+ path: TRACE_ROUTE,
649
+ handler: (req, res) => handleScrollTrace(req, res),
650
+ },
651
+ ]
652
+ const dispose = () => {
653
+ const disposals = []
654
+ for (const route of routes) {
655
+ try {
656
+ disposals.push(server.register(route))
657
+ } catch (error) {
658
+ console.error('[selection-annotations] 注册批注台账路由失败:', route.path, error)
659
+ }
660
+ }
661
+ return () => {
662
+ for (const disposal of disposals) {
663
+ if (typeof disposal !== 'function') continue
664
+ try {
665
+ disposal()
666
+ } catch {
667
+ /* 卸载失败不影响进程退出 */
668
+ }
669
+ }
670
+ }
671
+ }
672
+ try {
673
+ scope.effect(dispose, 'selection-annotations: annotation store routes')
674
+ } catch {
675
+ /* effect 不可用的宿主:直接注册,生命周期交给进程 */
676
+ dispose()
677
+ }
678
+ }
679
+
680
+ // webServer 是异步服务:apply 执行时通常还没就绪,必须等注入。
681
+ try {
682
+ if (typeof ctx.inject === 'function') {
683
+ ctx.inject(['webServer'], mount)
684
+ return
685
+ }
686
+ } catch {
687
+ /* 落到直接注册 */
688
+ }
689
+ mount(ctx)
690
+ }
691
+
692
+ /**
693
+ * 注册逐条答复工具。
694
+ *
695
+ * 模型的输出只有 text / reasoning / tool-call 三种块,想要「按对象逐条答复」只能走工具调用:
696
+ * 这个工具不产生副作用,只把结构化答复作为参数记录下来。工具调用事件本身会进入会话日志,
697
+ * 所以答复天然随 session 持久化,客户端以后可以直接从事件或投影读取并渲染。
698
+ */
699
+ function registerReplyTool(ctx) {
700
+ const mount = (scope) => {
701
+ let tools
702
+ let lookupError
703
+ try {
704
+ tools = scope.tools ?? (typeof scope.get === 'function' ? scope.get('tools') : undefined)
705
+ } catch (error) {
706
+ lookupError = error
707
+ tools = undefined
708
+ }
709
+ if (tools === undefined || tools === null || typeof tools.register !== 'function') {
710
+ // 与 webServer / systemPrompt 不同:缺了 tools 等于整条答复链路不存在。
711
+ // 这里必须出声,否则「系统提示要求调用一个不存在的工具」只能靠翻源码才能定位。
712
+ if (lookupError !== undefined) {
713
+ console.warn('[selection-annotations] annotation_replies 未注册:读取 tools 服务失败', lookupError)
714
+ } else {
715
+ console.warn('[selection-annotations] annotation_replies 未注册:当前宿主没有可用的 tools 服务')
716
+ }
717
+ return
718
+ }
719
+
720
+ const definition = {
721
+ name: 'annotation_replies',
722
+ description:
723
+ '提交对用户批注的逐条答复。处理完批注后必须调用:replies 里每一项用批注数据块里的 uuid 指明要答复的那一条,不要传序号、轮次。',
724
+ parameters: parameterSpecToJsonSchema({
725
+ replies: {
726
+ type: 'array',
727
+ required: true,
728
+ description: '逐条答复,必须覆盖本次所有批注;每项用 uuid 指定批注,不要传序号、轮次。',
729
+ items: replySchema({ requireUuid: true }),
730
+ },
731
+ }),
732
+ output: {
733
+ schema: valueSpecToJsonSchema({
734
+ type: 'object',
735
+ additionalProperties: false,
736
+ properties: {
737
+ replies: { type: 'array', required: true, items: replySchema({ requireUuid: false }) },
738
+ accepted: { type: 'integer', required: true },
739
+ partial: { type: 'integer', required: true },
740
+ rejected: { type: 'integer', required: true },
741
+ needsInfo: { type: 'integer', required: true },
742
+ saved: { type: 'boolean', required: true },
743
+ written: { type: 'integer', required: true },
744
+ // 编号对不上、但靠引文写进库内另一条时的「旧编号 → 库内编号」。
745
+ relocated: {
746
+ type: 'array',
747
+ required: true,
748
+ items: {
749
+ type: 'object',
750
+ additionalProperties: false,
751
+ properties: {
752
+ from: { type: 'string', required: true },
753
+ to: { type: 'string', required: true },
754
+ },
755
+ },
756
+ },
757
+ skipped: {
758
+ type: 'array',
759
+ required: true,
760
+ items: {
761
+ type: 'object',
762
+ additionalProperties: false,
763
+ properties: {
764
+ uuid: { type: 'string' },
765
+ index: { type: 'integer' },
766
+ // 入参里的第几条;没有 uuid 的跳过项只能靠它定位。
767
+ position: { type: 'integer' },
768
+ // 按引文匹配到多条候选时的候选数,供回执写「匹配到 N 条」。
769
+ candidates: { type: 'integer' },
770
+ reason: { type: 'string', required: true },
771
+ },
772
+ },
773
+ },
774
+ },
775
+ }),
776
+ render: (_args, value) => {
777
+ if (value?.saved === false) {
778
+ return [
779
+ {
780
+ type: 'text',
781
+ text: `已收到 ${value.replies.length} 条批注答复,但未能写入台账。`,
782
+ },
783
+ ]
784
+ }
785
+ const counts = `采纳 ${value.accepted}、部分 ${value.partial}、不采纳 ${value.rejected}、需澄清 ${value.needsInfo}`
786
+ // 回执按真实写入结果逐条报:模型和用户都能看出哪一条没写、为什么没写。
787
+ const lines = [`成功写入 ${value.written} 条批注答复(${counts})。`]
788
+ const relocated = Array.isArray(value.relocated) ? value.relocated : []
789
+ if (relocated.length > 0) {
790
+ lines.push(`按引文归位:${relocated.map((item) => `${item.from} → ${item.to}`).join('、')}。`)
791
+ }
792
+ const skipped = Array.isArray(value.skipped) ? value.skipped : []
793
+ if (skipped.length > 0) {
794
+ lines.push(`跳过 ${skipped.length} 条:${formatSkippedEntries(skipped)}。`)
795
+ }
796
+ lines.push('跳过原因会一并列出,不要只按成功条数判断。')
797
+ return [{ type: 'text', text: lines.join('\n') }]
798
+ },
799
+ },
800
+ async execute(args, exec) {
801
+ const replies = Array.isArray(args?.replies) ? args.replies : []
802
+ const sessionId = sessionIdOf(exec)
803
+ // 只把数据块里真实出现过的 uuid 的引文交给存储层:没见过的编号不会凭空匹配。
804
+ const quotes = {}
805
+ for (const reply of replies) {
806
+ const quote = quoteOfAnnotation(reply?.uuid)
807
+ if (quote !== undefined) quotes[reply.uuid] = quote
808
+ }
809
+ let result
810
+ if (sessionId !== undefined) {
811
+ try {
812
+ result = await appendReplyBatch(sessionId, { replies, quotes })
813
+ } catch (error) {
814
+ console.error('[selection-annotations] 批注答复落盘失败:', error)
815
+ }
816
+ }
817
+ // 计数按真实写入的答复算:被跳过的条目不计入采纳/部分/不采纳/需澄清。
818
+ const written = Array.isArray(result?.written) ? result.written : []
819
+ const skipped = Array.isArray(result?.skipped) ? result.skipped : []
820
+ const relocated = Array.isArray(result?.relocated) ? result.relocated : []
821
+ const counts = { accepted: 0, partial: 0, rejected: 0, needs_info: 0 }
822
+ for (const entry of written) {
823
+ if (typeof entry?.verdict === 'string' && Object.hasOwn(counts, entry.verdict)) {
824
+ counts[entry.verdict] += 1
825
+ }
826
+ }
827
+ return {
828
+ replies,
829
+ accepted: counts.accepted,
830
+ partial: counts.partial,
831
+ rejected: counts.rejected,
832
+ needsInfo: counts.needs_info,
833
+ saved: result !== undefined,
834
+ written: written.length,
835
+ relocated,
836
+ skipped,
837
+ }
838
+ },
839
+ }
840
+
841
+ let dispose
842
+ try {
843
+ dispose = tools.register(definition)
844
+ } catch (error) {
845
+ console.error('[selection-annotations] 注册 annotation_replies 工具失败:', error)
846
+ return
847
+ }
848
+ if (typeof dispose === 'function') {
849
+ try {
850
+ // effect 的回调会被立即执行,返回的才是清理函数;直接传 dispose 会当场注销注册。
851
+ scope.effect(() => dispose, 'selection-annotations: annotation replies tool')
852
+ return
853
+ } catch {
854
+ /* effect 不可用的宿主:保留注册,生命周期交给进程 */
855
+ }
856
+ }
857
+ }
858
+
859
+ // tools 在多数宿主上是同步服务;异步宿主用注入等待就绪。
860
+ try {
861
+ if (typeof ctx.inject === 'function') {
862
+ ctx.inject(['tools'], mount)
863
+ return
864
+ }
865
+ } catch {
866
+ /* 落到直接注册 */
867
+ }
868
+ mount(ctx)
869
+ }
870
+
871
+ /**
872
+ * 单条答复的 schema;parameters 与 output 各用一份,避免共享对象被编译修改。
873
+ * 工具参数只暴露 uuid:index / cardKey 只留在 output 的兼容分支里,不写进工具说明。
874
+ */
875
+ function replySchema({ requireUuid = true } = {}) {
876
+ const properties = {
877
+ uuid: {
878
+ type: 'string',
879
+ required: requireUuid,
880
+ description: '批注数据块里该条批注的 uuid;答复的唯一依据。',
881
+ },
882
+ verdict: {
883
+ type: 'string',
884
+ required: true,
885
+ enum: ['accepted', 'partial', 'rejected', 'needs_info'],
886
+ description: 'accepted 采纳 / partial 部分采纳 / rejected 不采纳 / needs_info 需要澄清',
887
+ },
888
+ reason: { type: 'string', required: true, description: '判定理由' },
889
+ next: { type: 'string', description: '下一步打算,可省略' },
890
+ }
891
+ if (!requireUuid) {
892
+ // 仅 output 回显老调用时保留;工具参数里没有这两个字段。
893
+ properties.index = { type: 'integer', description: '已弃用:仅用于兼容老调用。' }
894
+ properties.cardKey = { type: 'string', description: '已弃用:仅用于兼容老调用。' }
895
+ }
896
+ return { type: 'object', additionalProperties: false, properties }
897
+ }
898
+
899
+ /** 跳过原因的中文标签;逐条回执直接用它,不再按原因合并成计数。 */
900
+ const SKIP_REASON_LABELS = {
901
+ uuid_not_found: '编号不存在',
902
+ already_replied: '已答复过',
903
+ uuid_not_in_session: '不属于该会话',
904
+ invalid_reply: '载荷不合法',
905
+ uuid_required: '缺少编号',
906
+ batch_not_found: '找不到所属批次',
907
+ index_not_found: '找不到对应批注',
908
+ }
909
+
910
+ /** 一条跳过项的「编号(原因)」;没有编号时用入参位置代替。 */
911
+ function formatSkippedEntry(entry, position) {
912
+ const uuid = typeof entry?.uuid === 'string' && entry.uuid !== '' ? entry.uuid : undefined
913
+ const ordinal = Number.isSafeInteger(entry?.position) ? entry.position : position
914
+ const label = uuid ?? `第 ${ordinal} 条`
915
+ const reason =
916
+ entry?.reason === 'quote_ambiguous'
917
+ ? `按引文匹配到 ${Number.isSafeInteger(entry?.candidates) ? entry.candidates : 0} 条,无法确定`
918
+ : SKIP_REASON_LABELS[entry?.reason] ?? '其他原因'
919
+ return `${label}(${uuid === undefined ? `无编号,${reason}` : reason})`
920
+ }
921
+
922
+ /** 把每一条跳过项都写进回执,不合并、不省略。 */
923
+ function formatSkippedEntries(skipped) {
924
+ return skipped.map((entry, index) => formatSkippedEntry(entry, index + 1)).join('、')
925
+ }
926
+
927
+ /**
928
+ * ParameterSchemaSpec(根是隐式开放对象)转成 tools.register 要求的 JSON Schema。
929
+ * 注册接口不接受 spec 形态:`required` 必须提升为父级的字符串数组,否则会被拒绝。
930
+ */
931
+ function parameterSpecToJsonSchema(parameters) {
932
+ const properties = {}
933
+ const required = []
934
+ for (const [name, spec] of Object.entries(parameters ?? {})) {
935
+ properties[name] = valueSpecToJsonSchema(spec)
936
+ if (spec?.required === true) required.push(name)
937
+ }
938
+ const schema = { type: 'object', properties }
939
+ if (required.length > 0) schema.required = required
940
+ return schema
941
+ }
942
+
943
+ /** ValueSchemaSpec 转 JSON Schema,规则与 parameterSpecToJsonSchema 相同。 */
944
+ function valueSpecToJsonSchema(spec) {
945
+ const schema = { type: spec?.type }
946
+ if (spec?.description !== undefined) schema.description = spec.description
947
+ if (spec?.enum !== undefined) schema.enum = spec.enum
948
+ if (spec?.type === 'array') schema.items = valueSpecToJsonSchema(spec.items ?? { type: 'string' })
949
+ if (spec?.type === 'object') {
950
+ const properties = {}
951
+ const required = []
952
+ for (const [name, child] of Object.entries(spec.properties ?? {})) {
953
+ properties[name] = valueSpecToJsonSchema(child)
954
+ if (child?.required === true) required.push(name)
955
+ }
956
+ schema.properties = properties
957
+ if (required.length > 0) schema.required = required
958
+ if (spec.additionalProperties !== undefined) schema.additionalProperties = spec.additionalProperties
959
+ }
960
+ return schema
961
+ }
962
+
963
+ /* ------------------------------------------------- 逐条答复的落盘与保存 */
964
+
965
+ /** 执行上下文里的会话 id;拿不到或形状不合法都返回 undefined。 */
966
+ function sessionIdOf(exec) {
967
+ try {
968
+ const id = exec?.agent?.session?.id
969
+ return typeof id === 'string' && STORE_SAFE_ID.test(id) ? id : undefined
970
+ } catch {
971
+ return undefined
972
+ }
973
+ }
974
+
975
+ /**
976
+ * 记下一次回退:客户端轮询会话记录时据此清掉被撤回轮次的卡片,并把批注回放到待发送。
977
+ * 回退由 dsh-rewind-plugin 执行,它追加一条 source.kind='dsh-rewind' 的用户消息;
978
+ * 该消息的 turn 就是被撤回的起点(目标消息本身也一并撤回)。
979
+ */
980
+ function recordRewind(sessionId, turn) {
981
+ return annotationStore().recordRewind(sessionId, turn)
982
+ }
983
+
984
+ /** 把一批逐条答复写进会话记录:有 uuid 按 uuid,没有就退回「最近一批 + index」。 */
985
+ function appendReplyBatch(sessionId, value) {
986
+ return annotationStore().writeReplyBatch(sessionId, value)
987
+ }
988
+
989
+ /* ------------------------------------------------------------ 台账路由 */
990
+
991
+ /** 只服务本机页面:拒绝任何非回环 Host 的请求。 */
992
+ function isLoopbackRequest(req) {
993
+ const host = String(req.headers.host ?? '').toLowerCase()
994
+ return /^(127\.0\.0\.1|localhost|\[::1\])(:\d+)?$/.test(host)
995
+ }
996
+
997
+ function parseRequestUrl(req) {
998
+ try {
999
+ return new URL(req.url ?? '/', 'http://127.0.0.1')
1000
+ } catch {
1001
+ return undefined
1002
+ }
1003
+ }
1004
+
1005
+ /**
1006
+ * 删除单条批注必须带显式标记(`x-sa-explicit-delete: true`)。
1007
+ * 回退路径原来会推一份删除清单让宿主批量删,一次误判就把整会话的批注删光;
1008
+ * 那条批量通道已经撤掉,剩下的单条通道也要求调用方明确说出「确实要删」,
1009
+ * 免得同步、渲染之类的顺手逻辑把用户数据当成过期记录清掉。
1010
+ */
1011
+ function isExplicitDelete(req) {
1012
+ const header = req.headers['x-sa-explicit-delete']
1013
+ const value = Array.isArray(header) ? header[0] : header
1014
+ return String(value ?? '').trim().toLowerCase() === 'true'
1015
+ }
1016
+
1017
+ function sendJson(res, status, body) {
1018
+ res.writeHead(status, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
1019
+ res.end(body === undefined ? '' : JSON.stringify(body))
1020
+ }
1021
+
1022
+ /** 读一个 JSON 请求体;失败时已经回过响应,返回 undefined。 */
1023
+ async function readJsonBody(req, res) {
1024
+ let body
1025
+ try {
1026
+ body = await readBody(req, STORE_MAX_BYTES)
1027
+ } catch (error) {
1028
+ sendJson(res, error?.code === 'STORE_TOO_LARGE' ? 413 : 400, { error: String(error?.message ?? error) })
1029
+ return undefined
1030
+ }
1031
+ try {
1032
+ return JSON.parse(body.toString('utf8'))
1033
+ } catch {
1034
+ sendJson(res, 400, { error: 'invalid json' })
1035
+ return undefined
1036
+ }
1037
+ }
1038
+
1039
+ /** 串行追加链:多个页面同时报日志时按到达顺序落盘,不交错。 */
1040
+ let traceWriteChain = Promise.resolve()
1041
+
1042
+ /**
1043
+ * `POST /selection-annotations/debug/trace`:把客户端攒下的追踪行追加到
1044
+ * `$DSH_HOME/selection-annotations/scroll-trace.log`。每行前面加时间戳,
1045
+ * 整体只留最近 TRACE_MAX_LINES 行。只收纯文本行,不碰任何正文。
1046
+ */
1047
+ async function handleScrollTrace(req, res) {
1048
+ if (!isLoopbackRequest(req)) return sendJson(res, 403, { error: 'forbidden' })
1049
+ if (req.method !== 'POST') return sendJson(res, 405, { error: 'method not allowed' })
1050
+ let body
1051
+ try {
1052
+ body = await readBody(req, TRACE_MAX_BODY_BYTES)
1053
+ } catch (error) {
1054
+ return sendJson(res, error?.code === 'STORE_TOO_LARGE' ? 413 : 400, { error: String(error?.message ?? error) })
1055
+ }
1056
+ let parsed
1057
+ try {
1058
+ parsed = JSON.parse(body.toString('utf8'))
1059
+ } catch {
1060
+ return sendJson(res, 400, { error: 'invalid json' })
1061
+ }
1062
+ if (parsed === null || typeof parsed !== 'object' || !Array.isArray(parsed.lines)) {
1063
+ return sendJson(res, 400, { error: 'lines required' })
1064
+ }
1065
+ // 整行原样透传:每行是客户端序列化好的 JSON,宿主不解析、不挑字段,
1066
+ // 后加的字段(session / build 等)自动跟着落盘;这里只按长度兜底,防止异常长行。
1067
+ const lines = parsed.lines
1068
+ .filter((line) => typeof line === 'string' && line !== '')
1069
+ .map((line) => line.slice(0, 1000))
1070
+ if (lines.length === 0) return sendJson(res, 200, { ok: true })
1071
+ try {
1072
+ await appendScrollTrace(lines)
1073
+ return sendJson(res, 200, { ok: true })
1074
+ } catch (error) {
1075
+ console.error('[selection-annotations] 滚动追踪写入失败:', error)
1076
+ return sendJson(res, 500, { error: String(error?.message ?? error) })
1077
+ }
1078
+ }
1079
+
1080
+ /** 追加并裁剪:写完读回行数,超过上限就重写文件只留尾部。 */
1081
+ function appendScrollTrace(lines) {
1082
+ const run = async () => {
1083
+ const file = scrollTraceFile()
1084
+ await mkdir(dirname(file), { recursive: true })
1085
+ const stamp = new Date().toISOString()
1086
+ const text = lines.map((line) => `${stamp} ${line}`).join('\n')
1087
+ await appendFile(file, `${text}\n`, 'utf8')
1088
+ const all = (await readFile(file, 'utf8')).split('\n').filter((line) => line !== '')
1089
+ if (all.length <= TRACE_MAX_LINES) return
1090
+ await writeFile(file, `${all.slice(-TRACE_MAX_LINES).join('\n')}\n`, 'utf8')
1091
+ }
1092
+ traceWriteChain = traceWriteChain.then(run, run)
1093
+ return traceWriteChain
1094
+ }
1095
+
1096
+ /**
1097
+ * 老接口:`GET /selection-annotations/session/<id>` 返回老形状快照(由库拼出来),
1098
+ * `PUT|POST` 接受整份快照落库。客户端仍按这个形状读写,先不改。
1099
+ */
1100
+ async function handleSessionStore(req, res) {
1101
+ if (!isLoopbackRequest(req)) return sendJson(res, 403, { error: 'forbidden' })
1102
+ const url = parseRequestUrl(req)
1103
+ if (url === undefined) return sendJson(res, 400, { error: 'bad url' })
1104
+
1105
+ const raw = url.pathname.slice(STORE_ROUTE.length).replace(/^\//, '')
1106
+ const parts = raw.split('/').filter((part) => part !== '')
1107
+ const sessionId = safeDecode(parts[0] ?? '')
1108
+ if (sessionId === undefined || !STORE_SAFE_ID.test(sessionId)) {
1109
+ return sendJson(res, 400, { error: 'bad session id' })
1110
+ }
1111
+
1112
+ try {
1113
+ if (parts.length === 2 && parts[1] === 'batch') return await handleBatchCreate(req, res, sessionId)
1114
+ if (parts.length !== 1) return sendJson(res, 404, { error: 'not found' })
1115
+ if (req.method === 'GET' || req.method === 'HEAD') return handleSessionRead(req, res, sessionId)
1116
+ if (req.method === 'PUT' || req.method === 'POST') return await handleSessionWrite(req, res, sessionId)
1117
+ return sendJson(res, 405, { error: 'method not allowed' })
1118
+ } catch (error) {
1119
+ console.error('[selection-annotations] 会话记录读写失败:', error)
1120
+ if (!res.headersSent) sendJson(res, 500, { error: String(error?.message ?? error) })
1121
+ else res.end()
1122
+ }
1123
+ }
1124
+
1125
+ /** 老形状快照读回;库里没有这个会话就 204(与「文件不存在」时的旧行为一致)。 */
1126
+ function handleSessionRead(req, res, sessionId) {
1127
+ const snapshot = annotationStore().readSession(sessionId)
1128
+ if (snapshot === undefined) {
1129
+ sendJson(res, 204)
1130
+ return
1131
+ }
1132
+ const text = JSON.stringify(snapshot)
1133
+ res.writeHead(200, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
1134
+ res.end(req.method === 'HEAD' ? undefined : text)
1135
+ }
1136
+
1137
+ /**
1138
+ * 整份快照落库:合并规则(sent 只增、replies 按 at 去重、rewind 保留)都在存储层。
1139
+ * 快照里的 `sentRemoved` 删除清单一律忽略,存储层不再据此执行任何 DELETE;
1140
+ * 会话回退只在客户端给记录打标记,删批注只能走单条 deleteEntry。
1141
+ */
1142
+ async function handleSessionWrite(req, res, sessionId) {
1143
+ const parsed = await readJsonBody(req, res)
1144
+ if (parsed === undefined) return
1145
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
1146
+ sendJson(res, 400, { error: 'invalid payload' })
1147
+ return
1148
+ }
1149
+ annotationStore().saveSession(sessionId, parsed)
1150
+ sendJson(res, 200, { ok: true, sessionId })
1151
+ }
1152
+
1153
+ /** 新接口:`POST /session/<id>/batch` 新建一批批注,返回 batch_uuid / batch_seq。 */
1154
+ async function handleBatchCreate(req, res, sessionId) {
1155
+ if (req.method !== 'POST') return sendJson(res, 405, { error: 'method not allowed' })
1156
+ const parsed = await readJsonBody(req, res)
1157
+ if (parsed === undefined) return
1158
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
1159
+ return sendJson(res, 400, { error: 'invalid payload' })
1160
+ }
1161
+ if (!Array.isArray(parsed.items) || parsed.items.length === 0) {
1162
+ return sendJson(res, 400, { error: 'items required' })
1163
+ }
1164
+ const result = annotationStore().createBatch(sessionId, {
1165
+ turn: Number.isSafeInteger(parsed.turn) ? parsed.turn : undefined,
1166
+ anchorKey: typeof parsed.anchor_key === 'string' ? parsed.anchor_key : undefined,
1167
+ batchAt: Number.isFinite(parsed.batch_at) ? Number(parsed.batch_at) : undefined,
1168
+ items: parsed.items,
1169
+ // 客户端发送时生成的批次 uuid;同一批被重提时宿主靠它认出这是同一批。
1170
+ batchUuid: typeof parsed.batch_uuid === 'string' && parsed.batch_uuid !== '' ? parsed.batch_uuid : undefined,
1171
+ })
1172
+ sendJson(res, 200, result)
1173
+ }
1174
+
1175
+ /**
1176
+ * 新接口:`PATCH /selection-annotations/entry/<uuid>` 写答复,
1177
+ * `DELETE` 同地址删一条(必须带 `x-sa-explicit-delete: true`,否则 400)。
1178
+ * 条目首次答复后不可再改(409),要走改判用工具那条路。
1179
+ */
1180
+ async function handleEntryStore(req, res) {
1181
+ if (!isLoopbackRequest(req)) return sendJson(res, 403, { error: 'forbidden' })
1182
+ const url = parseRequestUrl(req)
1183
+ if (url === undefined) return sendJson(res, 400, { error: 'bad url' })
1184
+
1185
+ const raw = url.pathname.slice(ENTRY_ROUTE.length).replace(/^\//, '')
1186
+ if (raw === '' || raw.includes('/')) return sendJson(res, 400, { error: 'bad entry id' })
1187
+ const uuid = safeDecode(raw)
1188
+ if (uuid === undefined || uuid === '') return sendJson(res, 400, { error: 'bad entry id' })
1189
+
1190
+ try {
1191
+ if (req.method === 'DELETE') {
1192
+ if (!isExplicitDelete(req)) {
1193
+ return sendJson(res, 400, {
1194
+ error: 'explicit delete required',
1195
+ message: '删除单条批注必须带 x-sa-explicit-delete: true;不带标记的删除一律拒绝',
1196
+ })
1197
+ }
1198
+ const deleted = annotationStore().deleteEntry(uuid)
1199
+ return deleted ? sendJson(res, 200, { ok: true, uuid }) : sendJson(res, 404, { error: 'not found' })
1200
+ }
1201
+ if (req.method !== 'PATCH') return sendJson(res, 405, { error: 'method not allowed' })
1202
+
1203
+ const parsed = await readJsonBody(req, res)
1204
+ if (parsed === undefined) return
1205
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
1206
+ return sendJson(res, 400, { error: 'invalid payload' })
1207
+ }
1208
+ if (typeof parsed.verdict !== 'string' || !REPLY_VERDICTS.includes(parsed.verdict)) {
1209
+ return sendJson(res, 400, { error: 'bad verdict' })
1210
+ }
1211
+ const reason = typeof parsed.reason === 'string' ? parsed.reason : ''
1212
+ if (reason.trim() === '') return sendJson(res, 400, { error: 'reason required' })
1213
+ const result = annotationStore().patchEntry(uuid, {
1214
+ verdict: parsed.verdict,
1215
+ reason,
1216
+ next: typeof parsed.next === 'string' ? parsed.next : undefined,
1217
+ repliedSessionId: typeof parsed.session_id === 'string' ? parsed.session_id : undefined,
1218
+ })
1219
+ if (result.status === 'not_found') return sendJson(res, 404, { error: 'not found' })
1220
+ if (result.status === 'conflict') {
1221
+ return sendJson(res, 409, {
1222
+ error: 'already replied',
1223
+ message: '该批注已答复过,不能重复写入',
1224
+ })
1225
+ }
1226
+ return sendJson(res, 200, {
1227
+ ok: true,
1228
+ uuid,
1229
+ replied_at: result.replied_at,
1230
+ replied_session_id: result.replied_session_id,
1231
+ })
1232
+ } catch (error) {
1233
+ console.error('[selection-annotations] 单条批注读写失败:', error)
1234
+ if (!res.headersSent) sendJson(res, 500, { error: String(error?.message ?? error) })
1235
+ else res.end()
1236
+ }
1237
+ }
1238
+
1239
+ /**
1240
+ * `PATCH /selection-annotations/batch/<batch_uuid>`:消息真正入库后回填 turn 与 anchor_key。
1241
+ * 只补空值、不覆盖已写内容,重复调用结果一致(客户端可能重试)。
1242
+ */
1243
+ async function handleBatchStore(req, res) {
1244
+ if (!isLoopbackRequest(req)) return sendJson(res, 403, { error: 'forbidden' })
1245
+ const url = parseRequestUrl(req)
1246
+ if (url === undefined) return sendJson(res, 400, { error: 'bad url' })
1247
+
1248
+ const raw = url.pathname.slice(BATCH_ROUTE.length).replace(/^\//, '')
1249
+ if (raw === '' || raw.includes('/')) return sendJson(res, 400, { error: 'bad batch id' })
1250
+ const batchUuid = safeDecode(raw)
1251
+ if (batchUuid === undefined || batchUuid === '') return sendJson(res, 400, { error: 'bad batch id' })
1252
+ if (req.method !== 'PATCH') return sendJson(res, 405, { error: 'method not allowed' })
1253
+
1254
+ try {
1255
+ const parsed = await readJsonBody(req, res)
1256
+ if (parsed === undefined) return
1257
+ if (parsed === null || typeof parsed !== 'object' || Array.isArray(parsed)) {
1258
+ return sendJson(res, 400, { error: 'invalid payload' })
1259
+ }
1260
+ const result = annotationStore().patchBatch(batchUuid, {
1261
+ turn: Number.isSafeInteger(parsed.turn) ? parsed.turn : undefined,
1262
+ anchorKey: typeof parsed.anchor_key === 'string' ? parsed.anchor_key : undefined,
1263
+ })
1264
+ if (result.status === 'not_found') return sendJson(res, 404, { error: 'not found' })
1265
+ return sendJson(res, 200, {
1266
+ ok: true,
1267
+ batch_uuid: result.batch_uuid,
1268
+ turn: result.turn,
1269
+ anchor_key: result.anchor_key,
1270
+ })
1271
+ } catch (error) {
1272
+ console.error('[selection-annotations] 批次回填失败:', error)
1273
+ if (!res.headersSent) sendJson(res, 500, { error: String(error?.message ?? error) })
1274
+ else res.end()
1275
+ }
1276
+ }
1277
+
1278
+ function safeDecode(value) {
1279
+ try {
1280
+ return decodeURIComponent(value)
1281
+ } catch {
1282
+ return undefined
1283
+ }
1284
+ }
1285
+
1286
+ function readBody(req, limit) {
1287
+ return new Promise((resolve, reject) => {
1288
+ const chunks = []
1289
+ let total = 0
1290
+ req.on('data', (chunk) => {
1291
+ total += chunk.length
1292
+ if (total > limit) {
1293
+ const error = new Error('payload too large')
1294
+ error.code = 'STORE_TOO_LARGE'
1295
+ reject(error)
1296
+ req.destroy()
1297
+ return
1298
+ }
1299
+ chunks.push(chunk)
1300
+ })
1301
+ req.on('end', () => resolve(Buffer.concat(chunks)))
1302
+ req.on('error', reject)
1303
+ })
1304
+ }