@wwwfz/dsh-agent-bridge 0.9.0 → 0.11.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.
@@ -1,247 +1,209 @@
1
1
  import path from 'node:path'
2
+ import { readSkillPackage } from './skill-package.js'
2
3
  import {
3
4
  PROVIDER_NAME, PROVIDER_RANK, SkillActivationStore, SkillHandoff, SkillHandoffError,
4
5
  findProjectRoot, resolveSkillStoreRoot,
5
6
  } from './skill-handoff.js'
6
7
 
7
8
  function pathKey(value) {
8
- const normalized = path.normalize(value)
9
+ const normalized = path.normalize(value).replace(/^\\\\\?\\/, '')
9
10
  return process.platform === 'win32' ? normalized.toLowerCase() : normalized
10
11
  }
11
12
 
12
- function unavailableStatuses(skills, reason) {
13
+ function skillRecord(bundle) {
13
14
  return {
14
- available: false,
15
- projectRoot: undefined,
16
- managedSkills: [],
17
- skills: Object.fromEntries(skills.map(asset => [asset.id, {
18
- label: '仅可带入说明',
19
- state: 'handoff',
20
- action: 'view',
21
- allowed: false,
22
- current: false,
23
- sourceChanged: false,
24
- reason,
25
- }])),
15
+ name: bundle.name,
16
+ description: bundle.description,
17
+ invocation: bundle.invocation,
18
+ ...(bundle.whenToUse ? { whenToUse: bundle.whenToUse } : {}),
19
+ ...(bundle.metadata ? { metadata: bundle.metadata } : {}),
20
+ path: bundle.skillFile,
21
+ resourceBase: { kind: 'directory', path: bundle.sourceRoot },
22
+ provider: PROVIDER_NAME,
23
+ source: PROVIDER_NAME,
26
24
  }
27
25
  }
28
26
 
29
- async function defaultLoadProvider() {
30
- return import('@deepseek-ai/dsh-skill-filesystem')
27
+ async function readPrivateBundle(directory, expectedName, contentHash) {
28
+ const bundle = await readSkillPackage(path.join(directory, 'SKILL.md'), { content: true })
29
+ if (pathKey(bundle.sourceRoot) !== pathKey(directory)
30
+ || pathKey(bundle.skillFile) !== pathKey(path.join(directory, 'SKILL.md'))
31
+ || bundle.name !== expectedName || (contentHash !== undefined && bundle.contentHash !== contentHash)) {
32
+ throw new SkillHandoffError('snapshot-invalid', '私有技能包与启用记录不一致。')
33
+ }
34
+ return bundle
31
35
  }
32
36
 
33
- /**
34
- * Register the bridge-owned filesystem provider and expose the handoff
35
- * lifecycle to the panel. The official DSH provider remains the parser,
36
- * project-root resolver, catalog contributor, and resource-base provider.
37
- */
38
- export function createSkillBridge(ctx, {
39
- env = process.env,
40
- loadProvider = defaultLoadProvider,
41
- storeRoot = resolveSkillStoreRoot(env),
42
- } = {}) {
43
- const store = new SkillActivationStore(storeRoot)
44
- let control
45
- let disposer
46
- let disposed = false
47
- let failure
48
- let FileSystemSkillProvider
49
- let revisionTimer
50
- let observedRevision = 0
51
-
52
- const native = {
53
- list(options) {
54
- if (!ctx.get?.('skills') && !ctx.skills) throw new Error('ctx.skills is unavailable')
55
- return ctx.skills.list(options)
37
+ function mountProvider(store, handoff, contextSignal) {
38
+ async function projectState(options) {
39
+ contextSignal?.throwIfAborted()
40
+ options.signal?.throwIfAborted()
41
+ const project = await findProjectRoot(options.cwd)
42
+ if (!project) return
43
+ const state = await store.read()
44
+ return { state, active: handoff.activeSnapshots(state, project) }
45
+ }
46
+ async function inspectSnapshot(entry, options) {
47
+ const directory = store.snapshotPath(entry.id)
48
+ try {
49
+ const bundle = await readPrivateBundle(directory, entry.dshName, entry.contentHash)
50
+ return bundle
51
+ } catch {
52
+ return undefined
53
+ } finally {
54
+ contextSignal?.throwIfAborted()
55
+ options.signal?.throwIfAborted()
56
+ }
57
+ }
58
+ return {
59
+ name: PROVIDER_NAME,
60
+ async list(options = {}) {
61
+ const project = await projectState(options)
62
+ if (!project) return []
63
+ const { state, active } = project
64
+ const candidates = []
65
+ let complete = true
66
+ for (const entry of Object.values(state.snapshots)) {
67
+ if (!active.has(pathKey(store.snapshotPath(entry.id)))) continue
68
+ const bundle = await inspectSnapshot(entry, options)
69
+ if (bundle) candidates.push({ ...skillRecord(bundle), rank: PROVIDER_RANK, locator: { id: entry.id } })
70
+ else complete = false
71
+ }
72
+ return { candidates, complete }
56
73
  },
57
- get(name, options) {
58
- if (!ctx.get?.('skills') && !ctx.skills) throw new Error('ctx.skills is unavailable')
59
- return ctx.skills.get(name, options)
74
+ async get(candidate, options = {}) {
75
+ const project = await projectState(options)
76
+ const id = candidate?.locator?.id
77
+ if (!project || typeof id !== 'string' || !Object.hasOwn(project.state.snapshots, id)) return
78
+ const entry = project.state.snapshots[id]
79
+ if (entry.dshName !== candidate.name || !project.active.has(pathKey(store.snapshotPath(entry.id)))) return
80
+ const bundle = await inspectSnapshot(entry, options)
81
+ if (bundle) return { ...skillRecord(bundle), content: bundle.body }
60
82
  },
61
83
  }
84
+ }
85
+
86
+ function textOnly(assets) {
87
+ const unavailable = {
88
+ label: '仅可带入说明', state: 'handoff', action: 'view', allowed: false, current: false,
89
+ sourceChanged: false, reason: '当前 DSH 未提供可用的原生技能目录。',
90
+ }
91
+ return { available: false, managedSkills: [], skills: Object.fromEntries(assets.map(asset => [asset.id, unavailable])) }
92
+ }
62
93
 
94
+ export function createSkillBridge(ctx, { storeRoot = resolveSkillStoreRoot() } = {}) {
95
+ const store = new SkillActivationStore(storeRoot)
96
+ const service = () => ctx.get?.('skills') ?? ctx.skills
97
+ let refreshCatalog
98
+ let unregister
99
+ let timer
100
+ let stopped = false
101
+ let failure
63
102
  const handoff = new SkillHandoff({
64
103
  store,
65
- native,
66
- invalidate() {
67
- control?.invalidate?.()
104
+ native: {
105
+ list: options => service().list(options),
106
+ get: (name, options) => service().get(name, options),
68
107
  },
108
+ invalidate: () => refreshCatalog?.(),
69
109
  logger: ctx.logger,
70
- async validateBundle(directory, projectRoot, expectedName) {
71
- if (!FileSystemSkillProvider) throw new SkillHandoffError('native-unavailable', '官方技能加载器尚未就绪。')
72
- const lifecycle = new AbortController()
73
- const provider = new FileSystemSkillProvider(ctx, {
74
- signal: lifecycle.signal,
75
- invalidate() {},
76
- }, {
77
- providerName: 'agent-bridge-validation',
78
- includeDefaultRoots: false,
79
- customSkillDirs: [path.dirname(directory)],
80
- watch: false,
81
- })
82
- try {
83
- const output = await provider.list({ cwd: projectRoot, signal: lifecycle.signal })
84
- const candidates = Array.isArray(output) ? output : output?.candidates ?? []
85
- const candidate = candidates.find(item => (
86
- pathKey(item.resourceBase?.path ?? item.locator?.directory ?? '') === pathKey(directory)
87
- ))
88
- if (!candidate) throw new SkillHandoffError('invalid-package', 'DSH 未识别这个技能包。')
89
- const definition = await provider.get(candidate, { cwd: projectRoot, signal: lifecycle.signal })
90
- if (!definition || definition.name !== expectedName) {
91
- throw new SkillHandoffError('invalid-package', 'DSH 读取到的技能名与预览不一致。')
92
- }
93
- if (pathKey(definition.resourceBase?.path ?? '') !== pathKey(directory)) {
94
- throw new SkillHandoffError('invalid-package', 'DSH 未返回私有技能资源目录。')
95
- }
96
- } finally {
97
- lifecycle.abort(new Error('validation finished'))
98
- await provider.dispose().catch(() => {})
99
- }
110
+ async validateBundle(directory, _project, expectedName) {
111
+ await readPrivateBundle(directory, expectedName)
100
112
  },
101
113
  })
102
114
 
103
- const ready = (async () => {
104
- if (!ctx.get?.('skills') && !ctx.skills) {
105
- throw new SkillHandoffError('native-unavailable', '当前 DSH 未提供 ctx.skills。')
106
- }
107
- const module = await loadProvider()
108
- FileSystemSkillProvider = module.FileSystemSkillProvider
109
- if (typeof FileSystemSkillProvider !== 'function') {
110
- throw new SkillHandoffError('native-unavailable', '官方 FileSystemSkillProvider 不可用。')
115
+ try {
116
+ const skills = service()
117
+ if (typeof skills?.registerProvider !== 'function') {
118
+ throw new SkillHandoffError('native-unavailable', '当前 DSH 未提供 ctx.skills.registerProvider。')
111
119
  }
112
- if (disposed) return
113
- disposer = ctx.effect(() => ctx.skills.registerProvider(providerControl => {
114
- control = providerControl
115
- const inner = new FileSystemSkillProvider(ctx, providerControl, {
116
- providerName: PROVIDER_NAME,
117
- includeDefaultRoots: false,
118
- customSkillDirs: [store.bundlesDir],
119
- watch: false,
120
- })
121
- return {
122
- name: PROVIDER_NAME,
123
- async list(options) {
124
- const projectRoot = await findProjectRoot(options.cwd)
125
- if (!projectRoot) return []
126
- const output = await inner.list(options)
127
- const candidates = Array.isArray(output) ? output : output?.candidates ?? []
128
- const active = handoff.activeSnapshots(await store.read(), projectRoot)
129
- const filtered = candidates.filter(candidate => active.has(pathKey(
130
- candidate.resourceBase?.path ?? candidate.locator?.directory ?? '',
131
- ))).map(candidate => ({
132
- ...candidate,
133
- source: PROVIDER_NAME,
134
- rank: PROVIDER_RANK,
135
- }))
136
- return Array.isArray(output) ? filtered : { candidates: filtered, complete: output.complete }
137
- },
138
- async get(candidate, options) {
139
- const projectRoot = await findProjectRoot(options.cwd)
140
- if (!projectRoot) return undefined
141
- const active = handoff.activeSnapshots(await store.read(), projectRoot)
142
- const directory = candidate.resourceBase?.path ?? candidate.locator?.directory
143
- if (!directory || !active.has(pathKey(directory))) return undefined
144
- return inner.get(candidate, options)
145
- },
146
- }
120
+ unregister = ctx.effect(() => skills.registerProvider(lifecycle => {
121
+ refreshCatalog = () => lifecycle.invalidate()
122
+ return mountProvider(store, handoff, lifecycle.signal)
147
123
  }))
148
- observedRevision = await store.revision().catch(() => 0)
149
- const pollRevision = async () => {
150
- if (disposed) return
151
- try {
152
- const revision = await store.revision()
153
- if (revision !== observedRevision) {
154
- observedRevision = revision
155
- control?.invalidate?.()
156
- }
157
- } catch {
158
- // A host without a native skills service can keep running in text mode.
159
- } finally {
160
- if (!disposed) revisionTimer = setTimeout(pollRevision, 250)
161
- revisionTimer?.unref?.()
162
- }
163
- }
164
- revisionTimer = setTimeout(pollRevision, 250)
165
- revisionTimer.unref?.()
166
- })().catch(error => {
124
+ } catch (error) {
167
125
  failure = error
168
- ctx.logger?.warn?.(`agent-bridge native skills unavailable: ${error?.message ?? error}`)
169
- })
126
+ ctx.logger?.warn?.('agent-bridge native skills unavailable: ' + (error?.message ?? error))
127
+ }
128
+
129
+ const ready = (async () => {
130
+ if (failure) return
131
+ let previous = await store.revision().catch(() => 0)
132
+ const schedule = () => {
133
+ if (stopped) return
134
+ timer = setTimeout(async () => {
135
+ try {
136
+ const revision = await store.revision()
137
+ if (!stopped && revision !== previous) {
138
+ previous = revision
139
+ refreshCatalog?.()
140
+ }
141
+ } catch { /* Retry on the next read when the database is available. */ }
142
+ schedule()
143
+ }, 250)
144
+ timer.unref?.()
145
+ }
146
+ schedule()
147
+ })()
170
148
 
171
- async function ensure() {
149
+ async function requireProvider() {
172
150
  await ready
173
151
  if (failure) throw failure
152
+ if (stopped) throw new SkillHandoffError('native-unavailable', '原生技能目录已关闭。')
153
+ }
154
+ function command(method) {
155
+ return async (...args) => {
156
+ await requireProvider()
157
+ return handoff[method](...args)
158
+ }
174
159
  }
175
160
 
176
161
  const bridge = {
177
162
  ready,
178
- get available() {
179
- return !failure && Boolean(control)
180
- },
181
- get failure() {
182
- return failure
183
- },
163
+ get available() { return !failure && !stopped && Boolean(refreshCatalog) },
164
+ get failure() { return failure },
184
165
  async inspect(project, skills) {
166
+ await ready
185
167
  try {
186
- await ensure()
187
- return await handoff.inspect(project, skills)
188
- } catch (error) {
189
- failure ??= error
190
- try {
191
- return {
192
- ...await handoff.inspect(project, skills),
193
- available: false,
194
- }
195
- } catch {
196
- return unavailableStatuses(skills, '当前 DSH 未提供可用的原生技能目录。')
197
- }
168
+ const result = await handoff.inspect(project, skills)
169
+ return bridge.available ? result : { ...result, available: false }
170
+ } catch {
171
+ return textOnly(skills)
198
172
  }
199
173
  },
200
174
  async conversationCandidates(project, usedSkills, skills) {
201
175
  try {
202
- await ensure()
203
- const used = new Set((usedSkills ?? []).map(name => String(name).toLowerCase()))
204
- if (!used.size) return []
205
- const inspected = await handoff.inspect(project, skills)
206
- return skills.filter(asset => {
207
- const status = inspected.skills[asset.id]
208
- return status && (used.has(String(asset.name).toLowerCase())
209
- || used.has(String(status.dshName).toLowerCase()))
210
- }).slice(0, 3).map(asset => ({ assetId: asset.id, ...inspected.skills[asset.id] }))
176
+ await requireProvider()
177
+ const names = new Set((usedSkills ?? []).map(name => String(name).toLowerCase()))
178
+ if (!names.size) return []
179
+ const { skills: statuses } = await handoff.inspect(project, skills)
180
+ const relevant = []
181
+ for (const { id, name } of skills) {
182
+ const entry = statuses[id]
183
+ if (!entry || ![name, entry.dshName].some(value => names.has(String(value).toLowerCase()))) continue
184
+ relevant.push({ assetId: id, ...entry })
185
+ if (relevant.length === 3) break
186
+ }
187
+ return relevant
211
188
  } catch {
212
189
  return []
213
190
  }
214
191
  },
215
- async preview(project, assets) {
216
- await ensure()
217
- return handoff.preview(project, assets)
218
- },
219
- async authorizeTextOmission(project, assets) {
220
- await ensure()
221
- return handoff.authorizeTextOmission(project, assets)
222
- },
223
- async apply(ticket) {
224
- await ensure()
225
- return handoff.apply(ticket)
226
- },
227
- async deactivate(project, activationId) {
228
- await ensure()
229
- return handoff.deactivate(project, activationId)
230
- },
231
- async undo(project, activationId) {
232
- await ensure()
233
- return handoff.undo(project, activationId)
234
- },
192
+ preview: command('preview'),
193
+ authorizeTextOmission: command('authorizeTextOmission'),
194
+ apply: command('apply'),
195
+ deactivate: command('deactivate'),
196
+ undo: command('undo'),
235
197
  async revision() {
236
- await ensure()
198
+ await requireProvider()
237
199
  return store.revision()
238
200
  },
239
201
  dispose() {
240
- if (disposed) return
241
- disposed = true
242
- if (revisionTimer) clearTimeout(revisionTimer)
243
- revisionTimer = undefined
244
- try { disposer?.() } catch { /* The provider lifecycle is already being torn down. */ }
202
+ if (stopped) return
203
+ stopped = true
204
+ clearTimeout(timer)
205
+ refreshCatalog = undefined
206
+ try { unregister?.() } catch { /* The host may already have disposed the registration. */ }
245
207
  },
246
208
  }
247
209
  ctx.effect(() => () => bridge.dispose())
package/src/watch.js CHANGED
@@ -109,6 +109,11 @@ async function watchPlan(config, selected) {
109
109
  for (const archive of config.archiveFiles ?? []) file(archive, true);
110
110
  for (const project of selected) {
111
111
  const { cwd } = project;
112
+ for (const archive of [...(project.archives ?? [])]
113
+ .sort((left, right) => (Number(right.date) || Date.parse(right.date) || 0) - (Number(left.date) || Date.parse(left.date) || 0))
114
+ .slice(0, 12)) {
115
+ file(archive.file, archive.storage === 'sqlite' || ['opencode', 'agentsview'].includes(archive.kind));
116
+ }
112
117
  add(cwd, name => /^(?:agents|claude|gemini|qwen|memory)\.md$/i.test(name) || name === '.agent-bridge' || projectFolders.includes(name), 0);
113
118
  const bridge = path.join(cwd, '.agent-bridge');
114
119
  add(bridge, named('memory', 'handoffs'), 0);
@@ -150,7 +155,7 @@ async function watchPlan(config, selected) {
150
155
  for (const [provider, roots] of Object.entries(config.agentRoots ?? {})) {
151
156
  const agent = aliases[provider] ?? provider;
152
157
  for (const root of roots.slice(0, maxRootsPerAgent)) {
153
- if (agent === 'opencode' && (await stat(root).catch(() => undefined))?.isFile()) {
158
+ if (['opencode', 'copilot'].includes(agent) && (await stat(root).catch(() => undefined))?.isFile()) {
154
159
  file(root, true);
155
160
  continue;
156
161
  }
@@ -185,6 +190,11 @@ async function watchPlan(config, selected) {
185
190
  ? [root] : [path.join(root, 'workspaceStorage'), path.join(root, 'User', 'workspaceStorage')];
186
191
  for (const store of stores) jobs.push(childTranscripts(store, ['workspace.json', 'chatSessions']));
187
192
  }
193
+ if (agent === 'copilot') {
194
+ for (const base of [root, path.join(root, 'User')]) {
195
+ file(path.join(base, 'globalStorage', 'github.copilot-chat', 'session-store.db'), true);
196
+ }
197
+ }
188
198
  for (const folder of ['memory', 'memories', 'memories_v2', 'agent-memory', 'knowledge', 'qoder-knowledge', 'diary']) {
189
199
  add(path.join(root, folder), matches(note), 2);
190
200
  }
@@ -0,0 +1,22 @@
1
+ [data-chat-flow-kind='agent-bridge-source-process']:not(:has(.bridge-inline-process)) {
2
+ display: none;
3
+ }
4
+
5
+ .bridge-inline-process {
6
+ min-width: 0;
7
+ margin-block: 4px 8px;
8
+ padding: 7px 10px;
9
+ border-radius: 8px;
10
+ background: color-mix(in srgb, currentColor 5%, transparent);
11
+ font-size: 13px;
12
+ overflow-wrap: anywhere;
13
+ }
14
+
15
+ .bridge-inline-process summary { cursor: pointer; }
16
+ .bridge-inline-process article { margin-block: 10px; }
17
+ .bridge-inline-process pre {
18
+ margin: 4px 0 0;
19
+ max-height: 18rem;
20
+ overflow: auto;
21
+ white-space: pre-wrap;
22
+ }