@wwwfz/dsh-agent-bridge 0.0.0-stage → 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.
@@ -0,0 +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
+ }