@wwwfz/dsh-agent-bridge 0.9.0 → 0.11.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,747 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { existsSync } from 'node:fs'
3
+ import { mkdir, open, unlink } from 'node:fs/promises'
4
+ import path from 'node:path'
5
+ import { DatabaseSync } from 'node:sqlite'
6
+ import { keyFor } from './handoff.js'
7
+ import { isSessionId, traceDirectory } from './session-trace.js'
8
+
9
+ const pageBytes = 64 * 1024
10
+ const partLength = 8_000
11
+ const maxAttachmentBytes = 32 * 1024 * 1024
12
+ const lifetime = 10 * 60_000
13
+
14
+ function historyDirectory(config) {
15
+ return path.join(path.dirname(traceDirectory(config)), 'agent-bridge-history')
16
+ }
17
+
18
+ async function database(config, create = true) {
19
+ const directory = historyDirectory(config)
20
+ const file = path.join(directory, 'history.sqlite')
21
+ if (create) {
22
+ await mkdir(directory, { recursive: true, mode: 0o700 })
23
+ const handle = await open(file, 'a', 0o600)
24
+ await handle.close()
25
+ } else if (!existsSync(file)) return
26
+ const db = new DatabaseSync(file, { readOnly: !create })
27
+ try {
28
+ db.exec('PRAGMA trusted_schema = OFF; PRAGMA busy_timeout = 2000;')
29
+ if (!create) return db
30
+ db.exec(`
31
+ PRAGMA foreign_keys = ON;
32
+ CREATE TABLE IF NOT EXISTS snapshots (
33
+ id TEXT PRIMARY KEY, session_id TEXT UNIQUE NOT NULL,
34
+ state TEXT NOT NULL, created INTEGER NOT NULL,
35
+ project_id TEXT, source_id TEXT, target TEXT,
36
+ record TEXT, seed TEXT
37
+ );
38
+ CREATE INDEX IF NOT EXISTS snapshot_source ON snapshots(project_id, source_id, state);
39
+ CREATE TABLE IF NOT EXISTS entries (
40
+ snapshot_id TEXT NOT NULL REFERENCES snapshots(id) ON DELETE CASCADE,
41
+ seq INTEGER NOT NULL, part INTEGER NOT NULL,
42
+ turn INTEGER, call_id TEXT, kind TEXT NOT NULL, item TEXT NOT NULL,
43
+ PRIMARY KEY (snapshot_id, seq, part)
44
+ );
45
+ CREATE INDEX IF NOT EXISTS entry_call ON entries(snapshot_id, call_id, kind, seq);
46
+ CREATE INDEX IF NOT EXISTS entry_turn ON entries(snapshot_id, turn, seq, part);
47
+ CREATE INDEX IF NOT EXISTS entry_display ON entries(snapshot_id, COALESCE(turn, 0), seq, part);
48
+ CREATE TABLE IF NOT EXISTS attachments (
49
+ snapshot_id TEXT NOT NULL REFERENCES snapshots(id) ON DELETE CASCADE,
50
+ hash TEXT NOT NULL, type TEXT NOT NULL, bytes BLOB NOT NULL,
51
+ PRIMARY KEY (snapshot_id, hash)
52
+ );
53
+ `)
54
+ return db
55
+ } catch (error) {
56
+ db.close()
57
+ throw error
58
+ }
59
+ }
60
+
61
+ async function use(config, action, write = true) {
62
+ const db = await database(config, write)
63
+ if (!db) return
64
+ try { return action(db) } finally { db.close() }
65
+ }
66
+
67
+ function* parts(text) {
68
+ let offset = 0
69
+ do {
70
+ let end = Math.min(offset + partLength, text.length)
71
+ if (end < text.length && /[\uD800-\uDBFF]/u.test(text[end - 1])) end--
72
+ yield { text: text.slice(offset, end), offset, continued: end < text.length }
73
+ offset = end
74
+ } while (offset < text.length)
75
+ }
76
+
77
+ export function imageMediaType(buffer) {
78
+ if (buffer.subarray(0, 8).equals(Buffer.from('89504e470d0a1a0a', 'hex'))) return 'image/png'
79
+ if (buffer.subarray(0, 3).equals(Buffer.from('ffd8ff', 'hex'))) return 'image/jpeg'
80
+ if (['GIF87a', 'GIF89a'].includes(buffer.toString('ascii', 0, 6))) return 'image/gif'
81
+ if (buffer.toString('ascii', 0, 4) === 'RIFF' && buffer.toString('ascii', 8, 12) === 'WEBP') return 'image/webp'
82
+ }
83
+
84
+ function saveAttachment(db, id, item, data) {
85
+ if (!Buffer.isBuffer(data)) return { ...item, status: item.status ?? 'attachment-unavailable' }
86
+ if (data.length > maxAttachmentBytes) return { ...item, status: 'attachment-too-large' }
87
+ const attachmentId = createHash('sha256').update(data).digest('hex')
88
+ const mediaType = imageMediaType(data) ?? 'application/octet-stream'
89
+ db.prepare('INSERT OR IGNORE INTO attachments VALUES (?, ?, ?, ?)').run(id, attachmentId, mediaType, data)
90
+ return { ...item, status: 'saved', attachmentId, mediaType, bytes: data.length }
91
+ }
92
+
93
+ function appendProjection(messages, message, state) {
94
+ const text = message.text.slice(0, 24_000).replace(/[\uD800-\uDBFF]$/, '')
95
+ if (text.length < message.text.length) state.truncated = true
96
+ messages.push({ ...message, text })
97
+ state.characters += text.length
98
+ while (messages.length > 600 || state.characters > 160_000) {
99
+ const removed = messages.shift()
100
+ state.characters -= removed.text.length
101
+ if (removed.role === 'user') state.lastQuestion = removed
102
+ state.truncated = true
103
+ }
104
+ }
105
+
106
+ function disambiguateToolCalls(db, id, trace) {
107
+ const duplicates = db.prepare(`SELECT call_id FROM entries
108
+ WHERE snapshot_id=? AND call_id IS NOT NULL AND kind='tool_call' AND part=0
109
+ GROUP BY call_id HAVING count(*)>1`).all(id)
110
+ if (!duplicates.length) return
111
+ const read = db.prepare(`SELECT kind,seq,turn FROM entries
112
+ WHERE snapshot_id=? AND call_id=? AND part=0 ORDER BY seq`)
113
+ const update = db.prepare('UPDATE entries SET call_id=? WHERE snapshot_id=? AND seq=?')
114
+ const traceBySeq = new Map(trace.map(item => [item.seq, item]))
115
+ for (const { call_id: key } of duplicates) {
116
+ const entries = read.all(id, key)
117
+ const callsAndResults = entries.filter(item => item.kind === 'tool_call' || item.kind === 'tool_result')
118
+ // Pair a reused id only when each occurrence settled before the next call.
119
+ // Overlapping calls and extra or missing results keep their unknown owner.
120
+ if (callsAndResults.length % 2 || !callsAndResults.every((item, index) =>
121
+ item.kind === (index % 2 ? 'tool_result' : 'tool_call') && (index % 2 || item.turn !== null))) continue
122
+ let occurrence
123
+ for (const item of entries) {
124
+ if (item.kind === 'tool_call') occurrence = `${key}:${item.seq}`
125
+ if (!occurrence) continue
126
+ update.run(occurrence, id, item.seq)
127
+ const stamp = traceBySeq.get(item.seq)
128
+ if (stamp) stamp.callKey = occurrence
129
+ }
130
+ }
131
+ }
132
+
133
+ export async function stageConversation(config, metadata, events, redact, loadAttachment) {
134
+ const { id, sessionId } = metadata
135
+ const db = await database(config)
136
+ const messages = []
137
+ const trace = []
138
+ const usedSkills = new Set()
139
+ const stats = { userMessages: 0, assistantMessages: 0 }
140
+ const state = { characters: 0, truncated: false }
141
+ const history = { snapshotId: id, messages: 0, tools: 0, attachments: 0, gaps: 0, complete: true, nativeMessages: 0 }
142
+ let seq = 0
143
+ let timed = 0
144
+ let firstAt = Infinity
145
+ let lastAt = 0
146
+ let created = false
147
+ try {
148
+ db.prepare("DELETE FROM snapshots WHERE state IN ('loading','preview') AND created < ?").run(Date.now() - lifetime)
149
+ db.prepare("INSERT INTO snapshots(id,session_id,state,created,project_id,source_id,target) VALUES (?,?,'loading',?,?,?,?)")
150
+ .run(id, sessionId, Date.now(), metadata.projectId ?? null, metadata.sourceId ?? null, metadata.targetCwd ?? null)
151
+ created = true
152
+ const insert = db.prepare('INSERT INTO entries VALUES (?, ?, ?, ?, ?, ?, ?)')
153
+ const batch = []
154
+ let batchBytes = 0
155
+ const flush = () => {
156
+ if (!batch.length) return
157
+ db.exec('BEGIN')
158
+ try {
159
+ for (const row of batch) insert.run(id, ...row)
160
+ db.exec('COMMIT')
161
+ } catch (error) {
162
+ db.exec('ROLLBACK')
163
+ throw error
164
+ }
165
+ batch.length = 0
166
+ batchBytes = 0
167
+ }
168
+ const put = (item, callKey) => {
169
+ seq++
170
+ const chunks = 'text' in item ? parts(item.text) : [{ offset: 0 }]
171
+ for (const chunk of chunks) {
172
+ const json = JSON.stringify({ ...item, ...chunk, seq })
173
+ batch.push([seq, chunk.offset, item.turn ?? null, callKey ?? null, item.kind, json])
174
+ batchBytes += Buffer.byteLength(json)
175
+ if (batch.length >= 128 || batchBytes >= 512 * 1024) flush()
176
+ }
177
+ }
178
+ const endings = new Map()
179
+ for await (const raw of events) {
180
+ if (raw.kind === 'metadata') {
181
+ for (const skill of raw.usedSkills ?? []) usedSkills.add(skill)
182
+ if (raw.sourceStats?.tokens) stats.tokens = raw.sourceStats.tokens
183
+ continue
184
+ }
185
+ const item = { kind: raw.kind }
186
+ let callKey
187
+ if (Number.isSafeInteger(raw.turn) && raw.turn > 0) item.turn = raw.turn
188
+ if (Number.isFinite(raw.time) && raw.time > 0) item.time = raw.time
189
+ if (typeof raw.sourceId === 'string') item.sourceId = redact(raw.sourceId)
190
+ if (typeof raw.parentId === 'string') item.parentId = redact(raw.parentId)
191
+ if (typeof raw.branchId === 'string') item.branchId = redact(raw.branchId)
192
+ if (typeof raw.text === 'string') item.text = redact(raw.text)
193
+ if (typeof raw.callId === 'string' && raw.callId) {
194
+ item.callId = redact(raw.callId)
195
+ callKey = createHash('sha256').update(JSON.stringify([raw.branchId ?? '', raw.callId])).digest('hex')
196
+ }
197
+ if (raw.kind === 'message') {
198
+ if (!['user', 'assistant'].includes(raw.role) || !item.text?.trim()) continue
199
+ item.role = raw.role
200
+ history.messages++
201
+ stats[`${item.role}Messages`]++
202
+ if (item.time && raw.estimatedTime !== true) {
203
+ timed++
204
+ firstAt = Math.min(firstAt, item.time)
205
+ lastAt = Math.max(lastAt, item.time)
206
+ }
207
+ if (!item.branchId) appendProjection(messages, { role: item.role, text: item.text, time: item.time, turn: item.turn, sourceSeq: seq + 1 }, state)
208
+ } else if (raw.kind === 'gap') {
209
+ item.reason = redact(raw.reason)
210
+ history.gaps++
211
+ } else if (raw.kind === 'attachment') {
212
+ item.name = redact(raw.name ?? '附件').slice(0, 240)
213
+ if (['user', 'assistant'].includes(raw.role)) item.role = raw.role
214
+ if (raw.status) item.status = raw.status
215
+ const attachment = await loadAttachment?.(raw)
216
+ Object.assign(item, saveAttachment(db, id, { ...item, ...attachment?.details }, attachment?.bytes ?? raw.data))
217
+ history.attachments++
218
+ if (item.status !== 'saved') history.gaps++
219
+ if (raw.role === 'user' && raw.standalone === true && !item.branchId) {
220
+ item.standalone = true
221
+ appendProjection(messages, { role: 'user', text: `[来源附件 ${item.name},见完整历史]`, time: item.time, turn: item.turn, sourceSeq: seq + 1 }, state)
222
+ }
223
+ } else if (raw.kind === 'turn_end' && item.turn && ['completed', 'interrupted'].includes(raw.status)) {
224
+ item.status = raw.status
225
+ if (!item.branchId) endings.set(item.turn, raw.status)
226
+ } else if (['summary', 'tool_call', 'tool_result'].includes(raw.kind)) {
227
+ if (raw.name) item.name = redact(raw.name)
228
+ if (raw.status) item.status = raw.status
229
+ if (raw.kind === 'tool_call') history.tools++
230
+ trace.push({ ...item, callKey, seq: seq + 1, id: `source-${seq + 1}`, text: (item.text ?? '').slice(0, 8193) })
231
+ if (trace.length > 600) trace.shift()
232
+ } else continue
233
+ put(item, callKey)
234
+ }
235
+ flush()
236
+ disambiguateToolCalls(db, id, trace)
237
+ db.prepare(`UPDATE entries AS result SET turn = (
238
+ SELECT CASE WHEN COUNT(*)=1 THEN MIN(call.turn) END FROM entries AS call
239
+ WHERE call.snapshot_id=result.snapshot_id AND call.call_id=result.call_id AND call.kind='tool_call' AND call.part=0
240
+ ) WHERE result.snapshot_id=? AND (result.kind='tool_result' OR (result.kind='attachment' AND result.call_id IS NOT NULL))`).run(id)
241
+ const unmatched = db.prepare(`SELECT count(*) AS count FROM entries WHERE snapshot_id=? AND part=0 AND turn IS NULL
242
+ AND (kind='tool_result' OR (kind='attachment' AND call_id IS NOT NULL))`).get(id).count
243
+ if (unmatched) {
244
+ history.gaps += unmatched
245
+ put({ kind: 'gap', reason: `${unmatched} 条工具结果或附件的归属未知,原文见来源记录。` })
246
+ flush()
247
+ }
248
+ if (messages[0]?.role === 'assistant' && state.lastQuestion) {
249
+ while (messages.length >= 600 || state.characters + state.lastQuestion.text.length > 160_000) {
250
+ state.characters -= messages.shift().text.length
251
+ }
252
+ messages.unshift(state.lastQuestion)
253
+ }
254
+ const retained = messages.slice(messages.findIndex(message => message.role === 'user') < 0
255
+ ? messages.length : messages.findIndex(message => message.role === 'user'))
256
+ for (const message of retained) {
257
+ if (message.role === 'user' && endings.has(message.turn)) message.endReason = endings.get(message.turn)
258
+ }
259
+ history.nativeMessages = retained.length
260
+ if (retained[0]?.turn) history.nativeFirstTurn = retained[0].turn
261
+ if (retained.at(-1)?.turn) history.nativeLastTurn = retained.at(-1).turn
262
+ history.complete = history.gaps === 0
263
+ const anchors = new Map(retained.map((message, index) => [message.turn, index]))
264
+ 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")
265
+ const findResult = db.prepare("SELECT item FROM entries WHERE snapshot_id=? AND call_id=? AND kind='tool_result' ORDER BY seq LIMIT 1")
266
+ const pairedTrace = trace.flatMap(item => {
267
+ if (item.kind === 'tool_result') {
268
+ const call = item.callKey && findCall.get(id, item.callKey)
269
+ if (call?.count !== 1) return []
270
+ item.turn = call.turn
271
+ item.name ??= JSON.parse(call.item).name
272
+ }
273
+ if (item.kind === 'tool_call') {
274
+ const result = item.callKey && findCall.get(id, item.callKey).count === 1 && findResult.get(id, item.callKey)
275
+ item.status = result ? JSON.parse(result.item).status ?? 'ok' : 'missing'
276
+ }
277
+ const messageIndex = anchors.get(item.turn)
278
+ const { callKey, seq, ...reviewed } = item
279
+ return messageIndex === undefined ? [] : [{ ...reviewed, messageIndex }]
280
+ }).sort((a, b) => a.turn - b.turn)
281
+ const sourceStats = { ...stats, importedMessages: retained.length, partial: !history.complete,
282
+ ...(timed >= 2 && timed === history.messages ? { elapsedMs: lastAt - firstAt } : {}) }
283
+ const record = { ...metadata, history, sourceStats, messages: retained, trace: pairedTrace,
284
+ usedSkills: [...usedSkills], truncated: state.truncated || !history.complete }
285
+ db.prepare("UPDATE snapshots SET state='preview', created=?, record=? WHERE id=?")
286
+ .run(Date.now(), JSON.stringify(record), id)
287
+ return record
288
+ } catch (error) {
289
+ if (created) db.prepare("DELETE FROM snapshots WHERE id=? AND state='loading'").run(id)
290
+ throw error
291
+ } finally {
292
+ db.close()
293
+ }
294
+ }
295
+
296
+ function readRecord(row) {
297
+ return row?.record ? { ...JSON.parse(row.record), state: row.state, seed: row.seed ? JSON.parse(row.seed) : undefined } : undefined
298
+ }
299
+
300
+ export async function readConversationSnapshot(config, id) {
301
+ if (!isSessionId(id)) return
302
+ 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>=?))")
303
+ .get(id, Date.now() - lifetime)), false)
304
+ }
305
+
306
+ export async function readPendingConversation(config, projectId, sourceIds, target) {
307
+ return use(config, db => {
308
+ // Older versions allowed pending copies at multiple targets. The caller must
309
+ // identify one of those targets before a particular receipt can be resumed.
310
+ const rows = db.prepare(`SELECT record,state,seed FROM snapshots WHERE project_id=?
311
+ AND source_id IN (SELECT value FROM json_each(?)) AND (? IS NULL OR target=?) AND state='approved' LIMIT 2`)
312
+ .all(projectId, JSON.stringify(Array.isArray(sourceIds) ? sourceIds : [sourceIds]), target ?? null, target ?? null)
313
+ return rows.length === 1 ? readRecord(rows[0]) : undefined
314
+ }, false)
315
+ }
316
+
317
+ // Separate SQLite lock files let unrelated imports run concurrently. The OS releases each
318
+ // lock on process exit, including a crash partway through a DSH write. Only a successful
319
+ // callback may retire the ticket (completed, or replaced with a freshly reviewed target).
320
+ export async function withApprovedImportLock(config, id, action) {
321
+ if (!isSessionId(id)) throw new Error('Invalid import receipt')
322
+ const file = path.join(historyDirectory(config), id + '.lock')
323
+ const lock = new DatabaseSync(file)
324
+ let retired = false
325
+ try {
326
+ try { lock.exec('BEGIN EXCLUSIVE') } catch (error) {
327
+ if (error.errcode !== 5) throw error
328
+ throw Object.assign(new Error('这条会话正在迁入,请等待当前操作结束。'), { status: 409 })
329
+ }
330
+ const result = await action()
331
+ retired = true
332
+ return result
333
+ } finally {
334
+ lock.close()
335
+ if (retired) await unlink(file).catch(() => {})
336
+ }
337
+ }
338
+
339
+ export async function setConversationAttempt(config, id, attempt) {
340
+ return use(config, db => db.prepare(`UPDATE snapshots SET record=json_set(record,'$.importAttempt',?)
341
+ WHERE id=? AND state='approved' AND (?!='unwritten' OR seed IS NULL)`).run(attempt, id, attempt).changes)
342
+ }
343
+
344
+ export async function rebindConversation(config, previous, metadata, { approvedAttempt } = {}) {
345
+ const record = { ...previous, ...metadata,
346
+ history: { ...previous.history, snapshotId: metadata.id } }
347
+ delete record.state
348
+ delete record.seed
349
+ if (approvedAttempt) {
350
+ // Keep the reviewed archive and excerpt text durable through a close/reload. A new
351
+ // ticket binds the new target and requires a separate user request to write to DSH.
352
+ record.importAttempt = 'review'
353
+ if (record.continuation) {
354
+ const { firstMessage } = record.continuation
355
+ const items = record.continuation.items.map(item => item.snapshotId === previous.id ? { ...item, snapshotId: record.id } : item)
356
+ const refs = items.map(({ snapshotId, seq, offset }) => ({ snapshotId, seq, offset }))
357
+ record.continuation = { firstMessage, items, contextKey: keyFor(record.id, refs, firstMessage) }
358
+ }
359
+ }
360
+ return use(config, db => {
361
+ db.exec('BEGIN IMMEDIATE')
362
+ try {
363
+ const valid = approvedAttempt
364
+ ? db.prepare(`SELECT 1 FROM snapshots WHERE id=? AND state='approved' AND seed IS NULL AND json_extract(record,'$.importAttempt')=?
365
+ AND json_extract(record,'$.importAttempt') IN ('unwritten','review') AND NOT EXISTS (
366
+ SELECT 1 FROM snapshots AS other WHERE other.project_id=? AND other.id!=? AND other.state='approved'
367
+ AND other.source_id IN (SELECT value FROM json_each(?)))`)
368
+ .get(previous.id, approvedAttempt, record.projectId, previous.id, JSON.stringify(record.sourceIds ?? [record.sourceId]))
369
+ : db.prepare("SELECT 1 FROM snapshots WHERE id=? AND state='preview' AND created>=?").get(previous.id, Date.now() - lifetime)
370
+ if (!valid) {
371
+ db.exec('ROLLBACK')
372
+ return undefined
373
+ }
374
+ const state = approvedAttempt ? 'approved' : 'preview'
375
+ db.prepare('INSERT INTO snapshots(id,session_id,state,created,project_id,source_id,target,record) VALUES (?,?,?,?,?,?,?,?)')
376
+ .run(record.id, record.sessionId, state, Date.now(), record.projectId, record.sourceId, record.targetCwd, JSON.stringify(record))
377
+ db.prepare('INSERT INTO entries SELECT ?,seq,part,turn,call_id,kind,item FROM entries WHERE snapshot_id=?')
378
+ .run(record.id, previous.id)
379
+ db.prepare('INSERT INTO attachments SELECT ?,hash,type,bytes FROM attachments WHERE snapshot_id=?')
380
+ .run(record.id, previous.id)
381
+ db.prepare('DELETE FROM snapshots WHERE id=?').run(previous.id)
382
+ db.exec('COMMIT')
383
+ return { ...record, state }
384
+ } catch (error) {
385
+ db.exec('ROLLBACK')
386
+ throw error
387
+ }
388
+ })
389
+ }
390
+
391
+ export async function readStoredConversation(config, sessionId) {
392
+ if (!isSessionId(sessionId)) return
393
+ return use(config, db => readRecord(db.prepare("SELECT record,state FROM snapshots WHERE session_id=? AND state='done'").get(sessionId)), false)
394
+ }
395
+
396
+ export async function readCompletedConversationImports(config, projectId, sourceIds) {
397
+ if (!sourceIds.length) return []
398
+ const rows = await use(config, db => db.prepare(`
399
+ SELECT source_id AS sourceId, session_id AS sessionId, created AS importedAt,
400
+ json_type(record,'$.importedAt') IS NULL AS approximate
401
+ FROM snapshots WHERE project_id=? AND state='done'
402
+ AND source_id IN (SELECT value FROM json_each(?))
403
+ ORDER BY created DESC, rowid DESC
404
+ `).all(projectId, JSON.stringify(sourceIds)), false)
405
+ return rows ?? []
406
+ }
407
+
408
+ export async function approveConversation(config, id, continuation = null, { unavailableImports, sourceIds = [] } = {}) {
409
+ return use(config, db => db.prepare(`UPDATE snapshots AS proposed SET state='approved',
410
+ record=json_set(record,'$.continuation',json($continuation),'$.importAttempt','ready')
411
+ WHERE proposed.id=$id AND proposed.state='preview' AND proposed.created >= $cutoff AND NOT EXISTS (
412
+ SELECT 1 FROM snapshots AS active WHERE active.project_id=proposed.project_id
413
+ AND (active.source_id=proposed.source_id OR active.source_id IN (SELECT value FROM json_each($aliases)))
414
+ AND active.state='approved'
415
+ ) AND (
416
+ $unavailable IS NULL OR NOT EXISTS (
417
+ SELECT 1 FROM snapshots AS completed
418
+ WHERE completed.project_id=proposed.project_id AND completed.state='done'
419
+ AND (completed.source_id=proposed.source_id OR completed.source_id IN (SELECT value FROM json_each($aliases)))
420
+ AND completed.session_id NOT IN (SELECT value FROM json_each($unavailable))
421
+ )
422
+ )`)
423
+ .run({ $continuation: JSON.stringify(continuation), $id: id, $cutoff: Date.now() - lifetime, $aliases: JSON.stringify(sourceIds),
424
+ $unavailable: unavailableImports ? JSON.stringify(unavailableImports) : null }).changes)
425
+ }
426
+
427
+ export async function saveConversationSeed(config, id, seed) {
428
+ return use(config, db => {
429
+ db.prepare("UPDATE snapshots SET seed=? WHERE id=? AND state='approved' AND seed IS NULL").run(JSON.stringify(seed), id)
430
+ const row = db.prepare("SELECT seed FROM snapshots WHERE id=? AND state='approved'").get(id)
431
+ if (!row?.seed) throw new Error('Import receipt was not found')
432
+ return JSON.parse(row.seed)
433
+ })
434
+ }
435
+
436
+ export async function finishConversation(config, id, nativeTimeline) {
437
+ return use(config, db => {
438
+ // Older completed snapshots keep their preview timestamp in created.
439
+ const importedAt = Date.now()
440
+ if (!nativeTimeline) return db.prepare(`UPDATE snapshots SET state='done', seed=NULL,
441
+ created=$importedAt, record=json_set(record,'$.importedAt',$importedAt)
442
+ WHERE id=$id AND state='approved'`).run({ $id: id, $importedAt: importedAt })
443
+ return db.prepare(`UPDATE snapshots SET state='done', seed=NULL, created=$importedAt, record=json_set(record,
444
+ '$.importedAt', $importedAt, '$.history', json_patch(json_extract(record,'$.history'), json($timeline)),
445
+ '$.sourceStats.importedMessages', $messageCount)
446
+ WHERE id=$id AND state='approved'`).run({ $id: id, $importedAt: importedAt,
447
+ $timeline: JSON.stringify({ ...nativeTimeline, nativeTimeline: true }), $messageCount: nativeTimeline.nativeMessages })
448
+ })
449
+ }
450
+
451
+ export async function discardConversation(config, id) {
452
+ if (isSessionId(id)) await use(config, db => db.prepare("DELETE FROM snapshots WHERE id=? AND state='preview'").run(id))
453
+ }
454
+
455
+ export async function locateHistoryMessage(config, id, { turn, hash, offset }) {
456
+ return use(config, db => {
457
+ const rows = db.prepare(`SELECT seq,part,item FROM entries
458
+ WHERE snapshot_id=? AND turn=? AND kind='message' ORDER BY seq,part`).iterate(id, turn)
459
+ let seq
460
+ let part
461
+ let texts = []
462
+ const locate = () => {
463
+ if (!texts.length || keyFor(texts.join('')) !== hash || part === undefined) return
464
+ const before = part === 0 ? `${seq - 1}:999999999999999` : `${seq}:${part - 1}`
465
+ return { turn, cursor: `${id}:${turn}:${before}`, seq, offset: part }
466
+ }
467
+ for (const row of rows) {
468
+ if (row.seq !== seq) {
469
+ const found = locate()
470
+ if (found) return found
471
+ seq = row.seq
472
+ texts = []
473
+ part = undefined
474
+ }
475
+ const { text } = JSON.parse(row.item)
476
+ texts.push(text)
477
+ if (row.part <= offset && offset < row.part + text.length) part = row.part
478
+ }
479
+ return locate()
480
+ }, false)
481
+ }
482
+
483
+ export async function readContextExcerpts(config, projectId, excerpts) {
484
+ return use(config, db => {
485
+ const select = db.prepare(`SELECT e.turn,e.item,s.source_id AS sourceId,json_extract(s.record,'$.title') AS title
486
+ FROM entries e JOIN snapshots s ON s.id=e.snapshot_id
487
+ WHERE s.project_id=? AND s.id=? AND e.seq=? AND e.part=?
488
+ AND (s.state IN ('approved','done') OR (s.state='preview' AND s.created>=?))
489
+ AND e.kind IN ('message','tool_result','tool_call','summary')`)
490
+ return excerpts.map(excerpt => {
491
+ const row = select.get(projectId, excerpt.snapshotId, excerpt.seq, excerpt.offset, Date.now() - lifetime)
492
+ if (!row) return null
493
+ const item = JSON.parse(row.item)
494
+ if (!item.text?.trim()) return null
495
+ return { ...excerpt, sourceId: row.sourceId, title: row.title, turn: row.turn, kind: item.kind, role: item.role, text: item.text }
496
+ })
497
+ }, false)
498
+ }
499
+
500
+ export async function readRetainedRelaySnapshot(config, projectId, source) {
501
+ return use(config, db => {
502
+ const candidates = db.prepare(`SELECT s.id,e.item FROM snapshots s JOIN entries e ON e.snapshot_id=s.id
503
+ WHERE s.project_id=? AND s.source_id=? AND e.turn=? AND e.kind=? AND e.seq=? AND e.part=?
504
+ AND (s.state IN ('approved','done') OR (s.state='preview' AND s.created>=?))
505
+ ORDER BY s.created DESC,s.rowid DESC`).iterate(projectId, source.id, source.turn, source.kind, source.seq, source.offset, Date.now() - lifetime)
506
+ for (const row of candidates) {
507
+ if (keyFor(JSON.parse(row.item).text) === source.hash) {
508
+ return readRecord(db.prepare('SELECT record,state FROM snapshots WHERE id=?').get(row.id))
509
+ }
510
+ }
511
+ }, false)
512
+ }
513
+
514
+ export async function locateRelayExcerpt(config, id, { turn, kind, seq, offset, hash }) {
515
+ return use(config, db => {
516
+ const rows = db.prepare(`SELECT seq,part,item FROM entries WHERE snapshot_id=? AND turn=? AND kind=?
517
+ ORDER BY (seq=?) DESC,(part=?) DESC,seq,part`).iterate(id, turn, kind, seq, offset)
518
+ for (const row of rows) {
519
+ if (keyFor(JSON.parse(row.item).text) !== hash) continue
520
+ const before = row.part ? `${row.seq}:${row.part - 1}` : `${row.seq - 1}:999999999999999`
521
+ return { turn, cursor: `${id}:${turn}:${before}`, seq: row.seq, offset: row.part }
522
+ }
523
+ if (db.prepare('SELECT 1 FROM entries WHERE snapshot_id=? AND turn=? LIMIT 1').get(id, turn)) {
524
+ return { turn, changed: true }
525
+ }
526
+ }, false)
527
+ }
528
+
529
+ export function firstContinuationMessage(record) {
530
+ return record.continuation?.firstMessage ?? record.messages[0]?.text
531
+ }
532
+
533
+ function cursorPosition(cursor) {
534
+ if (cursor === undefined || cursor === null || cursor === '') return [0, 0, 0]
535
+ const values = typeof cursor === 'string' && /^\d{1,15}:\d{1,15}:\d{1,15}$/.test(cursor) ? cursor.split(':').map(Number) : undefined
536
+ if (!values) throw Object.assign(new Error('历史页位置无效。'), { status: 400 })
537
+ return values
538
+ }
539
+
540
+ const processKinds = "kind IN ('summary','tool_call','tool_result')"
541
+
542
+ function projectedPositions(db, record) {
543
+ if (record.messages.every(message => Number.isSafeInteger(message.sourceSeq))) {
544
+ return record.messages.map(message => message.sourceSeq)
545
+ }
546
+ // Earlier packages did not persist the positions. The projection retains
547
+ // the newest matching messages, including the user prompt restored at its head.
548
+ const rows = db.prepare(`
549
+ SELECT seq,kind,item FROM entries WHERE snapshot_id=? AND part=0
550
+ AND kind IN ('message','attachment') ORDER BY seq DESC
551
+ `).iterate(record.id)
552
+ const rest = db.prepare('SELECT item FROM entries WHERE snapshot_id=? AND seq=? AND part>0 AND part<24000 ORDER BY part')
553
+ const positions = []
554
+ let index = record.messages.length - 1
555
+ for (const row of rows) {
556
+ const message = record.messages[index]
557
+ const item = JSON.parse(row.item)
558
+ if (item.branchId || item.role !== message.role || item.turn !== message.turn || item.time !== message.time) continue
559
+ const text = row.kind === 'attachment' ? `[来源附件 ${item.name},见完整历史]` : item.text
560
+ if (!message.text.startsWith(text.slice(0, message.text.length))) continue
561
+ const source = row.kind === 'message' && item.continued
562
+ ? text + rest.all(record.id, row.seq).map(value => JSON.parse(value.item).text).join('')
563
+ : text
564
+ if (source.slice(0, 24000).replace(/[\uD800-\uDBFF]$/, '') !== message.text) continue
565
+ positions[index--] = row.seq
566
+ if (index < 0) return positions
567
+ }
568
+ return []
569
+ }
570
+
571
+ export async function* readNativeTurns(config, record) {
572
+ const db = await database(config, false)
573
+ if (!db) return
574
+ try {
575
+ const positions = projectedPositions(db, record)
576
+ const context = new Map(positions.map((seq, index) => [
577
+ seq, index === 0 ? firstContinuationMessage(record) : record.messages[index].text,
578
+ ]))
579
+ const initialTime = db.prepare(`
580
+ SELECT json_extract(item,'$.time') AS time FROM entries
581
+ WHERE snapshot_id=? AND part=0 AND turn IS NOT NULL AND kind IN ('message','attachment')
582
+ AND json_extract(item,'$.branchId') IS NULL AND json_extract(item,'$.time') IS NOT NULL
583
+ ORDER BY seq LIMIT 1
584
+ `).get(record.id)?.time
585
+ const rows = db.prepare(`
586
+ SELECT seq,turn,call_id,item FROM entries
587
+ WHERE snapshot_id=? AND turn IS NOT NULL AND kind != 'gap'
588
+ AND json_extract(item,'$.branchId') IS NULL
589
+ ORDER BY turn,seq,part
590
+ `).iterate(record.id)
591
+ let turn
592
+ let entries = []
593
+ let current
594
+ let text = []
595
+ const finish = () => {
596
+ if (!current) return
597
+ if (text.length > 1) current.text = text.join('')
598
+ entries.push(current)
599
+ }
600
+ for (const row of rows) {
601
+ const item = JSON.parse(row.item)
602
+ if (current?.seq === row.seq) {
603
+ text.push(item.text)
604
+ continue
605
+ }
606
+ finish()
607
+ if (turn !== undefined && row.turn !== turn) {
608
+ yield { entries, initialTime }
609
+ entries = []
610
+ }
611
+ turn = row.turn
612
+ current = { ...item, turn, callKey: row.call_id, contextText: context.get(row.seq) }
613
+ text = [item.text]
614
+ }
615
+ finish()
616
+ if (entries.length) yield { entries, initialTime }
617
+ } finally {
618
+ db.close()
619
+ }
620
+ }
621
+
622
+ export async function readProcessPlacements(config, record, events) {
623
+ return use(config, db => {
624
+ const positions = projectedPositions(db, record)
625
+ if (positions.length !== record.messages.length) return []
626
+ const totals = db.prepare(`
627
+ SELECT count(*) AS count, count(*) FILTER (WHERE kind='tool_call') AS calls
628
+ FROM entries WHERE snapshot_id=? AND turn=? AND seq>? AND seq<? AND part=0
629
+ AND ${processKinds} AND json_extract(item,'$.branchId') IS NULL
630
+ `)
631
+ const placements = []
632
+ let messageIndex = 0
633
+ let sourceTurn
634
+ let after
635
+ let start
636
+ for (const event of events) {
637
+ if (event.type === 'turn/start') start = event.seq
638
+ if (event.type === 'user/message') {
639
+ sourceTurn = record.messages[messageIndex].turn
640
+ after = positions[messageIndex++]
641
+ }
642
+ const tail = event.type === 'turn/end'
643
+ if (event.type !== 'assistant/message' && !tail) continue
644
+ const nextUser = record.messages[messageIndex]
645
+ const before = tail && nextUser?.turn !== sourceTurn ? undefined : positions[messageIndex]
646
+ if (sourceTurn && after !== undefined) {
647
+ const stat = totals.get(record.id, sourceTurn, after, before ?? Number.MAX_SAFE_INTEGER)
648
+ if (stat.count) placements.push({
649
+ nativeTurn: event.data.turn, sourceTurn, start, anchor: event.seq, tail, after, before, ...stat,
650
+ })
651
+ }
652
+ if (!tail) after = positions[messageIndex++]
653
+ }
654
+ return placements
655
+ }, false)
656
+ }
657
+
658
+ export async function readHistoryPage(config, id, cursor, turn, {
659
+ processOnly = false, after = 0, before = Number.MAX_SAFE_INTEGER, maxBytes = pageBytes,
660
+ } = {}) {
661
+ if (!isSessionId(id)) return
662
+ if (cursor && (typeof cursor !== 'string' || !cursor.startsWith(`${id}:`))) {
663
+ throw Object.assign(new Error('历史页位置与会话不匹配。'), { status: 400 })
664
+ }
665
+ let position = cursorPosition(cursor && cursor.slice(id.length + 1))
666
+ if (processOnly && cursor && (position[0] !== turn || position[1] <= after || position[1] >= before)) {
667
+ throw Object.assign(new Error('历史页位置与回合不匹配。'), { status: 400 })
668
+ }
669
+ return use(config, db => {
670
+ const snapshot = db.prepare(`SELECT json_extract(record,'$.history') AS history FROM snapshots
671
+ WHERE id=? AND (state IN ('approved','done') OR (state='preview' AND created>=?))`).get(id, Date.now() - lifetime)
672
+ if (!snapshot) return
673
+ const history = JSON.parse(snapshot.history)
674
+ if (!cursor && Number.isSafeInteger(turn) && turn > 0) {
675
+ const start = db.prepare('SELECT 1 FROM entries WHERE snapshot_id=? AND turn=? LIMIT 1').get(id, turn)
676
+ if (!start) return { history, items: [], nextCursor: null }
677
+ position = [turn, 0, 0]
678
+ }
679
+ const range = processOnly
680
+ ? `AND turn=? AND seq>? AND seq<? AND ${processKinds} AND json_extract(item,'$.branchId') IS NULL`
681
+ : ''
682
+ const rows = db.prepare(`SELECT seq,part,turn,call_id,item, COALESCE(turn,0) AS display_turn
683
+ FROM entries WHERE snapshot_id=? ${range} AND (COALESCE(turn,0),seq,part)>(?,?,?) ORDER BY display_turn,seq,part LIMIT 41`)
684
+ .iterate(id, ...(processOnly ? [turn, after, before, ...position] : position))
685
+ const items = []
686
+ const cursorTurn = cursor ? position[0] : undefined
687
+ let bytes = 0
688
+ let nextCursor = null
689
+ let continuesTurn
690
+ const find = db.prepare('SELECT item,COUNT(*) AS count FROM entries WHERE snapshot_id=? AND call_id=? AND kind=? AND part=0')
691
+ for (const row of rows) {
692
+ const length = Buffer.byteLength(row.item)
693
+ if (items.length && (bytes + length > maxBytes || items.length >= 40)) {
694
+ nextCursor = `${id}:${position.join(':')}`
695
+ if (row.display_turn === position[0]) continuesTurn = row.display_turn
696
+ break
697
+ }
698
+ const item = JSON.parse(row.item)
699
+ if (item.kind === 'attachment' && row.call_id) {
700
+ if (row.turn === null) delete item.turn
701
+ else item.turn = row.turn
702
+ } else if (item.kind === 'tool_result') {
703
+ const call = row.call_id && find.get(id, row.call_id, 'tool_call')
704
+ if (call?.count === 1) {
705
+ const { turn, name } = JSON.parse(call.item)
706
+ item.turn = turn
707
+ item.name ??= name
708
+ } else {
709
+ delete item.turn
710
+ item.status = 'unmatched'
711
+ }
712
+ } else if (item.kind === 'tool_call') {
713
+ const call = row.call_id && find.get(id, row.call_id, 'tool_call')
714
+ const result = call?.count === 1 && find.get(id, row.call_id, 'tool_result')
715
+ item.status = result?.count ? JSON.parse(result.item).status ?? 'ok' : 'missing'
716
+ }
717
+ items.push(item)
718
+ bytes += length
719
+ position = [row.display_turn, row.seq, row.part]
720
+ }
721
+ return { history, items, nextCursor,
722
+ ...(items.length && cursorTurn === (items[0].turn ?? 0) ? { continuedTurn: cursorTurn } : {}),
723
+ ...(continuesTurn !== undefined ? { continuesTurn } : {}) }
724
+ }, false)
725
+ }
726
+
727
+ export async function readHistoryAttachment(config, snapshotId, attachmentId, { seq, preview = false } = {}) {
728
+ if (!isSessionId(snapshotId) || typeof attachmentId !== 'string' || !/^[0-9a-f]{64}$/.test(attachmentId)) return
729
+ return use(config, db => {
730
+ const state = preview
731
+ ? "(s.state='approved' OR (s.state='preview' AND s.created>=?))"
732
+ : "s.state='done'"
733
+ const row = db.prepare(`
734
+ SELECT a.bytes, json_extract(e.item, '$.name') AS name
735
+ FROM attachments AS a
736
+ JOIN snapshots AS s ON s.id=a.snapshot_id
737
+ JOIN entries AS e ON e.snapshot_id=a.snapshot_id AND e.kind='attachment' AND e.part=0
738
+ AND json_extract(e.item, '$.attachmentId')=a.hash
739
+ WHERE a.snapshot_id=? AND a.hash=? AND (? IS NULL OR e.seq=?) AND ${state}
740
+ ORDER BY e.seq LIMIT 1
741
+ `).get(snapshotId, attachmentId, seq ?? null, seq ?? null, ...(preview ? [Date.now() - lifetime] : []))
742
+ if (!row) return
743
+ const bytes = Buffer.from(row.bytes)
744
+ if (createHash('sha256').update(bytes).digest('hex') !== attachmentId) return
745
+ return { bytes, name: row.name, mediaType: imageMediaType(bytes) ?? 'application/octet-stream' }
746
+ }, false)
747
+ }