@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.
- package/README.md +198 -194
- package/THIRD_PARTY_NOTICES.md +67 -0
- package/cordis.patch.yml +4 -4
- package/package.json +40 -40
- package/src/assets.js +405 -348
- package/src/catalog.js +906 -605
- package/src/client.js +623 -310
- package/src/config.js +88 -88
- package/src/export.js +241 -12
- package/src/index.js +160 -136
- package/src/project-archive.js +145 -145
- package/src/projects.js +1189 -980
- package/src/session-import.js +107 -93
- 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/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/markdown.js +225 -0
- package/web/panel.css +607 -502
- package/web/panel.html +277 -246
- package/web/panel.js +2334 -1559
- package/web/project-context.js +25 -25
- package/web/vendor/markdown-it-LICENSE.txt +156 -0
- package/web/vendor/markdown-it.mjs +3064 -0
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,241 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
return
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
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) {
|
|
126
|
+
const name = heading.replace(/[^\p{L}\p{N}._-]+/gu, '-').replace(/^[.-]+|[.-]+$/g, '')
|
|
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
|
+
}
|
|
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` }
|
|
241
|
+
}
|