@wwwfz/dsh-agent-bridge 0.9.0 → 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.
package/src/client.js CHANGED
@@ -1,623 +1,1189 @@
1
- window.__ModuleLoader__.load({
2
- id: '@wwwfz/dsh-agent-bridge',
3
- factory: (require) => {
4
- const { createElement: h, useCallback, useEffect, useRef, useState } = require('react');
5
- const { createPortal } = require('react-dom');
6
- const panelId = 'dsh-agent-bridge';
7
- const messages = {
8
- zh: {
9
- title: 'Agent 工作接续',
10
- trace: '来源记录',
11
- traceTitle: '来源记录',
12
- traceHint: '展开回合查看旧 Agent 的思考摘要和工具记录。',
13
- traceEmpty: '没有为这条会话保存来源记录。',
14
- traceFailed: '暂时无法读取来源记录。',
15
- traceClose: '关闭',
16
- traceCopy: '复制结果摘录',
17
- traceCopied: '已复制',
18
- traceTurn: '第 {turn} 轮',
19
- traceUnnumbered: '未标记轮次',
20
- traceOneItem: '1 项',
21
- traceItemCount: '{count} 项',
22
- traceCall: '调用',
23
- statsTitle: '原对话统计',
24
- statsTurns: '已读轮次',
25
- statsMessages: '已读消息',
26
- statsTools: '已保存工具调用',
27
- statsSpan: '消息时间跨度',
28
- statsTokens: '源记录 Token',
29
- statsRoles: '用户 {user} 条,助手 {assistant} 条',
30
- statsImported: '已迁入 {count} 条消息',
31
- statsFailed: '{count} 次失败',
32
- statsMissing: '{count} 次未记录结果',
33
- statsSummaries: '{count} 段思考摘要',
34
- statsTokenDetail: '输入 {input},输出 {output}',
35
- statsPartial: '消息与轮次仅统计已读取的部分原记录。',
36
- statsLegacy: '旧版迁入的会话,统计来自当时保存的来源记录。',
37
- },
38
- en: {
39
- title: 'Agent Workspace Handoff',
40
- trace: 'Source record',
41
- traceTitle: 'Source record',
42
- traceHint: 'Expand a turn to view reasoning summaries and tool records.',
43
- traceEmpty: 'No source record is saved for this session.',
44
- traceFailed: 'The source record cannot be read right now.',
45
- traceClose: 'Close',
46
- traceCopy: 'Copy result excerpt',
47
- traceCopied: 'Copied',
48
- traceTurn: 'Turn {turn}',
49
- traceUnnumbered: 'Unnumbered records',
50
- traceOneItem: '1 item',
51
- traceItemCount: '{count} items',
52
- traceCall: 'Call',
53
- statsTitle: 'Original conversation statistics',
54
- statsTurns: 'Turns read',
55
- statsMessages: 'Messages read',
56
- statsTools: 'Saved tool calls',
57
- statsSpan: 'Message time span',
58
- statsTokens: 'Source tokens',
59
- statsRoles: '{user} user and {assistant} assistant messages',
60
- statsImported: '{count} messages imported',
61
- statsFailed: 'Failed calls: {count}',
62
- statsMissing: 'Calls with no recorded result: {count}',
63
- statsSummaries: 'Reasoning summaries: {count}',
64
- statsTokenDetail: 'Input {input}, output {output}',
65
- statsPartial: 'The message and turn counts cover the part of the source that was read.',
66
- statsLegacy: 'Statistics for this older import come from its saved source records.',
67
- },
68
- };
69
-
70
- function validPath(value) {
71
- return typeof value === 'string' && value.length > 0 && value.length <= 4096
72
- && !/[\u0000-\u001f]/u.test(value);
73
- }
74
-
75
- function pathKey(path) {
76
- if (/^[a-z]:[\\/]|^\\\\|^\/\//i.test(path)) {
77
- return path.replace(/\//g, '\\').replace(/^\\\\\?\\UNC\\/i, '\\\\')
78
- .replace(/^\\\\\?\\/, '').replace(/\\+$/, '').toLowerCase();
79
- }
80
- return path.replace(/\/+$/, '');
81
- }
82
-
83
- function sessionRow(summary) {
84
- if (!summary || summary.blank || summary.origin === 'subagent' || !validPath(summary.cwd)) return;
85
- return {
86
- id: summary.id,
87
- title: (summary.title || summary.displayTitle || '未命名会话').slice(0, 240),
88
- path: summary.cwd,
89
- updatedAt: summary.updatedAt,
90
- };
91
- }
92
-
93
- function dialogueFrom(event) {
94
- if (event?.surfaceOp !== 'append') return;
95
- let content;
96
- let role;
97
- if (event.type === 'user/message' && event.data?.source?.kind === 'user') {
98
- role = 'user';
99
- content = event.data.content;
100
- } else if (event.type === 'assistant/message') {
101
- role = 'assistant';
102
- content = event.data?.message?.content;
103
- }
104
- if (!Array.isArray(content)) return;
105
- const text = content.filter(block => block?.type === 'text' && typeof block.text === 'string')
106
- .map(block => block.text).join('\n\n');
107
- return text.trim() ? { role, text } : undefined;
108
- }
109
-
110
- async function sessionDialogue(remote, sessionId, signal) {
111
- const collected = [];
112
- const address = { kind: 'session', sessionId };
113
- let remaining = 28_000;
114
- let throughSeq;
115
- let beforeSeq;
116
- let hasMore = true;
117
- let truncated = false;
118
- for (let page = 0; page < 8 && hasMore && !truncated; page++) {
119
- const result = await remote.events({ address, maxMessages: 40,
120
- ...(throughSeq === undefined ? {} : { throughSeq, beforeSeq }),
121
- }, signal);
122
- if (!result.ok) throw new Error('无法读取这条 DSH 会话的历史。');
123
- const { records, cursor } = result.value;
124
- hasMore = result.value.hasMore;
125
- throughSeq ??= cursor;
126
- for (let i = records.length - 1; i >= 0; i--) {
127
- const message = dialogueFrom(records[i].event);
128
- if (!message) continue;
129
- if (collected.length >= 24 || message.text.length > remaining) {
130
- if (!collected.length) collected.push({ ...message,
131
- text: message.text.slice(0, remaining).replace(/[\uD800-\uDBFF]$/, ''),
132
- });
133
- truncated = true;
134
- break;
135
- }
136
- collected.push(message);
137
- remaining -= message.text.length;
138
- }
139
- const firstSeq = records[0]?.event?.seq;
140
- if (hasMore && (!Number.isSafeInteger(firstSeq) || firstSeq <= 0 || firstSeq >= (beforeSeq ?? Infinity))) break;
141
- beforeSeq = firstSeq;
142
- }
143
- return { messages: collected.reverse(), truncated: truncated || hasMore };
144
- }
145
-
146
- function PanelIcon({ size = 16 }) {
147
- return h('svg', {
148
- width: size, height: size, viewBox: '0 0 24 24', fill: 'none',
149
- stroke: 'currentColor', strokeWidth: 1.7, strokeLinecap: 'round', strokeLinejoin: 'round',
150
- 'aria-hidden': true,
151
- }, h('path', { d: 'M3 17.5V6.5A1.5 1.5 0 0 1 4.5 5H9l2 2h8.5A1.5 1.5 0 0 1 21 8.5v9a1.5 1.5 0 0 1-1.5 1.5h-15A1.5 1.5 0 0 1 3 17.5Z M8 13h8m-3-3 3 3-3 3' }));
152
- }
153
-
154
- function apply(ctx) {
155
- ctx.effect(() => ctx.locale.register(panelId, messages), 'agent bridge locale');
156
- const t = ctx.locale.bind(panelId);
157
- const recentImports = new Map();
158
- const incompleteDrafts = new Map();
159
- let importing = false;
160
-
161
- async function exportRequest(request, signal) {
162
- if (request.path !== undefined && !validPath(request.path)) throw new Error('工作目录格式无效。');
163
- const scope = request.path === undefined ? undefined : pathKey(request.path);
164
- const snapshot = ctx.sessions.list.getSnapshot();
165
- if (snapshot.phase !== 'ready') throw new Error('DSH 会话列表正在加载,请稍后重试。');
166
- const rows = snapshot.ids.map(id => sessionRow(snapshot.byId[id]))
167
- .filter(row => row && (scope === undefined || pathKey(row.path) === scope));
168
- if (request.type === 'dsh-agent-bridge:sessions') return { sessions: rows };
169
-
170
- const selected = rows.find(row => row.id === request.sessionId);
171
- if (!selected) throw new Error('未在这个工作区找到可导出的 DSH 会话。');
172
- const dialogue = await sessionDialogue(ctx.remote.session, selected.id, signal);
173
- if (!dialogue.messages.length) throw new Error('这条 DSH 会话暂无可导出的文字。');
174
- return { conversation: { title: selected.title, path: selected.path, ...dialogue } };
175
- }
176
-
177
- function rememberImport(requestId, imported) {
178
- if (!recentImports.has(requestId) && recentImports.size >= 32) {
179
- recentImports.delete(recentImports.keys().next().value);
180
- }
181
- recentImports.set(requestId, imported);
182
- }
183
-
184
- async function rollbackDraft(imported, binding) {
185
- try {
186
- const session = binding?.session;
187
- const state = session?.getSnapshot();
188
- const input = binding && ctx.conversation.input.for(binding.ctx).snapshot;
189
- // A preserved draft, attachments, or a chat already in use belong to
190
- // the user. Archive only an unused, empty chat created by this handoff.
191
- if (state && (!state.blank || state.running || state.promptAttempted || state.removed)) return false;
192
- if (binding && (!input || input.draft !== '' || input.attachmentIds?.length
193
- || ['adjudicating', 'submitting', 'sending'].includes(input.phase))) return false;
194
- await ctx.workspaces.archiveSession(imported.sessionId);
195
- incompleteDrafts.delete(imported.path);
196
- for (const [key, item] of recentImports) if (item === imported) recentImports.delete(key);
197
- return true;
198
- } catch {
199
- return false;
200
- }
201
- }
202
-
203
- async function prepareSession(request, reveal) {
204
- const path = pathKey(request.path);
205
- let imported = recentImports.get(request.requestId) ?? incompleteDrafts.get(path);
206
- if (imported && imported.path !== path) throw new Error('交接工作目录已变化,请重新预览。');
207
- if (!imported) {
208
- const workspace = await ctx.workspaces.create({ path: request.path });
209
- const sessionId = await ctx.sessions.create({ workspaceId: workspace.workspaceId });
210
- imported = { sessionId, path, ready: false };
211
- incompleteDrafts.set(path, imported);
212
- }
213
- rememberImport(request.requestId, imported);
214
-
215
- let reference;
216
- try {
217
- if (!imported.ready) {
218
- let binding;
219
- let outcome;
220
- try {
221
- reference = ctx.sessions.retain(imported.sessionId, { source: panelId });
222
- binding = reference.binding;
223
- await reference.ready;
224
- outcome = ctx.conversation.input.requestDraftInitialization(binding, {
225
- prompt: request.prompt,
226
- whenDraftExists: 'keep',
227
- });
228
- } catch {
229
- // A Host error can also leave an empty session to roll back.
230
- }
231
- if (outcome !== 'applied') {
232
- if (outcome !== 'preserved' && await rollbackDraft(imported, binding)) {
233
- throw new Error('DSH 未能填入交接草稿。空白会话已归档,可重试。');
234
- }
235
- throw new Error(outcome === 'preserved'
236
- ? '会话中已有草稿,已原样保留。可打开会话并手动补入交接资料。'
237
- : 'DSH 未能填入交接草稿。可重试同一会话,或打开后手动补入交接资料。');
238
- }
239
- imported.ready = true;
240
- incompleteDrafts.delete(path);
241
- }
242
- reveal(imported.sessionId);
243
- return imported.sessionId;
244
- } finally {
245
- reference?.release();
246
- }
247
- }
248
-
249
- const traceKind = { summary: '思考摘要', tool_call: '工具调用', tool_result: '工具结果' };
250
- const traceState = { missing: '未记录结果', error: '失败', pending: '未完成', truncated: '已截取' };
251
- const traceStyle = {
252
- overlay: {
253
- position: 'fixed', inset: 0, zIndex: 2147483000, display: 'flex',
254
- alignItems: 'center', justifyContent: 'center', padding: '24px',
255
- background: 'rgba(0, 0, 0, 0.42)',
256
- },
257
- dialog: {
258
- width: 'min(720px, 100%)', maxHeight: 'min(76vh, 760px)', overflow: 'auto',
259
- borderRadius: '14px', padding: '20px 22px', background: 'var(--dsh-surface, #fff)',
260
- color: 'var(--dsh-text, #1f2328)', boxShadow: '0 24px 64px rgba(0, 0, 0, 0.32)',
261
- font: '13px/1.6 system-ui, -apple-system, "Segoe UI", sans-serif',
262
- },
263
- header: { display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: '12px' },
264
- heading: { margin: 0, fontSize: '15px', fontWeight: 600 },
265
- hint: { margin: '6px 0 14px', opacity: 0.7, fontSize: '12px' },
266
- stats: {
267
- marginBlock: '12px 8px', padding: '10px 12px', borderRadius: '9px',
268
- border: '1px solid var(--dsh-border, rgba(127, 127, 127, 0.22))',
269
- },
270
- statsHeading: { margin: 0, fontSize: '13px', fontWeight: 650 },
271
- statsGrid: {
272
- display: 'grid', gridTemplateColumns: 'repeat(auto-fit, minmax(min(104px, 100%), 1fr))',
273
- gap: '8px 12px', margin: '7px 0 0',
274
- },
275
- statsLabel: { opacity: 0.75, fontSize: '12px' },
276
- statsValue: { margin: 0, fontSize: '17px', fontWeight: 620, fontVariantNumeric: 'tabular-nums', overflowWrap: 'anywhere' },
277
- statsNote: { margin: '6px 0 0', opacity: 0.75, fontSize: '12px' },
278
- turn: { borderTop: '1px solid var(--dsh-border, rgba(127, 127, 127, 0.22))' },
279
- turnSummary: { display: 'list-item', padding: '9px 0', cursor: 'pointer', fontWeight: 600 },
280
- turnCount: { marginInlineStart: '9px', fontSize: '12px', fontWeight: 400, opacity: 0.72 },
281
- turnItems: { paddingInlineStart: '15px', paddingBottom: '5px' },
282
- item: {
283
- borderTop: '1px solid var(--dsh-border, rgba(127, 127, 127, 0.22))',
284
- padding: '10px 0', display: 'grid', gap: '4px',
285
- },
286
- meta: { display: 'flex', flexWrap: 'wrap', gap: '8px', alignItems: 'center', fontSize: '12px' },
287
- kind: { fontWeight: 600 },
288
- name: { fontFamily: 'ui-monospace, SFMono-Regular, Consolas, monospace', fontSize: '12px' },
289
- state: { opacity: 0.72 },
290
- body: { margin: 0, whiteSpace: 'pre-wrap', overflowWrap: 'anywhere' },
291
- button: {
292
- border: '1px solid var(--dsh-border, rgba(127, 127, 127, 0.3))',
293
- background: 'transparent', color: 'inherit', borderRadius: '7px',
294
- padding: '3px 9px', fontSize: '12px', cursor: 'pointer',
295
- },
296
- };
297
-
298
- const number = new Intl.NumberFormat().format;
299
-
300
- function formatSpan(milliseconds) {
301
- const seconds = Math.floor(milliseconds / 1000);
302
- const hours = Math.floor(seconds / 3600);
303
- const minutes = Math.floor(seconds / 60) % 60;
304
- const rest = String(seconds % 60).padStart(2, '0');
305
- return hours ? `${hours}:${String(minutes).padStart(2, '0')}:${rest}` : `${minutes}:${rest}`;
306
- }
307
-
308
- function SourceStats({ stats, counts = {}, t }) {
309
- const values = [];
310
- const notes = [];
311
- if (stats) {
312
- const total = stats.userMessages + stats.assistantMessages;
313
- values.push(['statsTurns', number(stats.userMessages)], ['statsMessages', number(total)]);
314
- notes.push(t('statsRoles').replace('{user}', number(stats.userMessages)).replace('{assistant}', number(stats.assistantMessages)));
315
- if (stats.importedMessages !== total) notes.push(t('statsImported').replace('{count}', number(stats.importedMessages)));
316
- }
317
- values.push(['statsTools', number(counts.toolCall ?? 0)]);
318
- if (stats?.elapsedMs !== undefined) values.push(['statsSpan', formatSpan(stats.elapsedMs)]);
319
- if (stats?.tokens) {
320
- values.push(['statsTokens', number(stats.tokens.total)]);
321
- const { input, output } = stats.tokens;
322
- if (input !== undefined && output !== undefined) {
323
- notes.push(t('statsTokenDetail').replace('{input}', number(input)).replace('{output}', number(output)));
324
- }
325
- }
326
- for (const [count, label] of [[counts.failed, 'statsFailed'], [counts.missing, 'statsMissing'], [counts.summary, 'statsSummaries']]) {
327
- if (count) notes.push(t(label).replace('{count}', number(count)));
328
- }
329
- const scope = stats ? (stats.partial ? t('statsPartial') : '') : t('statsLegacy');
330
- return h('section', { style: traceStyle.stats, 'aria-label': t('statsTitle') }, [
331
- h('h3', { key: 'title', style: traceStyle.statsHeading }, t('statsTitle')),
332
- h('dl', { key: 'values', style: traceStyle.statsGrid }, values.map(([label, value]) => h('div', { key: label }, [
333
- h('dt', { key: 'label', style: traceStyle.statsLabel }, t(label)),
334
- h('dd', { key: 'value', style: traceStyle.statsValue }, value),
335
- ]))),
336
- notes.length ? h('p', { key: 'notes', style: traceStyle.statsNote }, notes.join(' · ')) : null,
337
- scope ? h('p', { key: 'scope', style: traceStyle.statsNote }, scope) : null,
338
- ]);
339
- }
340
-
341
- // The header slot is clipped, so the panel portals to the document body.
342
- // Trace is read-only reference material: nothing here is sent back to DSH
343
- // as an event, and no tool is executed.
344
- function SourceTrace({ sessionId, t }) {
345
- const [sourceRecord, setSourceRecord] = useState();
346
- const [open, setOpen] = useState(false);
347
- const [error, setError] = useState('');
348
- const [copied, setCopied] = useState('');
349
- useEffect(() => {
350
- setOpen(false);
351
- setError('');
352
- setCopied('');
353
- if (typeof sessionId !== 'string' || !sessionId) return undefined;
354
- const controller = new AbortController();
355
- const url = new URL(`agent-bridge/session-trace?sessionId=${encodeURIComponent(sessionId)}`, document.baseURI);
356
- fetch(url, { signal: controller.signal, headers: { Accept: 'application/json' } })
357
- .then(response => response.ok ? response.json() : undefined)
358
- .then(value => {
359
- if (controller.signal.aborted) return;
360
- const readable = Array.isArray(value?.trace) && (value.trace.length || value.sourceStats);
361
- setSourceRecord(readable ? { sessionId, value } : undefined);
362
- })
363
- .catch(() => {});
364
- return () => controller.abort();
365
- }, [sessionId]);
366
- useEffect(() => {
367
- if (!open) return undefined;
368
- const dismiss = event => {
369
- if (event.key !== 'Escape' || event.defaultPrevented) return;
370
- event.preventDefault();
371
- setOpen(false);
372
- };
373
- document.addEventListener('keydown', dismiss);
374
- return () => document.removeEventListener('keydown', dismiss);
375
- }, [open]);
376
- const copy = useCallback(async item => {
377
- try {
378
- await navigator.clipboard.writeText(item.text ?? '');
379
- setCopied(item.id);
380
- setTimeout(() => setCopied(current => current === item.id ? '' : current), 1600);
381
- } catch {
382
- setError('无法写入剪贴板,请手动选择文本。');
383
- }
384
- }, []);
385
- if (!sourceRecord || sourceRecord.sessionId !== sessionId) return null;
386
- const { trace, sourceStats, traceCounts } = sourceRecord.value;
387
-
388
- const turns = new Map();
389
- for (const item of trace) {
390
- const items = turns.get(item.turn);
391
- if (items) items.push(item);
392
- else turns.set(item.turn, [item]);
393
- }
394
- const renderItem = (item, index) => h('article', { key: item.id || `${index}`, style: traceStyle.item }, [
395
- h('div', { key: 'meta', style: traceStyle.meta }, [
396
- h('span', { key: 'kind', style: traceStyle.kind }, traceKind[item.kind] ?? item.kind),
397
- item.name ? h('code', { key: 'name', style: traceStyle.name }, item.name) : null,
398
- item.callId ? h('code', { key: 'call', style: traceStyle.name }, `${t('traceCall')} ${item.callId}`) : null,
399
- traceState[item.status] ? h('span', { key: 'state', style: traceStyle.state }, traceState[item.status]) : null,
400
- item.truncated && item.status !== 'truncated' ? h('span', { key: 'cut', style: traceStyle.state }, '已截取') : null,
401
- item.kind === 'tool_result' && item.text
402
- ? h('button', {
403
- key: 'copy', type: 'button', style: traceStyle.button,
404
- onClick: () => copy(item),
405
- }, copied === item.id ? t('traceCopied') : t('traceCopy'))
406
- : null,
407
- ]),
408
- h('p', { key: 'text', style: traceStyle.body }, item.text || (item.kind === 'tool_result' ? t('traceEmpty') : '')),
409
- ]);
410
- const dialog = open && h('div', {
411
- style: traceStyle.overlay,
412
- onMouseDown: event => { if (event.target === event.currentTarget) setOpen(false); },
413
- }, h('div', {
414
- role: 'dialog', 'aria-modal': true, 'aria-label': t('traceTitle'), style: traceStyle.dialog,
415
- }, [
416
- h('div', { key: 'head', style: traceStyle.header }, [
417
- h('h2', { key: 'title', style: traceStyle.heading }, t('traceTitle')),
418
- h('button', { key: 'close', type: 'button', style: traceStyle.button, onClick: () => setOpen(false) }, t('traceClose')),
419
- ]),
420
- h(SourceStats, { key: 'stats', stats: sourceStats, counts: traceCounts, t }),
421
- trace.length ? h('p', { key: 'hint', style: traceStyle.hint }, t('traceHint')) : null,
422
- error ? h('p', { key: 'error', style: { ...traceStyle.hint, color: '#b42318' } }, error) : null,
423
- ...Array.from(turns, ([turn, items]) => {
424
- const title = turn ? t('traceTurn').replace('{turn}', turn) : t('traceUnnumbered');
425
- const count = items.length === 1 ? t('traceOneItem') : t('traceItemCount').replace('{count}', items.length);
426
- return h('details', { key: turn ?? 'unnumbered', style: traceStyle.turn }, [
427
- h('summary', { key: 'summary', style: traceStyle.turnSummary }, [
428
- h('span', { key: 'title' }, title),
429
- h('span', { key: 'count', style: traceStyle.turnCount }, count),
430
- ]),
431
- h('div', { key: 'items', style: traceStyle.turnItems }, items.map(renderItem)),
432
- ]);
433
- }),
434
- ]));
435
- return [
436
- h('button', {
437
- key: 'trigger', type: 'button', style: traceStyle.button,
438
- title: t('traceTitle'), onClick: () => setOpen(value => !value),
439
- }, t('trace')),
440
- dialog && typeof document !== 'undefined' ? createPortal(dialog, document.body) : null,
441
- ];
442
- }
443
-
444
- function Panel() {
445
- const iframe = useRef(null);
446
- const url = new URL('agent-bridge/panel', document.baseURI).href;
447
-
448
- useEffect(() => {
449
- const lifetime = new AbortController();
450
- async function onMessage(event) {
451
- const frame = iframe.current;
452
- if (!frame || event.source !== frame.contentWindow || event.origin !== window.origin) return;
453
- try {
454
- if (event.source.location.href !== url) return;
455
- } catch {
456
- return;
457
- }
458
- const request = event.data;
459
- if (typeof request?.requestId !== 'string' || !/^[a-zA-Z0-9_-]{1,128}$/.test(request.requestId)) return;
460
- const reply = (result) => {
461
- if (iframe.current !== frame) return;
462
- event.source.postMessage({ type: 'dsh-agent-bridge:result', requestId: request.requestId, ...result },
463
- event.origin === 'null' ? '*' : event.origin);
464
- };
465
-
466
- if (request.type === 'dsh-agent-bridge:sessions' || request.type === 'dsh-agent-bridge:session-export') {
467
- try {
468
- const signal = AbortSignal.any([lifetime.signal, AbortSignal.timeout(20_000)]);
469
- reply({ ok: true, ...await exportRequest(request, signal) });
470
- } catch (error) {
471
- reply({ ok: false, error: error instanceof Error ? error.message.slice(0, 500) : '无法导出 DSH 会话。' });
472
- }
473
- return;
474
- }
475
- if (request.type === 'dsh-agent-bridge:open-imported') {
476
- try {
477
- await ctx.sessions.refresh();
478
- const snapshot = ctx.sessions.list.getSnapshot();
479
- if (!Object.hasOwn(snapshot.byId, request.sessionId)) throw new Error('会话已保存,请从工作区列表打开。');
480
- if (iframe.current === frame) ctx.uiWorkspace.openSession(request.sessionId);
481
- reply({ ok: true });
482
- } catch (error) {
483
- reply({ ok: false, error: error instanceof Error ? error.message.slice(0, 500) : '会话已保存,请从工作区列表打开。' });
484
- }
485
- return;
486
- }
487
- if (request.type === 'dsh-agent-bridge:recover-draft') {
488
- const partial = recentImports.get(request.requestId);
489
- if (importing || !partial || partial.ready || partial.sessionId !== request.sessionId) {
490
- reply({ ok: false, error: '无法定位这条交接会话,请回到工作区检查。' });
491
- return;
492
- }
493
- try {
494
- ctx.uiWorkspace.openSession(partial.sessionId);
495
- reply({ ok: true });
496
- } catch {
497
- reply({ ok: false, error: '暂时无法打开这条会话,请在工作区列表中重试。' });
498
- }
499
- return;
500
- }
501
- if (request.type === 'dsh-agent-bridge:open-path') {
502
- const { projectId, directory, assetId, referenceId, bridgeNonce } = request;
503
- if (!/^[a-f0-9]{24}$/.test(projectId) || !/^[a-f0-9]{64}$/.test(bridgeNonce)
504
- || (directory !== true && !/^[a-f0-9]{24}$/.test(assetId) && !/^[a-f0-9-]{36}$/.test(referenceId))) {
505
- reply({ ok: false, error: '文件引用格式无效。' });
506
- return;
507
- }
508
- try {
509
- const session = ctx.remote.session;
510
- if (typeof session.openWorkspacePath !== 'function') {
511
- reply({ ok: false, error: '当前 DSH 不支持打开本机文件,可复制路径。' });
512
- return;
513
- }
514
- if (typeof session.canOpenWorkspacePath === 'function') {
515
- const availability = await session.canOpenWorkspacePath();
516
- if (!availability?.ok) {
517
- reply({ ok: false, error: '无法确认本机文件打开能力,可复制路径。' });
518
- return;
519
- }
520
- if (availability.value !== true) {
521
- reply({ ok: false, error: '当前 DSH 不支持打开本机文件,可复制路径。' });
522
- return;
523
- }
524
- }
525
- const signal = AbortSignal.any([lifetime.signal, AbortSignal.timeout(20_000)]);
526
- const resolve = async () => {
527
- const response = await fetch(new URL('api', url), {
528
- method: 'POST', signal,
529
- headers: { 'Content-Type': 'application/json', 'X-DSH-Agent-Bridge': bridgeNonce },
530
- body: JSON.stringify({ action: 'resolve-open-path', projectId, directory, assetId, referenceId }),
531
- });
532
- const target = await response.json();
533
- if (!response.ok || !validPath(target.path)) throw new Error(target.error || '无法核对文件路径。');
534
- return target;
535
- };
536
- const target = await resolve();
537
- const opened = await session.openWorkspacePath({ path: target.path,
538
- ...(target.revealOnly ? { action: 'reveal' } : {}),
539
- }, signal);
540
- if (opened?.ok) {
541
- reply({ ok: true, revealed: target.revealOnly === true });
542
- return;
543
- }
544
- // A viewer may be unavailable for an extension while the file
545
- // manager is not; revealing still gives the user the file.
546
- const revealed = !target.revealOnly
547
- && await session.openWorkspacePath({ path: (await resolve()).path, action: 'reveal' }, signal);
548
- reply(revealed?.ok
549
- ? { ok: true, revealed: true }
550
- : { ok: false, error: 'DSH 未能打开这个文件,可复制路径后在资源管理器中查看。' });
551
- } catch (error) {
552
- reply({ ok: false, error: error instanceof Error
553
- ? error.message.slice(0, 500) : 'DSH 未能打开这个文件,可复制路径。' });
554
- }
555
- return;
556
- }
557
- if (request.type !== 'dsh-agent-bridge:open') return;
558
- if (!validPath(request.path) || typeof request.prompt !== 'string'
559
- || !request.prompt.trim() || request.prompt.length > 65_536) {
560
- reply({ ok: false, error: '项目目录或交接草稿格式无效。' });
561
- return;
562
- }
563
- if (importing) {
564
- reply({ ok: false, error: '另一个项目正在导入。' });
565
- return;
566
- }
567
- importing = true;
568
- try {
569
- const sessionId = await prepareSession(request, (id) => {
570
- if (iframe.current !== frame) return;
571
- ctx.uiWorkspace.openSession(id);
572
- if (typeof request.bridgeNonce === 'string' && /^[a-f0-9]{64}$/.test(request.bridgeNonce)) {
573
- // The native workspace may replace the panel before it receives the reply.
574
- void fetch(new URL('api', url), {
575
- method: 'POST', keepalive: true,
576
- headers: { 'Content-Type': 'application/json', 'X-DSH-Agent-Bridge': request.bridgeNonce },
577
- body: JSON.stringify({ action: 'record-project-continuation', ticket: request.requestId }),
578
- }).catch(() => {});
579
- }
580
- });
581
- reply({ ok: true, sessionId });
582
- } catch (error) {
583
- const partial = recentImports.get(request.requestId);
584
- reply({
585
- ok: false,
586
- recoverySessionId: partial?.ready === false ? partial.sessionId : undefined,
587
- error: error instanceof Error ? error.message.slice(0, 500) : 'DSH 无法打开交接会话。',
588
- });
589
- } finally {
590
- importing = false;
591
- }
592
- }
593
-
594
- window.addEventListener('message', onMessage);
595
- return () => {
596
- lifetime.abort();
597
- window.removeEventListener('message', onMessage);
598
- };
599
- }, [url]);
600
-
601
- return h('iframe', {
602
- ref: iframe,
603
- src: url,
604
- title: t('title'),
605
- referrerPolicy: 'no-referrer',
606
- style: { display: 'block', width: '100%', height: '100%', border: 0 },
607
- });
608
- }
609
-
610
- ctx.slots.inject('main', () => ctx.slots.register({
611
- name: 'main', key: panelId, locale: panelId,
612
- }, Panel));
613
- ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
614
- name: 'sidebar.panellist', id: panelId, order: 20, label: () => t('title'), locale: panelId,
615
- }, PanelIcon));
616
- ctx.slots.inject('conversation.session.header.actions', () => ctx.slots.register({
617
- name: 'conversation.session.header.actions', id: 'agent-bridge-trace', order: 30, locale: panelId,
618
- }, SourceTrace));
619
- }
620
-
621
- return { apply, inject: ['slots', 'locale', 'uiWorkspace', 'workspaces', 'sessions', 'conversation', 'remote', 'remote.session'] };
622
- },
623
- });
1
+ window.__ModuleLoader__.load({
2
+ id: '@wwwfz/dsh-agent-bridge',
3
+ factory: (require) => {
4
+ const { createElement: h, useCallback, useEffect, useRef, useState } = require('react');
5
+ const { createPortal } = require('react-dom');
6
+ const panelId = 'dsh-agent-bridge';
7
+ const messages = {
8
+ zh: {
9
+ title: 'Agent 工作接续',
10
+ trace: '来源记录',
11
+ traceTitle: '来源记录',
12
+ traceExcerpt: '工具记录摘录',
13
+ inlineProcess: '历史过程',
14
+ inlineCalls: '{count} 次工具调用',
15
+ inlineSourceTurn: '来源第 {turn} 轮',
16
+ archiveExport: '导出来源全文',
17
+ traceEmpty: '没有为这条会话保存来源记录。',
18
+ traceFailed: '暂时无法读取来源记录。',
19
+ traceClose: '关闭',
20
+ traceCopy: '复制结果摘录',
21
+ traceCopied: '已复制',
22
+ traceTurn: '第 {turn} 轮',
23
+ traceUnnumbered: '未标记轮次',
24
+ traceOneItem: '1 项',
25
+ traceItemCount: '{count} 项',
26
+ traceCall: '调用',
27
+ statsTitle: '原对话统计',
28
+ statsOverview: '{turns} 轮 · {messages} 条消息',
29
+ statsTurns: '已读轮次',
30
+ statsMessages: '已读消息',
31
+ statsTools: '已保存工具调用',
32
+ statsSpan: '消息时间跨度',
33
+ statsTokens: '源记录 Token',
34
+ statsRoles: '用户 {user} 条,助手 {assistant} 条',
35
+ statsImported: '已迁入 {count} 条消息',
36
+ statsFailed: '{count} 次失败',
37
+ statsMissing: '{count} 次未记录结果',
38
+ statsSummaries: '{count} 段思考摘要',
39
+ statsTokenDetail: '输入 {input},输出 {output}',
40
+ statsPartial: '消息与轮次仅统计已读取的部分原记录。',
41
+ statsLegacy: '旧版迁入的会话,统计来自当时保存的来源记录。',
42
+ archiveTitle: '完整历史',
43
+ archiveIndex: '回合目录',
44
+ archiveDetails: '会话详情',
45
+ archiveDetailsShort: '详情',
46
+ archiveJump: '跳转',
47
+ archiveRead: '阅读对话',
48
+ archiveContinued: '接上页',
49
+ archiveMore: '本轮在下一页继续',
50
+ archiveMissingTurn: '找不到这一轮,可以输入其他轮次。',
51
+ archiveUnclear: '部分记录缺失',
52
+ archiveFiles: '{count} 个附件',
53
+ archiveLoading: '正在读取…',
54
+ archiveFirst: '最早一页',
55
+ archivePrevious: '上一页',
56
+ archiveNext: '下一页',
57
+ archivePage: '第 {page} 页',
58
+ archiveGo: '跳到回合',
59
+ archiveRound: '回合号',
60
+ archiveRetry: '重试',
61
+ archiveEmpty: '这页暂无来源记录。',
62
+ archivePartial: '有部分来源内容无法读取,详情见记录。',
63
+ archiveScope: '{messages} 条历史消息 · {tools} 条工具记录 · {attachments} 个附件 · 已迁入 {native} 条消息',
64
+ archiveNativeRange: '(原第 {turns} 轮)',
65
+ archiveContext: ' · 续聊上下文 {count} 条',
66
+ archiveWithTools: '附带工具和摘要',
67
+ archiveLocal: '下载来源全文(本机版)',
68
+ archiveShare: '下载来源全文(分享版)',
69
+ archiveAttachment: '附件',
70
+ archiveImageZoomIn: '放大图片',
71
+ archiveImageZoomOut: '缩小图片',
72
+ archiveImageUnavailable: '暂时无法显示缩略图,可下载原文件。',
73
+ archiveProcess: '过程',
74
+ archivePageItemCount: '本页 {count} 项',
75
+ archiveUser: '用户',
76
+ archiveAssistant: '助手',
77
+ archiveQuote: '引用到草稿',
78
+ archiveQuoted: '已填入草稿。',
79
+ archiveCopy: '复制摘录',
80
+ archiveSegment: '分段显示',
81
+ archiveBranch: '分支 {id}',
82
+ },
83
+ en: {
84
+ title: 'Agent Workspace Handoff',
85
+ trace: 'Source record',
86
+ traceTitle: 'Source record',
87
+ traceExcerpt: 'Tool record excerpts',
88
+ inlineProcess: 'Imported process',
89
+ inlineCalls: '{count} tool calls',
90
+ inlineSourceTurn: 'Source turn {turn}',
91
+ archiveExport: 'Export full history',
92
+ traceEmpty: 'No source record is saved for this session.',
93
+ traceFailed: 'The source record cannot be read right now.',
94
+ traceClose: 'Close',
95
+ traceCopy: 'Copy result excerpt',
96
+ traceCopied: 'Copied',
97
+ traceTurn: 'Turn {turn}',
98
+ traceUnnumbered: 'Unnumbered records',
99
+ traceOneItem: '1 item',
100
+ traceItemCount: '{count} items',
101
+ traceCall: 'Call',
102
+ statsTitle: 'Original conversation statistics',
103
+ statsOverview: '{turns} turns · {messages} messages',
104
+ statsTurns: 'Turns read',
105
+ statsMessages: 'Messages read',
106
+ statsTools: 'Saved tool calls',
107
+ statsSpan: 'Message time span',
108
+ statsTokens: 'Source tokens',
109
+ statsRoles: '{user} user and {assistant} assistant messages',
110
+ statsImported: '{count} messages imported',
111
+ statsFailed: 'Failed calls: {count}',
112
+ statsMissing: 'Calls with no recorded result: {count}',
113
+ statsSummaries: 'Reasoning summaries: {count}',
114
+ statsTokenDetail: 'Input {input}, output {output}',
115
+ statsPartial: 'The message and turn counts cover the part of the source that was read.',
116
+ statsLegacy: 'Statistics for this older import come from its saved source records.',
117
+ archiveTitle: 'Full history',
118
+ archiveIndex: 'Turn index',
119
+ archiveDetails: 'Session details',
120
+ archiveDetailsShort: 'Details',
121
+ archiveJump: 'Jump',
122
+ archiveRead: 'Read conversation',
123
+ archiveContinued: 'Continued',
124
+ archiveMore: 'Continue this turn on the next page',
125
+ archiveMissingTurn: 'This turn was not found. Try a different turn number.',
126
+ archiveUnclear: 'Partial record',
127
+ archiveFiles: '{count} attachments',
128
+ archiveLoading: 'Loading…',
129
+ archiveFirst: 'First page',
130
+ archivePrevious: 'Previous page',
131
+ archiveNext: 'Next page',
132
+ archivePage: 'Page {page}',
133
+ archiveGo: 'Go to turn',
134
+ archiveRound: 'Turn number',
135
+ archiveRetry: 'Retry',
136
+ archiveEmpty: 'There are no records on this page.',
137
+ archivePartial: 'Part of the source is unavailable. See the records for details.',
138
+ archiveScope: '{messages} history messages · {tools} tool records · {attachments} attachments · {native} messages imported',
139
+ archiveNativeRange: ' (source turns {turns})',
140
+ archiveContext: ' · {count} messages in continuation context',
141
+ archiveWithTools: 'Include tools and summaries',
142
+ archiveLocal: 'Download full history (local)',
143
+ archiveShare: 'Download full history (shareable)',
144
+ archiveAttachment: 'Attachment',
145
+ archiveImageZoomIn: 'Enlarge image',
146
+ archiveImageZoomOut: 'Shrink image',
147
+ archiveImageUnavailable: 'The thumbnail is unavailable. You can download the original.',
148
+ archiveProcess: 'Process',
149
+ archivePageItemCount: '{count} on this page',
150
+ archiveUser: 'User',
151
+ archiveAssistant: 'Assistant',
152
+ archiveQuote: 'Quote in draft',
153
+ archiveQuoted: 'Added to draft.',
154
+ archiveCopy: 'Copy excerpt',
155
+ archiveSegment: 'Shown in parts',
156
+ archiveBranch: 'Branch {id}',
157
+ },
158
+ };
159
+
160
+ function validPath(value) {
161
+ return typeof value === 'string' && value.length > 0 && value.length <= 4096
162
+ && !/[\u0000-\u001f]/u.test(value);
163
+ }
164
+
165
+ function pathKey(path) {
166
+ if (/^[a-z]:[\\/]|^\\\\|^\/\//i.test(path)) {
167
+ return path.replace(/\//g, '\\').replace(/^\\\\\?\\UNC\\/i, '\\\\')
168
+ .replace(/^\\\\\?\\/, '').replace(/\\+$/, '').toLowerCase();
169
+ }
170
+ return path.replace(/\/+$/, '');
171
+ }
172
+
173
+ function sessionRow(summary) {
174
+ if (!summary || summary.blank || summary.origin === 'subagent' || !validPath(summary.cwd)) return;
175
+ return {
176
+ id: summary.id,
177
+ title: (summary.title || summary.displayTitle || '未命名会话').slice(0, 240),
178
+ path: summary.cwd,
179
+ updatedAt: summary.updatedAt,
180
+ };
181
+ }
182
+
183
+ function dialogueFrom(event) {
184
+ if (event?.surfaceOp !== 'append') return;
185
+ let content;
186
+ let role;
187
+ if (event.type === 'user/message' && event.data?.source?.kind === 'user') {
188
+ role = 'user';
189
+ content = event.data.content;
190
+ } else if (event.type === 'assistant/message') {
191
+ role = 'assistant';
192
+ content = event.data?.message?.content;
193
+ }
194
+ if (!Array.isArray(content)) return;
195
+ const text = content.filter(block => block?.type === 'text' && typeof block.text === 'string')
196
+ .map(block => block.text).join('\n\n');
197
+ return text.trim() ? { role, text } : undefined;
198
+ }
199
+
200
+ async function sessionDialogue(remote, sessionId, signal) {
201
+ const collected = [];
202
+ const address = { kind: 'session', sessionId };
203
+ let remaining = 28_000;
204
+ let throughSeq;
205
+ let beforeSeq;
206
+ let hasMore = true;
207
+ let truncated = false;
208
+ for (let page = 0; page < 8 && hasMore && !truncated; page++) {
209
+ const result = await remote.events({ address, maxMessages: 40,
210
+ ...(throughSeq === undefined ? {} : { throughSeq, beforeSeq }),
211
+ }, signal);
212
+ if (!result.ok) throw new Error('无法读取这条 DSH 会话的历史。');
213
+ const { records, cursor } = result.value;
214
+ hasMore = result.value.hasMore;
215
+ throughSeq ??= cursor;
216
+ for (let i = records.length - 1; i >= 0; i--) {
217
+ const message = dialogueFrom(records[i].event);
218
+ if (!message) continue;
219
+ if (collected.length >= 24 || message.text.length > remaining) {
220
+ if (!collected.length) collected.push({ ...message,
221
+ text: message.text.slice(0, remaining).replace(/[\uD800-\uDBFF]$/, ''),
222
+ });
223
+ truncated = true;
224
+ break;
225
+ }
226
+ collected.push(message);
227
+ remaining -= message.text.length;
228
+ }
229
+ const firstSeq = records[0]?.event?.seq;
230
+ if (hasMore && (!Number.isSafeInteger(firstSeq) || firstSeq <= 0 || firstSeq >= (beforeSeq ?? Infinity))) break;
231
+ beforeSeq = firstSeq;
232
+ }
233
+ return { messages: collected.reverse(), truncated: truncated || hasMore };
234
+ }
235
+
236
+ function PanelIcon({ size = 16 }) {
237
+ return h('svg', {
238
+ width: size, height: size, viewBox: '0 0 24 24', fill: 'none',
239
+ stroke: 'currentColor', strokeWidth: 1.7, strokeLinecap: 'round', strokeLinejoin: 'round',
240
+ 'aria-hidden': true,
241
+ }, h('path', { d: 'M3 17.5V6.5A1.5 1.5 0 0 1 4.5 5H9l2 2h8.5A1.5 1.5 0 0 1 21 8.5v9a1.5 1.5 0 0 1-1.5 1.5h-15A1.5 1.5 0 0 1 3 17.5Z M8 13h8m-3-3 3 3-3 3' }));
242
+ }
243
+
244
+ function apply(ctx) {
245
+ ctx.effect(() => ctx.locale.register(panelId, messages), 'agent bridge locale');
246
+ const t = ctx.locale.bind(panelId);
247
+ const recentImports = new Map();
248
+ const incompleteDrafts = new Map();
249
+ let importing = false;
250
+
251
+ async function exportRequest(request, signal) {
252
+ if (request.path !== undefined && !validPath(request.path)) throw new Error('工作目录格式无效。');
253
+ const scope = request.path === undefined ? undefined : pathKey(request.path);
254
+ const snapshot = ctx.sessions.list.getSnapshot();
255
+ if (snapshot.phase !== 'ready') throw new Error('DSH 会话列表正在加载,请稍后重试。');
256
+ const rows = snapshot.ids.map(id => sessionRow(snapshot.byId[id]))
257
+ .filter(row => row && (scope === undefined || pathKey(row.path) === scope));
258
+ if (request.type === 'dsh-agent-bridge:sessions') return { sessions: rows };
259
+
260
+ const selected = rows.find(row => row.id === request.sessionId);
261
+ if (!selected) throw new Error('未在这个工作区找到可导出的 DSH 会话。');
262
+ const dialogue = await sessionDialogue(ctx.remote.session, selected.id, signal);
263
+ if (!dialogue.messages.length) throw new Error('这条 DSH 会话暂无可导出的文字。');
264
+ return { conversation: { title: selected.title, path: selected.path, ...dialogue } };
265
+ }
266
+
267
+ function rememberImport(requestId, imported) {
268
+ if (!recentImports.has(requestId) && recentImports.size >= 32) {
269
+ recentImports.delete(recentImports.keys().next().value);
270
+ }
271
+ recentImports.set(requestId, imported);
272
+ }
273
+
274
+ async function rollbackDraft(imported, binding) {
275
+ try {
276
+ const session = binding?.session;
277
+ const state = session?.getSnapshot();
278
+ const input = binding && ctx.conversation.input.for(binding.ctx).snapshot;
279
+ // A preserved draft, attachments, or a chat already in use belong to
280
+ // the user. Archive only an unused, empty chat created by this handoff.
281
+ if (state && (!state.blank || state.running || state.promptAttempted || state.removed)) return false;
282
+ if (binding && (!input || input.draft !== '' || input.attachmentIds?.length
283
+ || ['adjudicating', 'submitting', 'sending'].includes(input.phase))) return false;
284
+ await ctx.workspaces.archiveSession(imported.sessionId);
285
+ incompleteDrafts.delete(imported.path);
286
+ for (const [key, item] of recentImports) if (item === imported) recentImports.delete(key);
287
+ return true;
288
+ } catch {
289
+ return false;
290
+ }
291
+ }
292
+
293
+ async function prepareSession(request, reveal) {
294
+ const path = pathKey(request.path);
295
+ let imported = recentImports.get(request.requestId) ?? incompleteDrafts.get(path);
296
+ if (imported && imported.path !== path) throw new Error('交接工作目录已变化,请重新预览。');
297
+ if (!imported) {
298
+ const workspace = await ctx.workspaces.create({ path: request.path });
299
+ const sessionId = await ctx.sessions.create({ workspaceId: workspace.workspaceId });
300
+ imported = { sessionId, path, ready: false };
301
+ incompleteDrafts.set(path, imported);
302
+ }
303
+ rememberImport(request.requestId, imported);
304
+
305
+ let reference;
306
+ try {
307
+ if (!imported.ready) {
308
+ let binding;
309
+ let outcome;
310
+ try {
311
+ reference = ctx.sessions.retain(imported.sessionId, { source: panelId });
312
+ binding = reference.binding;
313
+ await reference.ready;
314
+ outcome = ctx.conversation.input.requestDraftInitialization(binding, {
315
+ prompt: request.prompt,
316
+ whenDraftExists: 'keep',
317
+ });
318
+ } catch {
319
+ // A Host error can also leave an empty session to roll back.
320
+ }
321
+ if (outcome !== 'applied') {
322
+ if (outcome !== 'preserved' && await rollbackDraft(imported, binding)) {
323
+ throw new Error('DSH 未能填入交接草稿。空白会话已归档,可重试。');
324
+ }
325
+ throw new Error(outcome === 'preserved'
326
+ ? '会话中已有草稿,已原样保留。可打开会话并手动补入交接资料。'
327
+ : 'DSH 未能填入交接草稿。可重试同一会话,或打开后手动补入交接资料。');
328
+ }
329
+ imported.ready = true;
330
+ incompleteDrafts.delete(path);
331
+ }
332
+ reveal(imported.sessionId);
333
+ return imported.sessionId;
334
+ } finally {
335
+ reference?.release();
336
+ }
337
+ }
338
+
339
+ async function quoteHistory(sessionId, text) {
340
+ if (typeof text !== 'string' || !text.trim() || text.length > 65_536 || /\0/u.test(text)) {
341
+ throw new Error('摘录为空或过长,请选择一段文字复制。');
342
+ }
343
+ const snapshot = ctx.sessions.list.getSnapshot();
344
+ if (snapshot.phase !== 'ready' || !Object.hasOwn(snapshot.byId, sessionId) || !sessionRow(snapshot.byId[sessionId])) {
345
+ throw new Error('找不到可以引用来源历史的 DSH 会话。');
346
+ }
347
+ const reference = ctx.sessions.retain(sessionId, { source: panelId });
348
+ try {
349
+ await reference.ready;
350
+ const prompt = text.split(/\r?\n/u).map(line => `> ${line}`).join('\n') + '\n\n';
351
+ const outcome = ctx.conversation.input.requestDraftInitialization(reference.binding, { prompt, whenDraftExists: 'append' });
352
+ if (outcome === 'preserved') throw new Error('已有草稿,已保留。可复制摘录后手动粘贴。');
353
+ if (outcome !== 'applied') throw new Error('无法填入草稿。可复制摘录后手动粘贴。');
354
+ } finally {
355
+ reference.release();
356
+ }
357
+ }
358
+
359
+ const traceKind = { summary: '思考摘要', tool_call: '工具调用', tool_result: '工具结果', turn_end: '回合结束' };
360
+ const traceState = {
361
+ missing: '未记录结果', error: '失败', pending: '未完成', truncated: '已截取', unmatched: '归属未知', incomplete: '未完成',
362
+ completed: '已完成', interrupted: '已中断',
363
+ };
364
+ const number = new Intl.NumberFormat().format;
365
+
366
+ function formatSpan(milliseconds) {
367
+ const seconds = Math.floor(milliseconds / 1000);
368
+ const hours = Math.floor(seconds / 3600);
369
+ const minutes = Math.floor(seconds / 60) % 60;
370
+ const rest = String(seconds % 60).padStart(2, '0');
371
+ return hours ? `${hours}:${String(minutes).padStart(2, '0')}:${rest}` : `${minutes}:${rest}`;
372
+ }
373
+
374
+ function SourceStats({ stats, counts = {}, t }) {
375
+ const values = [];
376
+ const notes = [];
377
+ if (stats) {
378
+ const total = stats.userMessages + stats.assistantMessages;
379
+ values.push(['statsTurns', number(stats.userMessages)], ['statsMessages', number(total)]);
380
+ notes.push(t('statsRoles').replace('{user}', number(stats.userMessages)).replace('{assistant}', number(stats.assistantMessages)));
381
+ if (stats.importedMessages !== total) notes.push(t('statsImported').replace('{count}', number(stats.importedMessages)));
382
+ }
383
+ values.push(['statsTools', number(counts.toolCall ?? 0)]);
384
+ if (stats?.elapsedMs !== undefined) values.push(['statsSpan', formatSpan(stats.elapsedMs)]);
385
+ if (stats?.tokens) {
386
+ values.push(['statsTokens', number(stats.tokens.total)]);
387
+ const { input, output } = stats.tokens;
388
+ if (input !== undefined && output !== undefined) {
389
+ notes.push(t('statsTokenDetail').replace('{input}', number(input)).replace('{output}', number(output)));
390
+ }
391
+ }
392
+ for (const [count, label] of [[counts.failed, 'statsFailed'], [counts.missing, 'statsMissing'], [counts.summary, 'statsSummaries']]) {
393
+ if (count) notes.push(t(label).replace('{count}', number(count)));
394
+ }
395
+ const scope = stats ? (stats.partial ? t('statsPartial') : '') : t('statsLegacy');
396
+ return h('details', { className: 'bridge-reader bridge-stats', open: !stats }, [
397
+ h('summary', { key: 'title', className: 'reader-summary' }, [
398
+ t('statsTitle'),
399
+ stats && h('small', { key: 'overview' }, t('statsOverview').replace('{turns}', number(stats.userMessages))
400
+ .replace('{messages}', number(stats.userMessages + stats.assistantMessages))),
401
+ ]),
402
+ h('dl', { key: 'values' }, values.map(([label, value]) => h('div', { key: label }, [
403
+ h('dt', { key: 'label' }, t(label)),
404
+ h('dd', { key: 'value' }, value),
405
+ ]))),
406
+ notes.length ? h('p', { key: 'notes' }, notes.join(' · ')) : null,
407
+ scope ? h('p', { key: 'scope' }, scope) : null,
408
+ ]);
409
+ }
410
+
411
+ function archiveUrl(route, sessionId, values = {}) {
412
+ const url = new URL(`agent-bridge/${route}`, document.baseURI);
413
+ url.search = new URLSearchParams({ sessionId, ...values }).toString();
414
+ return url.href;
415
+ }
416
+
417
+ const processIndexes = new Map();
418
+ function processIndex(sessionId) {
419
+ const cached = processIndexes.get(sessionId);
420
+ if (cached && cached.expires > Date.now()) return cached.request;
421
+ const request = fetch(archiveUrl('conversation-process', sessionId))
422
+ .then(response => {
423
+ if (response.status === 404) return { placements: [] };
424
+ if (!response.ok) throw new Error('Could not read imported process index');
425
+ return response.json();
426
+ });
427
+ request.catch(() => {
428
+ if (processIndexes.get(sessionId)?.request === request) processIndexes.delete(sessionId);
429
+ });
430
+ processIndexes.delete(sessionId);
431
+ processIndexes.set(sessionId, { request, expires: Date.now() + 60_000 });
432
+ if (processIndexes.size > 8) processIndexes.delete(processIndexes.keys().next().value);
433
+ return request;
434
+ }
435
+
436
+ const inlineProcessNode = 'agent-bridge-source-process';
437
+ const inlineProcessDefinition = {
438
+ kind: inlineProcessNode,
439
+ target: 'chat',
440
+ match: {
441
+ 'assistant/message': event => event.surfaceOp === 'append' && event.data.message?.source?.provider === 'agent-bridge-import'
442
+ ? { id: String(event.seq), role: 'start' } : null,
443
+ },
444
+ start: (_context, match) => match.event.seq,
445
+ update: context => context.state,
446
+ buildViewNode(context) {
447
+ const location = context.start?.location;
448
+ if (!location || (location.kind !== 'step' && location.kind !== 'turn')) return null;
449
+ return {
450
+ key: context.key, id: context.id, kind: inlineProcessNode, target: 'chat',
451
+ anchorSeq: context.state - 0.25, location, groupTree: 'turn', visibility: 'visible',
452
+ data: { anchor: context.state, turn: location.turn },
453
+ };
454
+ },
455
+ };
456
+
457
+ function InlineProcessNode({ sessionId, node, t }) {
458
+ return h(InlineProcess, { sessionId, ...node.data, t });
459
+ }
460
+
461
+ function InlineProcessTail({ sessionId, turn, t }) {
462
+ return h(InlineProcess, { sessionId, turn, anchor: turn.end?.seq, tail: true, t });
463
+ }
464
+
465
+ function InlineProcess({ sessionId, turn, anchor, tail = false, t }) {
466
+ const [index, setIndex] = useState();
467
+ useEffect(() => {
468
+ if (!sessionId) return undefined;
469
+ let mounted = true;
470
+ processIndex(sessionId).then(value => {
471
+ if (mounted) setIndex({ sessionId, placements: value.placements });
472
+ }, () => {});
473
+ return () => { mounted = false; };
474
+ }, [sessionId]);
475
+ const entry = index?.sessionId === sessionId ? index.placements.find(item =>
476
+ item.nativeTurn === turn.turn && item.anchor === anchor && item.tail === tail
477
+ && (turn.start ? item.start === turn.start.seq : !tail)) : undefined;
478
+ return entry ? h(InlineProcessDetails, { key: sessionId + ':' + entry.anchor, sessionId, entry, t }) : null;
479
+ }
480
+
481
+ function InlineProcessDetails({ sessionId, entry, t }) {
482
+ const [open, setOpen] = useState(false);
483
+ const [locations, setLocations] = useState([null]);
484
+ const [result, setResult] = useState();
485
+ const [attempt, retry] = useState(0);
486
+ const cursor = locations.at(-1);
487
+ useEffect(() => {
488
+ if (!open) return undefined;
489
+ const controller = new AbortController();
490
+ const values = { turn: entry.sourceTurn, after: entry.after,
491
+ ...(entry.before === undefined ? {} : { before: entry.before }), ...(cursor ? { cursor } : {}) };
492
+ setResult(undefined);
493
+ fetch(archiveUrl('conversation-process', sessionId, values), { signal: controller.signal })
494
+ .then(response => {
495
+ if (!response.ok) throw new Error('Could not read imported process');
496
+ return response.json();
497
+ })
498
+ .then(page => { if (!controller.signal.aborted) setResult({ cursor, page }); })
499
+ .catch(() => { if (!controller.signal.aborted) setResult({ cursor, failed: true }); });
500
+ return () => controller.abort();
501
+ }, [open, sessionId, entry.sourceTurn, entry.after, entry.before, cursor, attempt]);
502
+
503
+ const current = result?.cursor === cursor ? result : undefined;
504
+ const button = (key, label, onClick) => h('button', { key, type: 'button', onClick }, t(label));
505
+ const count = t(entry.calls ? 'inlineCalls' : 'traceItemCount').replace('{count}', number(entry.calls || entry.count));
506
+ const summary = [t('inlineProcess'), count,
507
+ t('inlineSourceTurn').replace('{turn}', number(entry.sourceTurn))].join(' · ');
508
+ return h('details', { className: 'bridge-inline-process',
509
+ onToggle: event => setOpen(event.currentTarget.open) }, [
510
+ h('summary', { key: 'summary' }, summary),
511
+ open && h('div', { key: 'body' }, [
512
+ !current && h('p', { key: 'loading', role: 'status' }, t('archiveLoading')),
513
+ current?.failed && h('div', { key: 'error', role: 'status' }, [
514
+ t('traceFailed'), ' ', button('retry', 'archiveRetry', () => retry(value => value + 1)),
515
+ ]),
516
+ ...((current?.page?.items ?? []).map(item => h('article', {
517
+ key: item.seq + ':' + (item.offset ?? 0),
518
+ }, [
519
+ h('strong', { key: 'label' }, [
520
+ traceKind[item.kind], item.name, item.callId ? t('traceCall') + ' ' + item.callId : '',
521
+ traceState[item.status], item.branchId ? t('archiveBranch').replace('{id}', item.branchId) : '',
522
+ item.offset || item.continued ? t('archiveSegment') : '',
523
+ ].filter(Boolean).join(' · ')),
524
+ h('pre', { key: 'text', tabIndex: 0 }, item.text || t('traceEmpty')),
525
+ ]))),
526
+ current?.page && (locations.length > 1 || current.page.nextCursor) ? h('nav', {
527
+ key: 'pages', 'aria-label': t('inlineProcess'),
528
+ }, [
529
+ locations.length > 1 && button('previous', 'archivePrevious', () => setLocations(values => values.slice(0, -1))),
530
+ ' ', t('archivePage').replace('{page}', number(locations.length)), ' ',
531
+ current.page.nextCursor && button('next', 'archiveNext',
532
+ () => setLocations(values => [...values, current.page.nextCursor])),
533
+ ]) : null,
534
+ ]),
535
+ ]);
536
+ }
537
+
538
+ const archiveIssues = new Map([
539
+ ['source-unavailable', '找不到会话来源。'],
540
+ ['source-unreadable', '无法读取部分来源记录。'],
541
+ ['source-mismatch', '来源的工作目录和项目不一致。'],
542
+ ['source-metadata-missing', '来源缺少用于核对会话身份的记录。'],
543
+ ['source-compacted', '来源已压缩早期历史,原文可能已不在源记录中。'],
544
+ ['source-dialogue-only', '来源只有已保存的问答,工具和附件记录可能缺失。'],
545
+ ['source-tool-output-truncated', '源记录中的工具输出已被截取。'],
546
+ ['archive-tool-details-unavailable', '归档缺少工具调用详情。'],
547
+ ['unresolved-branch', '无法确定部分分支的归属。'],
548
+ ['unresolved-source-projection', '有部分来源消息无法核对。'],
549
+ ['unsupported-source-schema', '当前版本不识别这份来源的存储结构。'],
550
+ ['unsupported-incremental-edit', '部分增量编辑无法恢复。'],
551
+ ['unsupported-source', '当前版本无法读取这类来源。'],
552
+ ['unsupported-compression', '当前 DSH 无法解压这份日志。'],
553
+ ['malformed-record', '有一条来源记录损坏或格式无法识别。'],
554
+ ['record-too-large', '有一条来源记录超过可读取的大小。'],
555
+ ['corrupt-compressed-source', '压缩日志不完整或已损坏。'],
556
+ ['source-changed', '读取期间,来源发生变化。'],
557
+ ['remote-reference', '此附件只有远程引用。'],
558
+ ['name-only', '来源只保存了附件名称。'],
559
+ ['outside-project', '附件不在可读取范围内。'],
560
+ ['attachment-unavailable', '附件已移动或无法访问。'],
561
+ ['attachment-too-large', '附件超过可保存的大小。'],
562
+ ]);
563
+
564
+ const readerPaths = {
565
+ book: 'M3 5.5c3-1.4 6-1.1 9 1 3-2.1 6-2.4 9-1v13c-3-1.4-6-1.1-9 1-3-2.1-6-2.4-9-1z M12 6.5v13',
566
+ file: 'M6 3.5h8l4 4v13H6z M14 3.5v5h4 M9 13h6 M9 16h4',
567
+ copy: 'M9 8h11v13H9z M15 8V3H4v13h5',
568
+ quote: 'M5 10h14v3a5 5 0 0 1-5 5H9 M9 6l-4 4 4 4',
569
+ back: 'M14.5 5.5 8 12l6.5 6.5',
570
+ next: 'm9.5 5.5 6.5 6.5-6.5 6.5',
571
+ close: 'm6 6 12 12 M18 6 6 18',
572
+ settings: 'M4 7h7m4 0h5M4 17h3m4 0h9 M11 4v6 M7 14v6',
573
+ };
574
+ function readerIcon(name) {
575
+ return h('svg', { key: name, viewBox: '0 0 24 24', width: 17, height: 17, fill: 'none', stroke: 'currentColor',
576
+ strokeWidth: 1.6, strokeLinecap: 'round', strokeLinejoin: 'round', 'aria-hidden': true },
577
+ h('path', { d: readerPaths[name] }));
578
+ }
579
+
580
+ function hasThumbnail(item) {
581
+ return item.status === 'saved' && item.attachmentId && ['image/png', 'image/jpeg', 'image/gif', 'image/webp'].includes(item.mediaType);
582
+ }
583
+
584
+ function HistoryAttachment({ item, sessionId, t }) {
585
+ const [imageFailed, setImageFailed] = useState(false);
586
+ const [enlarged, setEnlarged] = useState(false);
587
+ const name = item.name || t('archiveAttachment');
588
+ if (item.status !== 'saved' || !item.attachmentId) {
589
+ return h('div', { className: 'archive-attachment record-file unavailable' }, [
590
+ readerIcon('file'), h('strong', { key: 'name', className: 'archive-attachment-name' }, name),
591
+ h('p', { key: 'state', className: 'reader-body' }, archiveIssues.get(item.reason || item.status) || t('archivePartial')),
592
+ ]);
593
+ }
594
+ const url = archiveUrl('conversation-attachment', sessionId, {
595
+ attachmentId: item.attachmentId,
596
+ ...(Number.isSafeInteger(item.seq) ? { seq: item.seq } : {}),
597
+ });
598
+ const isImage = hasThumbnail(item);
599
+ const inlineUrl = url + '&inline=true';
600
+ return h('div', { className: isImage && !imageFailed ? 'archive-attachment record-image' : 'archive-attachment record-file' }, [
601
+ (!isImage || imageFailed) && readerIcon('file'),
602
+ isImage && !imageFailed ? h('button', {
603
+ key: 'preview', type: 'button', 'aria-pressed': enlarged,
604
+ 'aria-label': `${t(enlarged ? 'archiveImageZoomOut' : 'archiveImageZoomIn')} ${name}`,
605
+ onClick: () => setEnlarged(value => !value),
606
+ className: 'archive-attachment-preview',
607
+ }, h('img', {
608
+ src: inlineUrl, alt: name, loading: 'lazy', decoding: 'async',
609
+ onError: () => setImageFailed(true),
610
+ })) : null,
611
+ isImage && imageFailed ? h('p', { key: 'error', className: 'reader-body' }, t('archiveImageUnavailable')) : null,
612
+ h('a', {
613
+ key: 'download', className: 'archive-attachment-name',
614
+ href: url, download: name,
615
+ }, name),
616
+ ]);
617
+ }
618
+
619
+ function pageTurns(items) {
620
+ const turns = new Map();
621
+ for (const [index, item] of items.entries()) {
622
+ const id = item.turn || 0;
623
+ if (!turns.has(id)) turns.set(id, { id, rows: [], processes: new Map(), title: '' });
624
+ const turn = turns.get(id);
625
+ if (!turn.title && item.kind === 'message' && item.role === 'user') {
626
+ turn.title = (item.text || '').trim().slice(0, 100).replace(/\s+/gu, ' ');
627
+ }
628
+ if (['summary', 'tool_call', 'tool_result'].includes(item.kind)) {
629
+ const branch = item.branchId || '';
630
+ if (!turn.processes.has(branch)) {
631
+ const group = { process: true, branch, index, items: [], ids: new Set() };
632
+ turn.processes.set(branch, group);
633
+ turn.rows.push(group);
634
+ }
635
+ const group = turn.processes.get(branch);
636
+ group.items.push({ item, index });
637
+ group.ids.add(item.seq ?? index);
638
+ } else if (item.kind === 'attachment') {
639
+ let group = turn.rows.at(-1);
640
+ if (!group?.files || item.branchId !== group.branch) {
641
+ group = { index, branch: item.branchId, files: [] };
642
+ turn.rows.push(group);
643
+ }
644
+ group.files.push({ item, index });
645
+ } else {
646
+ turn.rows.push({ item, index });
647
+ }
648
+ }
649
+ return [...turns.values()];
650
+ }
651
+
652
+ function ArchiveDetails({ history, sessionId, t }) {
653
+ const [includeTrace, setIncludeTrace] = useState(false);
654
+ const { nativeFirstTurn: start, nativeLastTurn: end } = history;
655
+ const range = start && end ? t('archiveNativeRange').replace('{turns}', start === end ? start : start + '–' + end) : '';
656
+ const scope = t('archiveScope').replace('{messages}', number(history.messages ?? 0))
657
+ .replace('{tools}', number(history.tools ?? 0)).replace('{attachments}', number(history.attachments ?? 0))
658
+ .replace('{native}', number(history.nativeMessages ?? 0)) + range
659
+ + (history.nativeTimeline ? t('archiveContext').replace('{count}', number(history.contextMessages)) : '');
660
+ return h('section', { className: 'record-export' }, [
661
+ h('h3', { key: 'title' }, t('archiveExport')),
662
+ h('p', { key: 'info', className: 'reader-note' }, scope),
663
+ history.complete === false && h('p', { key: 'partial', className: 'reader-note' }, t('archivePartial')),
664
+ h('div', { key: 'links', className: 'reader-downloads' }, [
665
+ ...[['local', 'archiveLocal'], ['share', 'archiveShare']].map(([format, label]) =>
666
+ h('a', { key: format, className: 'reader-button', download: '', href: archiveUrl('conversation-export', sessionId, {
667
+ format, includeTrace: String(includeTrace),
668
+ }) }, t(label))),
669
+ h('label', { key: 'tools' }, [
670
+ h('input', { key: 'check', type: 'checkbox', checked: includeTrace,
671
+ onChange: event => setIncludeTrace(event.target.checked) }), ' ', t('archiveWithTools'),
672
+ ]),
673
+ ]),
674
+ ]);
675
+ }
676
+
677
+ function SourceArchive({ sessionId, t, hidden }) {
678
+ const [selected, setSelected] = useState(null);
679
+ const [locations, setLocations] = useState([{}]);
680
+ const [response, setResponse] = useState();
681
+ const [attempt, setAttempt] = useState(0);
682
+ const [notice, setNotice] = useState('');
683
+ const [quoting, setQuoting] = useState(false);
684
+ const records = useRef(null);
685
+ const locator = locations.at(-1);
686
+ useEffect(() => {
687
+ const request = new AbortController();
688
+ const url = archiveUrl('conversation-history', sessionId, locator);
689
+ setResponse(undefined);
690
+ setNotice('');
691
+ fetch(url, { signal: request.signal, headers: { Accept: 'application/json' } })
692
+ .then(async result => {
693
+ if (!result.ok) throw new Error(t('traceFailed'));
694
+ return result.json();
695
+ })
696
+ .then(page => { if (!request.signal.aborted) setResponse({ locator, page }); })
697
+ .catch(() => { if (!request.signal.aborted) setResponse({ locator, failed: true }); });
698
+ return () => request.abort();
699
+ }, [sessionId, locator, attempt]);
700
+
701
+ const current = response?.locator === locator ? response : undefined;
702
+ const page = current?.page;
703
+ const turns = pageTurns(page?.items || []);
704
+ const active = turns.find(turn => turn.id === selected) || turns.find(turn => turn.id > 0) || turns[0];
705
+ const round = id => id ? t('traceTurn').replace('{turn}', number(id)) : t('traceUnnumbered');
706
+ function move(values) {
707
+ setSelected(null);
708
+ setLocations(values);
709
+ }
710
+ useEffect(() => {
711
+ if (records.current) records.current.scrollTop = 0;
712
+ setNotice('');
713
+ }, [active?.id, locator]);
714
+ const button = (key, label, onClick, disabled, icon) => h('button', {
715
+ key, type: 'button', className: icon ? 'record-icon' : 'reader-button',
716
+ 'aria-label': t(label), title: t(label), onClick, disabled,
717
+ }, icon ? readerIcon(icon) : t(label));
718
+ const turnTitle = active && [round(active.id), active.id === page.continuedTurn ? t('archiveContinued') : ''].filter(Boolean).join(' · ');
719
+ const renderItem = (item, index, prefix) => {
720
+ const title = item.kind === 'message'
721
+ ? t(item.role === 'user' ? 'archiveUser' : 'archiveAssistant')
722
+ : (traceKind[item.kind] ?? t('archiveAttachment'));
723
+ const detail = [
724
+ item.kind === 'attachment' ? '' : item.name,
725
+ item.callId ? `${t('traceCall')} ${item.callId}` : '', traceState[item.status],
726
+ item.offset || item.continued ? t('archiveSegment') : '',
727
+ item.branchId ? t('archiveBranch').replace('{id}', item.branchId) : '',
728
+ ].filter(Boolean).join(' · ');
729
+ return h('article', { key: index, className: 'turn-entry',
730
+ 'data-role': item.role }, item.kind === 'gap'
731
+ ? h('p', { className: 'reader-body' }, archiveIssues.get(item.reason) || t('archivePartial'))
732
+ : [
733
+ h(prefix ? 'h3' : 'strong', { key: 'label', className: 'entry-label' }, prefix ? prefix + ' · ' + title : title),
734
+ detail && h('small', { key: 'detail', className: 'reader-detail' }, detail),
735
+ item.text ? h('p', { key: 'text', className: item.role === 'user' && item.text.length < 115 && !item.offset && !item.continued ? 'reader-body turn-question' : 'reader-body' }, item.text) : null,
736
+ item.text ? h('div', { key: 'actions', className: 'reader-actions' }, [
737
+ button('copy', 'archiveCopy', async () => {
738
+ try {
739
+ await navigator.clipboard.writeText(item.text);
740
+ setNotice(t('traceCopied'));
741
+ } catch {
742
+ setNotice('无法写入剪贴板,请手动选择文本。');
743
+ }
744
+ }, false, 'copy'),
745
+ item.text.length <= 65_536 ? button('quote', 'archiveQuote', async () => {
746
+ setQuoting(true);
747
+ try {
748
+ await quoteHistory(sessionId, item.text);
749
+ setNotice(t('archiveQuoted'));
750
+ } catch (error) {
751
+ setNotice(error.message);
752
+ } finally {
753
+ setQuoting(false);
754
+ }
755
+ }, quoting, 'quote') : null,
756
+ ]) : null,
757
+ ]);
758
+ };
759
+ function renderRow(row, position) {
760
+ if (row.item) return renderItem(row.item, row.index, position === 0 && row.item.kind === 'message' ? turnTitle : undefined);
761
+ const branch = row.branch ? t('archiveBranch').replace('{id}', row.branch) : '';
762
+ if (row.files) {
763
+ const images = [], documents = [];
764
+ for (const { item, index } of row.files) {
765
+ const list = hasThumbnail(item) ? images : documents;
766
+ list.push(h(HistoryAttachment, { key: index, item, sessionId, t }));
767
+ }
768
+ return h('section', { key: row.index, className: 'turn-files' }, [
769
+ h('h4', { key: 'heading' }, [t('archiveFiles').replace('{count}', row.files.length), branch].filter(Boolean).join(' · ')),
770
+ h('div', { key: 'files', className: 'file-gallery' }, [
771
+ images.length ? h('div', { key: 'images', className: 'file-images' }, images) : null,
772
+ documents.length ? h('div', { key: 'documents', className: 'file-documents' }, documents) : null,
773
+ ]),
774
+ ]);
775
+ }
776
+ const count = t('archivePageItemCount').replace('{count}', number(row.ids.size));
777
+ return h('details', { key: row.index, className: 'reader-process turn-process' }, [
778
+ h('summary', { key: 'label', className: 'reader-summary' },
779
+ [t('archiveProcess'), count, branch].filter(Boolean).join(' · ')),
780
+ h('div', { key: 'body', className: 'reader-process-items' }, row.items.map(({ item, index }) => renderItem(item, index))),
781
+ ]);
782
+ }
783
+ const shortTitle = turn => turn.title || (turn.id === page?.continuedTurn ? t('archiveContinued') : '');
784
+ const nextPage = () => move([...locations, { cursor: page.nextCursor }]);
785
+ return h('div', { className: 'history-browser', hidden }, [
786
+ h('aside', { key: 'index', className: 'turn-index', 'aria-label': t('archiveIndex') }, [
787
+ h('header', { key: 'header', className: 'index-heading' }, [
788
+ h('h3', { key: 'title' }, t('archiveIndex')),
789
+ h('details', { key: 'jump', className: 'index-jump' }, [
790
+ h('summary', { key: 'summary' }, t('archiveJump')),
791
+ h('form', { key: 'form', className: 'reader-jump', onSubmit: event => {
792
+ event.preventDefault();
793
+ const input = event.currentTarget.elements.namedItem('turn');
794
+ const turn = input.valueAsNumber;
795
+ if (Number.isSafeInteger(turn) && turn > 0) {
796
+ const disclosure = event.currentTarget.parentElement;
797
+ disclosure.open = false;
798
+ disclosure.querySelector('summary').focus();
799
+ move([{ turn }]);
800
+ }
801
+ } }, [
802
+ h('input', { key: 'input', type: 'number', name: 'turn', min: '1', required: true,
803
+ placeholder: t('archiveRound'), 'aria-label': t('archiveRound') }),
804
+ h('button', { key: 'go', type: 'submit', className: 'reader-button' }, t('archiveGo')),
805
+ ]),
806
+ ]),
807
+ ]),
808
+ h('div', { key: 'turns', className: 'index-list' }, turns.map(turn =>
809
+ h('button', { key: turn.id, type: 'button', 'aria-current': active?.id === turn.id ? 'true' : undefined,
810
+ title: [round(turn.id), shortTitle(turn)].filter(Boolean).join(' · '), onClick: () => setSelected(turn.id) }, [
811
+ h('span', { key: 'number', className: 'index-number', 'aria-label': round(turn.id) }, turn.id ? String(turn.id).padStart(2, '0') : '…'),
812
+ h('span', { key: 'title' }, shortTitle(turn) || round(turn.id)),
813
+ ]))),
814
+ h('select', { key: 'select', className: 'compact-turns', 'aria-label': t('archiveIndex'), value: active?.id ?? '',
815
+ disabled: !turns.length, onChange: event => setSelected(Number(event.target.value)) },
816
+ turns.map(turn => h('option', { key: turn.id, value: turn.id }, [round(turn.id), shortTitle(turn)].filter(Boolean).join(' · ')))),
817
+ h('nav', { key: 'nav', className: 'index-pages', 'aria-label': t('archiveIndex') }, [
818
+ (locations.length > 1 || locator.turn) ? button('first', 'archiveFirst', () => move([{}])) : null,
819
+ h('span', { key: 'page', role: 'status' }, t('archivePage').replace('{page}', number(locations.length))),
820
+ button('previous', 'archivePrevious', () => move(locations.slice(0, -1)), locations.length === 1, 'back'),
821
+ button('next', 'archiveNext', nextPage, !page?.nextCursor, 'next'),
822
+ ]),
823
+ ]),
824
+ h('section', { key: 'reading', ref: records, className: 'turn-sheet', tabIndex: 0, 'aria-label': t('archiveTitle') }, [
825
+ !current ? h('p', { key: 'loading', role: 'status' }, t('archiveLoading')) : null,
826
+ current?.failed ? h('div', { key: 'failure' }, [h('p', { key: 'error', role: 'status' }, t('traceFailed')),
827
+ button('retry', 'archiveRetry', () => setAttempt(value => value + 1))]) : null,
828
+ page && !turns.length ? h('p', { key: 'empty', role: 'status' }, t(locator.turn ? 'archiveMissingTurn' : 'archiveEmpty')) : null,
829
+ active && h('div', { key: [locator.cursor, locator.turn, active.id].join(':'), className: 'turn-page' }, [
830
+ active.rows[0]?.item?.kind !== 'message' && h('h3', { key: 'heading', className: 'turn-heading' }, turnTitle),
831
+ ...active.rows.map(renderRow),
832
+ active.id === page.continuesTurn && page.nextCursor ? button('continue', 'archiveMore', nextPage) : null,
833
+ ]),
834
+ h('p', { key: 'notice', role: 'status', className: 'reader-note' }, notice),
835
+ ]),
836
+ ]);
837
+ }
838
+
839
+ // The header slot is clipped, so the panel portals to the document body.
840
+ // Trace is read-only reference material: nothing here is sent back to DSH
841
+ // as an event, and no tool is executed.
842
+ function SourceTrace({ sessionId, t }) {
843
+ const [sourceRecord, setSourceRecord] = useState();
844
+ const [showDetails, setShowDetails] = useState(false);
845
+ const [open, setOpen] = useState(false);
846
+ const [error, setError] = useState('');
847
+ const [copied, setCopied] = useState('');
848
+ const modal = useRef(null);
849
+ const trigger = useRef(null);
850
+ useEffect(() => {
851
+ setOpen(false);
852
+ setError('');
853
+ setCopied('');
854
+ if (typeof sessionId !== 'string' || !sessionId) return undefined;
855
+ const controller = new AbortController();
856
+ const url = new URL(`agent-bridge/session-trace?sessionId=${encodeURIComponent(sessionId)}`, document.baseURI);
857
+ fetch(url, { signal: controller.signal, headers: { Accept: 'application/json' } })
858
+ .then(response => response.ok ? response.json() : undefined)
859
+ .then(value => {
860
+ if (controller.signal.aborted) return;
861
+ const readable = Boolean(value?.history) || (Array.isArray(value?.trace) && (value.trace.length || value.sourceStats));
862
+ setSourceRecord(readable ? { sessionId, value } : undefined);
863
+ })
864
+ .catch(() => {});
865
+ return () => controller.abort();
866
+ }, [sessionId]);
867
+ useEffect(() => {
868
+ if (!open) return undefined;
869
+ const element = modal.current;
870
+ if (!element) return undefined;
871
+ element.showModal();
872
+ return () => {
873
+ element.close();
874
+ trigger.current?.focus({ preventScroll: true });
875
+ };
876
+ }, [open]);
877
+ const copy = useCallback(async item => {
878
+ try {
879
+ await navigator.clipboard.writeText(item.text ?? '');
880
+ setCopied(item.id);
881
+ setTimeout(() => setCopied(current => current === item.id ? '' : current), 1600);
882
+ } catch {
883
+ setError('无法写入剪贴板,请手动选择文本。');
884
+ }
885
+ }, []);
886
+ if (!sourceRecord || sourceRecord.sessionId !== sessionId) return null;
887
+ const { trace = [], sourceStats, traceCounts, history } = sourceRecord.value;
888
+
889
+ const turns = new Map();
890
+ for (const item of trace) {
891
+ const items = turns.get(item.turn);
892
+ if (items) items.push(item);
893
+ else turns.set(item.turn, [item]);
894
+ }
895
+ const renderItem = (item, index) => h('article', { key: item.id || `${index}`, className: 'reader-excerpt' }, [
896
+ h('div', { key: 'meta', className: 'reader-excerpt-meta' }, [
897
+ h('span', { key: 'kind', className: 'reader-kind' }, traceKind[item.kind] ?? item.kind),
898
+ item.name ? h('code', { key: 'name', className: 'reader-name' }, item.name) : null,
899
+ item.callId ? h('code', { key: 'call', className: 'reader-name' }, `${t('traceCall')} ${item.callId}`) : null,
900
+ traceState[item.status] ? h('span', { key: 'state', className: 'reader-note' }, traceState[item.status]) : null,
901
+ item.truncated && item.status !== 'truncated' ? h('span', { key: 'cut', className: 'reader-note' }, '已截取') : null,
902
+ item.kind === 'tool_result' && item.text
903
+ ? h('button', {
904
+ key: 'copy', type: 'button', className: 'reader-button',
905
+ onClick: () => copy(item),
906
+ }, copied === item.id ? t('traceCopied') : t('traceCopy'))
907
+ : null,
908
+ ]),
909
+ h('p', { key: 'text', className: 'reader-body' }, item.text || (item.kind === 'tool_result' ? t('traceEmpty') : '')),
910
+ ]);
911
+ let theme = 'white';
912
+ if (open) {
913
+ try { theme = localStorage.getItem('dsh-agent-bridge.theme') || theme; } catch { /* Use the light palette. */ }
914
+ }
915
+ const detailsVisible = showDetails || !history;
916
+ const dialog = open && h('dialog', {
917
+ ref: modal, className: 'bridge-reader bridge-reader-dialog', 'data-theme': theme, 'aria-label': t('traceTitle'),
918
+ onCancel: event => { event.preventDefault(); setOpen(false); },
919
+ onClick: event => {
920
+ if (event.target !== event.currentTarget) return;
921
+ const rect = event.currentTarget.getBoundingClientRect();
922
+ if (event.clientX < rect.left || event.clientX > rect.right || event.clientY < rect.top || event.clientY > rect.bottom) setOpen(false);
923
+ },
924
+ }, [
925
+ h('link', { key: 'css', rel: 'stylesheet', href: new URL('agent-bridge/reader.css', document.baseURI).href }),
926
+ h('header', { key: 'head', className: 'reader-header' }, [
927
+ h('span', { key: 'icon', className: 'reader-emblem' }, readerIcon('book')),
928
+ h('div', { key: 'identity', className: 'record-identity' }, [
929
+ h('h2', { key: 'title' }, t('traceTitle')),
930
+ sourceStats && h('span', { key: 'size' }, t('statsOverview').replace('{turns}', number(sourceStats.userMessages))
931
+ .replace('{messages}', number(sourceStats.userMessages + sourceStats.assistantMessages))),
932
+ history?.complete === false && h('span', { key: 'partial', className: 'record-partial',
933
+ title: t('archivePartial') }, t('archiveUnclear')),
934
+ ]),
935
+ history && h('button', { key: 'details', type: 'button', className: 'record-mode',
936
+ 'aria-expanded': showDetails, 'aria-label': t(showDetails ? 'archiveRead' : 'archiveDetails'),
937
+ onClick: () => setShowDetails(value => !value) }, [
938
+ readerIcon(showDetails ? 'book' : 'settings'), t(showDetails ? 'archiveRead' : 'archiveDetailsShort'),
939
+ ]),
940
+ h('button', { key: 'close', type: 'button', className: 'record-icon', 'aria-label': t('traceClose'),
941
+ title: t('traceClose'), onClick: () => setOpen(false) }, readerIcon('close')),
942
+ ]),
943
+ history && h(SourceArchive, { key: sessionId, sessionId, t, hidden: detailsVisible }),
944
+ h('div', { key: 'content', hidden: !detailsVisible, className: 'reader-content' }, [
945
+ h(SourceStats, { key: 'stats', stats: sourceStats, counts: traceCounts, t }),
946
+ history && h(ArchiveDetails, { key: 'export', history, sessionId, t }),
947
+ error ? h('p', { key: 'error', className: 'reader-alert', role: 'status' }, error) : null,
948
+ trace.length ? h('details', { key: 'excerpts', className: 'reader-extra', open: !history }, [
949
+ h('summary', { key: 'title', className: 'reader-summary' }, t('traceExcerpt')),
950
+ ...Array.from(turns, ([turn, items]) => {
951
+ const title = turn ? t('traceTurn').replace('{turn}', turn) : t('traceUnnumbered');
952
+ const count = items.length === 1 ? t('traceOneItem') : t('traceItemCount').replace('{count}', items.length);
953
+ return h('details', { key: turn ?? 'unnumbered', className: 'reader-process' }, [
954
+ h('summary', { key: 'summary', className: 'reader-summary' }, [
955
+ h('span', { key: 'title' }, title),
956
+ h('small', { key: 'count' }, count),
957
+ ]),
958
+ h('div', { key: 'items', className: 'reader-process-items' }, items.map(renderItem)),
959
+ ]);
960
+ }),
961
+ ]) : null,
962
+ ]),
963
+ ]);
964
+ return [
965
+ h('button', {
966
+ key: 'trigger', ref: trigger, type: 'button', 'aria-haspopup': 'dialog',
967
+ style: { color: 'inherit', font: 'inherit', fontSize: '12px', cursor: 'pointer', padding: '3px 8px',
968
+ background: 'transparent', border: '1px solid color-mix(in srgb, currentColor 22%, transparent)', borderRadius: '5px' },
969
+ title: t('traceTitle'), onClick: () => { setShowDetails(false); setOpen(true); },
970
+ }, t('trace')),
971
+ dialog && typeof document !== 'undefined' ? createPortal(dialog, document.body) : null,
972
+ ];
973
+ }
974
+
975
+ function Panel() {
976
+ const iframe = useRef(null);
977
+ const url = new URL('agent-bridge/panel', document.baseURI).href;
978
+
979
+ useEffect(() => {
980
+ const lifetime = new AbortController();
981
+ async function onMessage(event) {
982
+ const frame = iframe.current;
983
+ if (!frame || event.source !== frame.contentWindow || event.origin !== window.origin) return;
984
+ try {
985
+ if (event.source.location.href !== url) return;
986
+ } catch {
987
+ return;
988
+ }
989
+ const request = event.data;
990
+ if (typeof request?.requestId !== 'string' || !/^[a-zA-Z0-9_-]{1,128}$/.test(request.requestId)) return;
991
+ const reply = (result) => {
992
+ if (iframe.current !== frame) return;
993
+ event.source.postMessage({ type: 'dsh-agent-bridge:result', requestId: request.requestId, ...result },
994
+ event.origin === 'null' ? '*' : event.origin);
995
+ };
996
+
997
+ if (request.type === 'dsh-agent-bridge:sessions' || request.type === 'dsh-agent-bridge:session-export') {
998
+ try {
999
+ const signal = AbortSignal.any([lifetime.signal, AbortSignal.timeout(20_000)]);
1000
+ reply({ ok: true, ...await exportRequest(request, signal) });
1001
+ } catch (error) {
1002
+ reply({ ok: false, error: error instanceof Error ? error.message.slice(0, 500) : '无法导出 DSH 会话。' });
1003
+ }
1004
+ return;
1005
+ }
1006
+ if (request.type === 'dsh-agent-bridge:open-imported') {
1007
+ try {
1008
+ await ctx.sessions.refresh();
1009
+ const snapshot = ctx.sessions.list.getSnapshot();
1010
+ if (!Object.hasOwn(snapshot.byId, request.sessionId)) throw new Error('会话已保存,请从工作区列表打开。');
1011
+ if (iframe.current === frame) ctx.uiWorkspace.openSession(request.sessionId);
1012
+ reply({ ok: true });
1013
+ } catch (error) {
1014
+ reply({ ok: false, error: error instanceof Error ? error.message.slice(0, 500) : '会话已保存,请从工作区列表打开。' });
1015
+ }
1016
+ return;
1017
+ }
1018
+ if (request.type === 'dsh-agent-bridge:quote-history') {
1019
+ try {
1020
+ await quoteHistory(request.sessionId, request.text);
1021
+ if (iframe.current === frame) ctx.uiWorkspace.openSession(request.sessionId);
1022
+ reply({ ok: true });
1023
+ } catch (error) {
1024
+ reply({ ok: false, error: error instanceof Error ? error.message : '无法填入草稿。' });
1025
+ }
1026
+ return;
1027
+ }
1028
+ if (request.type === 'dsh-agent-bridge:pick-history-directory') {
1029
+ try {
1030
+ const path = await ctx.uiWorkspace.pickDirectory();
1031
+ if (path !== null && !validPath(path)) throw new Error('目录格式无效。');
1032
+ reply({ ok: true, path });
1033
+ } catch {
1034
+ reply({ ok: false, error: '无法打开目录选择器,请输入本机绝对路径。' });
1035
+ }
1036
+ return;
1037
+ }
1038
+ if (request.type === 'dsh-agent-bridge:recover-draft') {
1039
+ const partial = recentImports.get(request.requestId);
1040
+ if (importing || !partial || partial.ready || partial.sessionId !== request.sessionId) {
1041
+ reply({ ok: false, error: '无法定位这条交接会话,请回到工作区检查。' });
1042
+ return;
1043
+ }
1044
+ try {
1045
+ ctx.uiWorkspace.openSession(partial.sessionId);
1046
+ reply({ ok: true });
1047
+ } catch {
1048
+ reply({ ok: false, error: '暂时无法打开这条会话,请在工作区列表中重试。' });
1049
+ }
1050
+ return;
1051
+ }
1052
+ if (request.type === 'dsh-agent-bridge:open-path') {
1053
+ const { projectId, directory, assetId, referenceId, bridgeNonce } = request;
1054
+ if (!/^[a-f0-9]{24}$/.test(projectId) || !/^[a-f0-9]{64}$/.test(bridgeNonce)
1055
+ || (directory !== true && !/^[a-f0-9]{24}$/.test(assetId) && !/^[a-f0-9-]{36}$/.test(referenceId))) {
1056
+ reply({ ok: false, error: '文件引用格式无效。' });
1057
+ return;
1058
+ }
1059
+ try {
1060
+ const session = ctx.remote.session;
1061
+ if (typeof session.openWorkspacePath !== 'function') {
1062
+ reply({ ok: false, error: '当前 DSH 不支持打开本机文件,可复制路径。' });
1063
+ return;
1064
+ }
1065
+ if (typeof session.canOpenWorkspacePath === 'function') {
1066
+ const availability = await session.canOpenWorkspacePath();
1067
+ if (!availability?.ok) {
1068
+ reply({ ok: false, error: '无法确认本机文件打开能力,可复制路径。' });
1069
+ return;
1070
+ }
1071
+ if (availability.value !== true) {
1072
+ reply({ ok: false, error: '当前 DSH 不支持打开本机文件,可复制路径。' });
1073
+ return;
1074
+ }
1075
+ }
1076
+ const signal = AbortSignal.any([lifetime.signal, AbortSignal.timeout(20_000)]);
1077
+ const resolve = async () => {
1078
+ const response = await fetch(new URL('api', url), {
1079
+ method: 'POST', signal,
1080
+ headers: { 'Content-Type': 'application/json', 'X-DSH-Agent-Bridge': bridgeNonce },
1081
+ body: JSON.stringify({ action: 'resolve-open-path', projectId, directory, assetId, referenceId }),
1082
+ });
1083
+ const target = await response.json();
1084
+ if (!response.ok || !validPath(target.path)) throw new Error(target.error || '无法核对文件路径。');
1085
+ return target;
1086
+ };
1087
+ const target = await resolve();
1088
+ const opened = await session.openWorkspacePath({ path: target.path,
1089
+ ...(target.revealOnly ? { action: 'reveal' } : {}),
1090
+ }, signal);
1091
+ if (opened?.ok) {
1092
+ reply({ ok: true, revealed: target.revealOnly === true });
1093
+ return;
1094
+ }
1095
+ // A viewer may be unavailable for an extension while the file
1096
+ // manager is not; revealing still gives the user the file.
1097
+ const revealed = !target.revealOnly
1098
+ && await session.openWorkspacePath({ path: (await resolve()).path, action: 'reveal' }, signal);
1099
+ reply(revealed?.ok
1100
+ ? { ok: true, revealed: true }
1101
+ : { ok: false, error: 'DSH 未能打开这个文件,可复制路径后在资源管理器中查看。' });
1102
+ } catch (error) {
1103
+ reply({ ok: false, error: error instanceof Error
1104
+ ? error.message.slice(0, 500) : 'DSH 未能打开这个文件,可复制路径。' });
1105
+ }
1106
+ return;
1107
+ }
1108
+ if (request.type !== 'dsh-agent-bridge:open') return;
1109
+ if (!validPath(request.path) || typeof request.prompt !== 'string'
1110
+ || !request.prompt.trim() || request.prompt.length > 65_536) {
1111
+ reply({ ok: false, error: '项目目录或交接草稿格式无效。' });
1112
+ return;
1113
+ }
1114
+ if (importing) {
1115
+ reply({ ok: false, error: '另一个项目正在导入。' });
1116
+ return;
1117
+ }
1118
+ importing = true;
1119
+ try {
1120
+ const sessionId = await prepareSession(request, (id) => {
1121
+ if (iframe.current !== frame) return;
1122
+ ctx.uiWorkspace.openSession(id);
1123
+ if (typeof request.bridgeNonce === 'string' && /^[a-f0-9]{64}$/.test(request.bridgeNonce)) {
1124
+ // The native workspace may replace the panel before it receives the reply.
1125
+ void fetch(new URL('api', url), {
1126
+ method: 'POST', keepalive: true,
1127
+ headers: { 'Content-Type': 'application/json', 'X-DSH-Agent-Bridge': request.bridgeNonce },
1128
+ body: JSON.stringify({ action: 'record-project-continuation', ticket: request.requestId }),
1129
+ }).catch(() => {});
1130
+ }
1131
+ });
1132
+ reply({ ok: true, sessionId });
1133
+ } catch (error) {
1134
+ const partial = recentImports.get(request.requestId);
1135
+ reply({
1136
+ ok: false,
1137
+ recoverySessionId: partial?.ready === false ? partial.sessionId : undefined,
1138
+ error: error instanceof Error ? error.message.slice(0, 500) : 'DSH 无法打开交接会话。',
1139
+ });
1140
+ } finally {
1141
+ importing = false;
1142
+ }
1143
+ }
1144
+
1145
+ window.addEventListener('message', onMessage);
1146
+ return () => {
1147
+ lifetime.abort();
1148
+ window.removeEventListener('message', onMessage);
1149
+ };
1150
+ }, [url]);
1151
+
1152
+ return h('iframe', {
1153
+ ref: iframe,
1154
+ src: url,
1155
+ title: t('title'),
1156
+ referrerPolicy: 'no-referrer',
1157
+ style: { display: 'block', width: '100%', height: '100%', border: 0 },
1158
+ });
1159
+ }
1160
+
1161
+ ctx.slots.inject('main', () => ctx.slots.register({
1162
+ name: 'main', key: panelId, locale: panelId,
1163
+ }, Panel));
1164
+ ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
1165
+ name: 'sidebar.panellist', id: panelId, order: 20, label: () => t('title'), locale: panelId,
1166
+ }, PanelIcon));
1167
+ ctx.slots.inject('conversation.session.header.actions', () => ctx.slots.register({
1168
+ name: 'conversation.session.header.actions', id: 'agent-bridge-trace', order: 30, locale: panelId,
1169
+ }, SourceTrace));
1170
+ ctx.effect(() => ctx.uiConversation?.events.register(inlineProcessDefinition), 'agent bridge process projection');
1171
+ ctx.effect(() => {
1172
+ if (!document.head) return;
1173
+ const css = document.createElement('link');
1174
+ css.rel = 'stylesheet';
1175
+ css.href = new URL('agent-bridge/inline-process.css', document.baseURI).href;
1176
+ document.head.append(css);
1177
+ return () => css.remove();
1178
+ }, 'agent bridge process stylesheet');
1179
+ ctx.slots.inject('conversation.chat.node', () => ctx.slots.register({
1180
+ name: 'conversation.chat.node', key: inlineProcessNode, locale: panelId,
1181
+ }, InlineProcessNode));
1182
+ ctx.slots.inject('conversation.chat.turnTail', () => ctx.slots.register({
1183
+ name: 'conversation.chat.turnTail', id: 'agent-bridge-inline-process', order: 30, locale: panelId,
1184
+ }, InlineProcessTail));
1185
+ }
1186
+
1187
+ return { apply, inject: ['slots', 'locale', 'uiWorkspace', 'workspaces', 'sessions', 'conversation', 'uiConversation', 'remote', 'remote.session'] };
1188
+ },
1189
+ });