@wwwfz/dsh-agent-bridge 0.8.3 → 0.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (40) hide show
  1. package/README.md +198 -194
  2. package/THIRD_PARTY_NOTICES.md +67 -0
  3. package/cordis.patch.yml +4 -4
  4. package/package.json +40 -40
  5. package/src/assets.js +405 -348
  6. package/src/catalog.js +906 -605
  7. package/src/client.js +623 -310
  8. package/src/config.js +88 -88
  9. package/src/export.js +241 -12
  10. package/src/index.js +160 -136
  11. package/src/project-archive.js +145 -145
  12. package/src/projects.js +1189 -980
  13. package/src/session-import.js +107 -93
  14. package/src/session-trace.js +121 -0
  15. package/src/skill-handoff.js +1327 -0
  16. package/src/skill-package.js +417 -0
  17. package/src/skill-provider.js +249 -0
  18. package/src/watch.js +309 -309
  19. package/web/Geist-OFL.txt +93 -93
  20. package/web/agent-icons/NOTICE.md +19 -19
  21. package/web/agent-icons/antigravity.svg +76 -76
  22. package/web/agent-icons/claude.svg +3 -3
  23. package/web/agent-icons/dsh.svg +58 -58
  24. package/web/agent-icons/licenses/copilot.txt +21 -21
  25. package/web/agent-icons/licenses/dsh.txt +21 -21
  26. package/web/agent-icons/licenses/gemini.txt +201 -201
  27. package/web/agent-icons/licenses/opencode.txt +21 -21
  28. package/web/agent-icons/licenses/qoder-notice.txt +18 -18
  29. package/web/agent-icons/licenses/qoder.txt +22 -22
  30. package/web/agent-icons/licenses/qwen.txt +202 -202
  31. package/web/agent-icons/qoder.svg +4 -4
  32. package/web/agent-icons/qwen.svg +5 -5
  33. package/web/agent-icons/workbuddy.svg +29 -29
  34. package/web/markdown.js +225 -0
  35. package/web/panel.css +607 -502
  36. package/web/panel.html +277 -246
  37. package/web/panel.js +2334 -1559
  38. package/web/project-context.js +25 -25
  39. package/web/vendor/markdown-it-LICENSE.txt +156 -0
  40. package/web/vendor/markdown-it.mjs +3064 -0
