@wwwfz/dsh-agent-bridge 0.8.2 → 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.
- package/README.md +105 -91
- package/THIRD_PARTY_NOTICES.md +67 -0
- package/package.json +2 -2
- package/src/assets.js +70 -13
- package/src/catalog.js +328 -27
- package/src/client.js +317 -4
- package/src/export.js +238 -9
- package/src/index.js +24 -0
- package/src/projects.js +232 -23
- package/src/session-import.js +14 -0
- package/src/session-trace.js +121 -0
- package/src/skill-handoff.js +1327 -0
- package/src/skill-package.js +417 -0
- package/src/skill-provider.js +249 -0
- package/web/markdown.js +225 -0
- package/web/panel.css +111 -6
- package/web/panel.html +32 -1
- package/web/panel.js +819 -44
- package/web/vendor/markdown-it-LICENSE.txt +156 -0
- package/web/vendor/markdown-it.mjs +3064 -0
package/src/client.js
CHANGED
|
@@ -1,11 +1,70 @@
|
|
|
1
1
|
window.__ModuleLoader__.load({
|
|
2
|
-
id: 'dsh-agent-bridge',
|
|
2
|
+
id: '@wwwfz/dsh-agent-bridge',
|
|
3
3
|
factory: (require) => {
|
|
4
|
-
const { createElement: h, useEffect, useRef } = require('react');
|
|
4
|
+
const { createElement: h, useCallback, useEffect, useRef, useState } = require('react');
|
|
5
|
+
const { createPortal } = require('react-dom');
|
|
5
6
|
const panelId = 'dsh-agent-bridge';
|
|
6
7
|
const messages = {
|
|
7
|
-
zh: {
|
|
8
|
-
|
|
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
|
+
},
|
|
9
68
|
};
|
|
10
69
|
|
|
11
70
|
function validPath(value) {
|
|
@@ -187,6 +246,201 @@ window.__ModuleLoader__.load({
|
|
|
187
246
|
}
|
|
188
247
|
}
|
|
189
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
|
+
|
|
190
444
|
function Panel() {
|
|
191
445
|
const iframe = useRef(null);
|
|
192
446
|
const url = new URL('agent-bridge/panel', document.baseURI).href;
|
|
@@ -244,6 +498,62 @@ window.__ModuleLoader__.load({
|
|
|
244
498
|
}
|
|
245
499
|
return;
|
|
246
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
|
+
}
|
|
247
557
|
if (request.type !== 'dsh-agent-bridge:open') return;
|
|
248
558
|
if (!validPath(request.path) || typeof request.prompt !== 'string'
|
|
249
559
|
|| !request.prompt.trim() || request.prompt.length > 65_536) {
|
|
@@ -303,6 +613,9 @@ window.__ModuleLoader__.load({
|
|
|
303
613
|
ctx.slots.inject('sidebar.panellist', () => ctx.slots.register({
|
|
304
614
|
name: 'sidebar.panellist', id: panelId, order: 20, label: () => t('title'), locale: panelId,
|
|
305
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));
|
|
306
619
|
}
|
|
307
620
|
|
|
308
621
|
return { apply, inject: ['slots', 'locale', 'uiWorkspace', 'workspaces', 'sessions', 'conversation', 'remote', 'remote.session'] };
|
package/src/export.js
CHANGED
|
@@ -1,12 +1,241 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
1
|
+
import path from 'node:path'
|
|
2
|
+
import { pathToFileURL } from 'node:url'
|
|
3
|
+
import { isMarkdownFile, markdownExportSpans, parseMarkdown } from '../web/markdown.js'
|
|
4
|
+
|
|
5
|
+
const control = /[\u0000-\u001f\u007f]+/g
|
|
6
|
+
|
|
7
|
+
function clean(value, limit = 240) {
|
|
8
|
+
return String(value ?? '').replace(control, ' ').trim().slice(0, limit)
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
function shortName(file) {
|
|
12
|
+
return clean(String(file).replace(/[\\/]+$/, '').replace(/^.*[\\/]/, ''), 160)
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function linkLabel(value) {
|
|
16
|
+
return String(value ?? '').replace(/[\\[\]]/g, character => `\\${character}`)
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function fileLink(label, target) {
|
|
20
|
+
return `[${linkLabel(label)}](<${target}>)`
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
function directoryUrl(directory) {
|
|
24
|
+
const href = pathToFileURL(directory).href
|
|
25
|
+
return href.endsWith('/') ? href : `${href}/`
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function relativeUrl(fromFile, target) {
|
|
29
|
+
const relative = path.relative(path.dirname(fromFile), target)
|
|
30
|
+
if (!relative || path.isAbsolute(relative)) return ''
|
|
31
|
+
return relative.split(path.sep).map(segment => encodeURIComponent(segment)).join('/')
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function projectRelative(root, target) {
|
|
35
|
+
if (!path.isAbsolute(root) || !target || !path.isAbsolute(target)) return ''
|
|
36
|
+
const relative = path.relative(root, target)
|
|
37
|
+
if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) return ''
|
|
38
|
+
return relative.split(path.sep).join('/')
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function codeSpan(value) {
|
|
42
|
+
const delimiter = '`'.repeat(1 + Math.max(0, ...(value.match(/`+/g) ?? []).map(run => run.length)))
|
|
43
|
+
const padding = /^[ `]|[ `]$/.test(value) ? ' ' : ''
|
|
44
|
+
return `${delimiter}${padding}${value}${padding}${delimiter}`
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function linkDestination(href, title) {
|
|
48
|
+
const target = href.replace(/&/g, '&').replace(/</g, '%3C').replace(/>/g, '%3E')
|
|
49
|
+
// Keep a reference title in the same table cell and on the same source line.
|
|
50
|
+
const tooltip = title ? ` "${title.replace(/[&"\\|\n\r]/g, char => `&#${char.charCodeAt(0)};`)}"` : ''
|
|
51
|
+
return `(<${target}>${tooltip})`
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function handoffBody(item, cwd, mode, savePath) {
|
|
55
|
+
if (!isMarkdownFile(item.file)) return item.text
|
|
56
|
+
const references = new Map((item.references ?? []).map(reference => [reference.href, reference]))
|
|
57
|
+
const { links, definitions } = markdownExportSpans(item.text)
|
|
58
|
+
// Materialize references before merging sections. A definition left in the
|
|
59
|
+
// combined document could bind an unresolved label in another source.
|
|
60
|
+
const edits = definitions.map(range => ({ ...range, text: '' }))
|
|
61
|
+
let droppedThrough = 0
|
|
62
|
+
for (const { href, start, labelEnd, end, relative, title } of links) {
|
|
63
|
+
if (start < droppedThrough) continue
|
|
64
|
+
let target = href
|
|
65
|
+
if (relative) {
|
|
66
|
+
const reference = references.get(href)
|
|
67
|
+
const verified = reference?.verifiedFile
|
|
68
|
+
target = ''
|
|
69
|
+
if (projectRelative(cwd, verified)) {
|
|
70
|
+
if (mode === 'local') target = pathToFileURL(verified).href.replace(/&/g, '%26')
|
|
71
|
+
else if (savePath) target = relativeUrl(savePath, verified)
|
|
72
|
+
}
|
|
73
|
+
if (!target) {
|
|
74
|
+
const caption = escapeProse(item.text.slice(start + 1, labelEnd - 1)).replace(/(?<!\\)[\[\]]/g, '\\$&')
|
|
75
|
+
const label = projectRelative(cwd, reference?.path)
|
|
76
|
+
edits.push({ start, end, text: label ? `${caption}(${codeSpan(label)})` : caption })
|
|
77
|
+
droppedThrough = end
|
|
78
|
+
continue
|
|
79
|
+
}
|
|
80
|
+
target += href.match(/#[^\s<>]*$/)?.[0] ?? ''
|
|
81
|
+
}
|
|
82
|
+
edits.push({ start: labelEnd, end, text: linkDestination(target, title) })
|
|
83
|
+
}
|
|
84
|
+
let rewritten = ''
|
|
85
|
+
let offset = 0
|
|
86
|
+
for (const { start, end, text } of edits.sort((a, b) => a.start - b.start)) {
|
|
87
|
+
rewritten += item.text.slice(offset, start) + text
|
|
88
|
+
offset = end
|
|
89
|
+
}
|
|
90
|
+
return rewritten + item.text.slice(offset)
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Keep plain user text and source excerpts from changing the document structure.
|
|
94
|
+
function escapeProse(text) {
|
|
95
|
+
return String(text ?? '').split('\n').map(line => {
|
|
96
|
+
if (/^ {0,3}(?:#{1,6}(?:[ \t]|$)|(?:-{3,}|={3,}|\*{3,}|_{3,})[ \t]*$|`{3,}|~{3,})/.test(line)) {
|
|
97
|
+
return line.replace(/^( {0,3})/, '$1\\')
|
|
98
|
+
}
|
|
99
|
+
return line
|
|
100
|
+
}).join('\n')
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
function stamp(date) {
|
|
104
|
+
return date.toISOString().slice(0, 19) + 'Z'
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// Body sections are quoted source material, so their Markdown stays intact.
|
|
108
|
+
// An unbalanced fence would swallow the rest of the document, so it is closed
|
|
109
|
+
// at the end of its own section instead.
|
|
110
|
+
function fenceSafe(text) {
|
|
111
|
+
const fence = parseMarkdown(text).at(-1)
|
|
112
|
+
if (fence?.type !== 'fence') return text
|
|
113
|
+
const lines = text.split(/\r\n|\n|\r/)
|
|
114
|
+
const [start, end] = fence.map
|
|
115
|
+
const closing = new RegExp(`^ {0,3}${fence.markup[0]}{${fence.markup.length},}[ \\t]*$`)
|
|
116
|
+
if (end > start + 1 && closing.test(lines[end - 1])) return text
|
|
117
|
+
const eol = text.match(/\r\n|\n|\r/)?.[0] ?? '\n'
|
|
118
|
+
return `${text}${/\r$|\n$/.test(text) ? '' : eol}${fence.markup}`
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function fileStamp(date) {
|
|
122
|
+
return date.toISOString().slice(0, 19).replace(/[-:]/g, '') + 'Z'
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
function filenameOf(heading, date) {
|
|
3
126
|
const name = heading.replace(/[^\p{L}\p{N}._-]+/gu, '-').replace(/^[.-]+|[.-]+$/g, '')
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
127
|
+
return `handoff-${Array.from(name).slice(0, 48).join('') || 'project'}-${fileStamp(date)}.md`
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function sourceValue(file, { format, savePath }) {
|
|
131
|
+
if (format === 'share') {
|
|
132
|
+
const relative = savePath ? relativeUrl(savePath, file) : ''
|
|
133
|
+
return relative ? fileLink(shortName(file), relative) : `\`${shortName(file)}\``
|
|
134
|
+
}
|
|
135
|
+
return fileLink(shortName(file), pathToFileURL(file).href)
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function conversationHeading(label) {
|
|
139
|
+
return clean(String(label ?? '').replace(/^近期会话\s*·\s*/, '')) || '消息'
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const traceKinds = { summary: '思考摘要', tool_call: '工具调用', tool_result: '工具结果' }
|
|
143
|
+
const traceStates = {
|
|
144
|
+
ok: '已完成', error: '失败', missing: '未记录结果', pending: '未完成', truncated: '已截取',
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
function traceLines(trace) {
|
|
148
|
+
if (!Array.isArray(trace) || !trace.length) return []
|
|
149
|
+
const lines = ['## 来源记录', '', '> 从旧 Agent 的会话记录中读取,只供查阅,不会重放任何工具调用。', '']
|
|
150
|
+
let turn
|
|
151
|
+
for (const item of trace.slice(0, 200)) {
|
|
152
|
+
if (item.turn && item.turn !== turn) {
|
|
153
|
+
turn = item.turn
|
|
154
|
+
lines.push('', `### 第 ${turn} 轮`, '')
|
|
155
|
+
}
|
|
156
|
+
const kind = traceKinds[item?.kind] ?? '记录'
|
|
157
|
+
const name = clean(item?.name, 120)
|
|
158
|
+
const state = traceStates[item?.status] ?? ''
|
|
159
|
+
const excerpt = item?.kind === 'tool_call' ? '' : clean(item?.text, 400)
|
|
160
|
+
if (item?.kind === 'summary') {
|
|
161
|
+
lines.push(`- ${[kind, excerpt].filter(Boolean).join(' · ')}`)
|
|
162
|
+
continue
|
|
163
|
+
}
|
|
164
|
+
const callId = clean(item.callId, 200).replace(/`/g, '')
|
|
165
|
+
lines.push(`- ${[kind, name && `\`${name.replace(/`/g, '')}\``, callId && `调用 \`${callId}\``, state,
|
|
166
|
+
item.truncated && item.status !== 'truncated' && '已截取'].filter(Boolean).join(' · ')}`)
|
|
167
|
+
if (excerpt) lines.push(` - ${escapeProse(excerpt).replace(/\n/g, '\n ')}`)
|
|
168
|
+
}
|
|
169
|
+
lines.push('')
|
|
170
|
+
return lines
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
export function makeExport({
|
|
174
|
+
title, origin, date = new Date(), preview = {}, prompt, truncated: legacyTruncated = false,
|
|
175
|
+
format = 'local', savePath, includeTrace = false,
|
|
176
|
+
} = {}) {
|
|
177
|
+
const heading = clean(title) || '项目交接'
|
|
178
|
+
const session = origin === 'DSH 会话'
|
|
179
|
+
const mode = format === 'share' ? 'share' : 'local'
|
|
180
|
+
const exportFile = typeof savePath === 'string' && path.isAbsolute(savePath) ? savePath : undefined
|
|
181
|
+
const legacy = typeof prompt === 'string' && prompt.trim() && !Array.isArray(preview.sections)
|
|
182
|
+
const sections = Array.isArray(preview.sections)
|
|
183
|
+
? preview.sections.filter(item => item && typeof item.text === 'string' && item.text.trim())
|
|
184
|
+
: []
|
|
185
|
+
const conversation = sections.filter(item => item.conversation === true)
|
|
186
|
+
const body = sections.filter(item => item.conversation !== true)
|
|
187
|
+
const files = body.filter(item => typeof item.file === 'string' && item.file)
|
|
188
|
+
const sources = (Array.isArray(preview.sources) ? preview.sources : [])
|
|
189
|
+
.map(value => clean(value, 40)).filter(Boolean)
|
|
190
|
+
const truncated = legacy ? legacyTruncated === true : preview.truncated === true
|
|
191
|
+
|
|
192
|
+
const lines = [`# ${heading} · ${session ? '会话记录' : '开发交接'}`, '']
|
|
193
|
+
const summary = [`来源:${sources.join('、') || clean(origin, 40) || '本地项目'}`, stamp(date)]
|
|
194
|
+
if (files.length) summary.push(`${files.length} 份资料`)
|
|
195
|
+
if (conversation.length) summary.push(`${conversation.length} 段对话`)
|
|
196
|
+
lines.push(`> ${summary.join(' · ')}`, '')
|
|
197
|
+
|
|
198
|
+
const cwd = typeof preview.cwd === 'string' && preview.cwd ? preview.cwd : ''
|
|
199
|
+
if (cwd) {
|
|
200
|
+
const name = clean(path.basename(cwd.replace(/[\\/]+$/, '')) || cwd, 120)
|
|
201
|
+
const value = mode === 'share' ? `\`${name}\`` : fileLink(name, directoryUrl(cwd))
|
|
202
|
+
lines.push(`**${session ? '原工作目录' : '工作目录'}**:${value}`, '')
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
if (legacy) {
|
|
206
|
+
lines.push(fenceSafe(prompt), '')
|
|
207
|
+
if (truncated) lines.push('> 部分内容已截取,完整内容见来源文件。', '')
|
|
208
|
+
if (preview.footer) lines.push(`> ${clean(preview.footer, 200)}`, '')
|
|
209
|
+
return { filename: filenameOf(heading, date), markdown: `${lines.join('\n').trimEnd()}\n` }
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
if (files.length) {
|
|
213
|
+
lines.push('## 资料索引', '')
|
|
214
|
+
for (const item of files) {
|
|
215
|
+
lines.push(`- ${sourceValue(item.file, { format: mode, savePath: exportFile })}${item.label ? ` · ${linkLabel(clean(item.label))}` : ''}`)
|
|
216
|
+
}
|
|
217
|
+
lines.push('')
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
for (const item of body) {
|
|
221
|
+
lines.push(`## ${clean(item.label) || '资料'}`, '')
|
|
222
|
+
if (typeof item.file === 'string' && item.file) {
|
|
223
|
+
lines.push(`来源:${sourceValue(item.file, { format: mode, savePath: exportFile })}`, '')
|
|
224
|
+
}
|
|
225
|
+
lines.push(fenceSafe(session ? item.text : handoffBody(item, cwd, mode, exportFile)), '')
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
if (conversation.length) {
|
|
229
|
+
lines.push('## 最近对话', '')
|
|
230
|
+
for (const item of conversation) {
|
|
231
|
+
lines.push(`### ${conversationHeading(item.label)}`, '',
|
|
232
|
+
item.markdown ? fenceSafe(item.text) : escapeProse(item.text.trimEnd()), '')
|
|
233
|
+
}
|
|
11
234
|
}
|
|
235
|
+
|
|
236
|
+
if (includeTrace === true) lines.push(...traceLines(preview.trace))
|
|
237
|
+
if (truncated) lines.push('> 部分内容已截取,完整内容见来源文件。', '')
|
|
238
|
+
if (preview.footer) lines.push(`> ${clean(preview.footer, 200)}`, '')
|
|
239
|
+
|
|
240
|
+
return { filename: filenameOf(heading, date), markdown: `${lines.join('\n').trimEnd()}\n` }
|
|
12
241
|
}
|
package/src/index.js
CHANGED
|
@@ -4,11 +4,14 @@ import { readFile } from 'node:fs/promises'
|
|
|
4
4
|
import { createCatalog } from './catalog.js'
|
|
5
5
|
import { loadConfig } from './config.js'
|
|
6
6
|
import { nativeSessionServices, saveNativeSession } from './session-import.js'
|
|
7
|
+
import { countTrace, isSessionId, readSessionTrace } from './session-trace.js'
|
|
8
|
+
import { createSkillBridge } from './skill-provider.js'
|
|
7
9
|
|
|
8
10
|
export const name = 'dsh-agent-bridge'
|
|
9
11
|
export const inject = {
|
|
10
12
|
connection: true, webServer: true,
|
|
11
13
|
sessions: false, sessionPersistence: false, workspaceRegistry: false, sessionProjectionCache: false,
|
|
14
|
+
skills: false,
|
|
12
15
|
}
|
|
13
16
|
|
|
14
17
|
const prefix = '/agent-bridge'
|
|
@@ -59,12 +62,27 @@ async function readBody(req) {
|
|
|
59
62
|
|
|
60
63
|
export function apply(ctx) {
|
|
61
64
|
const services = () => nativeSessionServices(ctx)
|
|
65
|
+
const skillHandoff = ctx.get?.('skills') ? createSkillBridge(ctx) : undefined
|
|
66
|
+
async function loadSourceRecord(sessionId) {
|
|
67
|
+
if (!isSessionId(sessionId)) throw Object.assign(new Error('会话标识无效。'), { status: 400 })
|
|
68
|
+
const session = await ctx.get?.('sessionPersistence')?.stat?.(sessionId)
|
|
69
|
+
if (session?.header?.id !== sessionId) {
|
|
70
|
+
throw Object.assign(new Error('找不到这条 DSH 会话。'), { status: 404 })
|
|
71
|
+
}
|
|
72
|
+
const saved = await readSessionTrace(await loadConfig(), sessionId)
|
|
73
|
+
if (!saved?.trace?.length && !saved?.sourceStats) {
|
|
74
|
+
throw Object.assign(new Error('没有为这条会话保存来源记录。'), { status: 404 })
|
|
75
|
+
}
|
|
76
|
+
return { ...saved, traceCounts: countTrace(saved.trace) }
|
|
77
|
+
}
|
|
62
78
|
const catalog = createCatalog(loadConfig, {
|
|
63
79
|
importConversation(record, cwd) {
|
|
64
80
|
const host = services()
|
|
65
81
|
if (!host) throw Object.assign(new Error('当前 DSH 未提供会话迁入服务。'), { status: 409 })
|
|
66
82
|
return saveNativeSession(host, record, cwd)
|
|
67
83
|
},
|
|
84
|
+
skillHandoff,
|
|
85
|
+
loadSourceRecord,
|
|
68
86
|
})
|
|
69
87
|
ctx.effect(() => () => catalog.dispose())
|
|
70
88
|
const nonce = randomBytes(32).toString('hex')
|
|
@@ -73,6 +91,8 @@ export function apply(ctx) {
|
|
|
73
91
|
['/panel.css', 'panel.css', 'text/css; charset=utf-8'],
|
|
74
92
|
['/panel.js', 'panel.js', 'text/javascript; charset=utf-8'],
|
|
75
93
|
['/project-context.js', 'project-context.js', 'text/javascript; charset=utf-8'],
|
|
94
|
+
['/markdown.js', 'markdown.js', 'text/javascript; charset=utf-8'],
|
|
95
|
+
['/vendor/markdown-it.mjs', 'vendor/markdown-it.mjs', 'text/javascript; charset=utf-8'],
|
|
76
96
|
['/geist-latin-wght-normal.woff2', 'geist-latin-wght-normal.woff2', 'font/woff2'],
|
|
77
97
|
]
|
|
78
98
|
const agentIcons = Object.create(null)
|
|
@@ -133,4 +153,8 @@ export function apply(ctx) {
|
|
|
133
153
|
const result = await catalog.execute(input.action, input)
|
|
134
154
|
json(res, 200, input.action === 'catalog' ? { ...result, agentIcons, nativeSessionImport } : result)
|
|
135
155
|
})
|
|
156
|
+
register('/session-trace', 'GET', async (req, res) => {
|
|
157
|
+
const sessionId = new URL(req.url ?? '/', 'http://localhost').searchParams.get('sessionId') ?? ''
|
|
158
|
+
json(res, 200, await loadSourceRecord(sessionId))
|
|
159
|
+
})
|
|
136
160
|
}
|