@wwwfz/dsh-agent-bridge 0.10.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,26 +1,17 @@
1
- import { constants } from 'node:fs'
2
- import { chmod, lstat, mkdir, open, readdir, realpath, rename, rm, stat, writeFile } from 'node:fs/promises'
3
1
  import { createHash } from 'node:crypto'
2
+ import { constants } from 'node:fs'
3
+ import { lstat, mkdir, mkdtemp, open, readdir, realpath, rename, rm, writeFile } from 'node:fs/promises'
4
4
  import path from 'node:path'
5
+ import { setTimeout as delay } from 'node:timers/promises'
5
6
  import { verifySourceAuthorization } from './assets.js'
6
7
 
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
8
  export const SKILL_NAME = /^[a-z0-9]+(?:-[a-z0-9]+)*$/
12
9
  export const PACKAGE_MAX_FILES = 1000
13
10
  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
- ])
11
+ const skipNames = new Set(['.git', '.DS_Store'])
12
+ const scriptName = /\.(?:sh|bash|zsh|fish|ps1|bat|cmd|py|js|mjs|cjs|ts|rb|pl|php|lua)$/i
13
+ const credentialName = /^(?:\.env(?:\..+)?|\.git-credentials|\.netrc|\.npmrc|\.pypirc|auth\.json|credentials\.json|secrets\.json|id_(?:ecdsa|ed25519|rsa))$|\.(?:key|p12|pem|pfx)$/i
14
+ const safeEnvExample = /^\.env\.(?:example|sample|template)$/i
24
15
 
25
16
  export class SkillPackageError extends Error {
26
17
  constructor(code, message, details) {
@@ -31,387 +22,378 @@ export class SkillPackageError extends Error {
31
22
  }
32
23
  }
33
24
 
34
- function pathKey(value) {
35
- const normalized = path.normalize(value)
25
+ function pathKey(file) {
26
+ const normalized = path.normalize(file)
36
27
  return process.platform === 'win32' ? normalized.toLowerCase() : normalized
37
28
  }
38
29
 
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))
30
+ function relativePath(root, file) {
31
+ const relative = path.relative(root, file)
32
+ return relative !== '..' && !relative.startsWith('..' + path.sep) && !path.isAbsolute(relative)
33
+ ? relative : undefined
42
34
  }
43
35
 
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("''", "'")
36
+ function sameIdentity(left, right) {
37
+ return left.dev === right.dev && left.ino === right.ino && left.size === right.size
38
+ && left.mtimeNs === right.mtimeNs && left.ctimeNs === right.ctimeNs
39
+ }
40
+
41
+ function changed() {
42
+ return new SkillPackageError('source-changed', 'The skill source changed while it was being read.')
43
+ }
44
+
45
+ function protectName(name) {
46
+ if (credentialName.test(name) && !safeEnvExample.test(name)) {
47
+ throw new SkillPackageError('sensitive-file', 'A skill package contains a credential-like file and was not copied.')
51
48
  }
52
- return text
53
49
  }
