@wwwfz/dsh-agent-bridge 0.8.2 → 0.8.3
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 +194 -184
- package/cordis.patch.yml +4 -4
- package/package.json +40 -40
- package/src/assets.js +348 -348
- package/src/catalog.js +605 -605
- package/src/client.js +310 -310
- package/src/config.js +88 -88
- package/src/export.js +12 -12
- package/src/index.js +136 -136
- package/src/project-archive.js +145 -145
- package/src/projects.js +980 -980
- package/src/session-import.js +93 -93
- package/src/watch.js +309 -309
- package/web/Geist-OFL.txt +93 -93
- package/web/agent-icons/NOTICE.md +19 -19
- package/web/agent-icons/antigravity.svg +76 -76
- package/web/agent-icons/claude.svg +3 -3
- package/web/agent-icons/dsh.svg +58 -58
- package/web/agent-icons/licenses/copilot.txt +21 -21
- package/web/agent-icons/licenses/dsh.txt +21 -21
- package/web/agent-icons/licenses/gemini.txt +201 -201
- package/web/agent-icons/licenses/opencode.txt +21 -21
- package/web/agent-icons/licenses/qoder-notice.txt +18 -18
- package/web/agent-icons/licenses/qoder.txt +22 -22
- package/web/agent-icons/licenses/qwen.txt +202 -202
- package/web/agent-icons/qoder.svg +4 -4
- package/web/agent-icons/qwen.svg +5 -5
- package/web/agent-icons/workbuddy.svg +29 -29
- package/web/panel.css +502 -502
- package/web/panel.html +246 -246
- package/web/panel.js +1559 -1559
- package/web/project-context.js +25 -25
package/src/config.js
CHANGED
|
@@ -1,88 +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
|
-
}
|
|
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
CHANGED
|
@@ -1,12 +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
|
-
}
|
|
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
CHANGED
|
@@ -1,136 +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
|
-
}
|
|
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
|
+
}
|