@wwwfz/dsh-agent-bridge 0.8.3 → 0.10.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.
Files changed (45) hide show
  1. package/README.md +132 -194
  2. package/THIRD_PARTY_NOTICES.md +67 -0
  3. package/cordis.patch.yml +4 -4
  4. package/package.json +40 -40
  5. package/src/assets.js +405 -348
  6. package/src/catalog.js +999 -605
  7. package/src/client.js +883 -4
  8. package/src/config.js +88 -88
  9. package/src/conversation-readers.js +198 -0
  10. package/src/conversation-store.js +583 -0
  11. package/src/export.js +273 -12
  12. package/src/index.js +282 -136
  13. package/src/native-transcript.js +217 -0
  14. package/src/project-archive.js +145 -145
  15. package/src/projects.js +1837 -980
  16. package/src/session-import.js +138 -93
  17. package/src/session-trace.js +121 -0
  18. package/src/skill-handoff.js +1327 -0
  19. package/src/skill-package.js +417 -0
  20. package/src/skill-provider.js +249 -0
  21. package/src/watch.js +319 -309
  22. package/web/Geist-OFL.txt +93 -93
  23. package/web/agent-icons/NOTICE.md +19 -19
  24. package/web/agent-icons/antigravity.svg +76 -76
  25. package/web/agent-icons/claude.svg +3 -3
  26. package/web/agent-icons/dsh.svg +58 -58
  27. package/web/agent-icons/licenses/copilot.txt +21 -21
  28. package/web/agent-icons/licenses/dsh.txt +21 -21
  29. package/web/agent-icons/licenses/gemini.txt +201 -201
  30. package/web/agent-icons/licenses/opencode.txt +21 -21
  31. package/web/agent-icons/licenses/qoder-notice.txt +18 -18
  32. package/web/agent-icons/licenses/qoder.txt +22 -22
  33. package/web/agent-icons/licenses/qwen.txt +202 -202
  34. package/web/agent-icons/qoder.svg +4 -4
  35. package/web/agent-icons/qwen.svg +5 -5
  36. package/web/agent-icons/workbuddy.svg +29 -29
  37. package/web/inline-process.css +22 -0
  38. package/web/markdown.js +225 -0
  39. package/web/panel.css +168 -151
  40. package/web/panel.html +82 -43
  41. package/web/panel.js +1316 -93
  42. package/web/project-context.js +25 -25
  43. package/web/reader.css +259 -0
  44. package/web/vendor/markdown-it-LICENSE.txt +156 -0
  45. package/web/vendor/markdown-it.mjs +3064 -0
