@wwwfz/dsh-agent-bridge 0.8.3 → 0.10.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.
Files changed (45) hide show
  1. package/README.md +132 -194
  2. package/THIRD_PARTY_NOTICES.md +67 -0
  3. package/cordis.patch.yml +4 -4
  4. package/package.json +40 -40
  5. package/src/assets.js +405 -348
  6. package/src/catalog.js +999 -605
  7. package/src/client.js +883 -4
  8. package/src/config.js +88 -88
  9. package/src/conversation-readers.js +198 -0
  10. package/src/conversation-store.js +583 -0
  11. package/src/export.js +273 -12
  12. package/src/index.js +282 -136
  13. package/src/native-transcript.js +217 -0
  14. package/src/project-archive.js +145 -145
  15. package/src/projects.js +1837 -980
  16. package/src/session-import.js +138 -93
  17. package/src/session-trace.js +121 -0
  18. package/src/skill-handoff.js +1327 -0
  19. package/src/skill-package.js +417 -0
  20. package/src/skill-provider.js +249 -0
  21. package/src/watch.js +319 -309
  22. package/web/Geist-OFL.txt +93 -93
  23. package/web/agent-icons/NOTICE.md +19 -19
  24. package/web/agent-icons/antigravity.svg +76 -76
  25. package/web/agent-icons/claude.svg +3 -3
  26. package/web/agent-icons/dsh.svg +58 -58
  27. package/web/agent-icons/licenses/copilot.txt +21 -21
  28. package/web/agent-icons/licenses/dsh.txt +21 -21
  29. package/web/agent-icons/licenses/gemini.txt +201 -201
  30. package/web/agent-icons/licenses/opencode.txt +21 -21
  31. package/web/agent-icons/licenses/qoder-notice.txt +18 -18
  32. package/web/agent-icons/licenses/qoder.txt +22 -22
  33. package/web/agent-icons/licenses/qwen.txt +202 -202
  34. package/web/agent-icons/qoder.svg +4 -4
  35. package/web/agent-icons/qwen.svg +5 -5
  36. package/web/agent-icons/workbuddy.svg +29 -29
  37. package/web/inline-process.css +22 -0
  38. package/web/markdown.js +225 -0
  39. package/web/panel.css +168 -151
  40. package/web/panel.html +82 -43
  41. package/web/panel.js +1316 -93
  42. package/web/project-context.js +25 -25
  43. package/web/reader.css +259 -0
  44. package/web/vendor/markdown-it-LICENSE.txt +156 -0
  45. package/web/vendor/markdown-it.mjs +3064 -0
