@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.
- package/README.md +56 -28
- package/THIRD_PARTY_NOTICES.md +5 -63
- package/package.json +2 -1
- package/src/assets.js +32 -19
- package/src/catalog.js +1139 -999
- package/src/client.js +37 -8
- package/src/conversation-search.js +55 -0
- package/src/conversation-store.js +189 -25
- package/src/export.js +3 -2
- package/src/handoff.js +149 -0
- package/src/history-attachment.js +41 -0
- package/src/index.js +31 -7
- package/src/project-archive.js +50 -0
- package/src/projects.js +109 -29
- package/src/session-import.js +17 -2
- package/src/skill-cli.js +287 -0
- package/src/skill-history.js +129 -0
- package/src/skill-output.js +19 -0
- package/src/skill-package.js +303 -321
- package/src/skill-provider.js +155 -193
- package/web/panel.css +28 -0
- package/web/panel.html +16 -3
- package/web/panel.js +632 -75
- package/web/reader.css +52 -0
- package/web/relay-categories.js +3 -0
- package/web/share-redaction.js +136 -0
- package/web/share-review.js +204 -0
package/src/skill-package.js
CHANGED
|
@@ -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
|
|
15
|
-
const
|
|
16
|
-
|
|
17
|
-
|
|
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(
|
|
35
|
-
const normalized = path.normalize(
|
|
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
|
|
40
|
-
const relative = path.relative(
|
|
41
|
-
return 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
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
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
|
-
|
|
56
|
-
const
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
const
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
const
|
|
70
|
-
|
|
71
|
-
|
|
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
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
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
|
|
113
|
+
return metadata
|
|
80
114
|
}
|
|
81
115
|
|
|
82
|
-
function
|
|
83
|
-
|
|
84
|
-
const
|
|
85
|
-
if (
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
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
|
-
|
|
156
|
+
return { fields, body: text.slice(boundary.lastIndex) }
|
|
94
157
|
}
|
|
95
158
|
|
|
96
|
-
function
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
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
|
-
|
|
102
|
-
|
|
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
|
-
|
|
112
|
-
|
|
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
|
|
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
|
-
|
|
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.
|
|
121
|
-
|
|
122
|
-
|
|
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
|
-
|
|
127
|
-
|
|
128
|
-
|
|
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
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
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
|
|
217
|
-
const
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
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
|
-
|
|
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
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
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
|
-
|
|
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
|
-
|
|
260
|
-
|
|
261
|
-
|
|
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
|
-
|
|
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('
|
|
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
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
const
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
throw new SkillPackageError('
|
|
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
|
|
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
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
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
|
-
|
|
319
|
-
|
|
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:
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
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
|
-
|
|
336
|
-
|
|
337
|
-
|
|
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)
|
|
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, {
|
|
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
|
|
354
|
-
|
|
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
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
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
|
-
|
|
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
|
-
|
|
374
|
-
|
|
375
|
-
if (
|
|
376
|
-
|
|
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,
|
|
386
|
-
if (process.platform !== 'win32')
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
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
|
|
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
|
-
}
|
|
395
|
-
|
|
396
|
-
|
|
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
|
|
398
|
+
return name + '-' + contentHash.slice(0, 16)
|
|
417
399
|
}
|