@wwwfz/dsh-agent-bridge 0.0.0-stage → 0.8.2
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 +183 -2
- package/cordis.patch.yml +4 -0
- package/package.json +38 -4
- package/src/assets.js +348 -0
- package/src/catalog.js +605 -0
- package/src/client.js +310 -0
- package/src/config.js +88 -0
- package/src/export.js +12 -0
- package/src/index.js +136 -0
- package/src/project-archive.js +145 -0
- package/src/projects.js +980 -0
- package/src/session-import.js +93 -0
- package/src/watch.js +309 -0
- package/web/Geist-OFL.txt +93 -0
- package/web/agent-icons/NOTICE.md +19 -0
- package/web/agent-icons/antigravity.svg +76 -0
- package/web/agent-icons/claude.svg +3 -0
- package/web/agent-icons/codex.png +0 -0
- package/web/agent-icons/copilot.svg +1 -0
- package/web/agent-icons/dsh.svg +58 -0
- package/web/agent-icons/gemini.png +0 -0
- package/web/agent-icons/licenses/copilot.txt +21 -0
- package/web/agent-icons/licenses/dsh.txt +21 -0
- package/web/agent-icons/licenses/gemini.txt +202 -0
- package/web/agent-icons/licenses/opencode.txt +21 -0
- package/web/agent-icons/licenses/qoder-notice.txt +18 -0
- package/web/agent-icons/licenses/qoder.txt +22 -0
- package/web/agent-icons/licenses/qwen.txt +203 -0
- package/web/agent-icons/opencode.png +0 -0
- package/web/agent-icons/qoder.svg +4 -0
- package/web/agent-icons/qwen.svg +5 -0
- package/web/agent-icons/trae.png +0 -0
- package/web/agent-icons/workbuddy.svg +29 -0
- package/web/geist-latin-wght-normal.woff2 +0 -0
- package/web/panel.css +502 -0
- package/web/panel.html +246 -0
- package/web/panel.js +1559 -0
- package/web/project-context.js +25 -0
package/src/client.js
ADDED
|
@@ -0,0 +1,310 @@
|
|
|
1
|
+
window.__ModuleLoader__.load({
|
|
2
|
+
id: '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
|
+
});
|
package/src/config.js
ADDED
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { readFile } from 'node:fs/promises'
|
|
2
|
+
import { homedir } from 'node:os'
|
|
3
|
+
import { dirname, isAbsolute, join, normalize, posix, resolve, win32 } from 'node:path'
|
|
4
|
+
|
|
5
|
+
export function discoverRoots(home, env, platform) {
|
|
6
|
+
const path = platform === 'win32' ? win32 : posix
|
|
7
|
+
const absolute = (...values) => [...new Set(values.filter(value => typeof value === 'string' && path.isAbsolute(value)).map(path.normalize))]
|
|
8
|
+
const data = absolute(env.XDG_DATA_HOME, path.join(home, '.local', 'share'))
|
|
9
|
+
const configs = absolute(env.XDG_CONFIG_HOME, path.join(home, '.config'))
|
|
10
|
+
const roaming = platform === 'win32' ? absolute(env.APPDATA, path.join(home, 'AppData', 'Roaming'))
|
|
11
|
+
: platform === 'darwin' ? [path.join(home, 'Library', 'Application Support')] : configs
|
|
12
|
+
const manager = absolute(env.AGENTSVIEW_DATA_DIR || env.AGENT_VIEWER_DATA_DIR, path.join(home, '.agentsview'))
|
|
13
|
+
return {
|
|
14
|
+
agentRoots: {
|
|
15
|
+
codex: absolute(env.CODEX_HOME, path.join(home, '.codex')),
|
|
16
|
+
claude: absolute(env.CLAUDE_CONFIG_DIR, path.join(home, '.claude')),
|
|
17
|
+
opencode: absolute(env.OPENCODE_DB, ...data.map(root => path.join(root, 'opencode'))),
|
|
18
|
+
qoder: [path.join(home, '.qoder-cn'), path.join(home, '.qoder')],
|
|
19
|
+
qwen: [path.join(home, '.qwen')],
|
|
20
|
+
workbuddy: [path.join(home, '.workbuddy')],
|
|
21
|
+
gemini: [path.join(home, '.gemini')],
|
|
22
|
+
antigravity: [path.join(home, '.gemini', 'antigravity'), path.join(home, '.gemini', 'antigravity-cli')],
|
|
23
|
+
trae: [...roaming.flatMap(root => ['Trae', 'Trae CN'].map(product => path.join(root, product, 'User'))),
|
|
24
|
+
path.join(home, '.trae'), path.join(home, '.trae-cn')],
|
|
25
|
+
copilot: [...roaming.flatMap(root => ['Code', 'Code - Insiders', 'VSCodium'].map(product => path.join(root, product, 'User'))),
|
|
26
|
+
path.join(home, '.copilot')],
|
|
27
|
+
},
|
|
28
|
+
opencodeSkillRoots: absolute(env.OPENCODE_CONFIG_DIR, ...configs.map(root => path.join(root, 'opencode'))),
|
|
29
|
+
workspaceHubRoots: manager.map(root => path.join(root, 'workspacehub')),
|
|
30
|
+
archiveFiles: manager.map(root => path.join(root, 'sessions.db')),
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function resolvePath(value, base, home) {
|
|
35
|
+
if (value === '~') return home
|
|
36
|
+
if (/^~[\\/]/.test(value)) return join(home, value.slice(2))
|
|
37
|
+
return isAbsolute(value) ? normalize(value) : resolve(base, value)
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function paths(value, key, base, home) {
|
|
41
|
+
if (value === undefined) return []
|
|
42
|
+
if (!Array.isArray(value) || value.some(item => typeof item !== 'string' || !item.trim())) {
|
|
43
|
+
throw new Error(`${key} 应为目录或文件路径数组。`)
|
|
44
|
+
}
|
|
45
|
+
return [...new Set(value.map(item => resolvePath(item, base, home)))]
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function pathMap(value, key, base, home) {
|
|
49
|
+
if (value != null && (typeof value !== 'object' || Array.isArray(value))) throw new Error(`${key} 应为名称到路径数组的映射。`)
|
|
50
|
+
return Object.fromEntries(Object.entries(value ?? {}).map(
|
|
51
|
+
([label, roots]) => [label, paths(roots, `${key}.${label}`, base, home)],
|
|
52
|
+
))
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export async function loadConfig(env = process.env) {
|
|
56
|
+
const nativeHome = process.platform === 'win32' ? env.USERPROFILE : env.HOME
|
|
57
|
+
const home = typeof nativeHome === 'string' && isAbsolute(nativeHome) ? normalize(nativeHome) : homedir()
|
|
58
|
+
const file = resolve(env.DSH_AGENT_BRIDGE_CONFIG || join(env.DSH_HOME || join(home, '.dsh'), 'agent-bridge.json'))
|
|
59
|
+
const base = dirname(file)
|
|
60
|
+
let raw = {}
|
|
61
|
+
try {
|
|
62
|
+
raw = JSON.parse((await readFile(file, 'utf8')).replace(/^\uFEFF/, ''))
|
|
63
|
+
} catch (error) {
|
|
64
|
+
if (error.code !== 'ENOENT') throw new Error('无法读取 agent-bridge.json。请检查 JSON 和文件权限。')
|
|
65
|
+
}
|
|
66
|
+
if (!raw || typeof raw !== 'object' || Array.isArray(raw)) throw new Error('agent-bridge.json 应为 JSON 对象。')
|
|
67
|
+
const detected = discoverRoots(home, env, process.platform)
|
|
68
|
+
const workspaceHubRoots = paths(raw.workspaceHubRoots ?? detected.workspaceHubRoots, 'workspaceHubRoots', base, home)
|
|
69
|
+
const archiveFiles = paths(raw.archiveFiles ?? [
|
|
70
|
+
...workspaceHubRoots.map(root => join(dirname(root), 'sessions.db')),
|
|
71
|
+
...detected.archiveFiles,
|
|
72
|
+
], 'archiveFiles', base, home)
|
|
73
|
+
const overrides = pathMap(raw.agentRoots, 'agentRoots', base, home)
|
|
74
|
+
const aliases = { 'claude-code': 'claude', 'open-code': 'opencode', 'qoder-cn': 'qoder', 'trae-cn': 'trae' }
|
|
75
|
+
for (const [alias, provider] of Object.entries(aliases)) {
|
|
76
|
+
if (Object.hasOwn(overrides, alias) && !Object.hasOwn(overrides, provider)) overrides[provider] = overrides[alias]
|
|
77
|
+
delete overrides[alias]
|
|
78
|
+
}
|
|
79
|
+
const memoryExports = Object.fromEntries(Object.entries(pathMap(raw.memoryExports, 'memoryExports', base, home))
|
|
80
|
+
.map(([workspace, exports]) => [resolvePath(workspace, base, home), exports]))
|
|
81
|
+
return {
|
|
82
|
+
home, configFile: file, workspaceHubRoots, archiveFiles, memoryExports,
|
|
83
|
+
agentRoots: { ...detected.agentRoots, ...overrides },
|
|
84
|
+
opencodeSkillRoots: paths(raw.opencodeSkillRoots ?? detected.opencodeSkillRoots, 'opencodeSkillRoots', base, home),
|
|
85
|
+
skillRoots: paths(raw.skillRoots, 'skillRoots', base, home),
|
|
86
|
+
projectRoots: paths(raw.projectRoots, 'projectRoots', base, home),
|
|
87
|
+
}
|
|
88
|
+
}
|
package/src/export.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export function makeExport({ title, prompt, origin, date = new Date(), truncated = false }) {
|
|
2
|
+
const heading = title.replace(/[\r\n\u0000-\u001f]+/g, ' ').trim() || '项目交接'
|
|
3
|
+
const name = heading.replace(/[^\p{L}\p{N}._-]+/gu, '-').replace(/^[.-]+|[.-]+$/g, '')
|
|
4
|
+
const stamp = date.toISOString()
|
|
5
|
+
const suffix = stamp.slice(0, 19).replace(/[-:]/g, '') + 'Z'
|
|
6
|
+
const metadata = [`来源:${origin}`, `导出时间:${stamp}`]
|
|
7
|
+
if (truncated) metadata.push('部分内容已截取。')
|
|
8
|
+
return {
|
|
9
|
+
filename: `handoff-${Array.from(name).slice(0, 48).join('') || 'project'}-${suffix}.md`,
|
|
10
|
+
markdown: [`# ${heading}`, '', metadata.join(' \n'), '', prompt.trimEnd(), ''].join('\n'),
|
|
11
|
+
}
|
|
12
|
+
}
|
package/src/index.js
ADDED
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto'
|
|
2
|
+
import { existsSync, readdirSync } from 'node:fs'
|
|
3
|
+
import { readFile } from 'node:fs/promises'
|
|
4
|
+
import { createCatalog } from './catalog.js'
|
|
5
|
+
import { loadConfig } from './config.js'
|
|
6
|
+
import { nativeSessionServices, saveNativeSession } from './session-import.js'
|
|
7
|
+
|
|
8
|
+
export const name = 'dsh-agent-bridge'
|
|
9
|
+
export const inject = {
|
|
10
|
+
connection: true, webServer: true,
|
|
11
|
+
sessions: false, sessionPersistence: false, workspaceRegistry: false, sessionProjectionCache: false,
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
const prefix = '/agent-bridge'
|
|
15
|
+
const pageHeaders = {
|
|
16
|
+
'Cache-Control': 'no-store',
|
|
17
|
+
'Referrer-Policy': 'no-referrer',
|
|
18
|
+
'X-Content-Type-Options': 'nosniff',
|
|
19
|
+
'Content-Security-Policy': "default-src 'none'; script-src 'self'; style-src 'self'; font-src 'self'; img-src 'self'; connect-src 'self'; frame-ancestors 'self'; base-uri 'none'; form-action 'none'",
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function respond(res, status, type, value) {
|
|
23
|
+
res.writeHead(status, { ...pageHeaders, 'Content-Type': type })
|
|
24
|
+
res.end(value)
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function json(res, status, data) {
|
|
28
|
+
respond(res, status, 'application/json; charset=utf-8', JSON.stringify(data))
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
function isLoopback(address) {
|
|
32
|
+
return typeof address === 'string' && (address === '::1' || /^(?:::ffff:)?127(?:\.\d{1,3}){3}$/.test(address))
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
async function readBody(req) {
|
|
36
|
+
const chunks = []
|
|
37
|
+
let bytes = 0
|
|
38
|
+
for await (const chunk of req.iterator({ destroyOnReturn: false })) {
|
|
39
|
+
bytes += chunk.length
|
|
40
|
+
if (bytes > 192 * 1024) {
|
|
41
|
+
const error = new Error('请求过大。')
|
|
42
|
+
error.status = 413
|
|
43
|
+
// Drain without buffering, so the client can receive a normal error response.
|
|
44
|
+
req.resume()
|
|
45
|
+
throw error
|
|
46
|
+
}
|
|
47
|
+
chunks.push(chunk)
|
|
48
|
+
}
|
|
49
|
+
try {
|
|
50
|
+
const data = JSON.parse(Buffer.concat(chunks).toString('utf8'))
|
|
51
|
+
if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error()
|
|
52
|
+
return data
|
|
53
|
+
} catch {
|
|
54
|
+
const error = new Error('请求格式无效。')
|
|
55
|
+
error.status = 400
|
|
56
|
+
throw error
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export function apply(ctx) {
|
|
61
|
+
const services = () => nativeSessionServices(ctx)
|
|
62
|
+
const catalog = createCatalog(loadConfig, {
|
|
63
|
+
importConversation(record, cwd) {
|
|
64
|
+
const host = services()
|
|
65
|
+
if (!host) throw Object.assign(new Error('当前 DSH 未提供会话迁入服务。'), { status: 409 })
|
|
66
|
+
return saveNativeSession(host, record, cwd)
|
|
67
|
+
},
|
|
68
|
+
})
|
|
69
|
+
ctx.effect(() => () => catalog.dispose())
|
|
70
|
+
const nonce = randomBytes(32).toString('hex')
|
|
71
|
+
const staticRoutes = [
|
|
72
|
+
['/panel', 'panel.html', 'text/html; charset=utf-8'],
|
|
73
|
+
['/panel.css', 'panel.css', 'text/css; charset=utf-8'],
|
|
74
|
+
['/panel.js', 'panel.js', 'text/javascript; charset=utf-8'],
|
|
75
|
+
['/project-context.js', 'project-context.js', 'text/javascript; charset=utf-8'],
|
|
76
|
+
['/geist-latin-wght-normal.woff2', 'geist-latin-wght-normal.woff2', 'font/woff2'],
|
|
77
|
+
]
|
|
78
|
+
const agentIcons = Object.create(null)
|
|
79
|
+
const iconsDirectory = new URL('../web/agent-icons/', import.meta.url)
|
|
80
|
+
if (existsSync(iconsDirectory)) {
|
|
81
|
+
for (const entry of readdirSync(iconsDirectory, { withFileTypes: true })) {
|
|
82
|
+
const match = /^([a-z][a-z0-9-]*)\.(svg|png)$/.exec(entry.name)
|
|
83
|
+
if (!entry.isFile() || !match) continue
|
|
84
|
+
const [, agent, extension] = match
|
|
85
|
+
const file = `agent-icons/${entry.name}`
|
|
86
|
+
agentIcons[agent] = file
|
|
87
|
+
staticRoutes.push([`/${file}`, file, extension === 'svg' ? 'image/svg+xml' : 'image/png'])
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
function register(path, method, action) {
|
|
91
|
+
ctx.effect(() => ctx.webServer.register({
|
|
92
|
+
kind: 'exact', path: prefix + path,
|
|
93
|
+
async handler(req, res) {
|
|
94
|
+
if (!isLoopback(req.socket.remoteAddress)
|
|
95
|
+
|| ctx.connection.admit?.(req)?.peer?.principal?.kind !== 'owner') {
|
|
96
|
+
json(res, 403, { error: '请使用本机 DSH 所有者身份打开 Agent 接续。' })
|
|
97
|
+
return
|
|
98
|
+
}
|
|
99
|
+
if (req.method !== method) {
|
|
100
|
+
res.setHeader('Allow', method)
|
|
101
|
+
json(res, 405, { error: '请求方法不受支持。' })
|
|
102
|
+
return
|
|
103
|
+
}
|
|
104
|
+
try {
|
|
105
|
+
await action(req, res)
|
|
106
|
+
} catch (error) {
|
|
107
|
+
if (!res.headersSent) json(res, error.status || 500, {
|
|
108
|
+
error: error.status ? error.message : '无法读取本地资料。请检查 agent-bridge.json 和文件权限后刷新。',
|
|
109
|
+
})
|
|
110
|
+
}
|
|
111
|
+
},
|
|
112
|
+
}))
|
|
113
|
+
}
|
|
114
|
+
for (const [path, file, type] of staticRoutes) {
|
|
115
|
+
register(path, 'GET', async (_req, res) => {
|
|
116
|
+
const body = await readFile(new URL(`../web/${file}`, import.meta.url))
|
|
117
|
+
respond(res, 200, type, file === 'panel.html' ? body.toString('utf8').replace('__DSH_BRIDGE_NONCE__', nonce) : body)
|
|
118
|
+
})
|
|
119
|
+
}
|
|
120
|
+
register('/api', 'POST', async (req, res) => {
|
|
121
|
+
if (req.headers['x-dsh-agent-bridge'] !== nonce
|
|
122
|
+
|| !/^application\/json(?:\s*;|$)/i.test(req.headers['content-type'] ?? '')) {
|
|
123
|
+
json(res, 403, { error: '面板已过期。重新打开 Agent 接续后重试。' })
|
|
124
|
+
return
|
|
125
|
+
}
|
|
126
|
+
const input = await readBody(req)
|
|
127
|
+
const conversationAction = ['list-conversations', 'preview-conversation', 'import-conversation'].includes(input.action)
|
|
128
|
+
const nativeSessionImport = (conversationAction || input.action === 'catalog') && Boolean(services())
|
|
129
|
+
if (conversationAction && !nativeSessionImport) {
|
|
130
|
+
json(res, 403, { error: '请在支持会话迁入的本机 DSH 主界面中使用。' })
|
|
131
|
+
return
|
|
132
|
+
}
|
|
133
|
+
const result = await catalog.execute(input.action, input)
|
|
134
|
+
json(res, 200, input.action === 'catalog' ? { ...result, agentIcons, nativeSessionImport } : result)
|
|
135
|
+
})
|
|
136
|
+
}
|