@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/index.js
CHANGED
|
@@ -1,136 +1,160 @@
|
|
|
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
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
'
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
}
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
const
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
}
|
|
133
|
-
|
|
134
|
-
|
|
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
|
+
import { countTrace, isSessionId, readSessionTrace } from './session-trace.js'
|
|
8
|
+
import { createSkillBridge } from './skill-provider.js'
|
|
9
|
+
|
|
10
|
+
export const name = 'dsh-agent-bridge'
|
|
11
|
+
export const inject = {
|
|
12
|
+
connection: true, webServer: true,
|
|
13
|
+
sessions: false, sessionPersistence: false, workspaceRegistry: false, sessionProjectionCache: false,
|
|
14
|
+
skills: false,
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
const prefix = '/agent-bridge'
|
|
18
|
+
const pageHeaders = {
|
|
19
|
+
'Cache-Control': 'no-store',
|
|
20
|
+
'Referrer-Policy': 'no-referrer',
|
|
21
|
+
'X-Content-Type-Options': 'nosniff',
|
|
22
|
+
'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'",
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function respond(res, status, type, value) {
|
|
26
|
+
res.writeHead(status, { ...pageHeaders, 'Content-Type': type })
|
|
27
|
+
res.end(value)
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
function json(res, status, data) {
|
|
31
|
+
respond(res, status, 'application/json; charset=utf-8', JSON.stringify(data))
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function isLoopback(address) {
|
|
35
|
+
return typeof address === 'string' && (address === '::1' || /^(?:::ffff:)?127(?:\.\d{1,3}){3}$/.test(address))
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
async function readBody(req) {
|
|
39
|
+
const chunks = []
|
|
40
|
+
let bytes = 0
|
|
41
|
+
for await (const chunk of req.iterator({ destroyOnReturn: false })) {
|
|
42
|
+
bytes += chunk.length
|
|
43
|
+
if (bytes > 192 * 1024) {
|
|
44
|
+
const error = new Error('请求过大。')
|
|
45
|
+
error.status = 413
|
|
46
|
+
// Drain without buffering, so the client can receive a normal error response.
|
|
47
|
+
req.resume()
|
|
48
|
+
throw error
|
|
49
|
+
}
|
|
50
|
+
chunks.push(chunk)
|
|
51
|
+
}
|
|
52
|
+
try {
|
|
53
|
+
const data = JSON.parse(Buffer.concat(chunks).toString('utf8'))
|
|
54
|
+
if (!data || typeof data !== 'object' || Array.isArray(data)) throw new Error()
|
|
55
|
+
return data
|
|
56
|
+
} catch {
|
|
57
|
+
const error = new Error('请求格式无效。')
|
|
58
|
+
error.status = 400
|
|
59
|
+
throw error
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function apply(ctx) {
|
|
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
|
+
}
|
|
78
|
+
const catalog = createCatalog(loadConfig, {
|
|
79
|
+
importConversation(record, cwd) {
|
|
80
|
+
const host = services()
|
|
81
|
+
if (!host) throw Object.assign(new Error('当前 DSH 未提供会话迁入服务。'), { status: 409 })
|
|
82
|
+
return saveNativeSession(host, record, cwd)
|
|
83
|
+
},
|
|
84
|
+
skillHandoff,
|
|
85
|
+
loadSourceRecord,
|
|
86
|
+
})
|
|
87
|
+
ctx.effect(() => () => catalog.dispose())
|
|
88
|
+
const nonce = randomBytes(32).toString('hex')
|
|
89
|
+
const staticRoutes = [
|
|
90
|
+
['/panel', 'panel.html', 'text/html; charset=utf-8'],
|
|
91
|
+
['/panel.css', 'panel.css', 'text/css; charset=utf-8'],
|
|
92
|
+
['/panel.js', 'panel.js', 'text/javascript; charset=utf-8'],
|
|
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'],
|
|
96
|
+
['/geist-latin-wght-normal.woff2', 'geist-latin-wght-normal.woff2', 'font/woff2'],
|
|
97
|
+
]
|
|
98
|
+
const agentIcons = Object.create(null)
|
|
99
|
+
const iconsDirectory = new URL('../web/agent-icons/', import.meta.url)
|
|
100
|
+
if (existsSync(iconsDirectory)) {
|
|
101
|
+
for (const entry of readdirSync(iconsDirectory, { withFileTypes: true })) {
|
|
102
|
+
const match = /^([a-z][a-z0-9-]*)\.(svg|png)$/.exec(entry.name)
|
|
103
|
+
if (!entry.isFile() || !match) continue
|
|
104
|
+
const [, agent, extension] = match
|
|
105
|
+
const file = `agent-icons/${entry.name}`
|
|
106
|
+
agentIcons[agent] = file
|
|
107
|
+
staticRoutes.push([`/${file}`, file, extension === 'svg' ? 'image/svg+xml' : 'image/png'])
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
function register(path, method, action) {
|
|
111
|
+
ctx.effect(() => ctx.webServer.register({
|
|
112
|
+
kind: 'exact', path: prefix + path,
|
|
113
|
+
async handler(req, res) {
|
|
114
|
+
if (!isLoopback(req.socket.remoteAddress)
|
|
115
|
+
|| ctx.connection.admit?.(req)?.peer?.principal?.kind !== 'owner') {
|
|
116
|
+
json(res, 403, { error: '请使用本机 DSH 所有者身份打开 Agent 接续。' })
|
|
117
|
+
return
|
|
118
|
+
}
|
|
119
|
+
if (req.method !== method) {
|
|
120
|
+
res.setHeader('Allow', method)
|
|
121
|
+
json(res, 405, { error: '请求方法不受支持。' })
|
|
122
|
+
return
|
|
123
|
+
}
|
|
124
|
+
try {
|
|
125
|
+
await action(req, res)
|
|
126
|
+
} catch (error) {
|
|
127
|
+
if (!res.headersSent) json(res, error.status || 500, {
|
|
128
|
+
error: error.status ? error.message : '无法读取本地资料。请检查 agent-bridge.json 和文件权限后刷新。',
|
|
129
|
+
})
|
|
130
|
+
}
|
|
131
|
+
},
|
|
132
|
+
}))
|
|
133
|
+
}
|
|
134
|
+
for (const [path, file, type] of staticRoutes) {
|
|
135
|
+
register(path, 'GET', async (_req, res) => {
|
|
136
|
+
const body = await readFile(new URL(`../web/${file}`, import.meta.url))
|
|
137
|
+
respond(res, 200, type, file === 'panel.html' ? body.toString('utf8').replace('__DSH_BRIDGE_NONCE__', nonce) : body)
|
|
138
|
+
})
|
|
139
|
+
}
|
|
140
|
+
register('/api', 'POST', async (req, res) => {
|
|
141
|
+
if (req.headers['x-dsh-agent-bridge'] !== nonce
|
|
142
|
+
|| !/^application\/json(?:\s*;|$)/i.test(req.headers['content-type'] ?? '')) {
|
|
143
|
+
json(res, 403, { error: '面板已过期。重新打开 Agent 接续后重试。' })
|
|
144
|
+
return
|
|
145
|
+
}
|
|
146
|
+
const input = await readBody(req)
|
|
147
|
+
const conversationAction = ['list-conversations', 'preview-conversation', 'import-conversation'].includes(input.action)
|
|
148
|
+
const nativeSessionImport = (conversationAction || input.action === 'catalog') && Boolean(services())
|
|
149
|
+
if (conversationAction && !nativeSessionImport) {
|
|
150
|
+
json(res, 403, { error: '请在支持会话迁入的本机 DSH 主界面中使用。' })
|
|
151
|
+
return
|
|
152
|
+
}
|
|
153
|
+
const result = await catalog.execute(input.action, input)
|
|
154
|
+
json(res, 200, input.action === 'catalog' ? { ...result, agentIcons, nativeSessionImport } : result)
|
|
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
|
+
})
|
|
160
|
+
}
|
package/src/project-archive.js
CHANGED
|
@@ -1,145 +1,145 @@
|
|
|
1
|
-
import { lstat, mkdir } from 'node:fs/promises'
|
|
2
|
-
import { dirname, isAbsolute, join } from 'node:path'
|
|
3
|
-
|
|
4
|
-
const applicationId = 0x44534841
|
|
5
|
-
const filename = 'agent-bridge-archive.sqlite'
|
|
6
|
-
|
|
7
|
-
export class ProjectArchiveError extends Error {}
|
|
8
|
-
|
|
9
|
-
function databasePath(config) {
|
|
10
|
-
const file = config.configFile
|
|
11
|
-
return typeof file === 'string' && isAbsolute(file) ? join(dirname(file), filename) : undefined
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
async function archiveExists(file) {
|
|
15
|
-
if (!file) return false
|
|
16
|
-
try {
|
|
17
|
-
const info = await lstat(file)
|
|
18
|
-
if (!info.isFile() || info.nlink > 1) {
|
|
19
|
-
throw new ProjectArchiveError(`${filename} 应为独立的常规文件。`)
|
|
20
|
-
}
|
|
21
|
-
return true
|
|
22
|
-
} catch (error) {
|
|
23
|
-
if (error.code !== 'ENOENT') throw error
|
|
24
|
-
return false
|
|
25
|
-
}
|
|
26
|
-
}
|
|
27
|
-
|
|
28
|
-
async function withArchive(file, readOnly, operation) {
|
|
29
|
-
const { DatabaseSync } = await import('node:sqlite')
|
|
30
|
-
const db = new DatabaseSync(file, { readOnly })
|
|
31
|
-
try {
|
|
32
|
-
db.exec('PRAGMA busy_timeout = 2000; PRAGMA trusted_schema = OFF')
|
|
33
|
-
db.exec(readOnly ? 'BEGIN' : 'BEGIN IMMEDIATE')
|
|
34
|
-
try {
|
|
35
|
-
const result = operation(db)
|
|
36
|
-
db.exec('COMMIT')
|
|
37
|
-
return result
|
|
38
|
-
} catch (error) {
|
|
39
|
-
try { db.exec('ROLLBACK') } catch { /* SQLite may already have rolled back the failed transaction. */ }
|
|
40
|
-
throw error
|
|
41
|
-
}
|
|
42
|
-
} finally {
|
|
43
|
-
db.close()
|
|
44
|
-
}
|
|
45
|
-
}
|
|
46
|
-
|
|
47
|
-
function initialized(db) {
|
|
48
|
-
const id = db.prepare('PRAGMA application_id').get().application_id
|
|
49
|
-
if (id === applicationId) return true
|
|
50
|
-
if (id === 0 && !db.prepare('SELECT 1 FROM sqlite_schema LIMIT 1').get()) return false
|
|
51
|
-
throw new ProjectArchiveError(`${filename} 不是 Agent 接续的项目归档数据库。`)
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
async function readArchive(config, operation) {
|
|
55
|
-
const file = databasePath(config)
|
|
56
|
-
if (!await archiveExists(file)) return undefined
|
|
57
|
-
return withArchive(file, true, db => initialized(db) ? operation(db) : undefined)
|
|
58
|
-
}
|
|
59
|
-
|
|
60
|
-
async function writeArchive(config, create, operation) {
|
|
61
|
-
const file = databasePath(config)
|
|
62
|
-
if (!file) throw new ProjectArchiveError('找不到插件配置文件对应的存储目录。')
|
|
63
|
-
if (!await archiveExists(file)) {
|
|
64
|
-
if (!create) return undefined
|
|
65
|
-
await mkdir(dirname(file), { recursive: true })
|
|
66
|
-
}
|
|
67
|
-
return withArchive(file, false, db => {
|
|
68
|
-
if (!initialized(db)) {
|
|
69
|
-
if (!create) return undefined
|
|
70
|
-
db.exec(`PRAGMA application_id = ${applicationId}; CREATE TABLE archived_projects (project_id TEXT PRIMARY KEY) STRICT`)
|
|
71
|
-
}
|
|
72
|
-
return operation(db)
|
|
73
|
-
})
|
|
74
|
-
}
|
|
75
|
-
|
|
76
|
-
function hasPreferences(db) {
|
|
77
|
-
return Boolean(db.prepare("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'project_preferences'").get())
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
function ensurePreferences(db) {
|
|
81
|
-
db.exec(`CREATE TABLE IF NOT EXISTS project_preferences (
|
|
82
|
-
project_id TEXT PRIMARY KEY,
|
|
83
|
-
pinned INTEGER NOT NULL DEFAULT 0 CHECK (pinned IN (0, 1)),
|
|
84
|
-
continued_at INTEGER CHECK (continued_at > 0),
|
|
85
|
-
selection_json TEXT
|
|
86
|
-
) STRICT`)
|
|
87
|
-
}
|
|
88
|
-
|
|
89
|
-
export async function readProjectState(config) {
|
|
90
|
-
return await readArchive(config, db => {
|
|
91
|
-
const archivedIds = new Set(db.prepare('SELECT project_id FROM archived_projects').all().map(row => row.project_id))
|
|
92
|
-
const rows = hasPreferences(db) ? db.prepare(
|
|
93
|
-
'SELECT project_id, pinned, continued_at FROM project_preferences WHERE pinned = 1 OR continued_at IS NOT NULL',
|
|
94
|
-
).all() : []
|
|
95
|
-
const preferences = new Map(rows.map(row => [row.project_id, { pinned: row.pinned === 1, continuedAt: row.continued_at }]))
|
|
96
|
-
return { archivedIds, preferences }
|
|
97
|
-
}) ?? { archivedIds: new Set(), preferences: new Map() }
|
|
98
|
-
}
|
|
99
|
-
|
|
100
|
-
export async function writeProjectArchive(config, projectIds, archived) {
|
|
101
|
-
return await writeArchive(config, archived, db => {
|
|
102
|
-
const update = db.prepare(archived
|
|
103
|
-
? 'INSERT INTO archived_projects (project_id) VALUES (?) ON CONFLICT (project_id) DO NOTHING'
|
|
104
|
-
: 'DELETE FROM archived_projects WHERE project_id = ?')
|
|
105
|
-
return projectIds.filter(projectId => update.run(projectId).changes > 0)
|
|
106
|
-
}) ?? []
|
|
107
|
-
}
|
|
108
|
-
|
|
109
|
-
export async function writeProjectPin(config, projectId, pinned) {
|
|
110
|
-
await writeArchive(config, pinned, db => {
|
|
111
|
-
if (!pinned) {
|
|
112
|
-
if (hasPreferences(db)) db.prepare('UPDATE project_preferences SET pinned = 0 WHERE project_id = ? AND pinned = 1').run(projectId)
|
|
113
|
-
return
|
|
114
|
-
}
|
|
115
|
-
ensurePreferences(db)
|
|
116
|
-
db.prepare(`INSERT INTO project_preferences (project_id, pinned) VALUES (?, 1)
|
|
117
|
-
ON CONFLICT (project_id) DO UPDATE SET pinned = excluded.pinned
|
|
118
|
-
WHERE project_preferences.pinned <> excluded.pinned`).run(projectId)
|
|
119
|
-
})
|
|
120
|
-
}
|
|
121
|
-
|
|
122
|
-
export async function readProjectSelection(config, projectId) {
|
|
123
|
-
const saved = await readArchive(config, db => hasPreferences(db)
|
|
124
|
-
? db.prepare('SELECT selection_json FROM project_preferences WHERE project_id = ?').get(projectId)?.selection_json
|
|
125
|
-
: undefined)
|
|
126
|
-
return saved == null ? null : JSON.parse(saved)
|
|
127
|
-
}
|
|
128
|
-
|
|
129
|
-
export async function writeProjectSelection(config, projectId, selection) {
|
|
130
|
-
await writeArchive(config, true, db => {
|
|
131
|
-
ensurePreferences(db)
|
|
132
|
-
db.prepare(`INSERT INTO project_preferences (project_id, selection_json) VALUES (?, ?)
|
|
133
|
-
ON CONFLICT (project_id) DO UPDATE SET selection_json = excluded.selection_json
|
|
134
|
-
WHERE project_preferences.selection_json IS NOT excluded.selection_json`).run(projectId, JSON.stringify(selection))
|
|
135
|
-
})
|
|
136
|
-
}
|
|
137
|
-
|
|
138
|
-
export async function writeProjectContinuation(config, projectId) {
|
|
139
|
-
return writeArchive(config, true, db => {
|
|
140
|
-
ensurePreferences(db)
|
|
141
|
-
return db.prepare(`INSERT INTO project_preferences (project_id, continued_at) VALUES (?, ?)
|
|
142
|
-
ON CONFLICT (project_id) DO UPDATE SET continued_at = MAX(COALESCE(project_preferences.continued_at, 0), excluded.continued_at)
|
|
143
|
-
RETURNING continued_at`).get(projectId, Date.now()).continued_at
|
|
144
|
-
})
|
|
145
|
-
}
|
|
1
|
+
import { lstat, mkdir } from 'node:fs/promises'
|
|
2
|
+
import { dirname, isAbsolute, join } from 'node:path'
|
|
3
|
+
|
|
4
|
+
const applicationId = 0x44534841
|
|
5
|
+
const filename = 'agent-bridge-archive.sqlite'
|
|
6
|
+
|
|
7
|
+
export class ProjectArchiveError extends Error {}
|
|
8
|
+
|
|
9
|
+
function databasePath(config) {
|
|
10
|
+
const file = config.configFile
|
|
11
|
+
return typeof file === 'string' && isAbsolute(file) ? join(dirname(file), filename) : undefined
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
async function archiveExists(file) {
|
|
15
|
+
if (!file) return false
|
|
16
|
+
try {
|
|
17
|
+
const info = await lstat(file)
|
|
18
|
+
if (!info.isFile() || info.nlink > 1) {
|
|
19
|
+
throw new ProjectArchiveError(`${filename} 应为独立的常规文件。`)
|
|
20
|
+
}
|
|
21
|
+
return true
|
|
22
|
+
} catch (error) {
|
|
23
|
+
if (error.code !== 'ENOENT') throw error
|
|
24
|
+
return false
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
async function withArchive(file, readOnly, operation) {
|
|
29
|
+
const { DatabaseSync } = await import('node:sqlite')
|
|
30
|
+
const db = new DatabaseSync(file, { readOnly })
|
|
31
|
+
try {
|
|
32
|
+
db.exec('PRAGMA busy_timeout = 2000; PRAGMA trusted_schema = OFF')
|
|
33
|
+
db.exec(readOnly ? 'BEGIN' : 'BEGIN IMMEDIATE')
|
|
34
|
+
try {
|
|
35
|
+
const result = operation(db)
|
|
36
|
+
db.exec('COMMIT')
|
|
37
|
+
return result
|
|
38
|
+
} catch (error) {
|
|
39
|
+
try { db.exec('ROLLBACK') } catch { /* SQLite may already have rolled back the failed transaction. */ }
|
|
40
|
+
throw error
|
|
41
|
+
}
|
|
42
|
+
} finally {
|
|
43
|
+
db.close()
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
function initialized(db) {
|
|
48
|
+
const id = db.prepare('PRAGMA application_id').get().application_id
|
|
49
|
+
if (id === applicationId) return true
|
|
50
|
+
if (id === 0 && !db.prepare('SELECT 1 FROM sqlite_schema LIMIT 1').get()) return false
|
|
51
|
+
throw new ProjectArchiveError(`${filename} 不是 Agent 接续的项目归档数据库。`)
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function readArchive(config, operation) {
|
|
55
|
+
const file = databasePath(config)
|
|
56
|
+
if (!await archiveExists(file)) return undefined
|
|
57
|
+
return withArchive(file, true, db => initialized(db) ? operation(db) : undefined)
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
async function writeArchive(config, create, operation) {
|
|
61
|
+
const file = databasePath(config)
|
|
62
|
+
if (!file) throw new ProjectArchiveError('找不到插件配置文件对应的存储目录。')
|
|
63
|
+
if (!await archiveExists(file)) {
|
|
64
|
+
if (!create) return undefined
|
|
65
|
+
await mkdir(dirname(file), { recursive: true })
|
|
66
|
+
}
|
|
67
|
+
return withArchive(file, false, db => {
|
|
68
|
+
if (!initialized(db)) {
|
|
69
|
+
if (!create) return undefined
|
|
70
|
+
db.exec(`PRAGMA application_id = ${applicationId}; CREATE TABLE archived_projects (project_id TEXT PRIMARY KEY) STRICT`)
|
|
71
|
+
}
|
|
72
|
+
return operation(db)
|
|
73
|
+
})
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
function hasPreferences(db) {
|
|
77
|
+
return Boolean(db.prepare("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'project_preferences'").get())
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
function ensurePreferences(db) {
|
|
81
|
+
db.exec(`CREATE TABLE IF NOT EXISTS project_preferences (
|
|
82
|
+
project_id TEXT PRIMARY KEY,
|
|
83
|
+
pinned INTEGER NOT NULL DEFAULT 0 CHECK (pinned IN (0, 1)),
|
|
84
|
+
continued_at INTEGER CHECK (continued_at > 0),
|
|
85
|
+
selection_json TEXT
|
|
86
|
+
) STRICT`)
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export async function readProjectState(config) {
|
|
90
|
+
return await readArchive(config, db => {
|
|
91
|
+
const archivedIds = new Set(db.prepare('SELECT project_id FROM archived_projects').all().map(row => row.project_id))
|
|
92
|
+
const rows = hasPreferences(db) ? db.prepare(
|
|
93
|
+
'SELECT project_id, pinned, continued_at FROM project_preferences WHERE pinned = 1 OR continued_at IS NOT NULL',
|
|
94
|
+
).all() : []
|
|
95
|
+
const preferences = new Map(rows.map(row => [row.project_id, { pinned: row.pinned === 1, continuedAt: row.continued_at }]))
|
|
96
|
+
return { archivedIds, preferences }
|
|
97
|
+
}) ?? { archivedIds: new Set(), preferences: new Map() }
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export async function writeProjectArchive(config, projectIds, archived) {
|
|
101
|
+
return await writeArchive(config, archived, db => {
|
|
102
|
+
const update = db.prepare(archived
|
|
103
|
+
? 'INSERT INTO archived_projects (project_id) VALUES (?) ON CONFLICT (project_id) DO NOTHING'
|
|
104
|
+
: 'DELETE FROM archived_projects WHERE project_id = ?')
|
|
105
|
+
return projectIds.filter(projectId => update.run(projectId).changes > 0)
|
|
106
|
+
}) ?? []
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export async function writeProjectPin(config, projectId, pinned) {
|
|
110
|
+
await writeArchive(config, pinned, db => {
|
|
111
|
+
if (!pinned) {
|
|
112
|
+
if (hasPreferences(db)) db.prepare('UPDATE project_preferences SET pinned = 0 WHERE project_id = ? AND pinned = 1').run(projectId)
|
|
113
|
+
return
|
|
114
|
+
}
|
|
115
|
+
ensurePreferences(db)
|
|
116
|
+
db.prepare(`INSERT INTO project_preferences (project_id, pinned) VALUES (?, 1)
|
|
117
|
+
ON CONFLICT (project_id) DO UPDATE SET pinned = excluded.pinned
|
|
118
|
+
WHERE project_preferences.pinned <> excluded.pinned`).run(projectId)
|
|
119
|
+
})
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export async function readProjectSelection(config, projectId) {
|
|
123
|
+
const saved = await readArchive(config, db => hasPreferences(db)
|
|
124
|
+
? db.prepare('SELECT selection_json FROM project_preferences WHERE project_id = ?').get(projectId)?.selection_json
|
|
125
|
+
: undefined)
|
|
126
|
+
return saved == null ? null : JSON.parse(saved)
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export async function writeProjectSelection(config, projectId, selection) {
|
|
130
|
+
await writeArchive(config, true, db => {
|
|
131
|
+
ensurePreferences(db)
|
|
132
|
+
db.prepare(`INSERT INTO project_preferences (project_id, selection_json) VALUES (?, ?)
|
|
133
|
+
ON CONFLICT (project_id) DO UPDATE SET selection_json = excluded.selection_json
|
|
134
|
+
WHERE project_preferences.selection_json IS NOT excluded.selection_json`).run(projectId, JSON.stringify(selection))
|
|
135
|
+
})
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export async function writeProjectContinuation(config, projectId) {
|
|
139
|
+
return writeArchive(config, true, db => {
|
|
140
|
+
ensurePreferences(db)
|
|
141
|
+
return db.prepare(`INSERT INTO project_preferences (project_id, continued_at) VALUES (?, ?)
|
|
142
|
+
ON CONFLICT (project_id) DO UPDATE SET continued_at = MAX(COALESCE(project_preferences.continued_at, 0), excluded.continued_at)
|
|
143
|
+
RETURNING continued_at`).get(projectId, Date.now()).continued_at
|
|
144
|
+
})
|
|
145
|
+
}
|