@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,217 @@
1
+ import { randomUUID } from 'node:crypto'
2
+ import { readHistoryAttachment, readNativeTurns } from './conversation-store.js'
3
+
4
+ const modelSource = { kind: 'model', provider: 'agent-bridge-import', model: 'imported' }
5
+ const systemSource = { kind: 'system-prompt' }
6
+ const textBlock = text => ({ type: 'text', text })
7
+ const message = (role, content, source) => ({ id: randomUUID(), role, content, source })
8
+
9
+ async function attachmentBlock(record, item, attachments, { file = false } = {}) {
10
+ if (item.attachmentId && attachments) {
11
+ const saved = await readHistoryAttachment(record.config, record.id, item.attachmentId, { seq: item.seq, preview: true })
12
+ if (saved) {
13
+ const { bytes: data, mediaType, name } = saved
14
+ try {
15
+ if (mediaType.startsWith('image/') && attachments.saveImage) {
16
+ return { type: 'image', attachment: await attachments.saveImage({ data, mediaType, name }) }
17
+ }
18
+ if (file && attachments.saveFile) return { type: 'file', attachment: await attachments.saveFile({ data, name }) }
19
+ } catch { /* The exact bytes remain available in the source archive. */ }
20
+ }
21
+ }
22
+ const name = item.name.replace(/[\\`*_[\]<>]/g, '\\$&')
23
+ const status = item.status === 'saved' ? '原件见来源记录' : item.status === 'name-only' ? '仅保留文件名' : '原件不可用'
24
+ return textBlock(`附件:${name}(${status})`)
25
+ }
26
+
27
+ export async function nativeTranscriptEvents(record, attachments, now = Date.now()) {
28
+ const events = []
29
+ const usedCallIds = new Set()
30
+ let time
31
+ let turn = 0
32
+ let step = 0
33
+ let nativeMessages = 0
34
+ let contextMessages = 0
35
+ let nativeFirstTurn
36
+ let nativeLastTurn
37
+ let excluded = []
38
+ const at = value => { time = Math.max(time ?? value ?? now, value ?? 0) }
39
+ const add = (type, data, surface) => {
40
+ const seq = events.length
41
+ events.push({ seq, time, type, data, ...surface })
42
+ return seq
43
+ }
44
+ const system = () => ({ turn, step, message: message('system', [], systemSource) })
45
+ const leaveInHistory = () => {
46
+ if (!excluded.length) return
47
+ // Native surface replacement keeps the original events available to Chat
48
+ // and Trajectory while an empty system node contributes no request message.
49
+ add('system/message', system(), {
50
+ surfaceOp: { op: 'replace', startSeq: excluded[0], endSeq: excluded.at(-1) },
51
+ sourceEventSeqs: excluded,
52
+ })
53
+ excluded = []
54
+ }
55
+ const append = (type, data, retain, sourceEventSeqs) => {
56
+ if (retain) leaveInHistory()
57
+ const seq = add(type, data, { surfaceOp: 'append', ...(sourceEventSeqs && { sourceEventSeqs }) })
58
+ if (!retain) excluded.push(seq)
59
+ return seq
60
+ }
61
+ const openStep = () => add('step/start', { turn, step: ++step })
62
+ const closeStep = () => add('step/end', { turn, step })
63
+
64
+ for await (const { entries, initialTime } of readNativeTurns(record.config, record)) {
65
+ const questions = new Map()
66
+ let currentQuestion
67
+ for (const item of entries) {
68
+ if (item.role !== 'user') continue
69
+ if (item.kind === 'message' || (item.kind === 'attachment' && (item.standalone || !currentQuestion))) {
70
+ currentQuestion = item
71
+ questions.set(item.seq, [])
72
+ }
73
+ if (item.kind === 'attachment') questions.get(currentQuestion.seq).push(item)
74
+ }
75
+ const question = entries.find(item => questions.has(item.seq))
76
+ if (!question) continue
77
+ nativeFirstTurn ??= question.turn
78
+ nativeLastTurn = question.turn
79
+ const results = new Map()
80
+ const resultAttachments = new Map()
81
+ for (const item of entries) {
82
+ if (!item.callKey) continue
83
+ const target = item.kind === 'tool_result' ? results : item.kind === 'attachment' ? resultAttachments : undefined
84
+ if (!target) continue
85
+ if (!target.has(item.callKey)) target.set(item.callKey, [])
86
+ target.get(item.callKey).push(item)
87
+ }
88
+
89
+ time ??= initialTime
90
+ at(question.time)
91
+ add('turn/start', { turn: ++turn })
92
+ step = 0
93
+ openStep()
94
+ if (turn === 1) add('system/message', system(), { surfaceOp: 'append' })
95
+ let needsStep = false
96
+ let replied = false
97
+ let reasoning = []
98
+ let calls = []
99
+ const writeQuestion = async item => {
100
+ if (needsStep) {
101
+ openStep()
102
+ needsStep = false
103
+ }
104
+ at(item.time)
105
+ replied = false
106
+ const files = questions.get(item.seq)
107
+ const content = item.kind === 'message' ? [textBlock(item.text)] : []
108
+ if (item.kind === 'message') nativeMessages++
109
+ for (const file of files) {
110
+ const block = await attachmentBlock(record, file, attachments, { file: true })
111
+ if (block.type === 'text' && content.length) block.text = '\n\n' + block.text
112
+ content.push(block)
113
+ }
114
+ const hasContext = item.contextText !== undefined
115
+ if (hasContext) contextMessages++
116
+ const userSeq = append('user/message', message('user', content, { kind: 'user' }), hasContext)
117
+ if (hasContext && (item.text !== item.contextText || files.length)) {
118
+ add('user/message', message('user', [textBlock(item.contextText)], { kind: 'agent-bridge-context' }), {
119
+ surfaceOp: { op: 'replace', startSeq: userSeq, endSeq: userSeq },
120
+ sourceEventSeqs: [userSeq],
121
+ })
122
+ }
123
+ leaveInHistory()
124
+ }
125
+ const flush = async (reply, followingSeq) => {
126
+ if (!reply && !reasoning.length && !calls.length) return
127
+ if (needsStep) openStep()
128
+ const content = reasoning.map(item => ({ type: 'reasoning', text: item.text }))
129
+ if (reply) content.push(reply.kind === 'attachment' ? await attachmentBlock(record, reply, attachments) : textBlock(reply.text))
130
+ for (const item of calls) content.push(item.block)
131
+ at(reply?.time ?? reasoning.at(-1)?.time ?? calls[0]?.time)
132
+ const keepReply = reply?.kind === 'message' && !reasoning.length && !calls.length && reply.contextText !== undefined
133
+ const needsPrefix = keepReply && reply.text !== reply.contextText
134
+ if (reply?.kind === 'message') nativeMessages++
135
+ if (keepReply) contextMessages++
136
+ if (needsPrefix) {
137
+ // The host settles Chat and Trajectory from the last assistant message
138
+ // of the step. Keep the reviewed prefix on the model surface and the
139
+ // final, full settlement in the timeline.
140
+ append('assistant/message', {
141
+ turn, step, stream: [], message: message('assistant', [textBlock(reply.contextText)], modelSource),
142
+ }, true)
143
+ }
144
+ append('assistant/message', {
145
+ turn, step, stream: [], message: message('assistant', content, modelSource),
146
+ }, keepReply && !needsPrefix)
147
+
148
+ const settled = []
149
+ for (const { entry, block } of calls) {
150
+ at(entry.time)
151
+ const callSeq = add('tool/call', {
152
+ turn, step, callId: block.id, name: block.name, arguments: block.arguments,
153
+ })
154
+ const output = results.get(entry.callKey)
155
+ if (output?.length) settled.push({ block, output, files: resultAttachments.get(entry.callKey) ?? [], callSeq })
156
+ }
157
+ settled.sort((a, b) => a.output[0].seq - b.output[0].seq)
158
+ for (const { block, output, files, callSeq } of settled) {
159
+ const last = output.at(-1)
160
+ // A late result annotates the original call. Its source timestamp
161
+ // remains in the archive and must not move subsequent replies forward.
162
+ if (last.seq < followingSeq) at(last.time)
163
+ const isError = ['error', 'incomplete'].includes(last.status)
164
+ const outputBlocks = output.flatMap((item, index) => index
165
+ ? [textBlock('\n\n---\n\n'), textBlock(item.text ?? '')]
166
+ : [textBlock(item.text ?? '')])
167
+ for (const item of files) outputBlocks.push(await attachmentBlock(record, item, attachments))
168
+ append('tool/result', {
169
+ turn, step,
170
+ message: {
171
+ ...message('tool', outputBlocks, { kind: 'tool', callId: block.id }),
172
+ toolCallId: block.id, isError,
173
+ },
174
+ }, false, [callSeq])
175
+ }
176
+ leaveInHistory()
177
+ closeStep()
178
+ needsStep = true
179
+ reasoning = []
180
+ calls = []
181
+ }
182
+
183
+ for (const item of entries) {
184
+ if (item.seq < question.seq) continue
185
+ if (questions.has(item.seq)) {
186
+ await flush(undefined, item.seq)
187
+ await writeQuestion(item)
188
+ } else if (item.kind === 'summary' && item.text?.trim()) {
189
+ if (calls.length) await flush(undefined, item.seq)
190
+ reasoning.push(item)
191
+ } else if (item.kind === 'tool_call' && item.name) {
192
+ let id = item.callId || `bridge-${item.seq}`
193
+ if (usedCallIds.has(id)) id = randomUUID()
194
+ usedCallIds.add(id)
195
+ calls.push({ entry: item, block: { type: 'tool-call', id, name: item.name, arguments: item.text || '{}' } })
196
+ } else if (item.kind === 'message' && item.role === 'assistant') {
197
+ await flush(undefined, item.seq)
198
+ await flush(item)
199
+ replied = true
200
+ } else if (item.kind === 'attachment' && item.role === 'assistant' && !item.callKey) {
201
+ await flush(undefined, item.seq)
202
+ await flush(item)
203
+ replied = true
204
+ }
205
+ }
206
+ await flush(undefined, 0)
207
+ if (!needsStep) closeStep()
208
+ const ending = entries.findLast(item => item.kind === 'turn_end')
209
+ // DSH uses "interrupted" specifically for recovery after its own crash.
210
+ const completed = ending ? ending.status === 'completed' : replied
211
+ add('turn/end', { turn, reason: completed ? { kind: 'completed' } : { kind: 'aborted', reason: { kind: 'legacy' } } })
212
+ }
213
+
214
+ if (!turn) throw new Error('The approved source archive has no importable turns')
215
+ add('session/title', { title: record.title, messageSeqs: [], source: { kind: 'user' } })
216
+ return { events, nativeTimeline: { nativeMessages, nativeFirstTurn, nativeLastTurn, contextMessages } }
217
+ }
@@ -143,3 +143,53 @@ export async function writeProjectContinuation(config, projectId) {
143
143
  RETURNING continued_at`).get(projectId, Date.now()).continued_at
144
144
  })