package/src/client.js CHANGED
@@ -1,310 +1,623 @@
1
- window.__ModuleLoader__.load({
2
- id: '@wwwfz/dsh-agent-bridge',
3
- factory: (require) => {
4
- const { createElement: h, useEffect, useRef } = require('react');
5
- const panelId = 'dsh-agent-bridge';
6
- const messages = {
7
- zh: { title: 'Agent 工作接续' },
8
- en: { title: 'Agent Workspace Handoff' },
9
- };
10
-
11
- function validPath(value) {
12
- return typeof value === 'string' && value.length > 0 && value.length <= 4096
13
- && !/[\u0000-\u001f]/u.test(value);
14
- }
15
-
16
- function pathKey(path) {
17
- if (/^[a-z]:[\\/]|^\\\\|^\/\//i.test(path)) {
18
- return path.replace(/\//g, '\\').replace(/^\\\\\?\\UNC\\/i, '\\\\')
19
- .replace(/^\\\\\?\\/, '').replace(/\\+$/, '').toLowerCase();
20
- }
21
- return path.replace(/\/+$/, '');
22
- }
23
-
24
- function sessionRow(summary) {
25
- if (!summary || summary.blank || summary.origin === 'subagent' || !validPath(summary.cwd)) return;
26
- return {
27
- id: summary.id,
28
- title: (summary.title || summary.displayTitle || '未命名会话').slice(0, 240),
29
- path: summary.cwd,
30
- updatedAt: summary.updatedAt,
31
- };
32
- }
33
-
34
- function dialogueFrom(event) {
35
- if (event?.surfaceOp !== 'append') return;
36
- let content;
37
- let role;
38
- if (event.type === 'user/message' && event.data?.source?.kind === 'user') {
39
- role = 'user';
40
- content = event.data.content;
41
- } else if (event.type === 'assistant/message') {
42
- role = 'assistant';
43
- content = event.data?.message?.content;
44
- }
45
- if (!Array.isArray(content)) return;
46
- const text = content.filter(block => block?.type === 'text' && typeof block.text === 'string')
47
- .map(block => block.text).join('\n\n');
48
- return text.trim() ? { role, text } : undefined;
49
- }
50
-
51
- async function sessionDialogue(remote, sessionId, signal) {
52
- const collected = [];
53
- const address = { kind: 'session', sessionId };
54
- let remaining = 28_000;
55
- let throughSeq;
56
- let beforeSeq;
57
- let hasMore = true;
58
- let truncated = false;
59
- for (let page = 0; page < 8 && hasMore && !truncated; page++) {
60
- const result = await remote.events({ address, maxMessages: 40,
61
- ...(throughSeq === undefined ? {} : { throughSeq, beforeSeq }),
62
- }, signal);
63
- if (!result.ok) throw new Error('无法读取这条 DSH 会话的历史。');
64
- const { records, cursor } = result.value;
65
- hasMore = result.value.hasMore;
66
- throughSeq ??= cursor;
67
- for (let i = records.length - 1; i >= 0; i--) {
68
- const message = dialogueFrom(records[i].event);
69
- if (!message) continue;
70
- if (collected.length >= 24 || message.text.length > remaining) {
71
- if (!collected.length) collected.push({ ...message,
72
- text: message.text.slice(0, remaining).replace(/[\uD800-\uDBFF]$/, ''),
73
- });
74
- truncated = true;
75
- break;
76
- }
77
- collected.push(message);
78
- remaining -= message.text.length;
79
- }
80
- const firstSeq = records[0]?.event?.seq;
81
- if (hasMore && (!Number.isSafeInteger(firstSeq) || firstSeq <= 0 || firstSeq >= (beforeSeq ?? Infinity))) break;
82
- beforeSeq = firstSeq;
83
- }
84
- return { messages: collected.reverse(), truncated: truncated || hasMore };
85
- }
86
-
87
- function PanelIcon({ size = 16 }) {
88
- return h('svg', {
89
- width: size, height: size, viewBox: '0 0 24 24', fill: 'none',
90
- stroke: 'currentColor', strokeWidth: 1.7, strokeLinecap: 'round', strokeLinejoin: 'round',
91
- 'aria-hidden': true,
92
- }, 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' }));
93
- }
94
-
95
- function apply(ctx) {
96
- ctx.effect(() => ctx.locale.register(panelId, messages), 'agent bridge locale');
97
- const t = ctx.locale.bind(panelId);
98
- const recentImports = new Map();
99
- const incompleteDrafts = new Map();
100
- let importing = false;
101
-
102
- async function exportRequest(request, signal) {
103
- if (request.path !== undefined && !validPath(request.path)) throw new Error('工作目录格式无效。');
104
- const scope = request.path === undefined ? undefined : pathKey(request.path);
105
- const snapshot = ctx.sessions.list.getSnapshot();
106
- if (snapshot.phase !== 'ready') throw new Error('DSH 会话列表正在加载,请稍后重试。');
107
- const rows = snapshot.ids.map(id => sessionRow(snapshot.byId[id]))
108
- .filter(row => row && (scope === undefined || pathKey(row.path) === scope));
109
- if (request.type === 'dsh-agent-bridge:sessions') return { sessions: rows };
110
-
111
- const selected = rows.find(row => row.id === request.sessionId);
112
- if (!selected) throw new Error('未在这个工作区找到可导出的 DSH 会话。');
113
- const dialogue = await sessionDialogue(ctx.remote.session, selected.id, signal);
114
- if (!dialogue.messages.length) throw new Error('这条 DSH 会话暂无可导出的文字。');
115
- return { conversation: { title: selected.title, path: selected.path, ...dialogue } };
116
- }
117
-
118
- function rememberImport(requestId, imported) {
119
- if (!recentImports.has(requestId) && recentImports.size >= 32) {
120
- recentImports.delete(recentImports.keys().next().value);
121
- }
122
- recentImports.set(requestId, imported);
123
- }
124
-
125
- async function rollbackDraft(imported, binding) {
126
- try {
127
- const session = binding?.session;
128
- const state = session?.getSnapshot();
129
- const input = binding && ctx.conversation.input.for(binding.ctx).snapshot;
130
- // A preserved draft, attachments, or a chat already in use belong to
131
- // the user. Archive only an unused, empty chat created by this handoff.
132
- if (state && (!state.blank || state.running || state.promptAttempted || state.removed)) return false;
133
- if (binding && (!input || input.draft !== '' || input.attachmentIds?.length
134
- || ['adjudicating', 'submitting', 'sending'].includes(input.phase))) return false;
135
- await ctx.workspaces.archiveSession(imported.sessionId);
136
- incompleteDrafts.delete(imported.path);
137
- for (const [key, item] of recentImports) if (item === imported) recentImports.delete(key);
138
- return true;
139
- } catch {
140
- return false;
141
- }
142
- }
143
-
144
- async function prepareSession(request, reveal) {
145
- const path = pathKey(request.path);
146
- let imported = recentImports.get(request.requestId) ?? incompleteDrafts.get(path);
147
- if (imported && imported.path !== path) throw new Error('交接工作目录已变化,请重新预览。');
148
- if (!imported) {
149
- const workspace = await ctx.workspaces.create({ path: request.path });
150
- const sessionId = await ctx.sessions.create({ workspaceId: workspace.workspaceId });
151
- imported = { sessionId, path, ready: false };
152
- incompleteDrafts.set(path, imported);
153
- }
154
- rememberImport(request.requestId, imported);
155
-
156
- let reference;
157
- try {
158
- if (!imported.ready) {
159
- let binding;
160
- let outcome;
161
- try {
162
- reference = ctx.sessions.retain(imported.sessionId, { source: panelId });
163
- binding = reference.binding;
164
- await reference.ready;
165
- outcome = ctx.conversation.input.requestDraftInitialization(binding, {
166
- prompt: request.prompt,
167
- whenDraftExists: 'keep',
168
- });
169
- } catch {
170
- // A Host error can also leave an empty session to roll back.
171
- }
172
- if (outcome !== 'applied') {
173
- if (outcome !== 'preserved' && await rollbackDraft(imported, binding)) {
174
- throw new Error('DSH 未能填入交接草稿。空白会话已归档,可重试。');
175
- }
176
- throw new Error(outcome === 'preserved'
177
- ? '会话中已有草稿,已原样保留。可打开会话并手动补入交接资料。'
178
- : 'DSH 未能填入交接草稿。可重试同一会话,或打开后手动补入交接资料。');
179
- }
180
- imported.ready = true;
181
- incompleteDrafts.delete(path);
182
- }
183
- reveal(imported.sessionId);
184
- return imported.sessionId;
185
- } finally {
186
- reference?.release();
187
- }
188
- }
189
-
190
- function Panel() {
191
- const iframe = useRef(null);
192
- const url = new URL('agent-bridge/panel', document.baseURI).href;
193
-
194
- useEffect(() => {
195
- const lifetime = new AbortController();
196
- async function onMessage(event) {
197
- const frame = iframe.current;
198
- if (!frame || event.source !== frame.contentWindow || event.origin !== window.origin) return;
199
- try {
200
- if (event.source.location.href !== url) return;
201
- } catch {
202
- return;
203
- }
204
- const request = event.data;
205
- if (typeof request?.requestId !== 'string' || !/^[a-zA-Z0-9_-]{1,128}$/.test(request.requestId)) return;
206
- const reply = (result) => {
207
- if (iframe.current !== frame) return;
208
- event.source.postMessage({ type: 'dsh-agent-bridge:result', requestId: request.requestId, ...result },
209
- event.origin === 'null' ? '*' : event.origin);
210
- };
211
-
212
- if (request.type === 'dsh-agent-bridge:sessions' || request.type === 'dsh-agent-bridge:session-export') {
213
- try {
214
- const signal = AbortSignal.any([lifetime.signal, AbortSignal.timeout(20_000)]);
215
- reply({ ok: true, ...await exportRequest(request, signal) });
216
- } catch (error) {
217
- reply({ ok: false, error: error instanceof Error ? error.message.slice(0, 500) : '无法导出 DSH 会话。' });
218
- }
219
- return;
220
- }
221
- if (request.type === 'dsh-agent-bridge:open-imported') {
222
- try {
223
- await ctx.sessions.refresh();
224
- const snapshot = ctx.sessions.list.getSnapshot();
225
- if (!Object.hasOwn(snapshot.byId, request.sessionId)) throw new Error('会话已保存,请从工作区列表打开。');
226
- if (iframe.current === frame) ctx.uiWorkspace.openSession(request.sessionId);
227
- reply({ ok: true });
228
- } catch (error) {
229
- reply({ ok: false, error: error instanceof Error ? error.message.slice(0, 500) : '会话已保存,请从工作区列表打开。' });
230
- }
231
- return;
232
- }
233
- if (request.type === 'dsh-agent-bridge:recover-draft') {
234
- const partial = recentImports.get(request.requestId);
235
- if (importing || !partial || partial.ready || partial.sessionId !== request.sessionId) {
236
- reply({ ok: false, error: '无法定位这条交接会话,请回到工作区检查。' });
237
- return;
238
- }
239
- try {
240
- ctx.uiWorkspace.openSession(partial.sessionId);
241
- reply({ ok: true });
242
- } catch {
243
- reply({ ok: false, error: '暂时无法打开这条会话,请在工作区列表中重试。' });
244
- }
245
- return;
246
- }
247
- if (request.type !== 'dsh-agent-bridge:open') return;
248
- if (!validPath(request.path) || typeof request.prompt !== 'string'
249
- || !request.prompt.trim() || request.prompt.length > 65_536) {
250
- reply({ ok: false, error: '项目目录或交接草稿格式无效。' });
251
- return;
252
- }
253
- if (importing) {
254
- reply({ ok: false, error: '另一个项目正在导入。' });
255
- return;
256
- }
257
- importing = true;
258
- try {
259
- const sessionId = await prepareSession(request, (id) => {
260
- if (iframe.current !== frame) return;
261
- ctx.uiWorkspace.openSession(id);
262
- if (typeof request.bridgeNonce === 'string' && /^[a-f0-9]{64}$/.test(request.bridgeNonce)) {
263
- // The native workspace may replace the panel before it receives the reply.
264
- void fetch(new URL('api', url), {
265
- method: 'POST', keepalive: true,
266
- headers: { 'Content-Type': 'application/json', 'X-DSH-Agent-Bridge': request.bridgeNonce },
267
- body: JSON.stringify({ action: 'record-project-continuation', ticket: request.requestId }),
268
- }).catch(() => {});
269
- }
270
- });
271
- reply({ ok: true, sessionId });
272
- } catch (error) {
273
- const partial = recentImports.get(request.requestId);
274
- reply({
275
- ok: false,
276
- recoverySessionId: partial?.ready === false ? partial.sessionId : undefined,
277
- error: error instanceof Error ? error.message.slice(0, 500) : 'DSH 无法打开交接会话。',
278
- });
279
- } finally {
280
- importing = false;
281
- }
282
- }
283
-
284
- window.addEventListener('message', onMessage);
285
- return () => {
286
- lifetime.abort();
287
- window.removeEventListener('message', onMessage);
288
- };
289
- }, [url]);
290
-
291
- return h('iframe', {
292
- ref: iframe,
293
- src: url,
294
- title: t('title'),
295
- referrerPolicy: 'no-referrer',
296
- style: { display: 'block', width: '100%', height: '100%', border: 0 },
297
- });
298
- }
299
-
300
- ctx.slots.inject('main', () => ctx.slots.register({
301
- name: 'main', key: panelId, locale: panelId,
302
- }, Panel));
303
- ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
304
- name: 'sidebar.panellist', id: panelId, order: 20, label: () => t('title'), locale: panelId,
305
- }, PanelIcon));
306
- }
307
-
308
- return { apply, inject: ['slots', 'locale', 'uiWorkspace', 'workspaces', 'sessions', 'conversation', 'remote', 'remote.session'] };
309
- },
310
- });
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
+ });