@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
|
@@ -0,0 +1,417 @@
|
|
|
1
|
+
import { constants } from 'node:fs'
|
|
2
|
+
import { chmod, lstat, mkdir, open, readdir, realpath, rename, rm, stat, writeFile } from 'node:fs/promises'
|
|
3
|
+
import { createHash } from 'node:crypto'
|
|
4
|
+
import path from 'node:path'
|
|
5
|
+
import { verifySourceAuthorization } from './assets.js'
|
|
6
|
+
|
|
7
|
+
// File discovery, frontmatter parsing, and package limits are adapted from
|
|
8
|
+
// dsh-mode-skills commit 706595127984c9bc87627f77d2a8e288b8dcbbbb
|
|
9
|
+
// (MIT). See THIRD_PARTY_NOTICES.md.
|
|
10
|
+
|
|
11
|
+
export const SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
|
|
12
|
+
export const PACKAGE_MAX_FILES = 1000
|
|
13
|
+
export const PACKAGE_MAX_BYTES = 25 * 1024 * 1024
|
|
14
|
+
const SKIPPED = new Set(['.git', '.DS_Store'])
|
|
15
|
+
const SENSITIVE_NAMES = new Set([
|
|
16
|
+
'.env', '.git-credentials', '.netrc', '.npmrc', '.pypirc',
|
|
17
|
+
'auth.json', 'credentials.json', 'id_ecdsa', 'id_ed25519', 'id_rsa', 'secrets.json',
|
|
18
|
+
])
|
|
19
|
+
const SENSITIVE_EXTENSIONS = new Set(['.key', '.p12', '.pem', '.pfx'])
|
|
20
|
+
const SCRIPT_EXTENSIONS = new Set([
|
|
21
|
+
'.sh', '.bash', '.zsh', '.fish', '.ps1', '.bat', '.cmd', '.py',
|
|
22
|
+
'.js', '.mjs', '.cjs', '.ts', '.rb', '.pl', '.php', '.lua',
|
|
23
|
+
])
|
|
24
|
+
|
|
25
|
+
export class SkillPackageError extends Error {
|
|
26
|
+
constructor(code, message, details) {
|
|
27
|
+
super(message)
|
|
28
|
+
this.name = 'SkillPackageError'
|
|
29
|
+
this.code = code
|
|
30
|
+
this.details = details
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function pathKey(value) {
|
|
35
|
+
const normalized = path.normalize(value)
|
|
36
|
+
return process.platform === 'win32' ? normalized.toLowerCase() : normalized
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function isPathInside(root, file) {
|
|
40
|
+
const relative = path.relative(pathKey(root), pathKey(file))
|
|
41
|
+
return relative === '' || (relative !== '..' && !relative.startsWith(`..${path.sep}`) && !path.isAbsolute(relative))
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function unquote(value) {
|
|
45
|
+
const text = value.trim()
|
|
46
|
+
if (text.length >= 2 && ((text.startsWith('"') && text.endsWith('"'))
|
|
47
|
+
|| (text.startsWith("'") && text.endsWith("'")))) {
|
|
48
|
+
return text.startsWith('"')
|
|
49
|
+
? text.slice(1, -1).replace(/\\(["\\nt])/g, (_, escaped) => ({ n: '\n', t: '\t' })[escaped] ?? escaped)
|
|
50
|
+
: text.slice(1, -1).replaceAll("''", "'")
|
|
51
|
+
}
|
|
52
|
+
return text
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function parseSkillFile(text) {
|
|
56
|
+
const match = /^\uFEFF?---\r?\n([\s\S]*?)\r?\n---[ \t]*(?:\r?\n|$)/.exec(text)
|
|
57
|
+
if (match === null) return { fields: {}, body: text }
|
|
58
|
+
const fields = {}
|
|
59
|
+
const lines = match[1].split(/\r?\n/)
|
|
60
|
+
for (let index = 0; index < lines.length; index++) {
|
|
61
|
+
const line = /^([A-Za-z][\w-]*):(?:[ \t]+(.*))?$/.exec(lines[index])
|
|
62
|
+
if (line === null) continue
|
|
63
|
+
const [, key, raw = ''] = line
|
|
64
|
+
const block = /^([|>])([+-]?)\s*$/.exec(raw.trim())
|
|
65
|
+
if (block === null) {
|
|
66
|
+
if (raw.trim() !== '') fields[key] = unquote(raw)
|
|
67
|
+
continue
|
|
68
|
+
}
|
|
69
|
+
const collected = []
|
|
70
|
+
while (index + 1 < lines.length && (lines[index + 1].trim() === '' || /^[ \t]/.test(lines[index + 1]))) {
|
|
71
|
+
collected.push(lines[++index])
|
|
72
|
+
}
|
|
73
|
+
const indent = Math.min(...collected.filter(entry => entry.trim() !== '')
|
|
74
|
+
.map(entry => /^[ \t]*/.exec(entry)[0].length))
|
|
75
|
+
const rows = collected.map(entry => entry.slice(Number.isFinite(indent) ? indent : 0))
|
|
76
|
+
const joined = block[1] === '|' ? rows.join('\n') : rows.join('\n').replace(/([^\n])\n(?=[^\n])/g, '$1 ')
|
|
77
|
+
fields[key] = block[2] === '+' ? joined : joined.replace(/\s+$/, '')
|
|
78
|
+
}
|
|
79
|
+
return { fields, body: text.slice(match[0].length) }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function frontmatterBoolean(fields, key) {
|
|
83
|
+
if (!Object.hasOwn(fields, key)) return undefined
|
|
84
|
+
const value = fields[key]
|
|
85
|
+
if (typeof value === 'boolean') return value
|
|
86
|
+
if (value === 1 || value === '1') return true
|
|
87
|
+
if (value === 0 || value === '0') return false
|
|
88
|
+
if (typeof value === 'string') {
|
|
89
|
+
const normalized = value.toLowerCase()
|
|
90
|
+
if (['true', 'yes', 'on'].includes(normalized)) return true
|
|
91
|
+
if (['false', 'no', 'off'].includes(normalized)) return false
|
|
92
|
+
}
|
|
93
|
+
throw new SkillPackageError('invalid-invocation', `Frontmatter ${key} must be a boolean.`)
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function invocationPolicy(fields) {
|
|
97
|
+
if (Object.hasOwn(fields, 'disableModelInvocation') || Object.hasOwn(fields, 'modelInvocable')
|
|
98
|
+
|| Object.hasOwn(fields, 'userInvocable')) {
|
|
99
|
+
throw new SkillPackageError('invalid-invocation', 'Skill invocation fields must use the kebab-case names.')
|
|
100
|
+
}
|
|
101
|
+
const modelDisabled = frontmatterBoolean(fields, 'disable-model-invocation')
|
|
102
|
+
const userDisabled = frontmatterBoolean(fields, 'user-invocable')
|
|
103
|
+
return {
|
|
104
|
+
modelInvocable: modelDisabled !== true,
|
|
105
|
+
userInvocable: userDisabled !== false,
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
export function skillLocation(file) {
|
|
110
|
+
return path.basename(file) === 'SKILL.md'
|
|
111
|
+
? { layout: 'directory', root: path.dirname(file), file }
|
|
112
|
+
: { layout: 'flat', root: path.dirname(file), file }
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
async function stableFileBuffer(file, expected) {
|
|
116
|
+
let handle
|
|
117
|
+
try {
|
|
118
|
+
handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0))
|
|
119
|
+
const before = await handle.stat({ bigint: true })
|
|
120
|
+
if (!before.isFile() || before.size !== expected.size
|
|
121
|
+
|| before.dev !== expected.dev || before.ino !== expected.ino) {
|
|
122
|
+
throw new SkillPackageError('source-changed', 'A skill file changed while it was being read.')
|
|
123
|
+
}
|
|
124
|
+
const bytes = await handle.readFile()
|
|
125
|
+
const after = await handle.stat({ bigint: true })
|
|
126
|
+
if (before.size !== after.size || before.mtimeNs !== after.mtimeNs || before.ctimeNs !== after.ctimeNs
|
|
127
|
+
|| BigInt(bytes.length) !== after.size) {
|
|
128
|
+
throw new SkillPackageError('source-changed', 'A skill file changed while it was being read (read).')
|
|
129
|
+
}
|
|
130
|
+
return bytes
|
|
131
|
+
} finally {
|
|
132
|
+
await handle?.close()
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
async function walkPackage(base, directory, files, totals) {
|
|
137
|
+
let entries
|
|
138
|
+
try {
|
|
139
|
+
entries = await readdir(directory, { withFileTypes: true })
|
|
140
|
+
} catch (error) {
|
|
141
|
+
throw new SkillPackageError('unreadable-package', `Cannot read skill directory: ${error.message}`)
|
|
142
|
+
}
|
|
143
|
+
entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0)
|
|
144
|
+
for (const entry of entries) {
|
|
145
|
+
if (SKIPPED.has(entry.name)) continue
|
|
146
|
+
const lowerName = entry.name.toLowerCase()
|
|
147
|
+
const envFile = lowerName.startsWith('.env.')
|
|
148
|
+
&& !['.env.example', '.env.sample', '.env.template'].includes(lowerName)
|
|
149
|
+
if (SENSITIVE_NAMES.has(lowerName) || envFile
|
|
150
|
+
|| SENSITIVE_EXTENSIONS.has(path.extname(entry.name).toLowerCase())) {
|
|
151
|
+
throw new SkillPackageError('sensitive-file', 'A skill package contains a credential-like file and was not copied.')
|
|
152
|
+
}
|
|
153
|
+
const candidate = path.join(directory, entry.name)
|
|
154
|
+
let info
|
|
155
|
+
try {
|
|
156
|
+
info = await lstat(candidate, { bigint: true })
|
|
157
|
+
} catch (error) {
|
|
158
|
+
throw new SkillPackageError('unreadable-package', `Cannot inspect skill file: ${error.message}`)
|
|
159
|
+
}
|
|
160
|
+
let source = candidate
|
|
161
|
+
let type = info.isDirectory() ? 'directory' : info.isFile() ? 'file' : info.isSymbolicLink() ? 'link' : 'other'
|
|
162
|
+
if (type === 'link') {
|
|
163
|
+
let target
|
|
164
|
+
try {
|
|
165
|
+
target = await realpath(candidate)
|
|
166
|
+
} catch {
|
|
167
|
+
throw new SkillPackageError('unsafe-link', 'A skill contains a broken link.')
|
|
168
|
+
}
|
|
169
|
+
if (!isPathInside(base, target)) {
|
|
170
|
+
throw new SkillPackageError('unsafe-link', 'A skill links outside its package.')
|
|
171
|
+
}
|
|
172
|
+
const targetInfo = await stat(target, { bigint: true }).catch(() => undefined)
|
|
173
|
+
if (targetInfo?.isFile()) {
|
|
174
|
+
source = target
|
|
175
|
+
info = targetInfo
|
|
176
|
+
type = 'file'
|
|
177
|
+
} else if (targetInfo?.isDirectory()) {
|
|
178
|
+
throw new SkillPackageError('unsafe-link', 'A skill directory link is not accepted.')
|
|
179
|
+
} else {
|
|
180
|
+
throw new SkillPackageError('unsafe-link', 'A skill contains an unsupported link.')
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
const relative = path.relative(base, candidate)
|
|
184
|
+
if (relative === '..' || relative.startsWith(`..${path.sep}`) || path.isAbsolute(relative)) {
|
|
185
|
+
throw new SkillPackageError('unsafe-path', 'A skill path leaves its package.')
|
|
186
|
+
}
|
|
187
|
+
if (type === 'directory') {
|
|
188
|
+
await walkPackage(base, candidate, files, totals)
|
|
189
|
+
continue
|
|
190
|
+
}
|
|
191
|
+
if (type !== 'file') {
|
|
192
|
+
throw new SkillPackageError('special-file', 'A skill contains a special file.')
|
|
193
|
+
}
|
|
194
|
+
totals.files++
|
|
195
|
+
totals.bytes += Number(info.size)
|
|
196
|
+
if (totals.files > PACKAGE_MAX_FILES || totals.bytes > PACKAGE_MAX_BYTES) {
|
|
197
|
+
throw new SkillPackageError('package-too-large', 'The skill is too large to copy safely.', {
|
|
198
|
+
files: PACKAGE_MAX_FILES,
|
|
199
|
+
bytes: PACKAGE_MAX_BYTES,
|
|
200
|
+
})
|
|
201
|
+
}
|
|
202
|
+
const extension = path.extname(relative).toLowerCase()
|
|
203
|
+
files.push({
|
|
204
|
+
path: source,
|
|
205
|
+
rel: relative.split(path.sep).join('/'),
|
|
206
|
+
size: info.size,
|
|
207
|
+
mtimeNs: info.mtimeNs,
|
|
208
|
+
dev: info.dev,
|
|
209
|
+
ino: info.ino,
|
|
210
|
+
mode: Number(info.mode),
|
|
211
|
+
script: SCRIPT_EXTENSIONS.has(extension),
|
|
212
|
+
})
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function hashFiles(files, buffers) {
|
|
217
|
+
const content = createHash('sha256')
|
|
218
|
+
for (const file of files) {
|
|
219
|
+
content.update(file.rel)
|
|
220
|
+
content.update('\0')
|
|
221
|
+
content.update(buffers.get(file.rel))
|
|
222
|
+
content.update('\n')
|
|
223
|
+
}
|
|
224
|
+
return content.digest('hex')
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
function quickHash(files) {
|
|
228
|
+
const quick = createHash('sha256')
|
|
229
|
+
for (const file of files) {
|
|
230
|
+
quick.update(`${file.rel}\0${file.size}\0${file.mtimeNs}\n`)
|
|
231
|
+
}
|
|
232
|
+
return quick.digest('hex')
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
function resourceSummary(files) {
|
|
236
|
+
const resources = { scripts: 0, references: 0, assets: 0 }
|
|
237
|
+
for (const file of files) {
|
|
238
|
+
if (file.rel.startsWith('scripts/')) resources.scripts++
|
|
239
|
+
else if (file.rel.startsWith('references/')) resources.references++
|
|
240
|
+
else if (file.rel.startsWith('assets/')) resources.assets++
|
|
241
|
+
}
|
|
242
|
+
return resources
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
/**
|
|
246
|
+
* Read a skill directory bundle without following links outside it.
|
|
247
|
+
* Content is read only when requested, while the quick hash always comes from
|
|
248
|
+
* the stable path/size/mtime list.
|
|
249
|
+
*/
|
|
250
|
+
export async function readSkillPackage(file, { content = false, authorization } = {}) {
|
|
251
|
+
if (typeof file !== 'string' || !path.isAbsolute(file)) {
|
|
252
|
+
throw new SkillPackageError('invalid-path', 'The skill path is not absolute.')
|
|
253
|
+
}
|
|
254
|
+
const location = skillLocation(file)
|
|
255
|
+
let base
|
|
256
|
+
let skillFile
|
|
257
|
+
let skillInfo
|
|
258
|
+
try {
|
|
259
|
+
if (authorization) {
|
|
260
|
+
if (authorization.file !== file || authorization.directory !== location.root) {
|
|
261
|
+
throw new SkillPackageError('unsafe-path', 'The skill authorization does not match this package.')
|
|
262
|
+
}
|
|
263
|
+
const verified = await verifySourceAuthorization(authorization)
|
|
264
|
+
base = verified.directory
|
|
265
|
+
skillFile = verified.file
|
|
266
|
+
skillInfo = verified.fileInfo
|
|
267
|
+
} else {
|
|
268
|
+
base = await realpath(location.root)
|
|
269
|
+
skillFile = await realpath(location.file)
|
|
270
|
+
}
|
|
271
|
+
} catch (error) {
|
|
272
|
+
if (error instanceof SkillPackageError) throw error
|
|
273
|
+
if (error?.code === 'ASSET_SOURCE_CHANGED') {
|
|
274
|
+
throw new SkillPackageError('source-changed', 'The skill source changed or left its authorized root.')
|
|
275
|
+
}
|
|
276
|
+
throw new SkillPackageError('missing', 'The skill file or folder no longer exists.')
|
|
277
|
+
}
|
|
278
|
+
if (!isPathInside(base, skillFile) || !(await stat(skillFile)).isFile()) {
|
|
279
|
+
throw new SkillPackageError('unsafe-path', 'The skill file cannot be resolved inside its package.')
|
|
280
|
+
}
|
|
281
|
+
skillInfo ??= await lstat(skillFile, { bigint: true })
|
|
282
|
+
if (!skillInfo.isFile() || skillInfo.nlink > 1n) {
|
|
283
|
+
throw new SkillPackageError('unsafe-file', 'SKILL.md must be a regular file.')
|
|
284
|
+
}
|
|
285
|
+
const skillText = (await stableFileBuffer(skillFile, skillInfo)).toString('utf8')
|
|
286
|
+
const parsed = parseSkillFile(skillText)
|
|
287
|
+
const name = typeof parsed.fields.name === 'string' ? parsed.fields.name.trim() : ''
|
|
288
|
+
const description = typeof parsed.fields.description === 'string' ? parsed.fields.description.trim() : ''
|
|
289
|
+
if (!name || !description) {
|
|
290
|
+
throw new SkillPackageError('invalid-frontmatter', 'SKILL.md needs name and description frontmatter.')
|
|
291
|
+
}
|
|
292
|
+
if (!SKILL_NAME.test(name)) {
|
|
293
|
+
throw new SkillPackageError('invalid-name', 'The skill name is not valid kebab-case.')
|
|
294
|
+
}
|
|
295
|
+
const invocation = invocationPolicy(parsed.fields)
|
|
296
|
+
|
|
297
|
+
const files = []
|
|
298
|
+
const totals = { files: 0, bytes: 0 }
|
|
299
|
+
if (location.layout === 'directory') {
|
|
300
|
+
await walkPackage(base, base, files, totals)
|
|
301
|
+
if (!files.some(entry => entry.rel === 'SKILL.md')) {
|
|
302
|
+
throw new SkillPackageError('missing', 'SKILL.md is missing from the package list.')
|
|
303
|
+
}
|
|
304
|
+
} else {
|
|
305
|
+
files.push({
|
|
306
|
+
path: skillFile,
|
|
307
|
+
rel: 'SKILL.md',
|
|
308
|
+
size: skillInfo.size,
|
|
309
|
+
mtimeNs: skillInfo.mtimeNs,
|
|
310
|
+
dev: skillInfo.dev,
|
|
311
|
+
ino: skillInfo.ino,
|
|
312
|
+
mode: Number(skillInfo.mode),
|
|
313
|
+
script: false,
|
|
314
|
+
})
|
|
315
|
+
totals.files = 1
|
|
316
|
+
totals.bytes = Number(skillInfo.size)
|
|
317
|
+
}
|
|
318
|
+
const buffers = new Map()
|
|
319
|
+
let contentHash
|
|
320
|
+
if (content) {
|
|
321
|
+
for (const entry of files) {
|
|
322
|
+
buffers.set(entry.rel, await stableFileBuffer(entry.path, entry))
|
|
323
|
+
}
|
|
324
|
+
contentHash = hashFiles(files, buffers)
|
|
325
|
+
}
|
|
326
|
+
const resources = resourceSummary(files)
|
|
327
|
+
return {
|
|
328
|
+
layout: location.layout,
|
|
329
|
+
name,
|
|
330
|
+
description,
|
|
331
|
+
invocation,
|
|
332
|
+
body: parsed.body.trim(),
|
|
333
|
+
sourceFile: file,
|
|
334
|
+
...(authorization ? { authorization } : {}),
|
|
335
|
+
sourceRoot: base,
|
|
336
|
+
skillFile,
|
|
337
|
+
files,
|
|
338
|
+
fileCount: files.length,
|
|
339
|
+
bytes: totals.bytes,
|
|
340
|
+
quickHash: quickHash(files),
|
|
341
|
+
...(contentHash === undefined ? {} : { contentHash }),
|
|
342
|
+
resources,
|
|
343
|
+
hasScripts: resources.scripts > 0 || files.some(entry => entry.script),
|
|
344
|
+
scriptFiles: files.filter(entry => entry.script).map(entry => entry.rel).slice(0, 20),
|
|
345
|
+
}
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
export async function sourceState(file, recorded, { authorization } = {}) {
|
|
349
|
+
let current
|
|
350
|
+
try {
|
|
351
|
+
current = await readSkillPackage(file, { content: false, authorization })
|
|
352
|
+
} catch (error) {
|
|
353
|
+
if (error instanceof SkillPackageError && error.code === 'missing') return 'missing'
|
|
354
|
+
if (error instanceof SkillPackageError) return 'invalid'
|
|
355
|
+
throw error
|
|
356
|
+
}
|
|
357
|
+
if (recorded?.quickHash === current.quickHash && recorded?.contentHash !== undefined) return 'same'
|
|
358
|
+
const full = await readSkillPackage(file, { content: true, authorization })
|
|
359
|
+
return full.contentHash === recorded?.contentHash ? 'same' : 'changed'
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/**
|
|
363
|
+
* Copy a validated package snapshot into a fresh directory and verify the
|
|
364
|
+
* destination before the caller makes it visible.
|
|
365
|
+
*/
|
|
366
|
+
export async function copySkillPackage(snapshot, destination) {
|
|
367
|
+
if (snapshot.layout !== 'directory') {
|
|
368
|
+
throw new SkillPackageError('flat-package', 'Only directory skill bundles can be enabled.')
|
|
369
|
+
}
|
|
370
|
+
const partial = `${destination}.partial-${process.pid}-${Date.now()}`
|
|
371
|
+
await mkdir(path.dirname(destination), { recursive: true })
|
|
372
|
+
try {
|
|
373
|
+
await mkdir(partial, { recursive: true })
|
|
374
|
+
const ordered = [...snapshot.files].sort((left, right) => {
|
|
375
|
+
if (left.rel === 'SKILL.md') return 1
|
|
376
|
+
if (right.rel === 'SKILL.md') return -1
|
|
377
|
+
return left.rel.localeCompare(right.rel)
|
|
378
|
+
})
|
|
379
|
+
for (const file of ordered) {
|
|
380
|
+
const target = path.join(partial, ...file.rel.split('/'))
|
|
381
|
+
if (!isPathInside(partial, target)) {
|
|
382
|
+
throw new SkillPackageError('unsafe-path', 'A skill file leaves its destination.')
|
|
383
|
+
}
|
|
384
|
+
await mkdir(path.dirname(target), { recursive: true })
|
|
385
|
+
await writeFile(target, await stableFileBuffer(file.path, file))
|
|
386
|
+
if (process.platform !== 'win32') await chmod(target, file.mode & 0o777)
|
|
387
|
+
}
|
|
388
|
+
const copied = await readSkillPackage(path.join(partial, 'SKILL.md'), { content: true })
|
|
389
|
+
if (copied.contentHash !== snapshot.contentHash || copied.fileCount !== snapshot.fileCount) {
|
|
390
|
+
throw new SkillPackageError('source-changed', 'The skill changed while its snapshot was being copied.')
|
|
391
|
+
}
|
|
392
|
+
await moveIntoPlace(partial, destination)
|
|
393
|
+
return copied
|
|
394
|
+
} catch (error) {
|
|
395
|
+
await rm(partial, { recursive: true, force: true }).catch(() => {})
|
|
396
|
+
throw error
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
async function moveIntoPlace(source, destination) {
|
|
401
|
+
let last
|
|
402
|
+
for (let attempt = 0; attempt < 6; attempt++) {
|
|
403
|
+
try {
|
|
404
|
+
await rename(source, destination)
|
|
405
|
+
return
|
|
406
|
+
} catch (error) {
|
|
407
|
+
last = error
|
|
408
|
+
if (!['EPERM', 'EBUSY', 'EACCES', 'EEXIST'].includes(error.code) || attempt === 5) break
|
|
409
|
+
await new Promise(resolve => setTimeout(resolve, 40 * (attempt + 1)))
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
throw last
|
|
413
|
+
}
|
|
414
|
+
|
|
415
|
+
export function snapshotIdFor(name, contentHash) {
|
|
416
|
+
return `${name}-${contentHash.slice(0, 16)}`
|
|
417
|
+
}
|
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
import path from 'node:path'
|
|
2
|
+
import {
|
|
3
|
+
PROVIDER_NAME, PROVIDER_RANK, SkillActivationStore, SkillHandoff, SkillHandoffError,
|
|
4
|
+
findProjectRoot, resolveSkillStoreRoot,
|
|
5
|
+
} from './skill-handoff.js'
|
|
6
|
+
|
|
7
|
+
function pathKey(value) {
|
|
8
|
+
const normalized = path.normalize(value)
|
|
9
|
+
return process.platform === 'win32' ? normalized.toLowerCase() : normalized
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
function unavailableStatuses(skills, reason) {
|
|
13
|
+
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
|
+
}])),
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async function defaultLoadProvider() {
|
|
30
|
+
return import('@deepseek-ai/dsh-skill-filesystem')
|
|
31
|
+
}
|
|
32
|
+
|
|
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)
|
|
56
|
+
},
|
|
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)
|
|
60
|
+
},
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
const handoff = new SkillHandoff({
|
|
64
|
+
store,
|
|
65
|
+
native,
|
|
66
|
+
invalidate() {
|
|
67
|
+
control?.invalidate?.()
|
|
68
|
+
},
|
|
69
|
+
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
|
+
}
|
|
100
|
+
},
|
|
101
|
+
})
|
|
102
|
+
|
|
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 不可用。')
|
|
111
|
+
}
|
|
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
|
+
}
|
|
147
|
+
}))
|
|
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 => {
|
|
167
|
+
failure = error
|
|
168
|
+
ctx.logger?.warn?.(`agent-bridge native skills unavailable: ${error?.message ?? error}`)
|
|
169
|
+
})
|
|
170
|
+
|
|
171
|
+
async function ensure() {
|
|
172
|
+
await ready
|
|
173
|
+
if (failure) throw failure
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
const bridge = {
|
|
177
|
+
ready,
|
|
178
|
+
get available() {
|
|
179
|
+
return !failure && Boolean(control)
|
|
180
|
+
},
|
|
181
|
+
get failure() {
|
|
182
|
+
return failure
|
|
183
|
+
},
|
|
184
|
+
async inspect(project, skills) {
|
|
185
|
+
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
|
+
}
|
|
198
|
+
}
|
|
199
|
+
},
|
|
200
|
+
async conversationCandidates(project, usedSkills, skills) {
|
|
201
|
+
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] }))
|
|
211
|
+
} catch {
|
|
212
|
+
return []
|
|
213
|
+
}
|
|
214
|
+
},
|
|
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
|
+
},
|
|
235
|
+
async revision() {
|
|
236
|
+
await ensure()
|
|
237
|
+
return store.revision()
|
|
238
|
+
},
|
|
239
|
+
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. */ }
|
|
245
|
+
},
|
|
246
|
+
}
|
|
247
|
+
ctx.effect(() => () => bridge.dispose())
|
|
248
|
+
return bridge
|
|
249
|
+
}
|