@@ -0,0 +1,583 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { existsSync } from 'node:fs'
3
+ import { mkdir, open } from 'node:fs/promises'
4
+ import path from 'node:path'
5
+ import { DatabaseSync } from 'node:sqlite'
6
+ import { isSessionId, traceDirectory } from './session-trace.js'
7
+
8
+ const pageBytes = 64 * 1024
9
+ const partLength = 8_000
10
+ const maxAttachmentBytes = 32 * 1024 * 1024
11
+ const lifetime = 10 * 60_000
12
+
13
+ async function database(config, create = true) {
14
+ const directory = path.join(path.dirname(traceDirectory(config)), 'agent-bridge-history')
15
+ const file = path.join(directory, 'history.sqlite')
16
+ if (create) {
17
+ await mkdir(directory, { recursive: true, mode: 0o700 })
18
+ const handle = await open(file, 'a', 0o600)
19
+ await handle.close()
20
+ } else if (!existsSync(file)) return
21
+ const db = new DatabaseSync(file, { readOnly: !create })
22
+ try {
23
+ db.exec('PRAGMA trusted_schema = OFF; PRAGMA busy_timeout = 2000;')
24
+ if (!create) return db
25
+ db.exec(`
26
+ PRAGMA foreign_keys = ON;
27
+ CREATE TABLE IF NOT EXISTS snapshots (
28
+ id TEXT PRIMARY KEY, session_id TEXT UNIQUE NOT NULL,
29
+ state TEXT NOT NULL, created INTEGER NOT NULL,
30
+ project_id TEXT, source_id TEXT, target TEXT,
31
+ record TEXT, seed TEXT
32
+ );
33
+ CREATE INDEX IF NOT EXISTS snapshot_source ON snapshots(project_id, source_id, state);
34
+ CREATE TABLE IF NOT EXISTS entries (
35
+ snapshot_id TEXT NOT NULL REFERENCES snapshots(id) ON DELETE CASCADE,
36
+ seq INTEGER NOT NULL, part INTEGER NOT NULL,
37
+ turn INTEGER, call_id TEXT, kind TEXT NOT NULL, item TEXT NOT NULL,
38
+ PRIMARY KEY (snapshot_id, seq, part)
39
+ );
40
+ CREATE INDEX IF NOT EXISTS entry_call ON entries(snapshot_id, call_id, kind, seq);
41
+ CREATE INDEX IF NOT EXISTS entry_turn ON entries(snapshot_id, turn, seq, part);
42
+ CREATE INDEX IF NOT EXISTS entry_display ON entries(snapshot_id, COALESCE(turn, 0), seq, part);
43
+ CREATE TABLE IF NOT EXISTS attachments (
44
+ snapshot_id TEXT NOT NULL REFERENCES snapshots(id) ON DELETE CASCADE,
45
+ hash TEXT NOT NULL, type TEXT NOT NULL, bytes BLOB NOT NULL,
46
+ PRIMARY KEY (snapshot_id, hash)
47
+ );
48
+ `)
49
+ return db
50
+ } catch (error) {
51
+ db.close()
52
+ throw error
53
+ }
54
+ }
55
+
56
+ async function use(config, action, write = true) {
57
+ const db = await database(config, write)
58
+ if (!db) return
59
+ try { return action(db) } finally { db.close() }
60
+ }
61
+
62
+ function* parts(text) {
63
+ let offset = 0
64
+ do {
65
+ let end = Math.min(offset + partLength, text.length)
66
+ if (end < text.length && /[\uD800-\uDBFF]/u.test(text[end - 1])) end--
67
+ yield { text: text.slice(offset, end), offset, continued: end < text.length }
68
+ offset = end
69
+ } while (offset < text.length)
70
+ }
71
+
72
+ export function imageMediaType(buffer) {
73
+ if (buffer.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex'))) return 'image/png'
74
+ if (buffer.subarray(0, 3).equals(Buffer.from('ffd8ff', 'hex'))) return 'image/jpeg'
75
+ if (['GIF87a', 'GIF89a'].includes(buffer.toString('ascii', 0, 6))) return 'image/gif'
76
+ if (buffer.toString('ascii', 0, 4) === 'RIFF' && buffer.toString('ascii', 8, 12) === 'WEBP') return 'image/webp'
77
+ }
78
+
79
+ function saveAttachment(db, id, item, data) {
80
+ if (!Buffer.isBuffer(data)) return { ...item, status: item.status ?? 'attachment-unavailable' }
81
+ if (data.length > maxAttachmentBytes) return { ...item, status: 'attachment-too-large' }
82
+ const attachmentId = createHash('sha256').update(data).digest('hex')
83
+ const mediaType = imageMediaType(data) ?? 'application/octet-stream'
84
+ db.prepare('INSERT OR IGNORE INTO attachments VALUES (?, ?, ?, ?)').run(id, attachmentId, mediaType, data)
85
+ return { ...item, status: 'saved', attachmentId, mediaType, bytes: data.length }
86
+ }
87
+
88
+ function appendProjection(messages, message, state) {
89
+ const text = message.text.slice(0, 24_000).replace(/[\uD800-\uDBFF]$/, '')
90
+ if (text.length < message.text.length) state.truncated = true
91
+ messages.push({ ...message, text })
92
+ state.characters += text.length
93
+ while (messages.length > 600 || state.characters > 160_000) {
94
+ const removed = messages.shift()
95
+ state.characters -= removed.text.length
96
+ if (removed.role === 'user') state.lastQuestion = removed
97
+ state.truncated = true
98
+ }
99
+ }
100
+
101
+ function disambiguateToolCalls(db, id, trace) {
102
+ const duplicates = db.prepare(`SELECT call_id FROM entries
103
+ WHERE snapshot_id=? AND call_id IS NOT NULL AND kind='tool_call' AND part=0
104
+ GROUP BY call_id HAVING count(*)>1`).all(id)
105
+ if (!duplicates.length) return
106
+ const read = db.prepare(`SELECT kind,seq,turn FROM entries
107
+ WHERE snapshot_id=? AND call_id=? AND part=0 ORDER BY seq`)
108
+ const update = db.prepare('UPDATE entries SET call_id=? WHERE snapshot_id=? AND seq=?')
109
+ const traceBySeq = new Map(trace.map(item => [item.seq, item]))
110
+ for (const { call_id: key } of duplicates) {
111
+ const entries = read.all(id, key)
112
+ const callsAndResults = entries.filter(item => item.kind === 'tool_call' || item.kind === 'tool_result')
113
+ // Pair a reused id only when each occurrence settled before the next call.
114
+ // Overlapping calls and extra or missing results keep their unknown owner.
115
+ if (callsAndResults.length % 2 || !callsAndResults.every((item, index) =>
116
+ item.kind === (index % 2 ? 'tool_result' : 'tool_call') && (index % 2 || item.turn !== null))) continue
117
+ let occurrence
118
+ for (const item of entries) {
119
+ if (item.kind === 'tool_call') occurrence = `${key}:${item.seq}`
120
+ if (!occurrence) continue
121
+ update.run(occurrence, id, item.seq)
122
+ const stamp = traceBySeq.get(item.seq)
123
+ if (stamp) stamp.callKey = occurrence
124
+ }
125
+ }
126
+ }
127
+
128
+ export async function stageConversation(config, metadata, events, redact, loadAttachment) {
129
+ const { id, sessionId } = metadata
130
+ const db = await database(config)
131
+ const messages = []
132
+ const trace = []
133
+ const usedSkills = new Set()
134
+ const stats = { userMessages: 0, assistantMessages: 0 }
135
+ const state = { characters: 0, truncated: false }
136
+ const history = { snapshotId: id, messages: 0, tools: 0, attachments: 0, gaps: 0, complete: true, nativeMessages: 0 }
137
+ let seq = 0
138
+ let timed = 0
139
+ let firstAt = Infinity
140
+ let lastAt = 0
141
+ let created = false
142
+ try {
143
+ db.prepare("DELETE FROM snapshots WHERE state IN ('loading','preview') AND created < ?").run(Date.now() - lifetime)
144
+ db.prepare("INSERT INTO snapshots(id,session_id,state,created,project_id,source_id,target) VALUES (?,?,'loading',?,?,?,?)")
145
+ .run(id, sessionId, Date.now(), metadata.projectId ?? null, metadata.sourceId ?? null, metadata.targetCwd ?? null)
146
+ created = true
147
+ const insert = db.prepare('INSERT INTO entries VALUES (?, ?, ?, ?, ?, ?, ?)')
148
+ const batch = []
149
+ let batchBytes = 0
150
+ const flush = () => {
151
+ if (!batch.length) return
152
+ db.exec('BEGIN')
153
+ try {
154
+ for (const row of batch) insert.run(id, ...row)
155
+ db.exec('COMMIT')
156
+ } catch (error) {
157
+ db.exec('ROLLBACK')
158
+ throw error
159
+ }
160
+ batch.length = 0
161
+ batchBytes = 0
162
+ }
163
+ const put = (item, callKey) => {
164
+ seq++
165
+ const chunks = 'text' in item ? parts(item.text) : [{ offset: 0 }]
166
+ for (const chunk of chunks) {
167
+ const json = JSON.stringify({ ...item, ...chunk, seq })
168
+ batch.push([seq, chunk.offset, item.turn ?? null, callKey ?? null, item.kind, json])
169
+ batchBytes += Buffer.byteLength(json)
170
+ if (batch.length >= 128 || batchBytes >= 512 * 1024) flush()
171
+ }
172
+ }
173
+ const endings = new Map()
174
+ for await (const raw of events) {
175
+ if (raw.kind === 'metadata') {
176
+ for (const skill of raw.usedSkills ?? []) usedSkills.add(skill)
177
+ if (raw.sourceStats?.tokens) stats.tokens = raw.sourceStats.tokens
178
+ continue
179
+ }
180
+ const item = { kind: raw.kind }
181
+ let callKey
182
+ if (Number.isSafeInteger(raw.turn) && raw.turn > 0) item.turn = raw.turn
183
+ if (Number.isFinite(raw.time) && raw.time > 0) item.time = raw.time
184
+ if (typeof raw.sourceId === 'string') item.sourceId = redact(raw.sourceId)
185
+ if (typeof raw.parentId === 'string') item.parentId = redact(raw.parentId)
186
+ if (typeof raw.branchId === 'string') item.branchId = redact(raw.branchId)
187
+ if (typeof raw.text === 'string') item.text = redact(raw.text)
188
+ if (typeof raw.callId === 'string' && raw.callId) {
189
+ item.callId = redact(raw.callId)
190
+ callKey = createHash('sha256').update(JSON.stringify([raw.branchId ?? '', raw.callId])).digest('hex')
191
+ }
192
+ if (raw.kind === 'message') {
193
+ if (!['user', 'assistant'].includes(raw.role) || !item.text?.trim()) continue
194
+ item.role = raw.role
195
+ history.messages++
196
+ stats[`${item.role}Messages`]++
197
+ if (item.time && raw.estimatedTime !== true) {
198
+ timed++
199
+ firstAt = Math.min(firstAt, item.time)
200
+ lastAt = Math.max(lastAt, item.time)
201
+ }
202
+ if (!item.branchId) appendProjection(messages, { role: item.role, text: item.text, time: item.time, turn: item.turn, sourceSeq: seq + 1 }, state)
203
+ } else if (raw.kind === 'gap') {
204
+ item.reason = redact(raw.reason)
205
+ history.gaps++
206
+ } else if (raw.kind === 'attachment') {
207
+ item.name = redact(raw.name ?? '附件').slice(0, 240)
208
+ if (['user', 'assistant'].includes(raw.role)) item.role = raw.role
209
+ if (raw.status) item.status = raw.status
210
+ const attachment = await loadAttachment?.(raw)
211
+ Object.assign(item, saveAttachment(db, id, { ...item, ...attachment?.details }, attachment?.bytes ?? raw.data))
212
+ history.attachments++
213
+ if (item.status !== 'saved') history.gaps++
214
+ if (raw.role === 'user' && raw.standalone === true && !item.branchId) {
215
+ item.standalone = true
216
+ appendProjection(messages, { role: 'user', text: `[来源附件 ${item.name},见完整历史]`, time: item.time, turn: item.turn, sourceSeq: seq + 1 }, state)
217
+ }
218
+ } else if (raw.kind === 'turn_end' && item.turn && ['completed', 'interrupted'].includes(raw.status)) {
219
+ item.status = raw.status
220
+ if (!item.branchId) endings.set(item.turn, raw.status)
221
+ } else if (['summary', 'tool_call', 'tool_result'].includes(raw.kind)) {
222
+ if (raw.name) item.name = redact(raw.name)
223
+ if (raw.status) item.status = raw.status
224
+ if (raw.kind === 'tool_call') history.tools++
225
+ trace.push({ ...item, callKey, seq: seq + 1, id: `source-${seq + 1}`, text: (item.text ?? '').slice(0, 8193) })
226
+ if (trace.length > 600) trace.shift()
227
+ } else continue
228
+ put(item, callKey)
229
+ }
230
+ flush()
231
+ disambiguateToolCalls(db, id, trace)
232
+ db.prepare(`UPDATE entries AS result SET turn = (
233
+ SELECT CASE WHEN COUNT(*)=1 THEN MIN(call.turn) END FROM entries AS call
234
+ WHERE call.snapshot_id=result.snapshot_id AND call.call_id=result.call_id AND call.kind='tool_call' AND call.part=0
235
+ ) WHERE result.snapshot_id=? AND (result.kind='tool_result' OR (result.kind='attachment' AND result.call_id IS NOT NULL))`).run(id)
236
+ const unmatched = db.prepare(`SELECT count(*) AS count FROM entries WHERE snapshot_id=? AND part=0 AND turn IS NULL
237
+ AND (kind='tool_result' OR (kind='attachment' AND call_id IS NOT NULL))`).get(id).count
238
+ if (unmatched) {
239
+ history.gaps += unmatched
240
+ put({ kind: 'gap', reason: `${unmatched} 条工具结果或附件的归属未知,原文见来源记录。` })
241
+ flush()
242
+ }
243
+ if (messages[0]?.role === 'assistant' && state.lastQuestion) {
244
+ while (messages.length >= 600 || state.characters + state.lastQuestion.text.length > 160_000) {
245
+ state.characters -= messages.shift().text.length
246
+ }
247
+ messages.unshift(state.lastQuestion)
248
+ }
249
+ const retained = messages.slice(messages.findIndex(message => message.role === 'user') < 0
250
+ ? messages.length : messages.findIndex(message => message.role === 'user'))
251
+ for (const message of retained) {
252
+ if (message.role === 'user' && endings.has(message.turn)) message.endReason = endings.get(message.turn)
253
+ }
254
+ history.nativeMessages = retained.length
255
+ if (retained[0]?.turn) history.nativeFirstTurn = retained[0].turn
256
+ if (retained.at(-1)?.turn) history.nativeLastTurn = retained.at(-1).turn
257
+ history.complete = history.gaps === 0
258
+ const anchors = new Map(retained.map((message, index) => [message.turn, index]))
259
+ const findCall = db.prepare("SELECT turn,item,COUNT(*) AS count FROM entries WHERE snapshot_id=? AND call_id=? AND kind='tool_call' AND part=0")
260
+ const findResult = db.prepare("SELECT item FROM entries WHERE snapshot_id=? AND call_id=? AND kind='tool_result' ORDER BY seq LIMIT 1")
261
+ const pairedTrace = trace.flatMap(item => {
262
+ if (item.kind === 'tool_result') {
263
+ const call = item.callKey && findCall.get(id, item.callKey)
264
+ if (call?.count !== 1) return []
265
+ item.turn = call.turn
266
+ item.name ??= JSON.parse(call.item).name
267
+ }
268
+ if (item.kind === 'tool_call') {
269
+ const result = item.callKey && findCall.get(id, item.callKey).count === 1 && findResult.get(id, item.callKey)
270
+ item.status = result ? JSON.parse(result.item).status ?? 'ok' : 'missing'
271
+ }
272
+ const messageIndex = anchors.get(item.turn)
273
+ const { callKey, seq, ...reviewed } = item
274
+ return messageIndex === undefined ? [] : [{ ...reviewed, messageIndex }]
275
+ }).sort((a, b) => a.turn - b.turn)
276
+ const sourceStats = { ...stats, importedMessages: retained.length, partial: !history.complete,
277
+ ...(timed >= 2 && timed === history.messages ? { elapsedMs: lastAt - firstAt } : {}) }
278
+ const record = { ...metadata, history, sourceStats, messages: retained, trace: pairedTrace,
279
+ usedSkills: [...usedSkills], truncated: state.truncated || !history.complete }
280
+ db.prepare("UPDATE snapshots SET state='preview', created=?, record=? WHERE id=?")
281
+ .run(Date.now(), JSON.stringify(record), id)
282
+ return record
283
+ } catch (error) {
284
+ if (created) db.prepare("DELETE FROM snapshots WHERE id=? AND state='loading'").run(id)
285
+ throw error
286
+ } finally {
287
+ db.close()
288
+ }
289
+ }
290
+
291
+ function readRecord(row) {
292
+ return row?.record ? { ...JSON.parse(row.record), state: row.state, seed: row.seed ? JSON.parse(row.seed) : undefined } : undefined
293
+ }
294
+
295
+ export async function readConversationSnapshot(config, id) {
296
+ if (!isSessionId(id)) return
297
+ return use(config, db => readRecord(db.prepare("SELECT record,state,seed FROM snapshots WHERE id=? AND (state IN ('approved','done') OR (state='preview' AND created>=?))")
298
+ .get(id, Date.now() - lifetime)), false)
299
+ }
300
+
301
+ export async function readPendingConversation(config, projectId, sourceId, target) {
302
+ return use(config, db => readRecord(db.prepare("SELECT record,state,seed FROM snapshots WHERE project_id=? AND source_id=? AND target=? AND state='approved' ORDER BY created DESC LIMIT 1")
303
+ .get(projectId, sourceId, target)), false)
304
+ }
305
+
306
+ export async function rebindConversation(config, previous, metadata) {
307
+ const record = { ...previous, ...metadata,
308
+ history: { ...previous.history, snapshotId: metadata.id } }
309
+ delete record.state
310
+ delete record.seed
311
+ return use(config, db => {
312
+ db.exec('BEGIN IMMEDIATE')
313
+ try {
314
+ const valid = db.prepare("SELECT 1 FROM snapshots WHERE id=? AND state='preview' AND created>=?")
315
+ .get(previous.id, Date.now() - lifetime)
316
+ if (!valid) {
317
+ db.exec('ROLLBACK')
318
+ return undefined
319
+ }
320
+ db.prepare("INSERT INTO snapshots(id,session_id,state,created,project_id,source_id,target,record) VALUES (?,?,'preview',?,?,?,?,?)")
321
+ .run(record.id, record.sessionId, Date.now(), record.projectId, record.sourceId, record.targetCwd, JSON.stringify(record))
322
+ db.prepare('INSERT INTO entries SELECT ?,seq,part,turn,call_id,kind,item FROM entries WHERE snapshot_id=?')
323
+ .run(record.id, previous.id)
324
+ db.prepare('INSERT INTO attachments SELECT ?,hash,type,bytes FROM attachments WHERE snapshot_id=?')
325
+ .run(record.id, previous.id)
326
+ db.prepare('DELETE FROM snapshots WHERE id=?').run(previous.id)
327
+ db.exec('COMMIT')
328
+ return record
329
+ } catch (error) {
330
+ db.exec('ROLLBACK')
331
+ throw error
332
+ }
333
+ })
334
+ }
335
+
336
+ export async function readStoredConversation(config, sessionId) {
337
+ if (!isSessionId(sessionId)) return
338
+ return use(config, db => readRecord(db.prepare("SELECT record,state FROM snapshots WHERE session_id=? AND state='done'").get(sessionId)), false)
339
+ }
340
+
341
+ export async function approveConversation(config, id) {
342
+ return use(config, db => db.prepare(`UPDATE snapshots AS proposed SET state='approved'
343
+ WHERE proposed.id=? AND proposed.state='preview' AND proposed.created>=? AND NOT EXISTS (
344
+ SELECT 1 FROM snapshots AS active WHERE active.project_id=proposed.project_id AND active.source_id=proposed.source_id
345
+ AND active.target=proposed.target AND active.state='approved'
346
+ )`)
347
+ .run(id, Date.now() - lifetime).changes)
348
+ }
349
+
350
+ export async function saveConversationSeed(config, id, seed) {
351
+ return use(config, db => {
352
+ db.prepare("UPDATE snapshots SET seed=? WHERE id=? AND state='approved' AND seed IS NULL").run(JSON.stringify(seed), id)
353
+ const row = db.prepare("SELECT seed FROM snapshots WHERE id=? AND state='approved'").get(id)
354
+ if (!row?.seed) throw new Error('Import receipt was not found')
355
+ return JSON.parse(row.seed)
356
+ })
357
+ }
358
+
359
+ export async function finishConversation(config, id, nativeTimeline) {
360
+ return use(config, db => {
361
+ if (!nativeTimeline) return db.prepare("UPDATE snapshots SET state='done', seed=NULL WHERE id=? AND state='approved'").run(id)
362
+ return db.prepare(`UPDATE snapshots SET state='done', seed=NULL, record=json_set(record,
363
+ '$.history', json_patch(json_extract(record,'$.history'), json(?)),
364
+ '$.sourceStats.importedMessages', ?)
365
+ WHERE id=? AND state='approved'`).run(JSON.stringify({ ...nativeTimeline, nativeTimeline: true }), nativeTimeline.nativeMessages, id)
366
+ })
367
+ }
368
+
369
+ export async function discardConversation(config, id) {
370
+ if (isSessionId(id)) await use(config, db => db.prepare("DELETE FROM snapshots WHERE id=? AND state='preview'").run(id))
371
+ }
372
+
373
+ function cursorPosition(cursor) {
374
+ if (cursor === undefined || cursor === null || cursor === '') return [0, 0, 0]
375
+ const values = typeof cursor === 'string' && /^\d{1,15}:\d{1,15}:\d{1,15}$/.test(cursor) ? cursor.split(':').map(Number) : undefined
376
+ if (!values) throw Object.assign(new Error('历史页位置无效。'), { status: 400 })
377
+ return values
378
+ }
379
+
380
+ const processKinds = "kind IN ('summary','tool_call','tool_result')"
381
+
382
+ function projectedPositions(db, record) {
383
+ if (record.messages.every(message => Number.isSafeInteger(message.sourceSeq))) {
384
+ return record.messages.map(message => message.sourceSeq)
385
+ }
386
+ // Earlier packages did not persist the positions. The projection retains
387
+ // the newest matching messages, including the user prompt restored at its head.
388
+ const rows = db.prepare(`
389
+ SELECT seq,kind,item FROM entries WHERE snapshot_id=? AND part=0
390
+ AND kind IN ('message','attachment') ORDER BY seq DESC
391
+ `).iterate(record.id)
392
+ const rest = db.prepare('SELECT item FROM entries WHERE snapshot_id=? AND seq=? AND part>0 AND part<24000 ORDER BY part')
393
+ const positions = []
394
+ let index = record.messages.length - 1
395
+ for (const row of rows) {
396
+ const message = record.messages[index]
397
+ const item = JSON.parse(row.item)
398
+ if (item.branchId || item.role !== message.role || item.turn !== message.turn || item.time !== message.time) continue
399
+ const text = row.kind === 'attachment' ? `[来源附件 ${item.name},见完整历史]` : item.text
400
+ if (!message.text.startsWith(text.slice(0, message.text.length))) continue
401
+ const source = row.kind === 'message' && item.continued
402
+ ? text + rest.all(record.id, row.seq).map(value => JSON.parse(value.item).text).join('')
403
+ : text
404
+ if (source.slice(0, 24000).replace(/[\uD800-\uDBFF]$/, '') !== message.text) continue
405
+ positions[index--] = row.seq
406
+ if (index < 0) return positions
407
+ }
408
+ return []
409
+ }
410
+
411
+ export async function* readNativeTurns(config, record) {
412
+ const db = await database(config, false)
413
+ if (!db) return
414
+ try {
415
+ const positions = projectedPositions(db, record)
416
+ const context = new Map(positions.map((seq, index) => [seq, record.messages[index].text]))
417
+ const initialTime = db.prepare(`
418
+ SELECT json_extract(item,'$.time') AS time FROM entries
419
+ WHERE snapshot_id=? AND part=0 AND turn IS NOT NULL AND kind IN ('message','attachment')
420
+ AND json_extract(item,'$.branchId') IS NULL AND json_extract(item,'$.time') IS NOT NULL
421
+ ORDER BY seq LIMIT 1
422
+ `).get(record.id)?.time
423
+ const rows = db.prepare(`
424
+ SELECT seq,turn,call_id,item FROM entries
425
+ WHERE snapshot_id=? AND turn IS NOT NULL AND kind != 'gap'
426
+ AND json_extract(item,'$.branchId') IS NULL
427
+ ORDER BY turn,seq,part
428
+ `).iterate(record.id)
429
+ let turn
430
+ let entries = []
431
+ let current
432
+ let text = []
433
+ const finish = () => {
434
+ if (!current) return
435
+ if (text.length > 1) current.text = text.join('')
436
+ entries.push(current)
437
+ }
438
+ for (const row of rows) {
439
+ const item = JSON.parse(row.item)
440
+ if (current?.seq === row.seq) {
441
+ text.push(item.text)
442
+ continue
443
+ }
444
+ finish()
445
+ if (turn !== undefined && row.turn !== turn) {
446
+ yield { entries, initialTime }
447
+ entries = []
448
+ }
449
+ turn = row.turn
450
+ current = { ...item, turn, callKey: row.call_id, contextText: context.get(row.seq) }
451
+ text = [item.text]
452
+ }
453
+ finish()
454
+ if (entries.length) yield { entries, initialTime }
455
+ } finally {
456
+ db.close()
457
+ }
458
+ }
459
+
460
+ export async function readProcessPlacements(config, record, events) {
461
+ return use(config, db => {
462
+ const positions = projectedPositions(db, record)
463
+ if (positions.length !== record.messages.length) return []
464
+ const totals = db.prepare(`
465
+ SELECT count(*) AS count, count(*) FILTER (WHERE kind='tool_call') AS calls
466
+ FROM entries WHERE snapshot_id=? AND turn=? AND seq>? AND seq<? AND part=0
467
+ AND ${processKinds} AND json_extract(item,'$.branchId') IS NULL
468
+ `)
469
+ const placements = []
470
+ let messageIndex = 0
471
+ let sourceTurn
472
+ let after
473
+ let start
474
+ for (const event of events) {
475
+ if (event.type === 'turn/start') start = event.seq
476
+ if (event.type === 'user/message') {
477
+ sourceTurn = record.messages[messageIndex].turn
478
+ after = positions[messageIndex++]
479
+ }
480
+ const tail = event.type === 'turn/end'
481
+ if (event.type !== 'assistant/message' && !tail) continue
482
+ const nextUser = record.messages[messageIndex]
483
+ const before = tail && nextUser?.turn !== sourceTurn ? undefined : positions[messageIndex]
484
+ if (sourceTurn && after !== undefined) {
485
+ const stat = totals.get(record.id, sourceTurn, after, before ?? Number.MAX_SAFE_INTEGER)
486
+ if (stat.count) placements.push({
487
+ nativeTurn: event.data.turn, sourceTurn, start, anchor: event.seq, tail, after, before, ...stat,
488
+ })
489
+ }
490
+ if (!tail) after = positions[messageIndex++]
491
+ }
492
+ return placements
493
+ }, false)
494
+ }
495
+
496
+ export async function readHistoryPage(config, id, cursor, turn, { processOnly = false, after = 0, before = Number.MAX_SAFE_INTEGER } = {}) {
497
+ if (!isSessionId(id)) return
498
+ if (cursor && (typeof cursor !== 'string' || !cursor.startsWith(`${id}:`))) {
499
+ throw Object.assign(new Error('历史页位置与会话不匹配。'), { status: 400 })
500
+ }
501
+ let position = cursorPosition(cursor && cursor.slice(id.length + 1))
502
+ if (processOnly && cursor && (position[0] !== turn || position[1] <= after || position[1] >= before)) {
503
+ throw Object.assign(new Error('历史页位置与回合不匹配。'), { status: 400 })
504
+ }
505
+ return use(config, db => {
506
+ const snapshot = db.prepare(`SELECT json_extract(record,'$.history') AS history FROM snapshots
507
+ WHERE id=? AND (state IN ('approved','done') OR (state='preview' AND created>=?))`).get(id, Date.now() - lifetime)
508
+ if (!snapshot) return
509
+ const history = JSON.parse(snapshot.history)
510
+ if (!cursor && Number.isSafeInteger(turn) && turn > 0) {
511
+ const start = db.prepare('SELECT 1 FROM entries WHERE snapshot_id=? AND turn=? LIMIT 1').get(id, turn)
512
+ if (!start) return { history, items: [], nextCursor: null }
513
+ position = [turn, 0, 0]
514
+ }
515
+ const range = processOnly
516
+ ? `AND turn=? AND seq>? AND seq<? AND ${processKinds} AND json_extract(item,'$.branchId') IS NULL`
517
+ : ''
518
+ const rows = db.prepare(`SELECT seq,part,turn,call_id,item, COALESCE(turn,0) AS display_turn
519
+ FROM entries WHERE snapshot_id=? ${range} AND (COALESCE(turn,0),seq,part)>(?,?,?) ORDER BY display_turn,seq,part LIMIT 41`)
520
+ .iterate(id, ...(processOnly ? [turn, after, before, ...position] : position))
521
+ const items = []
522
+ const cursorTurn = cursor ? position[0] : undefined
523
+ let bytes = 0
524
+ let nextCursor = null
525
+ let continuesTurn
526
+ const find = db.prepare('SELECT item,COUNT(*) AS count FROM entries WHERE snapshot_id=? AND call_id=? AND kind=? AND part=0')
527
+ for (const row of rows) {
528
+ const length = Buffer.byteLength(row.item)
529
+ if (items.length && (bytes + length > pageBytes || items.length >= 40)) {
530
+ nextCursor = `${id}:${position.join(':')}`
531
+ if (row.display_turn === position[0]) continuesTurn = row.display_turn
532
+ break
533
+ }
534
+ const item = JSON.parse(row.item)
535
+ if (item.kind === 'attachment' && row.call_id) {
536
+ if (row.turn === null) delete item.turn
537
+ else item.turn = row.turn
538
+ } else if (item.kind === 'tool_result') {
539
+ const call = row.call_id && find.get(id, row.call_id, 'tool_call')
540
+ if (call?.count === 1) {
541
+ const { turn, name } = JSON.parse(call.item)
542
+ item.turn = turn
543
+ item.name ??= name
544
+ } else {
545
+ delete item.turn
546
+ item.status = 'unmatched'
547
+ }
548
+ } else if (item.kind === 'tool_call') {
549
+ const call = row.call_id && find.get(id, row.call_id, 'tool_call')
550
+ const result = call?.count === 1 && find.get(id, row.call_id, 'tool_result')
551
+ item.status = result?.count ? JSON.parse(result.item).status ?? 'ok' : 'missing'
552
+ }
553
+ items.push(item)
554
+ bytes += length
555
+ position = [row.display_turn, row.seq, row.part]
556
+ }
557
+ return { history, items, nextCursor,
558
+ ...(items.length && cursorTurn === (items[0].turn ?? 0) ? { continuedTurn: cursorTurn } : {}),
559
+ ...(continuesTurn !== undefined ? { continuesTurn } : {}) }
560
+ }, false)
561
+ }
562
+
563
+ export async function readHistoryAttachment(config, snapshotId, attachmentId, { seq, preview = false } = {}) {
564
+ if (!isSessionId(snapshotId) || typeof attachmentId !== 'string' || !/^[0-9a-f]{64}$/.test(attachmentId)) return
565
+ return use(config, db => {
566
+ const state = preview
567
+ ? "(s.state='approved' OR (s.state='preview' AND s.created>=?))"
568
+ : "s.state='done'"
569
+ const row = db.prepare(`
570
+ SELECT a.bytes, json_extract(e.item, '$.name') AS name
571
+ FROM attachments AS a
572
+ JOIN snapshots AS s ON s.id=a.snapshot_id
573
+ JOIN entries AS e ON e.snapshot_id=a.snapshot_id AND e.kind='attachment' AND e.part=0
574
+ AND json_extract(e.item, '$.attachmentId')=a.hash
575
+ WHERE a.snapshot_id=? AND a.hash=? AND (? IS NULL OR e.seq=?) AND ${state}
576
+ ORDER BY e.seq LIMIT 1
577
+ `).get(snapshotId, attachmentId, seq ?? null, seq ?? null, ...(preview ? [Date.now() - lifetime] : []))
578
+ if (!row) return
579
+ const bytes = Buffer.from(row.bytes)
580
+ if (createHash('sha256').update(bytes).digest('hex') !== attachmentId) return
581
+ return { bytes, name: row.name, mediaType: imageMediaType(bytes) ?? 'application/octet-stream' }
582
+ }, false)
583
+ }