54
50
 
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])
51
+ function yamlScalar(text) {
52
+ const raw = text.trim()
53
+ const quote = raw[0]
54
+ if (quote !== '"' && quote !== "'") return raw.replace(/[ \t]+#.*$/, '').trimEnd()
55
+ const pairs = quote === '"' ? /^"((?:[^"\\]|\\.)*)"[ \t]*(?:#.*)?$/ : /^'((?:[^']|'')*)'[ \t]*(?:#.*)?$/
56
+ const match = pairs.exec(raw)
57
+ if (!match) throw new SkillPackageError('invalid-frontmatter', 'The skill contains a malformed quoted value.')
58
+ if (quote === "'") return match[1].replaceAll("''", "'")
59
+ const escapes = {
60
+ '0': '\0', a: '\x07', b: '\b', t: '\t', n: '\n', v: '\v', f: '\f', r: '\r', e: '\x1b',
61
+ ' ': ' ', '"': '"', '/': '/', '\\': '\\', N: '\u0085', _: '\u00a0', L: '\u2028', P: '\u2029',
62
+ }
63
+ return match[1].replace(/\\(x[0-9a-fA-F]{2}|u[0-9a-fA-F]{4}|U[0-9a-fA-F]{8}|.)/g, (_, escaped) => {
64
+ if (Object.hasOwn(escapes, escaped)) return escapes[escaped]
65
+ const codepoint = escaped.length > 1 ? Number.parseInt(escaped.slice(1), 16) : -1
66
+ if (codepoint < 0 || codepoint > 0x10ffff || (codepoint >= 0xd800 && codepoint <= 0xdfff)) {
67
+ throw new SkillPackageError('invalid-frontmatter', 'The skill contains an unsupported YAML escape.')
72
68
  }
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+$/, '')
69
+ return String.fromCodePoint(codepoint)
70
+ })
71
+ }
72
+
73
+ function blockScalar(rows, mode) {
74
+ const indent = rows.reduce((min, line) => line.trim() ? Math.min(min, line.match(/^[ \t]*/)[0].length) : min, Infinity)
75
+ const dedented = rows.map(line => line.slice(indent))
76
+ if (mode === '|') return dedented.join('\n')
77
+ return dedented.reduce((value, line, index) => {
78
+ const previous = dedented[index - 1]
79
+ const separator = previous === undefined ? '' : previous && line ? ' ' : '\n'
80
+ return value + separator + line
81
+ }, '')
82
+ }
83
+
84
+ const fieldPattern = /^([A-Za-z_][\w.-]*|"[^"\\]*(?:\\.[^"\\]*)*"|'(?:[^']|'')*')[ \t]*:[ \t]*(.*)$/
85
+ const spaces = line => line.match(/^[ \t]*/)[0].length
86
+ const policyKeys = new Set(['disable-model-invocation', 'user-invocable'])
87
+
88
+ function metadataValue(value, children) {
89
+ if (value.startsWith('{')) {
90
+ try {
91
+ const parsed = JSON.parse(value)
92
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) return parsed
93
+ } catch { /* Non-JSON flow mappings are outside the supported metadata subset. */ }
94
+ return undefined
95
+ }
96
+ if (value || !children.length) return undefined
97
+ const metadata = Object.create(null)
98
+ const indent = spaces(children[0])
99
+ for (const line of children) {
100
+ const entry = fieldPattern.exec(line.slice(indent))
101
+ if (spaces(line) !== indent || !entry || !entry[2]) return undefined
102
+ const key = yamlScalar(entry[1])
103
+ if (Object.hasOwn(metadata, key)) return undefined
104
+ const scalar = yamlScalar(entry[2])
105
+ if (/^[\[{&*!|>]/.test(scalar) && !/^[\"']/.test(entry[2])) return undefined
106
+ if (/^[\"']/.test(entry[2])) metadata[key] = scalar
107
+ else if (/^(?:null|~)$/i.test(scalar)) metadata[key] = null
108
+ else if (/^(?:true|false)$/i.test(scalar)) metadata[key] = scalar.toLowerCase() === 'true'
109
+ else if (/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i.test(scalar) && Number.isFinite(Number(scalar))) {
110
+ metadata[key] = Number(scalar)
111
+ } else metadata[key] = scalar
78
112
  }
79
- return { fields, body: text.slice(match[0].length) }
113
+ return metadata
80
114
  }
81
115
 
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
116
+ export function parseSkillFile(text) {
117
+ const opening = /^\uFEFF?---[ \t]*\r?\n/.exec(text)
118
+ const fields = Object.create(null)
119
+ if (!opening) return { fields, body: text }
120
+ const boundary = /^---[ \t]*(?:\r?\n|$)/gm
121
+ boundary.lastIndex = opening[0].length
122
+ const end = boundary.exec(text)
123
+ if (!end) return { fields, body: text }
124
+ const header = text.slice(opening[0].length, end.index)
125
+ const rows = header.replace(/\r?\n$/, '').split(/\r?\n/)
126
+ const meaningful = line => Boolean(line.trim() && !line.trimStart().startsWith('#'))
127
+ const indent = rows.reduce((min, line) => meaningful(line) ? Math.min(min, spaces(line)) : min, Infinity)
128
+ for (let row = 0; row < rows.length; row++) {
129
+ if (!meaningful(rows[row])) continue
130
+ const property = spaces(rows[row]) === indent && fieldPattern.exec(rows[row].slice(indent))
131
+ if (!property) {
132
+ throw new SkillPackageError('invalid-frontmatter', 'The skill frontmatter contains an unsupported YAML field or policy.')
133
+ }
134
+ const key = yamlScalar(property[1])
135
+ const value = property[2].trimEnd()
136
+ if (Object.hasOwn(fields, key) || key === '<<') {
137
+ throw new SkillPackageError('invalid-frontmatter', 'The skill frontmatter contains a duplicate field or YAML merge.')
138
+ }
139
+ const children = []
140
+ while (row + 1 < rows.length && (!meaningful(rows[row + 1]) || spaces(rows[row + 1]) > indent)) {
141
+ children.push(rows[++row])
142
+ }
143
+ const operator = /^([|>])([+-]?)[ \t]*(?:#.*)?$/.exec(value)
144
+ if (key === 'metadata') {
145
+ fields[key] = metadataValue(value, children.filter(meaningful))
146
+ } else if (operator) {
147
+ const block = blockScalar(children.filter(line => !line.trim() || spaces(line) > indent), operator[1])
148
+ fields[key] = operator[2] === '+' ? block : block.trimEnd()
149
+ } else {
150
+ if (policyKeys.has(key) && children.some(meaningful)) {
151
+ throw new SkillPackageError('invalid-invocation', 'The skill invocation policy must use a scalar value.')
152
+ }
153
+ fields[key] = yamlScalar(value)
154
+ }
92
155
  }
93
- throw new SkillPackageError('invalid-invocation', `Frontmatter ${key} must be a boolean.`)
156
+ return { fields, body: text.slice(boundary.lastIndex) }
94
157
  }
95
158
 
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.')
159
+ function readInvocation(fields) {
160
+ function flag(name, fallback) {
161
+ if (!Object.hasOwn(fields, name)) return fallback
162
+ const value = fields[name].toLowerCase()
163
+ if (/^(?:true|yes|on|1)$/.test(value)) return true
164
+ if (/^(?:false|no|off|0)$/.test(value)) return false
165
+ throw new SkillPackageError('invalid-invocation', 'Frontmatter ' + name + ' must be a boolean.')
100
166
  }
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,
167
+ if (['disableModelInvocation', 'modelInvocable', 'userInvocable'].some(name => Object.hasOwn(fields, name))) {
168
+ throw new SkillPackageError('invalid-invocation', 'Skill invocation fields must use kebab-case.')
106
169
  }
170
+ return { modelInvocable: !flag('disable-model-invocation', false), userInvocable: flag('user-invocable', true) }
107
171
  }
108
172
 
109
173
  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 }
174
+ return { layout: path.basename(file) === 'SKILL.md' ? 'directory' : 'flat', root: path.dirname(file), file }
175
+ }
176
+
177
+ async function scanFile(root, entry, info, rel) {
178
+ const target = await realpath(entry)
179
+ const relative = relativePath(root, target)
180
+ if (relative === undefined) throw new SkillPackageError('unsafe-link', 'A skill links outside its package.')
181
+ if (info.isSymbolicLink()) {
182
+ relative.split(path.sep).forEach(protectName)
183
+ info = await lstat(target, { bigint: true })
184
+ if (!info.isFile()) throw new SkillPackageError('unsafe-link', 'A skill link must resolve to a regular file.')
185
+ } else if (pathKey(entry) !== pathKey(target)) throw changed()
186
+ if (!info.isFile() || info.nlink !== 1n) {
187
+ throw new SkillPackageError('unsafe-file', 'Skill files must be regular files without hard links.')
188
+ }
189
+ return { entry, path: target, rel, script: scriptName.test(rel), info }
113
190
  }
114
191
 
115
- async function stableFileBuffer(file, expected) {
192
+ async function readChecked(root, rootInfo, file) {
193
+ async function checkPath() {
194
+ const now = await lstat(root, { bigint: true })
195
+ if (!now.isDirectory() || now.dev !== rootInfo.dev || now.ino !== rootInfo.ino
196
+ || pathKey(await realpath(root)) !== pathKey(root)
197
+ || pathKey(await realpath(file.entry)) !== pathKey(file.path)) throw changed()
198
+ }
116
199
  let handle
117
200
  try {
118
- handle = await open(file, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0))
201
+ await checkPath()
202
+ handle = await open(file.path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0) | (constants.O_NONBLOCK ?? 0))
119
203
  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.')
204
+ if (!before.isFile() || before.nlink !== 1n || !sameIdentity(before, file.info)) throw changed()
205
+ const size = Number(before.size)
206
+ if (size > PACKAGE_MAX_BYTES) throw packageLimit()
207
+ const bytes = Buffer.allocUnsafe(size)
208
+ let progress = 0
209
+ while (progress < size) {
210
+ const { bytesRead } = await handle.read(bytes, progress, size - progress, progress)
211
+ if (!bytesRead) throw changed()
212
+ progress += bytesRead
123
213
  }
124
- const bytes = await handle.readFile()
125
214
  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
- }
215
+ await checkPath()
216
+ if (after.nlink !== 1n || !sameIdentity(before, after)
217
+ || !sameIdentity(after, await lstat(file.path, { bigint: true }))) throw changed()
130
218
  return bytes
219
+ } catch (error) {
220
+ if (error instanceof SkillPackageError) throw error
221
+ throw changed()
131
222
  } finally {
132
223
  await handle?.close()
133
224
  }
134
225
  }
135
226
 
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
- }
227
+ function packageLimit() {
228
+ return new SkillPackageError('package-too-large', 'The skill is too large to copy safely.', {
229
+ files: PACKAGE_MAX_FILES, bytes: PACKAGE_MAX_BYTES,
230
+ })
214
231
  }
215
232
 
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')
233
+ async function inventory(root, skillFile, layout) {
234
+ const files = []
235
+ let bytes = 0
236
+ function remember(file) {
237
+ bytes += Number(file.info.size)
238
+ if (bytes > PACKAGE_MAX_BYTES || files.length >= PACKAGE_MAX_FILES) throw packageLimit()
239
+ files.push(file)
223
240
  }
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`)
241
+ if (layout === 'flat') {
242
+ remember(await scanFile(root, skillFile, await lstat(skillFile, { bigint: true }), 'SKILL.md'))
243
+ return { files, bytes }
231
244
  }
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++
245
+ const visit = async directory => {
246
+ if (pathKey(await realpath(directory)) !== pathKey(directory)) throw changed()
247
+ for (const name of (await readdir(directory)).sort()) {
248
+ if (skipNames.has(name)) continue
249
+ protectName(name)
250
+ const entry = path.join(directory, name)
251
+ const info = await lstat(entry, { bigint: true })
252
+ if (info.isDirectory()) await visit(entry)
253
+ else {
254
+ const rel = path.relative(root, entry).split(path.sep).join('/')
255
+ remember(await scanFile(root, entry, info, rel))
256
+ }
257
+ }
258
+ if (pathKey(await realpath(directory)) !== pathKey(directory)) throw changed()
241
259
  }
242
- return resources
260
+ await visit(root)
261
+ return { files, bytes }
243
262
  }
244
263
 
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 } = {}) {
264
+ async function sourceLocation(file, authorization) {
251
265
  if (typeof file !== 'string' || !path.isAbsolute(file)) {
252
266
  throw new SkillPackageError('invalid-path', 'The skill path is not absolute.')
253
267
  }
254
268
  const location = skillLocation(file)
255
- let base
256
- let skillFile
257
- let skillInfo
258
269
  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
+ const authorized = authorization && await verifySourceAuthorization(authorization)
271
+ if (authorized && (authorized.file !== file || authorized.directory !== location.root)) {
272
+ throw new SkillPackageError('unsafe-path', 'The skill authorization does not match this package.')
270
273
  }
274
+ const root = authorized?.directory ?? await realpath(location.root)
275
+ const rootInfo = await lstat(root, { bigint: true })
276
+ if (!rootInfo.isDirectory()) throw new SkillPackageError('unsafe-path', 'The skill root is not a directory.')
277
+ const skillFile = path.join(root, path.basename(file))
278
+ await lstat(skillFile)
279
+ return { root, rootInfo, skillFile, layout: location.layout }
271
280
  } catch (error) {
272
281
  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.')
282
+ if (error?.code === 'ASSET_SOURCE_CHANGED') throw changed()
283
+ if (error?.code === 'ENOENT' || error?.code === 'ENOTDIR') {
284
+ throw new SkillPackageError('missing', 'The skill file or folder no longer exists.')
275
285
  }
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.')
286
+ throw new SkillPackageError('unreadable-package', 'The skill package could not be inspected.')
284
287
  }
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.')
288
+ }
289
+
290
+ export async function readSkillPackage(file, { content = false, authorization } = {}) {
291
+ const { root, rootInfo, skillFile, layout } = await sourceLocation(file, authorization)
292
+ let manifest
293
+ try { manifest = await inventory(root, skillFile, layout) }
294
+ catch (error) {
295
+ if (error instanceof SkillPackageError) throw error
296
+ throw new SkillPackageError('unreadable-package', 'The skill package could not be inspected.')
294
297
  }
295
- const invocation = invocationPolicy(parsed.fields)
298
+ const { files, bytes } = manifest
299
+ const instruction = files.find(entry => entry.rel === 'SKILL.md')
300
+ if (!instruction) throw new SkillPackageError('missing', 'SKILL.md is missing from the package.')
301
+ const instructions = await readChecked(root, rootInfo, instruction)
302
+ const { fields, body } = parseSkillFile(instructions.toString('utf8'))
303
+ const name = fields.name?.trim()
304
+ const description = fields.description?.trim()
305
+ if (!name || !description) throw new SkillPackageError('invalid-frontmatter', 'SKILL.md needs name and description frontmatter.')
306
+ if (!SKILL_NAME.test(name)) throw new SkillPackageError('invalid-name', 'The skill name is not valid kebab-case.')
307
+ const invocation = readInvocation(fields)
308
+ const metadata = createHash('sha256')
309
+ const contents = content ? createHash('sha256') : undefined
310
+ const resources = { scripts: 0, references: 0, assets: 0 }
296
311
 
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.')
312
+ // The on-disk activation receipts use these version-1 fingerprint encodings.
313
+ // Preserve the sorted depth-first order, slash form and field delimiters.
314
+ for (const entry of files) {
315
+ metadata.update(entry.rel).update('\0' + entry.info.size + '\0' + entry.info.mtimeNs + '\n')
316
+ const folder = entry.rel.split('/')[0]
317
+ if (Object.hasOwn(resources, folder) && entry.rel.includes('/')) resources[folder]++
318
+ if (contents) {
319
+ const data = entry === instruction ? instructions : await readChecked(root, rootInfo, entry)
320
+ contents.update(entry.rel).update('\0').update(data).update('\n')
303
321
  }
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
322
  }
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)
323
+ if (authorization) {
324
+ try { await verifySourceAuthorization(authorization) } catch { throw changed() }
325
325
  }
326
- const resources = resourceSummary(files)
327
326
  return {
328
- layout: location.layout,
329
- name,
330
- description,
331
- invocation,
332
- body: parsed.body.trim(),
333
- sourceFile: file,
327
+ layout, name, description, invocation, body: body.trim(),
328
+ ...(fields.whenToUse?.trim() ? { whenToUse: fields.whenToUse.trim() } : {}),
329
+ ...(fields.metadata ? { metadata: fields.metadata } : {}),
330
+ sourceFile: file, sourceRoot: root, skillFile: instruction.path,
334
331
  ...(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,
332
+ files, fileCount: files.length, bytes, resources,
333
+ quickHash: metadata.digest('hex'),
334
+ ...(contents ? { contentHash: contents.digest('hex') } : {}),
343
335
  hasScripts: resources.scripts > 0 || files.some(entry => entry.script),
344
- scriptFiles: files.filter(entry => entry.script).map(entry => entry.rel).slice(0, 20),
336
+ scriptFiles: files.filter(entry => entry.script).slice(0, 20).map(entry => entry.rel),
345
337
  }
346
338
  }
347
339
 
348
340
  export async function sourceState(file, recorded, { authorization } = {}) {
349
- let current
350
341
  try {
351
- current = await readSkillPackage(file, { content: false, authorization })
342
+ const current = await readSkillPackage(file, { authorization })
343
+ if (current.quickHash === recorded?.quickHash && recorded?.contentHash !== undefined) return 'same'
344
+ const verified = await readSkillPackage(file, { content: true, authorization })
345
+ return verified.contentHash === recorded?.contentHash ? 'same' : 'changed'
352
346
  } catch (error) {
353
- if (error instanceof SkillPackageError && error.code === 'missing') return 'missing'
354
- if (error instanceof SkillPackageError) return 'invalid'
355
- throw error
347
+ if (!(error instanceof SkillPackageError)) throw error
348
+ return error.code === 'missing' ? 'missing' : 'invalid'
356
349
  }
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
350
  }
361
351
 
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.')
352
+ async function publishDirectory(staging, destination) {
353
+ for (let attempt = 0; ; attempt++) {
354
+ try {
355
+ await rename(staging, destination)
356
+ return
357
+ } catch (error) {
358
+ if (attempt === 5 || !['EACCES', 'EBUSY', 'EPERM'].includes(error.code)) throw error
359
+ await delay(40 * (attempt + 1))
360
+ }
369
361
  }
370
- const partial = `${destination}.partial-${process.pid}-${Date.now()}`
362
+ }
363
+
364
+ export async function copySkillPackage(snapshot, destination) {
365
+ if (snapshot.layout !== 'directory') throw new SkillPackageError('flat-package', 'Only directory skill bundles can be enabled.')
366
+ const current = await readSkillPackage(snapshot.sourceFile, { content: true, authorization: snapshot.authorization })
367
+ if (current.contentHash !== snapshot.contentHash || current.quickHash !== snapshot.quickHash) throw changed()
368
+ const { sourceRoot: root } = current
369
+ const rootInfo = await lstat(root, { bigint: true })
371
370
  await mkdir(path.dirname(destination), { recursive: true })
371
+ const stage = await mkdtemp(destination + '.part-')
372
+ let committed = false
372
373
  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
- }
374
+ for (const file of current.files) {
375
+ const target = path.join(stage, ...file.rel.split('/'))
376
+ if (!relativePath(stage, target)) throw new SkillPackageError('unsafe-path', 'A skill file leaves its destination.')
377
+ const bytes = await readChecked(root, rootInfo, file)
384
378
  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.')
379
+ await writeFile(target, bytes, { flag: 'wx', mode: 0o600 })
380
+ if (process.platform !== 'win32') {
381
+ const handle = await open(target, 'r')
382
+ try { await handle.chmod(Number(file.info.mode) & 0o777) } finally { await handle.close() }
383
+ }
391
384
  }
392
- await moveIntoPlace(partial, destination)
385
+ const copied = await readSkillPackage(path.join(stage, 'SKILL.md'), { content: true })
386
+ if (copied.contentHash !== snapshot.contentHash || copied.fileCount !== snapshot.fileCount) throw changed()
387
+ await publishDirectory(stage, destination)
388
+ committed = true
393
389
  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)))
390
+ } finally {
391
+ if (!committed && path.dirname(stage) === path.dirname(destination)) {
392
+ await rm(stage, { recursive: true, force: true }).catch(() => {})
410
393
  }
411
394
  }
412
- throw last
413
395
  }
414
396
 
415
397
  export function snapshotIdFor(name, contentHash) {
416
- return `${name}-${contentHash.slice(0, 16)}`
398
+ return name + '-' + contentHash.slice(0, 16)
417
399
  }