145
145
  }
146
+
147
+ export async function readCodexAliases(config) {
148
+ const projects = new Map()
149
+ await readArchive(config, db => {
150
+ if (!db.prepare("SELECT 1 FROM sqlite_schema WHERE type='table' AND name='codex_source_aliases'").get()) return
151
+ for (const { project_id, source_id, alias } of db.prepare('SELECT project_id,source_id,alias FROM codex_source_aliases WHERE source_id IS NOT NULL').iterate()) {
152
+ if (!projects.has(project_id)) projects.set(project_id, new Map())
153
+ const sources = projects.get(project_id)
154
+ if (!sources.has(source_id)) sources.set(source_id, [])
155
+ sources.get(source_id).push(alias)
156
+ }
157
+ })
158
+ return projects
159
+ }
160
+
161
+ export async function saveCodexAliases(config, projectId, links) {
162
+ await writeArchive(config, true, db => {
163
+ db.exec(`CREATE TABLE IF NOT EXISTS codex_source_aliases (
164
+ project_id TEXT NOT NULL, alias TEXT NOT NULL, source_id TEXT, PRIMARY KEY (project_id,alias)
165
+ ) STRICT`)
166
+ const insert = db.prepare(`INSERT INTO codex_source_aliases VALUES (?,?,?) ON CONFLICT(project_id,alias)
167
+ DO UPDATE SET source_id=NULL WHERE source_id<>excluded.source_id`)
168
+ for (const [source, alias] of links) insert.run(projectId, alias, source.id)
169
+ })
170
+ }
171
+
172
+ export async function readProjectRelay(config, projectId) {
173
+ return await readArchive(config, db => {
174
+ if (!db.prepare("SELECT 1 FROM sqlite_schema WHERE name='project_relay' AND type='table'").get()) return []
175
+ return db.prepare('SELECT item FROM project_relay WHERE project_id=? ORDER BY rowid')
176
+ .all(projectId).map(row => JSON.parse(row.item))
177
+ }) ?? []
178
+ }
179
+
180
+ export async function changeProjectRelay(config, projectId, id, change, previousIds = []) {
181
+ return writeArchive(config, true, db => {
182
+ db.exec(`CREATE TABLE IF NOT EXISTS project_relay (
183
+ project_id TEXT NOT NULL, id TEXT NOT NULL, item TEXT NOT NULL, PRIMARY KEY (project_id,id)
184
+ ) STRICT`)
185
+ const row = db.prepare(`SELECT id,item FROM project_relay WHERE project_id=? AND id IN (SELECT value FROM json_each(?))
186
+ ORDER BY (id=?) DESC,rowid LIMIT 1`).get(projectId, JSON.stringify([id, ...previousIds]), id)
187
+ const storedId = row?.id ?? id
188
+ const item = change(row && JSON.parse(row.item))
189
+ if (item) {
190
+ db.prepare(`INSERT INTO project_relay VALUES (?,?,?) ON CONFLICT(project_id,id)
191
+ DO UPDATE SET item=excluded.item`).run(projectId, storedId, JSON.stringify(item))
192
+ } else db.prepare('DELETE FROM project_relay WHERE project_id=? AND id=?').run(projectId, storedId)
193
+ return item ?? null
194
+ })
195
+ }