@@ -0,0 +1,1327 @@
1
+ import { randomUUID, createHash } from 'node:crypto'
2
+ import { lstat, mkdir, readFile, realpath, rename, rm } from 'node:fs/promises'
3
+ import { homedir } from 'node:os'
4
+ import path from 'node:path'
5
+ import { verifyAssetSource } from './assets.js'
6
+ import {
7
+ SkillPackageError, copySkillPackage, readSkillPackage, snapshotIdFor, sourceState,
8
+ } from './skill-package.js'
9
+
10
+ export const PROVIDER_NAME = 'agent-bridge'
11
+ export const PROVIDER_RANK = 700
12
+ const STATE_VERSION = 1
13
+ const SKILL_DATABASE_NAME = 'state.sqlite'
14
+ const SKILL_DATABASE_VERSION = 2
15
+ const SKILL_APPLICATION_ID = 0x44534853
16
+ const TICKET_LIFETIME = 10 * 60_000
17
+ const MAX_SELECTION = 8
18
+ const labels = {
19
+ callable: 'DSH 已发现',
20
+ enable: '可为此项目启用',
21
+ handoff: '仅可带入说明',
22
+ sameName: '同名,待核对',
23
+ pending: '待确认',
24
+ disabled: '当前模式不可调用',
25
+ }
26
+
27
+ export class SkillHandoffError extends Error {
28
+ constructor(code, message, details) {
29
+ super(message)
30
+ this.name = 'SkillHandoffError'
31
+ this.code = code
32
+ this.details = details
33
+ this.status = code.startsWith('state-') || code === 'snapshot-invalid' ? 503 : 409
34
+ }
35
+ }
36
+
37
+ function keyFor(...values) {
38
+ return createHash('sha256').update(JSON.stringify(values)).digest('hex').slice(0, 24)
39
+ }
40
+
41
+ function pathKey(value) {
42
+ const normalized = path.normalize(value).replace(/^\\\\\?\\/, '')
43
+ return process.platform === 'win32' ? normalized.toLowerCase() : normalized
44
+ }
45
+
46
+ function inside(root, file) {
47
+ const relative = path.relative(pathKey(root), pathKey(file))
48
+ return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
49
+ }
50
+
51
+ export function resolveSkillStoreRoot(env = process.env, home = homedir()) {
52
+ const configFile = env.DSH_AGENT_BRIDGE_CONFIG
53
+ ? path.resolve(env.DSH_AGENT_BRIDGE_CONFIG)
54
+ : path.join(path.resolve(env.DSH_HOME || path.join(home, '.dsh')), 'agent-bridge.json')
55
+ return path.join(path.dirname(configFile), 'agent-bridge-skills')
56
+ }
57
+
58
+ export async function findProjectRoot(cwd) {
59
+ if (typeof cwd !== 'string' || !path.isAbsolute(cwd)) return undefined
60
+ let current
61
+ try {
62
+ current = await realpath(cwd)
63
+ if (!(await lstat(current)).isDirectory()) return undefined
64
+ } catch {
65
+ return undefined
66
+ }
67
+ const start = current
68
+ while (true) {
69
+ try {
70
+ const info = await lstat(path.join(current, '.git'))
71
+ if (info.isDirectory() || info.isFile()) return current
72
+ } catch { /* Walk up until a real .git marker or the filesystem root. */ }
73
+ const parent = path.dirname(current)
74
+ if (parent === current) return start
75
+ current = parent
76
+ }
77
+ }
78
+
79
+ function emptyState() {
80
+ return { version: STATE_VERSION, projects: {}, snapshots: {} }
81
+ }
82
+
83
+ function object(value) {
84
+ return value !== null && typeof value === 'object' && !Array.isArray(value)
85
+ }
86
+
87
+ function validateState(value) {
88
+ if (!object(value) || value.version !== STATE_VERSION || !object(value.projects) || !object(value.snapshots)) {
89
+ throw new SkillHandoffError('state-invalid', '技能启用记录格式无效,未修改任何文件。')
90
+ }
91
+ for (const [project, bucket] of Object.entries(value.projects)) {
92
+ if (!object(bucket) || typeof bucket.root !== 'string' || !object(bucket.activations)) {
93
+ throw new SkillHandoffError('state-invalid', '技能项目记录格式无效。', { project })
94
+ }
95
+ for (const [name, record] of Object.entries(bucket.activations)) {
96
+ if (!object(record) || typeof record.assetId !== 'string' || record.dshName !== name
97
+ || typeof record.sourceFile !== 'string' || typeof record.sourceRoot !== 'string'
98
+ || typeof record.contentHash !== 'string' || typeof record.quickHash !== 'string'
99
+ || !['snapshot', 'native'].includes(record.mode)
100
+ || (record.snapshotId !== null && typeof record.snapshotId !== 'string')
101
+ || (record.previousSnapshotId !== null && typeof record.previousSnapshotId !== 'string')) {
102
+ throw new SkillHandoffError('state-invalid', '技能启用项格式无效。', { project, name })
103
+ }
104
+ }
105
+ }
106
+ for (const [id, snapshot] of Object.entries(value.snapshots)) {
107
+ if (!object(snapshot) || snapshot.id !== id || typeof snapshot.dshName !== 'string'
108
+ || typeof snapshot.contentHash !== 'string' || typeof snapshot.quickHash !== 'string') {
109
+ throw new SkillHandoffError('state-invalid', '技能快照记录格式无效。', { snapshot: id })
110
+ }
111
+ }
112
+ return value
113
+ }
114
+
115
+ export class SkillActivationStore {
116
+ constructor(root) {
117
+ if (typeof root !== 'string' || !path.isAbsolute(root)) throw new TypeError('Skill store root must be absolute')
118
+ this.root = path.resolve(root)
119
+ this.stateFile = path.join(this.root, 'state.json')
120
+ this.databaseFile = path.join(this.root, SKILL_DATABASE_NAME)
121
+ this.bundlesDir = path.join(this.root, 'bundles')
122
+ this.stagingDir = path.join(this.root, 'staging')
123
+ }
124
+
125
+ async read() {
126
+ const databaseExists = await this.#databaseExists()
127
+ const legacyExists = await this.#legacyExists()
128
+ if (!databaseExists && !legacyExists) return emptyState()
129
+ if (databaseExists) {
130
+ try {
131
+ return await this.#withDatabase(false, db => {
132
+ if (!this.#schemaReady(db)) throw this.#uninitializedDatabase()
133
+ if (legacyExists && !this.#migrationDone(db)) throw this.#uninitializedDatabase()
134
+ return this.#loadState(db)
135
+ })
136
+ } catch (error) {
137
+ if (error?.code !== 'skill-db-uninitialized') throw error
138
+ }
139
+ }
140
+ const legacy = await this.#readLegacyState()
141
+ if (!legacy) return emptyState()
142
+ return this.#withDatabase(true, db => this.#loadState(db), legacy)
143
+ }
144
+
145
+ async readDirect() {
146
+ return this.read()
147
+ }
148
+
149
+ async #databaseExists() {
150
+ try {
151
+ const info = await lstat(this.databaseFile)
152
+ if (!info.isFile() || info.nlink > 1) {
153
+ throw new SkillHandoffError('state-invalid', '技能状态数据库必须是独立常规文件。')
154
+ }
155
+ return true
156
+ } catch (error) {
157
+ if (error.code === 'ENOENT') return false
158
+ if (error instanceof SkillHandoffError) throw error
159
+ throw new SkillHandoffError('state-unreadable', '无法读取技能状态数据库。', { cause: error })
160
+ }
161
+ }
162
+
163
+ async #legacyExists() {
164
+ try {
165
+ const info = await lstat(this.stateFile)
166
+ if (!info.isFile() || info.nlink > 1) {
167
+ throw new SkillHandoffError('state-invalid', '旧的技能启用记录必须是独立常规文件。')
168
+ }
169
+ return true
170
+ } catch (error) {
171
+ if (error.code === 'ENOENT') return false
172
+ if (error instanceof SkillHandoffError) throw error
173
+ throw new SkillHandoffError('state-unreadable', '无法检查旧的技能启用记录。', { cause: error })
174
+ }
175
+ }
176
+
177
+ async #readLegacyState() {
178
+ let text
179
+ try {
180
+ const info = await lstat(this.stateFile)
181
+ if (!info.isFile() || info.nlink > 1) {
182
+ throw new SkillHandoffError('state-invalid', '技能启用记录必须是独立常规文件。')
183
+ }
184
+ text = await readFile(this.stateFile, 'utf8')
185
+ } catch (error) {
186
+ if (error.code === 'ENOENT') return undefined
187
+ if (error instanceof SkillHandoffError) throw error
188
+ throw new SkillHandoffError('state-unreadable', '无法读取技能启用记录。', { cause: error })
189
+ }
190
+ let parsed
191
+ try {
192
+ parsed = JSON.parse(text)
193
+ } catch {
194
+ throw new SkillHandoffError('state-invalid', '技能启用记录不是有效 JSON。')
195
+ }
196
+ return validateState(parsed)
197
+ }
198
+
199
+ #uninitializedDatabase() {
200
+ return Object.assign(new Error('技能状态数据库尚未初始化。'), { code: 'skill-db-uninitialized' })
201
+ }
202
+
203
+ async #withDatabase(write, operation, legacyState) {
204
+ if (write) await mkdir(this.root, { recursive: true })
205
+ const { DatabaseSync } = await import('node:sqlite')
206
+ const db = new DatabaseSync(this.databaseFile, { readOnly: !write })
207
+ try {
208
+ db.exec('PRAGMA busy_timeout = 5000; PRAGMA trusted_schema = OFF')
209
+ db.exec(write ? 'BEGIN IMMEDIATE' : 'BEGIN')
210
+ try {
211
+ if (write) {
212
+ this.#ensureSchema(db)
213
+ if (legacyState && !this.#migrationDone(db)) this.#migrateLegacy(db, legacyState)
214
+ } else if (!this.#schemaReady(db)) {
215
+ throw this.#uninitializedDatabase()
216
+ }
217
+ const result = operation(db)
218
+ db.exec('COMMIT')
219
+ return result
220
+ } catch (error) {
221
+ try { db.exec('ROLLBACK') } catch { /* SQLite may already have rolled back. */ }
222
+ throw error
223
+ }
224
+ } catch (error) {
225
+ if (error instanceof SkillHandoffError || error?.code === 'skill-db-uninitialized') throw error
226
+ throw new SkillHandoffError(
227
+ write ? 'state-write-failed' : 'state-unreadable',
228
+ write ? '无法保存技能启用记录。' : '无法读取技能启用记录。',
229
+ { cause: error },
230
+ )
231
+ } finally {
232
+ db.close()
233
+ }
234
+ }
235
+
236
+ #ensureSchema(db) {
237
+ const applicationId = Number(db.prepare('PRAGMA application_id').get()?.application_id ?? 0)
238
+ const hasTables = Boolean(db.prepare('SELECT 1 FROM sqlite_schema LIMIT 1').get())
239
+ if (applicationId === 0) {
240
+ if (hasTables) throw new SkillHandoffError('state-invalid', '技能状态数据库不是 Agent Bridge 存储。')
241
+ db.exec(`PRAGMA application_id = ${SKILL_APPLICATION_ID}`)
242
+ } else if (applicationId !== SKILL_APPLICATION_ID) {
243
+ throw new SkillHandoffError('state-invalid', '技能状态数据库不是 Agent Bridge 存储。')
244
+ }
245
+ db.exec(`
246
+ CREATE TABLE IF NOT EXISTS skill_projects (
247
+ project_key TEXT PRIMARY KEY,
248
+ root TEXT NOT NULL
249
+ ) STRICT;
250
+ CREATE TABLE IF NOT EXISTS skill_activations (
251
+ project_key TEXT NOT NULL,
252
+ dsh_name TEXT NOT NULL,
253
+ record_json TEXT NOT NULL,
254
+ PRIMARY KEY (project_key, dsh_name)
255
+ ) STRICT;
256
+ CREATE TABLE IF NOT EXISTS skill_snapshots (
257
+ snapshot_id TEXT PRIMARY KEY,
258
+ snapshot_json TEXT NOT NULL
259
+ ) STRICT;
260
+ CREATE TABLE IF NOT EXISTS skill_revisions (
261
+ project_key TEXT NOT NULL,
262
+ dsh_name TEXT NOT NULL,
263
+ revision INTEGER NOT NULL,
264
+ PRIMARY KEY (project_key, dsh_name)
265
+ ) STRICT;
266
+ CREATE TABLE IF NOT EXISTS skill_meta (
267
+ key TEXT PRIMARY KEY,
268
+ value TEXT NOT NULL
269
+ ) STRICT;
270
+ `)
271
+ db.prepare(`INSERT INTO skill_meta (key, value) VALUES ('schema_version', ?)
272
+ ON CONFLICT (key) DO NOTHING`).run(String(SKILL_DATABASE_VERSION))
273
+ db.prepare(`INSERT INTO skill_meta (key, value) VALUES ('state_revision', '0')
274
+ ON CONFLICT (key) DO NOTHING`).run()
275
+ }
276
+
277
+ #schemaReady(db) {
278
+ const applicationId = Number(db.prepare('PRAGMA application_id').get()?.application_id ?? 0)
279
+ return applicationId === SKILL_APPLICATION_ID
280
+ && Boolean(db.prepare("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'skill_activations'").get())
281
+ && Boolean(db.prepare("SELECT 1 FROM sqlite_schema WHERE type = 'table' AND name = 'skill_revisions'").get())
282
+ }
283
+
284
+ #migrationDone(db) {
285
+ return Boolean(db.prepare("SELECT 1 FROM skill_meta WHERE key = 'legacy-json-migrated'").get())
286
+ }
287
+
288
+ #migrateLegacy(db, state) {
289
+ const project = db.prepare(`INSERT INTO skill_projects (project_key, root) VALUES (?, ?)
290
+ ON CONFLICT (project_key) DO UPDATE SET root = excluded.root`)
291
+ const activation = db.prepare(`INSERT INTO skill_activations (project_key, dsh_name, record_json)
292
+ VALUES (?, ?, ?) ON CONFLICT (project_key, dsh_name) DO NOTHING`)
293
+ const snapshot = db.prepare(`INSERT INTO skill_snapshots (snapshot_id, snapshot_json)
294
+ VALUES (?, ?) ON CONFLICT (snapshot_id) DO NOTHING`)
295
+ for (const [projectKey, bucket] of Object.entries(state.projects)) {
296
+ project.run(projectKey, bucket.root)
297
+ for (const [name, record] of Object.entries(bucket.activations)) {
298
+ activation.run(projectKey, name, JSON.stringify(record))
299
+ db.prepare(`INSERT INTO skill_revisions (project_key, dsh_name, revision)
300
+ VALUES (?, ?, 1) ON CONFLICT (project_key, dsh_name) DO NOTHING`).run(projectKey, name)
301
+ }
302
+ }
303
+ for (const [id, value] of Object.entries(state.snapshots)) {
304
+ snapshot.run(id, JSON.stringify(value))
305
+ }
306
+ db.prepare(`INSERT INTO skill_meta (key, value) VALUES ('legacy-json-migrated', '1')
307
+ ON CONFLICT (key) DO NOTHING`).run()
308
+ }
309
+
310
+ #loadState(db) {
311
+ const projects = {}
312
+ for (const project of db.prepare('SELECT project_key, root FROM skill_projects ORDER BY project_key').all()) {
313
+ projects[project.project_key] = { root: project.root, activations: {} }
314
+ }
315
+ for (const row of db.prepare('SELECT project_key, dsh_name, record_json FROM skill_activations').all()) {
316
+ if (!projects[row.project_key]) continue
317
+ projects[row.project_key].activations[row.dsh_name] = JSON.parse(row.record_json)
318
+ }
319
+ const snapshots = {}
320
+ for (const row of db.prepare('SELECT snapshot_id, snapshot_json FROM skill_snapshots').all()) {
321
+ snapshots[row.snapshot_id] = JSON.parse(row.snapshot_json)
322
+ }
323
+ return validateState({ version: STATE_VERSION, projects, snapshots })
324
+ }
325
+
326
+ #loadRevisions(db) {
327
+ return Object.fromEntries(db.prepare('SELECT project_key, dsh_name, revision FROM skill_revisions')
328
+ .all().map(row => [`${row.project_key}\0${row.dsh_name}`, row.revision]))
329
+ }
330
+
331
+ #stateRevision(db) {
332
+ return Number(db.prepare("SELECT value FROM skill_meta WHERE key = 'state_revision'").get()?.value ?? 0)
333
+ }
334
+
335
+ #bumpStateRevision(db) {
336
+ db.prepare(`INSERT INTO skill_meta (key, value) VALUES ('state_revision', '1')
337
+ ON CONFLICT (key) DO UPDATE SET value = CAST(CAST(value AS INTEGER) + 1 AS TEXT)`).run()
338
+ }
339
+
340
+ #getRevision(db, projectKey, dshName) {
341
+ return Number(db.prepare('SELECT revision FROM skill_revisions WHERE project_key = ? AND dsh_name = ?')
342
+ .get(projectKey, dshName)?.revision ?? 0)
343
+ }
344
+
345
+ #bumpRevision(db, projectKey, dshName) {
346
+ db.prepare(`INSERT INTO skill_revisions (project_key, dsh_name, revision) VALUES (?, ?, 1)
347
+ ON CONFLICT (project_key, dsh_name) DO UPDATE SET revision = skill_revisions.revision + 1`)
348
+ .run(projectKey, dshName)
349
+ }
350
+
351
+ #upsertProject(db, projectKey, root) {
352
+ db.prepare(`INSERT INTO skill_projects (project_key, root) VALUES (?, ?)
353
+ ON CONFLICT (project_key) DO UPDATE SET root = excluded.root`).run(projectKey, root)
354
+ }
355
+
356
+ #upsertActivation(db, projectKey, name, record) {
357
+ db.prepare(`INSERT INTO skill_activations (project_key, dsh_name, record_json) VALUES (?, ?, ?)
358
+ ON CONFLICT (project_key, dsh_name) DO UPDATE SET record_json = excluded.record_json`)
359
+ .run(projectKey, name, JSON.stringify(record))
360
+ }
361
+
362
+ #upsertSnapshot(db, snapshot) {
363
+ db.prepare(`INSERT INTO skill_snapshots (snapshot_id, snapshot_json) VALUES (?, ?)
364
+ ON CONFLICT (snapshot_id) DO UPDATE SET snapshot_json = excluded.snapshot_json`)
365
+ .run(snapshot.id, JSON.stringify(snapshot))
366
+ }
367
+
368
+ async recordActivations(root, entries) {
369
+ if (!Array.isArray(entries)) throw new TypeError('Skill records must be an array')
370
+ await this.read()
371
+ return this.#withDatabase(true, db => {
372
+ const projectKey = pathKey(root)
373
+ this.#upsertProject(db, projectKey, root)
374
+ for (const entry of entries) {
375
+ const existing = db.prepare('SELECT record_json FROM skill_activations WHERE project_key = ? AND dsh_name = ?')
376
+ .get(projectKey, entry.dshName)
377
+ const currentRevision = this.#getRevision(db, projectKey, entry.dshName)
378
+ const expectedRevision = entry.expectedRevision
379
+ if (existing) {
380
+ const current = JSON.parse(existing.record_json)
381
+ const sameSource = sameFile(current.sourceFile, entry.record.sourceFile)
382
+ const sameContent = current.contentHash === entry.record.contentHash
383
+ if (!sameSource) {
384
+ throw new SkillHandoffError('name-conflict', '这个项目已经启用了同名但来源不同的技能,未替换原技能。')
385
+ }
386
+ if (expectedRevision !== undefined && expectedRevision !== currentRevision) {
387
+ if (sameContent) continue
388
+ throw new SkillHandoffError('preview-stale', '技能登记已变化,请重新预览后再提交。')
389
+ }
390
+ if (sameContent) continue
391
+ } else if (expectedRevision !== undefined && expectedRevision !== currentRevision) {
392
+ throw new SkillHandoffError('preview-stale', '技能登记已变化,请重新预览后再提交。')
393
+ }
394
+ this.#upsertActivation(db, projectKey, entry.dshName, entry.record)
395
+ this.#bumpRevision(db, projectKey, entry.dshName)
396
+ this.#bumpStateRevision(db)
397
+ if (entry.snapshot) this.#upsertSnapshot(db, entry.snapshot)
398
+ }
399
+ return this.#loadState(db)
400
+ })
401
+ }
402
+
403
+ async removeActivation(root, activationId) {
404
+ await this.read()
405
+ return this.#withDatabase(true, db => {
406
+ const projectKey = pathKey(root)
407
+ const rows = db.prepare('SELECT dsh_name, record_json FROM skill_activations WHERE project_key = ?').all(projectKey)
408
+ const entry = rows.map(row => [row.dsh_name, JSON.parse(row.record_json)])
409
+ .find(([, record]) => record.id === activationId)
410
+ if (!entry) throw new SkillHandoffError('activation-missing', '找不到该项目的技能启用记录。')
411
+ db.prepare('DELETE FROM skill_activations WHERE project_key = ? AND dsh_name = ?').run(projectKey, entry[0])
412
+ this.#bumpRevision(db, projectKey, entry[0])
413
+ this.#bumpStateRevision(db)
414
+ return { record: entry[1], dshName: entry[0], projectRoot: root, state: this.#loadState(db) }
415
+ })
416
+ }
417
+
418
+ async updateActivation(root, activationId, expected, next) {
419
+ if (!expected || !next) throw new TypeError('Activation records are required')
420
+ await this.read()
421
+ return this.#withDatabase(true, db => {
422
+ const projectKey = pathKey(root)
423
+ const rows = db.prepare('SELECT dsh_name, record_json FROM skill_activations WHERE project_key = ?').all(projectKey)
424
+ const entry = rows.map(row => [row.dsh_name, JSON.parse(row.record_json)])
425
+ .find(([, record]) => record.id === activationId)
426
+ if (!entry) throw new SkillHandoffError('activation-missing', '找不到该项目的技能启用记录。')
427
+ if (entry[0] !== expected.dshName
428
+ || JSON.stringify(entry[1]) !== JSON.stringify(expected)) {
429
+ throw new SkillHandoffError('activation-changed', '技能启用记录已变化,请重新读取后再试。')
430
+ }
431
+ this.#upsertProject(db, projectKey, root)
432
+ this.#upsertActivation(db, projectKey, next.dshName, next)
433
+ this.#bumpRevision(db, projectKey, next.dshName)
434
+ this.#bumpStateRevision(db)
435
+ return { dshName: next.dshName, activationId: next.id, state: this.#loadState(db) }
436
+ })
437
+ }
438
+
439
+ async readVersioned() {
440
+ await this.read()
441
+ if (!await this.#databaseExists()) return { state: emptyState(), revisions: {} }
442
+ return this.#withDatabase(false, db => ({
443
+ state: this.#loadState(db),
444
+ revisions: this.#loadRevisions(db),
445
+ revision: this.#stateRevision(db),
446
+ }))
447
+ }
448
+
449
+ async skillRevision(root, dshName) {
450
+ const { revisions } = await this.readVersioned()
451
+ return revisions[`${pathKey(root)}\0${dshName}`] ?? 0
452
+ }
453
+
454
+ async revision() {
455
+ return (await this.readVersioned()).revision ?? 0
456
+ }
457
+
458
+ snapshotPath(id) {
459
+ return path.join(this.bundlesDir, id)
460
+ }
461
+ }
462
+
463
+ function projectBucket(state, root, create = false) {
464
+ const key = pathKey(root)
465
+ if (!create) return state.projects[key]
466
+ state.projects[key] ??= { root, activations: {} }
467
+ state.projects[key].root = root
468
+ return state.projects[key]
469
+ }
470
+
471
+ function activationId(root, name) {
472
+ return keyFor('skill-activation', pathKey(root), name)
473
+ }
474
+
475
+ function sanitizeItem(item) {
476
+ return {
477
+ assetId: item.assetId,
478
+ name: item.sourceName,
479
+ dshName: item.dshName,
480
+ state: item.state,
481
+ action: item.action,
482
+ label: item.label,
483
+ detail: item.detail,
484
+ reason: item.reason,
485
+ allowed: item.allowed,
486
+ current: item.current,
487
+ registered: item.registered,
488
+ discovered: item.discovered,
489
+ verified: item.verified,
490
+ activationId: item.activationId,
491
+ sourceChanged: item.sourceChanged,
492
+ expectedRevision: item.expectedRevision,
493
+ manualOnly: item.manualOnly,
494
+ modelInvocable: item.modelInvocable,
495
+ userInvocable: item.userInvocable,
496
+ disabled: item.disabled,
497
+ canOmitBody: item.canOmitBody,
498
+ hasScripts: item.hasScripts,
499
+ scriptFiles: item.scriptFiles,
500
+ fileCount: item.fileCount,
501
+ bytes: item.bytes,
502
+ resources: item.resources,
503
+ scopeRoot: item.scopeRoot,
504
+ }
505
+ }
506
+
507
+ function sameFile(first, second) {
508
+ return typeof first === 'string' && typeof second === 'string' && pathKey(first) === pathKey(second)
509
+ }
510
+
511
+ function normalizedInvocation(invocation) {
512
+ if (typeof invocation?.modelInvocable !== 'boolean'
513
+ || typeof invocation?.userInvocable !== 'boolean') return undefined
514
+ return {
515
+ modelInvocable: invocation.modelInvocable,
516
+ userInvocable: invocation.userInvocable,
517
+ }
518
+ }
519
+
520
+ const unknownPolicy = {
521
+ modelInvocable: false,
522
+ userInvocable: false,
523
+ manualOnly: false,
524
+ disabled: false,
525
+ canOmitBody: false,
526
+ }
527
+
528
+ export class SkillHandoff {
529
+ constructor({ store, native, validateBundle, invalidate, logger = console, clock = Date.now } = {}) {
530
+ if (!store) throw new TypeError('SkillHandoff requires a store')
531
+ this.store = store
532
+ this.native = native
533
+ this.validateBundle = validateBundle
534
+ this.invalidate = invalidate ?? (() => {})
535
+ this.logger = logger
536
+ this.clock = clock
537
+ this.tickets = new Map()
538
+ }
539
+
540
+ async #nativeList(root) {
541
+ if (!this.native?.list) return { ok: false, summaries: [] }
542
+ try {
543
+ return { ok: true, summaries: await this.native.list({ cwd: root }) }
544
+ } catch (error) {
545
+ this.logger.warn?.(`agent-bridge: skill lookup failed: ${error.message ?? error}`)
546
+ return { ok: false, summaries: [] }
547
+ }
548
+ }
549
+
550
+ async #sameNamedNative(item, root, summaries) {
551
+ return summaries.find(summary => summary.name === item.dshName && summary.provider !== PROVIDER_NAME)
552
+ }
553
+
554
+ async #nativeSkill(summary, root) {
555
+ if (!summary || !this.native?.get) return undefined
556
+ try {
557
+ const definition = await this.native.get(summary.name, { cwd: root })
558
+ if (!definition) return undefined
559
+ const skillPackage = definition.resourceBase?.kind === 'directory'
560
+ ? await readSkillPackage(path.join(definition.resourceBase.path, 'SKILL.md'), { content: true })
561
+ : undefined
562
+ return {
563
+ definition,
564
+ invocation: normalizedInvocation(definition.invocation),
565
+ package: skillPackage,
566
+ }
567
+ } catch {
568
+ return undefined
569
+ }
570
+ }
571
+
572
+ async #nativePackage(summary, root) {
573
+ return (await this.#nativeSkill(summary, root))?.package
574
+ }
575
+
576
+ #policy(invocation) {
577
+ const modelInvocable = invocation?.modelInvocable !== false
578
+ const userInvocable = invocation?.userInvocable !== false
579
+ return {
580
+ modelInvocable,
581
+ userInvocable,
582
+ manualOnly: !modelInvocable && userInvocable,
583
+ disabled: !modelInvocable && !userInvocable,
584
+ canOmitBody: modelInvocable || userInvocable,
585
+ }
586
+ }
587
+
588
+ async inspect(project, skills) {
589
+ const root = await findProjectRoot(project.cwd)
590
+ const state = await this.store.read()
591
+ const native = root ? await this.#nativeList(root) : { ok: false, summaries: [] }
592
+ const statuses = {}
593
+ await Promise.all(skills.map(async asset => {
594
+ statuses[asset.id] = await this.#inspectAsset(asset, root, state, native)
595
+ }))
596
+ const managedSkills = await this.#managedSkills(root, state, native, skills, statuses)
597
+ return {
598
+ available: Boolean(native.ok && root),
599
+ projectRoot: root,
600
+ skills: statuses,
601
+ managedSkills,
602
+ }
603
+ }
604
+
605
+ async revision() {
606
+ return this.store.revision()
607
+ }
608
+
609
+ async #managedSkills(root, state, native, assets, statuses) {
610
+ if (!root) return []
611
+ const bucket = projectBucket(state, root)
612
+ const result = []
613
+ for (const [dshName, record] of Object.entries(bucket?.activations ?? {})) {
614
+ const asset = assets.find(item => item.id === record.assetId || sameFile(item.file, record.sourceFile))
615
+ const current = asset ? statuses[asset.id] : undefined
616
+ const verification = await this.#verifyRecord(record, native.summaries, root)
617
+ const verified = verification.verified
618
+ let sourceState = current?.sourceState
619
+ if (!sourceState) {
620
+ sourceState = await lstat(record.sourceFile).then(info => info.isFile() ? 'changed' : 'missing').catch(() => 'missing')
621
+ }
622
+ const policy = verification.policy ?? unknownPolicy
623
+ const label = !verified ? labels.pending
624
+ : policy.disabled ? labels.disabled : labels.callable
625
+ result.push({
626
+ activationId: record.id,
627
+ assetId: record.assetId,
628
+ dshName,
629
+ sourceName: record.sourceName,
630
+ sourceFile: record.sourceFile,
631
+ mode: record.mode,
632
+ snapshotId: record.snapshotId,
633
+ updatedAt: record.updatedAt,
634
+ sourceState,
635
+ sourceChanged: sourceState !== 'same',
636
+ canUndo: Boolean(record.previousSnapshotId),
637
+ registered: true,
638
+ discovered: verification.discovered,
639
+ verified,
640
+ label,
641
+ state: !verified ? 'pending' : policy.disabled ? 'disabled' : 'active',
642
+ action: 'manage',
643
+ allowed: true,
644
+ ...policy,
645
+ detail: !verified ? '启用记录已保存,等待 DSH 确认当前快照。'
646
+ : sourceState === 'missing' ? '来源已移除,仍可使用私有快照。'
647
+ : sourceState !== 'same' ? '来源有变化,当前仍使用已确认快照。'
648
+ : policy.manualOnly ? '仅可手动调用;模型自动入口未开放。'
649
+ : '当前项目已登记,DSH 可发现该技能。',
650
+ })
651
+ }
652
+ return result.sort((left, right) => left.dshName.localeCompare(right.dshName))
653
+ }
654
+
655
+ async #inspectAsset(asset, root, state, native) {
656
+ const handoff = detail => ({
657
+ label: labels.handoff, state: 'handoff', action: 'view', allowed: false,
658
+ current: false, sourceChanged: false, registered: false, discovered: false, verified: false, ...detail,
659
+ })
660
+ if (!root) return handoff({ reason: '当前项目目录不可访问,不能确认 DSH 项目范围。' })
661
+ if (!native.ok) return handoff({ reason: '当前 DSH 未提供原生技能服务。' })
662
+
663
+ if (asset.scope !== 'project') {
664
+ let discovered
665
+ let authorization
666
+ try {
667
+ authorization = await verifyAssetSource(asset)
668
+ discovered = await readSkillPackage(asset.file, { content: false, authorization })
669
+ } catch (error) {
670
+ return handoff({ reason: error.message })
671
+ }
672
+ const nativeSkill = native.summaries.find(item => item.name === discovered.name)
673
+ if (nativeSkill && sameFile(nativeSkill.path, asset.file)) {
674
+ const effective = await this.#nativeSkill(nativeSkill, root)
675
+ if (!effective) return handoff({ reason: 'DSH 已发现同名技能,但当前无法确认实际生效版本。' })
676
+ if (!effective.invocation) {
677
+ return {
678
+ ...handoff({
679
+ dshName: discovered.name,
680
+ reason: 'DSH 已发现该技能,但无法确认当前生效副本的模型与手动调用策略。',
681
+ }),
682
+ state: 'pending',
683
+ discovered: true,
684
+ ...unknownPolicy,
685
+ }
686
+ }
687
+ const policy = this.#policy(effective.invocation)
688
+ return {
689
+ label: policy.disabled ? labels.disabled : labels.callable,
690
+ state: policy.disabled ? 'disabled' : 'native', action: 'view', allowed: false,
691
+ current: true, sourceChanged: false, dshName: discovered.name,
692
+ ...policy,
693
+ invocation: effective.invocation,
694
+ verified: true,
695
+ discovered: true,
696
+ registered: false,
697
+ detail: policy.disabled
698
+ ? '模型与手动调用均已禁用。'
699
+ : policy.manualOnly ? '仅可手动调用;模型自动入口未开放。'
700
+ : '由 DSH 原生来源发现,无需为项目再次复制。',
701
+ }
702
+ }
703
+ }
704
+
705
+ const bucket = projectBucket(state, root)
706
+ const currentRecord = Object.values(bucket?.activations ?? {}).find(record => (
707
+ record.assetId === asset.id || sameFile(record.sourceFile, asset.file)
708
+ ))
709
+ if (currentRecord) {
710
+ let source = 'same'
711
+ let authorization
712
+ try {
713
+ authorization = await verifyAssetSource(asset)
714
+ source = await sourceState(currentRecord.sourceFile, currentRecord, { authorization })
715
+ } catch {
716
+ source = 'invalid'
717
+ }
718
+ const sourceChanged = source !== 'same'
719
+ const verification = await this.#verifyRecord(currentRecord, native.summaries, root)
720
+ if (!verification.verified) {
721
+ return {
722
+ label: labels.pending, state: 'pending', action: 'manage', allowed: true,
723
+ current: false, activationId: currentRecord.id, dshName: currentRecord.dshName,
724
+ sourceChanged, sourceState: source, ...unknownPolicy, invocation: undefined,
725
+ registered: true, discovered: verification.discovered, verified: false,
726
+ canUndo: Boolean(currentRecord.previousSnapshotId),
727
+ reason: '已保存启用记录,但 DSH 当前生效版本、内容或调用策略无法确认;草稿会保留技能正文。',
728
+ }
729
+ }
730
+ const policy = verification.policy
731
+ return {
732
+ label: policy.disabled ? labels.disabled : labels.callable,
733
+ state: policy.disabled ? 'disabled' : 'active',
734
+ action: source === 'missing' ? 'deactivate' : sourceChanged ? 'preview-update' : 'deactivate',
735
+ allowed: true, current: true, activationId: currentRecord.id, dshName: currentRecord.dshName,
736
+ sourceChanged, sourceState: source, ...policy, invocation: verification.invocation,
737
+ registered: true, discovered: true, verified: true,
738
+ canUndo: Boolean(currentRecord.previousSnapshotId),
739
+ detail: source === 'missing' ? '来源已移除;当前私有快照仍可调用。'
740
+ : sourceChanged ? '来源有变化,更新需要重新预览。'
741
+ : policy.disabled ? '模型与手动调用均已禁用。'
742
+ : policy.manualOnly ? '仅可手动调用;模型自动入口未开放。'
743
+ : '当前项目已登记,DSH 可发现该技能。',
744
+ }
745
+ }
746
+
747
+ let skill
748
+ let authorization
749
+ try {
750
+ authorization = await verifyAssetSource(asset)
751
+ skill = await readSkillPackage(asset.file, { content: false, authorization })
752
+ } catch (error) {
753
+ return handoff({ reason: error.message })
754
+ }
755
+ if (skill.layout !== 'directory') return handoff({ reason: '扁平 Markdown Skill 不包含完整技能包。' })
756
+
757
+ const record = bucket?.activations?.[skill.name]
758
+ const summary = native.summaries.find(item => item.name === skill.name)
759
+ if (record) {
760
+ const sourceChanged = true
761
+ if (!sameFile(record.sourceFile, asset.file)) {
762
+ return handoff({
763
+ dshName: skill.name,
764
+ activationId: record.id,
765
+ reason: '这个项目已有同名技能;首版保留原有来源,不自动替换。',
766
+ })
767
+ }
768
+ return {
769
+ label: labels.callable, state: 'active', action: 'preview-update',
770
+ allowed: true, current: true, activationId: record.id, dshName: skill.name, sourceChanged,
771
+ detail: '来源有变化,更新需要重新预览。',
772
+ }
773
+ }
774
+
775
+ if (summary && sameFile(summary.path, asset.file)) {
776
+ const effective = await this.#nativeSkill(summary, root)
777
+ if (!effective) {
778
+ return {
779
+ label: labels.pending, state: 'pending', action: 'view', allowed: false,
780
+ current: false, sourceChanged: false, dshName: skill.name,
781
+ registered: false, discovered: true, verified: false,
782
+ reason: 'DSH 已发现同名技能,但无法读取当前生效定义。',
783
+ }
784
+ }
785
+ if (!effective.invocation) {
786
+ return {
787
+ label: labels.pending, state: 'pending', action: 'view', allowed: false,
788
+ current: false, sourceChanged: false, dshName: skill.name,
789
+ registered: false, discovered: true, verified: false, ...unknownPolicy,
790
+ reason: 'DSH 已发现该技能,但无法确认当前生效副本的模型与手动调用策略。',
791
+ }
792
+ }
793
+ const policy = this.#policy(effective.invocation)
794
+ return {
795
+ label: policy.disabled ? labels.disabled : labels.callable,
796
+ state: policy.disabled ? 'disabled' : 'native', action: 'view', allowed: false,
797
+ current: true, sourceChanged: false, dshName: skill.name,
798
+ ...policy, invocation: effective.invocation,
799
+ registered: false, discovered: true, verified: true,
800
+ detail: policy.disabled ? '模型与手动调用均已禁用。'
801
+ : policy.manualOnly ? '仅可手动调用;模型自动入口未开放。'
802
+ : '由 DSH 原生来源发现,无需再复制。',
803
+ }
804
+ }
805
+ if (summary) {
806
+ return {
807
+ label: labels.sameName, state: 'unverified', action: 'view', allowed: false,
808
+ current: false, sourceChanged: false, dshName: skill.name,
809
+ registered: false, discovered: true, verified: false,
810
+ reason: 'DSH 已有同名技能;详情中可核对内容是否相同,未核对前保留原技能。',
811
+ }
812
+ }
813
+ return {
814
+ label: labels.enable, state: 'available', action: 'enable', allowed: true,
815
+ current: false, sourceChanged: false, dshName: skill.name,
816
+ registered: false, discovered: false, verified: false,
817
+ ...this.#policy(skill.invocation), invocation: skill.invocation,
818
+ detail: skill.invocation.modelInvocable
819
+ ? '完整包可复制到 DSH 私有目录,只对当前项目根生效。'
820
+ : '完整包可启用,但技能声明为仅可手动调用。',
821
+ }
822
+ }
823
+
824
+ async conversationCandidates(project, usedSkills) {
825
+ const used = new Set((usedSkills ?? []).map(name => String(name).toLowerCase()))
826
+ if (!used.size) return []
827
+ const root = await findProjectRoot(project.cwd)
828
+ if (!root) return []
829
+ const { skills } = await this.inspect(project, project.skillAssets ?? [])
830
+ return (project.skillAssets ?? []).filter(asset => {
831
+ const status = skills[asset.id]
832
+ return status && (used.has(String(asset.name).toLowerCase())
833
+ || used.has(String(status.dshName).toLowerCase()))
834
+ }).slice(0, 3).map(asset => ({ assetId: asset.id, ...status }))
835
+ }
836
+
837
+ async authorizeTextOmission(project, assets) {
838
+ const inspected = await this.inspect(project, assets)
839
+ return assets.map(asset => {
840
+ const status = inspected.skills[asset.id]
841
+ if (!status?.verified || !status.canOmitBody
842
+ || !['active', 'native'].includes(status.state)) {
843
+ throw new SkillHandoffError(
844
+ 'skill-not-active',
845
+ `技能「${status?.dshName || asset.name}」尚未确认由当前 DSH 项目原生提供,不能省略正文。`,
846
+ )
847
+ }
848
+ return {
849
+ assetId: asset.id,
850
+ dshName: status.dshName,
851
+ invocation: status.invocation,
852
+ }
853
+ })
854
+ }
855
+
856
+ async preview(project, assets) {
857
+ if (!Array.isArray(assets) || !assets.length || assets.length > MAX_SELECTION) {
858
+ throw new SkillHandoffError('invalid-selection', `每次最多预览 ${MAX_SELECTION} 个技能。`)
859
+ }
860
+ const root = await findProjectRoot(project.cwd)
861
+ if (!root) throw new SkillHandoffError('project-unavailable', '当前项目目录不可访问。')
862
+ const native = await this.#nativeList(root)
863
+ if (!native.ok) throw new SkillHandoffError('native-unavailable', '当前 DSH 未提供原生技能服务。')
864
+ const { state, revisions } = await this.store.readVersioned()
865
+ const items = []
866
+ for (const asset of assets) {
867
+ items.push(await this.#previewAsset(project, asset, root, state, native.summaries, revisions))
868
+ }
869
+ const counts = new Map()
870
+ for (const item of items) counts.set(item.dshName, (counts.get(item.dshName) ?? 0) + 1)
871
+ for (const item of items) {
872
+ if ((counts.get(item.dshName) ?? 0) > 1) {
873
+ item.action = 'conflict'
874
+ item.allowed = false
875
+ item.label = labels.handoff
876
+ item.reason = '本次选择的技能包使用了同一个 DSH 技能名。'
877
+ }
878
+ }
879
+ const ticket = randomUUID()
880
+ for (const [id, record] of this.tickets) {
881
+ if (this.clock() - record.created > TICKET_LIFETIME) this.tickets.delete(id)
882
+ }
883
+ if (this.tickets.size >= 40) this.tickets.delete(this.tickets.keys().next().value)
884
+ this.tickets.set(ticket, {
885
+ created: this.clock(), projectId: project.id, projectRoot: root, items,
886
+ })
887
+ return { ticket, projectRoot: root, items: items.map(sanitizeItem) }
888
+ }
889
+
890
+ async #previewAsset(project, asset, root, state, summaries, revisions) {
891
+ const base = {
892
+ assetId: asset.id, sourceName: asset.name, scopeRoot: root, activationId: null,
893
+ sourceChanged: false, hasScripts: false, scriptFiles: [], fileCount: 0, bytes: 0,
894
+ current: false, registered: false, discovered: false, verified: false,
895
+ resources: { scripts: 0, references: 0, assets: 0 }, state: 'available',
896
+ }
897
+ let skill
898
+ let authorization
899
+ try {
900
+ authorization = await verifyAssetSource(asset)
901
+ skill = await readSkillPackage(asset.file, { content: true, authorization })
902
+ } catch (error) {
903
+ if (error?.code === 'ASSET_SOURCE_CHANGED') {
904
+ throw new SkillHandoffError('source-changed', '技能来源已变化或离开了原授权目录,请刷新后重新预览。')
905
+ }
906
+ return { ...base, action: 'invalid', allowed: false, label: labels.handoff, reason: error.message }
907
+ }
908
+ const enriched = {
909
+ ...base,
910
+ sourceName: asset.name,
911
+ dshName: skill.name,
912
+ fileCount: skill.fileCount,
913
+ bytes: skill.bytes,
914
+ resources: skill.resources,
915
+ hasScripts: skill.hasScripts,
916
+ scriptFiles: skill.scriptFiles,
917
+ ...this.#policy(skill.invocation),
918
+ invocation: skill.invocation,
919
+ sourceFile: asset.file,
920
+ authorization,
921
+ sourceRoot: skill.sourceRoot,
922
+ contentHash: skill.contentHash,
923
+ quickHash: skill.quickHash,
924
+ expectedRevision: revisions[`${pathKey(root)}\0${skill.name}`] ?? 0,
925
+ }
926
+ if (skill.layout !== 'directory') {
927
+ return { ...enriched, action: 'invalid', allowed: false, label: labels.handoff,
928
+ reason: '只有目录技能包可以完整启用。' }
929
+ }
930
+
931
+ const bucket = projectBucket(state, root)
932
+ const record = bucket?.activations?.[skill.name]
933
+ const summary = summaries.find(item => item.name === skill.name)
934
+ if (record) {
935
+ enriched.activationId = record.id
936
+ if (!sameFile(record.sourceFile, asset.file)) {
937
+ return { ...enriched, action: 'conflict', allowed: false, label: labels.handoff,
938
+ reason: '这个项目已有同名技能;首版保留原有来源,不自动替换。' }
939
+ }
940
+ if (record.mode === 'native') {
941
+ const nativeRecord = await this.#sameNamedNative(enriched, root, summaries)
942
+ if (nativeRecord) {
943
+ const effective = await this.#nativeSkill(nativeRecord, root)
944
+ if (effective?.package?.contentHash === skill.contentHash) {
945
+ if (!effective.invocation) {
946
+ return { ...enriched, ...unknownPolicy, action: 'pending', allowed: false,
947
+ label: labels.pending, state: 'pending', current: true, verified: false,
948
+ discovered: true, registered: true,
949
+ reason: '同名同款原生技能已发现,但无法确认当前生效副本的调用策略;草稿会保留正文。' }
950
+ }
951
+ const policy = this.#policy(effective.invocation)
952
+ return {
953
+ ...enriched, ...policy, invocation: effective.invocation,
954
+ action: policy.disabled ? 'native-disabled' : 'reuse-active',
955
+ allowed: !policy.disabled,
956
+ label: policy.disabled ? labels.disabled : labels.callable,
957
+ state: policy.disabled ? 'disabled' : 'active',
958
+ current: true, verified: true, discovered: true, registered: true,
959
+ detail: policy.disabled ? '同名同款原生技能的模型与手动调用均已禁用。'
960
+ : '当前项目继续复用相同的 DSH 原生技能。',
961
+ }
962
+ }
963
+ return { ...enriched, action: 'conflict', allowed: false, label: labels.handoff,
964
+ reason: 'DSH 的同名原生技能仍在且内容不同;首版保留原生技能。' }
965
+ }
966
+ return { ...enriched, action: 'enable', allowed: true, label: labels.enable,
967
+ current: false, detail: '之前的同名原生技能已不可用;可保存当前完整包。' }
968
+ }
969
+ if (record.contentHash === skill.contentHash) {
970
+ const verification = await this.#verifyRecord(record, summaries, root)
971
+ if (!verification.verified) {
972
+ return { ...enriched, ...unknownPolicy, action: 'pending', allowed: false,
973
+ label: labels.pending, state: 'pending', current: true, registered: true,
974
+ discovered: verification.discovered, verified: false,
975
+ reason: 'DSH 当前生效版本、内容或调用策略与已确认记录不一致;草稿会保留技能正文。' }
976
+ }
977
+ const policy = verification.policy
978
+ return {
979
+ ...enriched, ...policy, invocation: verification.invocation,
980
+ action: policy.disabled ? 'native-disabled' : 'reuse-active',
981
+ allowed: !policy.disabled,
982
+ label: policy.disabled ? labels.disabled : labels.callable,
983
+ state: policy.disabled ? 'disabled' : 'active',
984
+ current: true, registered: true, discovered: true, verified: true,
985
+ detail: policy.disabled ? '当前快照的模型与手动调用均已禁用。'
986
+ : '当前项目已经使用相同内容,不会重复安装。',
987
+ }
988
+ }
989
+ const verification = await this.#verifyRecord(record, summaries, root)
990
+ return {
991
+ ...enriched, action: 'update', allowed: true,
992
+ label: verification.verified ? labels.callable : labels.pending,
993
+ state: verification.verified ? 'active' : 'pending',
994
+ current: verification.verified, sourceChanged: true, registered: true,
995
+ discovered: verification.discovered, verified: verification.verified,
996
+ detail: verification.verified
997
+ ? '将保存新快照并切换;上一份可撤销。'
998
+ : '当前生效版本、内容或调用策略无法确认;仍可重新预览并保存当前来源。',
999
+ }
1000
+ }
1001
+
1002
+ const exactNative = summaries.find(summary => sameFile(summary.path, asset.file))
1003
+ if (exactNative) {
1004
+ const effective = await this.#nativeSkill(exactNative, root)
1005
+ if (!effective) {
1006
+ return { ...enriched, action: 'conflict', allowed: false, label: labels.pending,
1007
+ reason: 'DSH 已发现该技能,但无法读取当前生效定义。' }
1008
+ }
1009
+ if (!effective.invocation) {
1010
+ return { ...enriched, ...unknownPolicy, action: 'pending', allowed: false,
1011
+ label: labels.pending, state: 'pending', current: true, verified: false,
1012
+ discovered: true, registered: false,
1013
+ reason: 'DSH 已发现该技能,但无法确认当前生效副本的模型与手动调用策略。' }
1014
+ }
1015
+ const policy = this.#policy(effective.invocation)
1016
+ return {
1017
+ ...enriched, ...policy, invocation: effective.invocation,
1018
+ action: 'native', allowed: false,
1019
+ label: policy.disabled ? labels.disabled : labels.callable,
1020
+ state: policy.disabled ? 'disabled' : 'native',
1021
+ current: true, verified: true, discovered: true, registered: false,
1022
+ detail: policy.disabled ? '模型与手动调用均已禁用。'
1023
+ : '这份技能已由 DSH 原生发现,不需要再复制。',
1024
+ }
1025
+ }
1026
+ const conflict = await this.#sameNamedNative(enriched, root, summaries)
1027
+ if (conflict) {
1028
+ const effective = await this.#nativeSkill(conflict, root)
1029
+ if (effective?.package?.contentHash === skill.contentHash) {
1030
+ if (!effective.invocation) {
1031
+ return { ...enriched, ...unknownPolicy, action: 'pending', allowed: false,
1032
+ label: labels.pending, state: 'pending', current: true, verified: false,
1033
+ discovered: true, registered: false,
1034
+ reason: '同名同款原生技能已发现,但无法确认当前生效副本的调用策略;草稿会保留正文。' }
1035
+ }
1036
+ const policy = this.#policy(effective.invocation)
1037
+ return {
1038
+ ...enriched, ...policy, invocation: effective.invocation,
1039
+ action: policy.disabled ? 'native-disabled' : 'reuse-native',
1040
+ allowed: !policy.disabled,
1041
+ label: policy.disabled ? labels.disabled : labels.callable,
1042
+ state: policy.disabled ? 'disabled' : 'active',
1043
+ current: true, verified: true, discovered: true, registered: false,
1044
+ detail: policy.disabled ? '同名同款原生技能的模型与手动调用均已禁用。'
1045
+ : `复用已有的同名同款技能(${conflict.provider})。`,
1046
+ }
1047
+ }
1048
+ return { ...enriched, action: 'conflict', allowed: false, label: labels.handoff,
1049
+ reason: effective
1050
+ ? 'DSH 已有同名但内容不同的技能;首版保留原技能,不覆盖也不自动改名。'
1051
+ : 'DSH 已有同名技能,但内容无法核对;不能当作同款复用。' }
1052
+ }
1053
+ return { ...enriched, action: 'enable', allowed: true, label: labels.enable,
1054
+ state: 'available', current: false,
1055
+ detail: '将保存完整包,只对当前 DSH 项目根生效;调用仍受当前模式权限限制。' }
1056
+ }
1057
+
1058
+ async apply(ticketId) {
1059
+ const ticket = this.tickets.get(ticketId)
1060
+ if (!ticket || this.clock() - ticket.created > TICKET_LIFETIME) {
1061
+ throw new SkillHandoffError('ticket-expired', '技能预览已过期,请重新预览。')
1062
+ }
1063
+ if (ticket.result) return ticket.result
1064
+ if (ticket.pending) return ticket.pending
1065
+ ticket.pending = (async () => {
1066
+ const state = await this.store.read()
1067
+ const root = await findProjectRoot(ticket.projectRoot)
1068
+ if (!root || pathKey(root) !== pathKey(ticket.projectRoot)) {
1069
+ throw new SkillHandoffError('project-changed', '项目根目录已变化,请重新预览。')
1070
+ }
1071
+ const native = await this.#nativeList(root)
1072
+ if (!native.ok) throw new SkillHandoffError('native-unavailable', '当前 DSH 未提供原生技能服务。')
1073
+ const results = []
1074
+ const drafts = []
1075
+ for (const item of ticket.items) {
1076
+ if (!item.allowed || ['handoff', 'invalid', 'native', 'conflict'].includes(item.action)) {
1077
+ results.push({ ...sanitizeItem(item), applied: false, verified: false, reason: item.reason })
1078
+ continue
1079
+ }
1080
+ let result
1081
+ try {
1082
+ result = await this.#applyItem(item, root, state, native.summaries)
1083
+ if (result.draft) drafts.push({ draft: result.draft, result: result.result })
1084
+ results.push(result.result)
1085
+ } catch (error) {
1086
+ if (error instanceof SkillPackageError || error instanceof SkillHandoffError) {
1087
+ results.push({ ...sanitizeItem(item), applied: false, verified: false, reason: error.message })
1088
+ } else {
1089
+ throw error
1090
+ }
1091
+ }
1092
+ }
1093
+ let committed = state
1094
+ if (drafts.length) {
1095
+ for (const entry of drafts) {
1096
+ try {
1097
+ committed = await this.store.recordActivations(root, [entry.draft])
1098
+ } catch (error) {
1099
+ if (error instanceof SkillHandoffError) {
1100
+ entry.result.applied = false
1101
+ entry.result.verified = false
1102
+ entry.result.reason = error.message
1103
+ continue
1104
+ }
1105
+ throw error
1106
+ }
1107
+ this.invalidate()
1108
+ }
1109
+ }
1110
+ const after = drafts.some(entry => entry.result.applied) ? await this.#nativeList(root) : native
1111
+ for (const result of results) {
1112
+ if (!result.applied) continue
1113
+ const record = projectBucket(committed, root)?.activations?.[result.dshName]
1114
+ result.activationId = record?.id
1115
+ const verification = await this.#verifyRecord(record, after.summaries, root)
1116
+ result.verified = verification.verified
1117
+ if (verification.verified) {
1118
+ Object.assign(result, verification.policy, { invocation: verification.invocation })
1119
+ result.label = verification.policy.disabled ? labels.disabled : labels.callable
1120
+ }
1121
+ result.status = result.verified ? 'registered' : 'pending'
1122
+ result.reason = result.verified ? 'DSH 已发现该技能。' : '启用记录已保存,等待 DSH 确认。'
1123
+ }
1124
+ ticket.result = { projectRoot: root, items: results }
1125
+ return ticket.result
1126
+ })().finally(() => { delete ticket.pending })
1127
+ return ticket.pending
1128
+ }
1129
+
1130
+ async #applyItem(item, root, state, summaries) {
1131
+ if (item.action === 'reuse-active') {
1132
+ return {
1133
+ draft: null,
1134
+ result: { ...sanitizeItem(item), action: 'reuse-active', applied: true, verified: false,
1135
+ current: true, reason: '当前项目已经使用相同内容,不会重复安装。' },
1136
+ }
1137
+ }
1138
+ const current = await readSkillPackage(item.sourceFile, {
1139
+ content: true, authorization: item.authorization,
1140
+ })
1141
+ if (current.contentHash !== item.contentHash || current.quickHash !== item.quickHash
1142
+ || current.fileCount !== item.fileCount) {
1143
+ throw new SkillHandoffError('source-changed', '预览后源技能发生变化,请重新预览。')
1144
+ }
1145
+ const record = projectBucket(state, root)?.activations?.[item.dshName]
1146
+ if (record && record.assetId !== item.assetId && !sameFile(record.sourceFile, item.sourceFile)) {
1147
+ throw new SkillHandoffError('name-conflict', '这个项目已经启用了同名但来源不同的技能,未替换原技能。')
1148
+ }
1149
+ const conflict = await this.#sameNamedNative(item, root, summaries)
1150
+ if (conflict) {
1151
+ const nativePackage = await this.#nativePackage(conflict, root)
1152
+ if (nativePackage?.contentHash !== item.contentHash) {
1153
+ throw new SkillHandoffError('name-conflict', 'DSH 已出现同名但内容不同的技能,未覆盖原技能。')
1154
+ }
1155
+ }
1156
+
1157
+ if (item.action === 'reuse-native' || conflict) {
1158
+ const now = this.clock()
1159
+ return {
1160
+ draft: {
1161
+ dshName: item.dshName,
1162
+ expectedRevision: item.expectedRevision,
1163
+ record: this.#record(item, root, record, {
1164
+ mode: 'native', snapshotId: null, previousSnapshotId: record?.snapshotId ?? null,
1165
+ contentHash: item.contentHash, quickHash: item.quickHash, now,
1166
+ }),
1167
+ },
1168
+ result: { ...sanitizeItem(item), action: 'reuse-native', applied: true, verified: false,
1169
+ current: true, reason: '已登记复用 DSH 原生同名同款技能。' },
1170
+ }
1171
+ }
1172
+
1173
+ const snapshotId = snapshotIdFor(item.dshName, item.contentHash)
1174
+ let snapshot = state.snapshots[snapshotId]
1175
+ if (snapshot) {
1176
+ const existing = await readSkillPackage(path.join(this.store.snapshotPath(snapshotId), 'SKILL.md'), {
1177
+ content: true,
1178
+ })
1179
+ if (existing.contentHash !== item.contentHash || snapshot.contentHash !== item.contentHash) {
1180
+ throw new SkillHandoffError('snapshot-invalid', '已有私有技能快照与记录不一致,未切换。')
1181
+ }
1182
+ } else {
1183
+ await mkdir(this.store.bundlesDir, { recursive: true })
1184
+ await mkdir(this.store.stagingDir, { recursive: true })
1185
+ const staging = path.join(this.store.stagingDir, randomUUID())
1186
+ try {
1187
+ const copied = await copySkillPackage(current, staging)
1188
+ if (this.validateBundle) await this.validateBundle(staging, root, item.dshName)
1189
+ const final = this.store.snapshotPath(snapshotId)
1190
+ try {
1191
+ await rename(staging, final)
1192
+ } catch (error) {
1193
+ if (error.code !== 'EEXIST' && error.code !== 'EPERM') throw error
1194
+ const existing = await readSkillPackage(path.join(final, 'SKILL.md'), { content: true })
1195
+ if (existing.contentHash !== item.contentHash) throw error
1196
+ await rm(staging, { recursive: true, force: true })
1197
+ }
1198
+ snapshot = {
1199
+ id: snapshotId,
1200
+ dshName: item.dshName,
1201
+ path: final,
1202
+ contentHash: copied.contentHash,
1203
+ quickHash: copied.quickHash,
1204
+ fileCount: copied.fileCount,
1205
+ bytes: copied.bytes,
1206
+ createdAt: this.clock(),
1207
+ }
1208
+ } catch (error) {
1209
+ await rm(staging, { recursive: true, force: true }).catch(() => {})
1210
+ throw error
1211
+ }
1212
+ }
1213
+ const now = this.clock()
1214
+ return {
1215
+ draft: {
1216
+ dshName: item.dshName,
1217
+ expectedRevision: item.expectedRevision,
1218
+ snapshot,
1219
+ record: this.#record(item, root, record, {
1220
+ mode: 'snapshot', snapshotId, previousSnapshotId: record?.snapshotId ?? null,
1221
+ contentHash: item.contentHash, quickHash: item.quickHash, now,
1222
+ }),
1223
+ },
1224
+ result: { ...sanitizeItem(item), action: record ? 'update' : 'enable', applied: true,
1225
+ verified: false, current: true, reason: '完整技能包已保存。' },
1226
+ }
1227
+ }
1228
+
1229
+ #record(item, root, previous, { mode, snapshotId, previousSnapshotId, contentHash, quickHash, now }) {
1230
+ return {
1231
+ id: previous?.id ?? activationId(root, item.dshName),
1232
+ assetId: item.assetId,
1233
+ dshName: item.dshName,
1234
+ sourceName: item.sourceName,
1235
+ sourceFile: item.sourceFile,
1236
+ sourceRoot: item.sourceRoot,
1237
+ contentHash,
1238
+ quickHash,
1239
+ mode,
1240
+ snapshotId,
1241
+ previousSnapshotId,
1242
+ activatedAt: previous?.activatedAt ?? now,
1243
+ updatedAt: now,
1244
+ }
1245
+ }
1246
+
1247
+ async #verifyRecord(record, summaries, root) {
1248
+ if (!record) return { verified: false, discovered: false }
1249
+ const summary = summaries.find(item => item.name === record.dshName)
1250
+ if (!summary) return { verified: false, discovered: false }
1251
+ const effective = await this.#nativeSkill(summary, root)
1252
+ const owned = record.mode === 'native'
1253
+ ? summary.provider !== PROVIDER_NAME
1254
+ : summary.provider === PROVIDER_NAME && Boolean(summary.path
1255
+ && inside(this.store.snapshotPath(record.snapshotId), summary.path))
1256
+ const sameContent = effective?.package?.contentHash === record.contentHash
1257
+ if (!effective || !effective.invocation || !owned || !sameContent) {
1258
+ return { verified: false, discovered: Boolean(summary) }
1259
+ }
1260
+ return {
1261
+ verified: true,
1262
+ discovered: true,
1263
+ invocation: effective.invocation,
1264
+ policy: this.#policy(effective.invocation),
1265
+ }
1266
+ }
1267
+
1268
+ async deactivate(project, activationIdValue) {
1269
+ const root = await findProjectRoot(project.cwd)
1270
+ if (!root) throw new SkillHandoffError('project-unavailable', '当前项目目录不可访问。')
1271
+ const removed = await this.store.removeActivation(root, activationIdValue)
1272
+ const result = {
1273
+ dshName: removed.dshName,
1274
+ assetId: removed.record.assetId,
1275
+ projectRoot: root,
1276
+ }
1277
+ this.invalidate()
1278
+ return result
1279
+ }
1280
+
1281
+ async undo(project, activationIdValue) {
1282
+ const root = await findProjectRoot(project.cwd)
1283
+ if (!root) throw new SkillHandoffError('project-unavailable', '当前项目目录不可访问。')
1284
+ const state = await this.store.read()
1285
+ const bucket = projectBucket(state, root)
1286
+ const entry = Object.entries(bucket?.activations ?? {}).find(([, record]) => record.id === activationIdValue)
1287
+ if (!entry) throw new SkillHandoffError('activation-missing', '找不到该项目的技能启用记录。')
1288
+ const [name, record] = entry
1289
+ if (record.mode !== 'snapshot' || !record.previousSnapshotId) {
1290
+ throw new SkillHandoffError('no-previous-version', '没有可回退的上一份技能快照。')
1291
+ }
1292
+ const previous = state.snapshots[record.previousSnapshotId]
1293
+ if (!previous) throw new SkillHandoffError('snapshot-missing', '上一份技能快照记录不存在。')
1294
+ const previousPackage = await readSkillPackage(path.join(this.store.snapshotPath(previous.id), 'SKILL.md'), {
1295
+ content: true,
1296
+ }).catch(error => {
1297
+ throw new SkillHandoffError('snapshot-missing', '上一份技能快照不可读取。', { cause: error })
1298
+ })
1299
+ if (previousPackage.contentHash !== previous.contentHash) {
1300
+ throw new SkillHandoffError('snapshot-invalid', '上一份技能快照与记录不一致,未切换。')
1301
+ }
1302
+ const updated = {
1303
+ ...record,
1304
+ previousSnapshotId: record.snapshotId,
1305
+ snapshotId: previous.id,
1306
+ contentHash: previous.contentHash,
1307
+ quickHash: previous.quickHash,
1308
+ mode: 'snapshot',
1309
+ updatedAt: this.clock(),
1310
+ }
1311
+ await this.store.updateActivation(root, activationIdValue, record, updated)
1312
+ const result = { dshName: name, activationId: updated.id, snapshotId: previous.id, projectRoot: root }
1313
+ this.invalidate()
1314
+ return result
1315
+ }
1316
+
1317
+ activeSnapshots(state, root) {
1318
+ const bucket = projectBucket(state, root)
1319
+ const paths = new Set()
1320
+ for (const record of Object.values(bucket?.activations ?? {})) {
1321
+ if (record.mode === 'snapshot' && record.snapshotId) {
1322
+ paths.add(pathKey(this.store.snapshotPath(record.snapshotId)))
1323
+ }
1324
+ }
1325
+ return paths
1326
+ }
1327
+ }