nish 0.41.0 → 0.44.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 +16 -4
- package/bin/nish-skills.js +233 -0
- package/docs/AI.md +282 -126
- package/llms.txt +4 -0
- package/package.json +14 -11
- package/runtime/core.d.ts +16 -0
- package/runtime/core.mjs +5 -0
- package/runtime/nish.d.ts +204 -33
- package/runtime/nish.h +19 -3
- package/runtime/nish.mjs +5 -1
- package/runtime/runtime-cross.c +15 -0
- package/runtime/runtime-net.c +876 -10
- package/runtime/runtime-region.c +21 -0
- package/runtime/runtime-sandbox.c +112 -15
- package/runtime/runtime-text.c +11 -0
- package/runtime/runtime-uring.c +533 -77
- package/runtime/runtime-wasm.c +3 -0
- package/runtime/runtime.c +474 -5
- package/runtime/sqlite/README.md +16 -3
- package/runtime/sqlite/nish-sqlite.c +940 -29
- package/scripts/build.sh +125 -29
- package/scripts/link-skills.mjs +1039 -0
- package/scripts/postinstall.mjs +43 -0
- package/skills/writing-nish/SKILL.md +144 -0
- package/std/README.md +3 -3
- package/std/crypto/base64url.ts +102 -1
- package/std/crypto/scram.ts +142 -0
- package/std/crypto/sha1.ts +99 -41
- package/std/host/ring.ts +1 -1
- package/std/host/text.ts +1 -1
- package/std/net/fetch.ts +9 -1
- package/std/net/handler.ts +79 -15
- package/std/net/http-server.ts +2 -3
- package/std/net/http1-server.ts +294 -51
- package/std/net/http3-server.ts +26 -15
- package/std/net/http3.ts +2 -2
- package/std/net/oidc.ts +1107 -0
- package/std/net/postgres-async.ts +64 -33
- package/std/net/postgres.ts +65 -76
- package/std/net/quic-conn-ack.ts +57 -7
- package/std/net/quic-frame.ts +104 -2
- package/std/net/quic-listener.ts +9 -2
- package/std/net/quic.ts +16 -1
- package/std/net/serve.ts +10 -8
- package/std/net/websocket.ts +188 -49
- package/std/sqlite.ts +325 -0
- package/std/text.ts +80 -11
|
@@ -0,0 +1,1039 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Find the agent skills of a project's installed Nish packages, and link the
|
|
3
|
+
* ones the user has accepted into its `.claude/skills/`, where Claude Code
|
|
4
|
+
* loads project skills from.
|
|
5
|
+
*
|
|
6
|
+
* A package ships a skill as `skills/<name>/SKILL.md` at its root, and the
|
|
7
|
+
* skill's id is `<name>`. The packages that qualify are `nish` itself and every
|
|
8
|
+
* top-level `node_modules/<pkg>` or `node_modules/@scope/<pkg>` whose
|
|
9
|
+
* `package.json` `exports` uses a `nish` condition. A plain npm package with a
|
|
10
|
+
* `skills/` directory is not a Nish package and is left alone.
|
|
11
|
+
*
|
|
12
|
+
* **Nothing is linked without consent.** A skill is instructions for Claude,
|
|
13
|
+
* and its frontmatter and body can grant tools, register hooks or run shell
|
|
14
|
+
* commands when it loads; any package in the tree can ship one, so the unit of
|
|
15
|
+
* consent is one package, one skill name and one hash of the whole skill
|
|
16
|
+
* directory. The accepted triples live in `.claude/skills/.nish-skills.json`;
|
|
17
|
+
* a new package, a rival claiming the same name, or a changed hash is not
|
|
18
|
+
* accepted until the user says so again. What a skill grants is read against an
|
|
19
|
+
* allowlist of inert frontmatter keys, so a key this file does not know counts
|
|
20
|
+
* as a grant.
|
|
21
|
+
*
|
|
22
|
+
* **Everything a package controls is checked, never trusted**: a skill name
|
|
23
|
+
* must match `NAME` before it is linked or printed in a command, and every
|
|
24
|
+
* other package string reaches the terminal only through `clean`.
|
|
25
|
+
*
|
|
26
|
+
* **Links, not copies**: `.claude/skills/<name>` is a relative symlink to
|
|
27
|
+
* `../../node_modules/<pkg>/skills/<name>`, so it survives moving the project.
|
|
28
|
+
* On win32 it is a junction to the absolute path, because a directory symlink
|
|
29
|
+
* there needs elevation. A link also follows an upgrade, which is the gap the
|
|
30
|
+
* hash cannot close on its own: the next run unlinks a skill whose hash moved.
|
|
31
|
+
*
|
|
32
|
+
* **The linker owns only its own links.** An entry under `.claude/skills/` is
|
|
33
|
+
* the linker's only if it is a link whose target resolves inside
|
|
34
|
+
* `<project>/node_modules/`. Anything else -- a real directory, a file, a link
|
|
35
|
+
* pointing elsewhere -- belongs to the user and is never replaced or removed.
|
|
36
|
+
* Every check is an `lstat`, and nothing follows a link before that test.
|
|
37
|
+
*
|
|
38
|
+
* Plain Node with `node:` built-ins only: it ships in the package, which keeps
|
|
39
|
+
* no runtime dependency, and `bin/nish-skills.js` runs it.
|
|
40
|
+
*/
|
|
41
|
+
import crypto from "node:crypto"
|
|
42
|
+
import fs from "node:fs"
|
|
43
|
+
import path from "node:path"
|
|
44
|
+
|
|
45
|
+
/** The `lstat` of a path, or null when nothing is there. */
|
|
46
|
+
const lstatOrNull = (file) => {
|
|
47
|
+
try {
|
|
48
|
+
return fs.lstatSync(file)
|
|
49
|
+
} catch {
|
|
50
|
+
return null
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** Whether an `exports` value uses a `nish` condition anywhere in it. */
|
|
55
|
+
const usesNishCondition = (exports) => {
|
|
56
|
+
if (Array.isArray(exports)) {
|
|
57
|
+
return exports.some(usesNishCondition)
|
|
58
|
+
}
|
|
59
|
+
if (exports === null || typeof exports !== "object") {
|
|
60
|
+
return false
|
|
61
|
+
}
|
|
62
|
+
return Object.entries(exports).some(([key, value]) => key === "nish" || usesNishCondition(value))
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* The parsed `package.json` in `dir`, or null when it is missing, malformed or
|
|
67
|
+
* anything but a regular file: a FIFO or a link to `/dev/zero` would hang the read.
|
|
68
|
+
*/
|
|
69
|
+
const packageJson = (dir) => {
|
|
70
|
+
const file = path.join(dir, "package.json")
|
|
71
|
+
try {
|
|
72
|
+
return fs.lstatSync(file).isFile() ? JSON.parse(fs.readFileSync(file, "utf8")) : null
|
|
73
|
+
} catch {
|
|
74
|
+
return null
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** Whether the package at `dir` is a Nish package: `nish` itself, or one whose exports use the `nish` condition. */
|
|
79
|
+
const isNishPackage = (name, dir) => name === "nish" || usesNishCondition(packageJson(dir)?.exports)
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The names of the directories in `dir`, links to one included, or none when
|
|
83
|
+
* it cannot be read. Only for `node_modules`, where a workspace member is a
|
|
84
|
+
* link; a skill directory is never reached through a link (see `skillsOf`).
|
|
85
|
+
*/
|
|
86
|
+
const subdirectories = (dir) => {
|
|
87
|
+
try {
|
|
88
|
+
return fs
|
|
89
|
+
.readdirSync(dir, { withFileTypes: true })
|
|
90
|
+
.filter((e) => e.isDirectory() || e.isSymbolicLink())
|
|
91
|
+
.map((e) => e.name)
|
|
92
|
+
} catch {
|
|
93
|
+
return []
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/**
|
|
98
|
+
* The qualifying packages under `node_modules`, one level and one under each
|
|
99
|
+
* `@scope`: `nish` first, so no library can shadow its skills, then the rest by
|
|
100
|
+
* name.
|
|
101
|
+
*/
|
|
102
|
+
const nishPackages = (nodeModules) => {
|
|
103
|
+
const found = []
|
|
104
|
+
for (const entry of subdirectories(nodeModules)) {
|
|
105
|
+
if (entry.startsWith(".")) {
|
|
106
|
+
continue
|
|
107
|
+
}
|
|
108
|
+
const names = entry.startsWith("@")
|
|
109
|
+
? subdirectories(path.join(nodeModules, entry)).map((n) => `${entry}/${n}`)
|
|
110
|
+
: [entry]
|
|
111
|
+
for (const name of names) {
|
|
112
|
+
const dir = path.join(nodeModules, name)
|
|
113
|
+
if (isNishPackage(name, dir)) {
|
|
114
|
+
found.push({ name, dir })
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
// Code-unit order, not the locale's, so every machine picks the same first claimant.
|
|
119
|
+
const rank = (p) => (p.name === "nish" ? "" : p.name)
|
|
120
|
+
return found.sort((a, b) => Number(rank(a) > rank(b)) - Number(rank(a) < rank(b)))
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Code-unit order, not the locale's, so every machine sorts the same way. */
|
|
124
|
+
const byCodeUnit = (a, b) => Number(a > b) - Number(a < b)
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* The names a skill may have: Claude Code's own shape. Anything else is never
|
|
128
|
+
* linked, so every name that reaches a path, the record or a command the user is
|
|
129
|
+
* told to run is safe in all three.
|
|
130
|
+
*/
|
|
131
|
+
const NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/
|
|
132
|
+
|
|
133
|
+
/**
|
|
134
|
+
* The skills a package ships, read by `lstat` alone: each `skills/<name>/`
|
|
135
|
+
* that is a real directory holding a regular `SKILL.md`, with `skills/`
|
|
136
|
+
* itself a real directory. A link at any of those three places is never
|
|
137
|
+
* followed: what it points at is outside what the hash covers, so the entry is
|
|
138
|
+
* reported as skipped instead.
|
|
139
|
+
*
|
|
140
|
+
* @param {{ name: string, dir: string }} pkg The package.
|
|
141
|
+
* @param {{ name: string, reason: string }[]} skipped Where an entry left out is reported.
|
|
142
|
+
* @returns {string[]} The skill names, in code-unit order.
|
|
143
|
+
*/
|
|
144
|
+
const skillsOf = (pkg, skipped) => {
|
|
145
|
+
const at = path.join(pkg.dir, "skills")
|
|
146
|
+
const st = lstatOrNull(at)
|
|
147
|
+
if (st === null || !(st.isDirectory() || st.isSymbolicLink())) {
|
|
148
|
+
return []
|
|
149
|
+
}
|
|
150
|
+
if (st.isSymbolicLink()) {
|
|
151
|
+
skipped.push({ name: "skills", reason: `in ${pkg.name} is a link, so none of its skills is linked` })
|
|
152
|
+
return []
|
|
153
|
+
}
|
|
154
|
+
let entries
|
|
155
|
+
try {
|
|
156
|
+
entries = fs.readdirSync(at, { withFileTypes: true })
|
|
157
|
+
} catch {
|
|
158
|
+
skipped.push({ name: "skills", reason: `in ${pkg.name} cannot be read, so none of its skills is linked` })
|
|
159
|
+
return []
|
|
160
|
+
}
|
|
161
|
+
const names = []
|
|
162
|
+
for (const e of entries) {
|
|
163
|
+
if (e.name.startsWith(".")) {
|
|
164
|
+
continue
|
|
165
|
+
}
|
|
166
|
+
if (e.isSymbolicLink()) {
|
|
167
|
+
skipped.push({ name: e.name, reason: `in ${pkg.name} is a link, so it is not linked` })
|
|
168
|
+
continue
|
|
169
|
+
}
|
|
170
|
+
if (!e.isDirectory()) {
|
|
171
|
+
continue
|
|
172
|
+
}
|
|
173
|
+
const md = lstatOrNull(path.join(at, e.name, "SKILL.md"))
|
|
174
|
+
if (md?.isFile()) {
|
|
175
|
+
names.push(e.name)
|
|
176
|
+
} else if (md !== null) {
|
|
177
|
+
skipped.push({
|
|
178
|
+
name: e.name,
|
|
179
|
+
reason: `in ${pkg.name} has a SKILL.md that is ${md.isSymbolicLink() ? "a link" : "not a regular file"}, so it is not linked`,
|
|
180
|
+
})
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
return names.sort(byCodeUnit)
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/** A link's target as an absolute path, without the `\\?\` prefix win32 gives a junction's. */
|
|
187
|
+
const targetOf = (link) => {
|
|
188
|
+
const raw = fs.readlinkSync(link)
|
|
189
|
+
const target = raw.startsWith("\\\\?\\") ? raw.slice(4) : raw
|
|
190
|
+
return path.resolve(path.dirname(link), target)
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
/** Whether two paths name one directory: by their real paths where both exist, else as written. */
|
|
194
|
+
const sameDir = (a, b) => {
|
|
195
|
+
try {
|
|
196
|
+
return fs.realpathSync(a) === fs.realpathSync(b)
|
|
197
|
+
} catch {
|
|
198
|
+
return a === b
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** The name a link is written under before it is renamed into place; see `tempName`. */
|
|
203
|
+
const TEMP = /^\..+\.\d+\.tmp$/
|
|
204
|
+
|
|
205
|
+
/** The temporary name for skill `name`'s link, unique to this process. */
|
|
206
|
+
const tempName = (name) => `.${name}.${process.pid}.tmp`
|
|
207
|
+
|
|
208
|
+
/** Whether `child` lies strictly inside `parent`. */
|
|
209
|
+
const inside = (child, parent) => {
|
|
210
|
+
const rel = path.relative(parent, child)
|
|
211
|
+
return rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel)
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
/**
|
|
215
|
+
* The project a copy of `nish` at `nishRoot` is installed in, searching from
|
|
216
|
+
* `start` upwards: `start` itself or the nearest ancestor holding a
|
|
217
|
+
* `package.json` whose `node_modules/nish` is that copy. In a workspace that is
|
|
218
|
+
* the root nish was hoisted to, not the member `start` names. Null when no
|
|
219
|
+
* directory above `start` installs this copy -- a checkout, or npx's cache.
|
|
220
|
+
*
|
|
221
|
+
* @param {string} start Where to start: npm's `INIT_CWD`, or the current directory.
|
|
222
|
+
* @param {string} nishRoot The root of the `nish` package asking.
|
|
223
|
+
* @returns {string | null} The project directory, or null.
|
|
224
|
+
*/
|
|
225
|
+
export const projectOf = (start, nishRoot) => {
|
|
226
|
+
const here = fs.realpathSync(nishRoot)
|
|
227
|
+
const from = path.resolve(start)
|
|
228
|
+
for (let dir = from; ; dir = path.dirname(dir)) {
|
|
229
|
+
const candidate = path.join(dir, "node_modules", "nish")
|
|
230
|
+
if (
|
|
231
|
+
(dir === from || fs.existsSync(path.join(dir, "package.json"))) &&
|
|
232
|
+
fs.existsSync(candidate) &&
|
|
233
|
+
fs.realpathSync(candidate) === here
|
|
234
|
+
) {
|
|
235
|
+
return dir
|
|
236
|
+
}
|
|
237
|
+
if (path.dirname(dir) === dir) {
|
|
238
|
+
return null
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/** How many directories deep `readSkill` reads before the rest counts as `TOO_LARGE`. */
|
|
244
|
+
const MAX_DEPTH = 32
|
|
245
|
+
|
|
246
|
+
/** How many entries `readSkill` reads before the rest counts as `TOO_LARGE`. */
|
|
247
|
+
const MAX_ENTRIES = 10_000
|
|
248
|
+
|
|
249
|
+
/** How many bytes of files `readSkill` reads before the rest counts as `TOO_LARGE`. */
|
|
250
|
+
const MAX_BYTES = 64 * 1024 * 1024
|
|
251
|
+
|
|
252
|
+
/** The grant of a skill too deep or too large to read whole. */
|
|
253
|
+
const TOO_LARGE = "too large to read whole"
|
|
254
|
+
|
|
255
|
+
/**
|
|
256
|
+
* A skill directory read whole, for its hash and its `SKILL.md`.
|
|
257
|
+
*
|
|
258
|
+
* @typedef {object} SkillTree
|
|
259
|
+
* @property {string} hash `sha256-<hex>` over the directory.
|
|
260
|
+
* @property {string[]} grants What its shape grants: a link, a special file, an unreadable entry, or more than `MAX_DEPTH`, `MAX_ENTRIES` or `MAX_BYTES` inside it.
|
|
261
|
+
* @property {Buffer | null} skillMd The bytes of its `SKILL.md`, or null when they could not be read.
|
|
262
|
+
*/
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Read a skill directory: the sha256 of every entry's path relative to `dir`
|
|
266
|
+
* and kind, with a regular file's bytes and a link's target string, in
|
|
267
|
+
* code-unit order of the path, each part length-prefixed so no two trees frame
|
|
268
|
+
* to the same bytes. Nothing is followed.
|
|
269
|
+
*
|
|
270
|
+
* Three kinds of entry hold content the hash cannot pin: a link (its target's
|
|
271
|
+
* bytes are not hashed), a special file such as a FIFO or a device, and an
|
|
272
|
+
* entry that cannot be read. Each is a grant, so `--yes` refuses the skill,
|
|
273
|
+
* and each mixes a fresh random value into the hash, so a name that accepts
|
|
274
|
+
* such a skill accepts it for that run only: the next run finds it changed and
|
|
275
|
+
* asks again, rather than keep serving content nobody saw. A tree deeper than
|
|
276
|
+
* `MAX_DEPTH`, or holding more than `MAX_ENTRIES` entries or `MAX_BYTES` of
|
|
277
|
+
* files, is read no further and counts the same way, so a package cannot stall
|
|
278
|
+
* the run or exhaust its memory with the skill it ships.
|
|
279
|
+
*
|
|
280
|
+
* @param {string} dir The skill directory, already known to be a real directory.
|
|
281
|
+
* @returns {SkillTree}
|
|
282
|
+
*/
|
|
283
|
+
const readSkill = (dir) => {
|
|
284
|
+
const entries = []
|
|
285
|
+
const grants = new Set()
|
|
286
|
+
let bytes = 0
|
|
287
|
+
/** A file's bytes, or null when they would take `bytes` past `MAX_BYTES`; read no further than that. */
|
|
288
|
+
const readBounded = (file) => {
|
|
289
|
+
const room = MAX_BYTES - bytes
|
|
290
|
+
const stat = fs.lstatSync(file)
|
|
291
|
+
if (!stat.isFile()) {
|
|
292
|
+
throw new Error(`${file} changed while it was read`)
|
|
293
|
+
}
|
|
294
|
+
if (stat.size > room) {
|
|
295
|
+
return null
|
|
296
|
+
}
|
|
297
|
+
// A FIFO swapped in after the lstat must not block the open, and what was
|
|
298
|
+
// opened is checked again before a byte is read.
|
|
299
|
+
const fd = fs.openSync(
|
|
300
|
+
file,
|
|
301
|
+
fs.constants.O_RDONLY | (fs.constants.O_NOFOLLOW ?? 0) | (fs.constants.O_NONBLOCK ?? 0)
|
|
302
|
+
)
|
|
303
|
+
try {
|
|
304
|
+
if (!fs.fstatSync(fd).isFile()) {
|
|
305
|
+
throw new Error(`${file} changed while it was read`)
|
|
306
|
+
}
|
|
307
|
+
const chunks = []
|
|
308
|
+
let total = 0
|
|
309
|
+
const chunk = Buffer.alloc(Math.min(room + 1, 1 << 20))
|
|
310
|
+
for (;;) {
|
|
311
|
+
const n = fs.readSync(fd, chunk, 0, Math.min(chunk.length, room + 1 - total), null)
|
|
312
|
+
if (n === 0) {
|
|
313
|
+
return Buffer.concat(chunks, total)
|
|
314
|
+
}
|
|
315
|
+
chunks.push(Buffer.from(chunk.subarray(0, n)))
|
|
316
|
+
total += n
|
|
317
|
+
if (total > room) {
|
|
318
|
+
return null
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
} finally {
|
|
322
|
+
fs.closeSync(fd)
|
|
323
|
+
}
|
|
324
|
+
}
|
|
325
|
+
const walk = (at, rel, depth) => {
|
|
326
|
+
if (depth > MAX_DEPTH) {
|
|
327
|
+
grants.add(TOO_LARGE)
|
|
328
|
+
return
|
|
329
|
+
}
|
|
330
|
+
let handle
|
|
331
|
+
try {
|
|
332
|
+
handle = fs.opendirSync(at)
|
|
333
|
+
} catch {
|
|
334
|
+
grants.add("contains an unreadable entry")
|
|
335
|
+
entries.push({ name: rel, kind: "unreadable", data: Buffer.alloc(0) })
|
|
336
|
+
return
|
|
337
|
+
}
|
|
338
|
+
try {
|
|
339
|
+
// One entry at a time, so a directory of millions stops at MAX_ENTRIES
|
|
340
|
+
// rather than being listed whole first.
|
|
341
|
+
for (;;) {
|
|
342
|
+
let e
|
|
343
|
+
try {
|
|
344
|
+
e = handle.readSync()
|
|
345
|
+
} catch {
|
|
346
|
+
grants.add("contains an unreadable entry")
|
|
347
|
+
entries.push({ name: rel, kind: "unreadable", data: Buffer.alloc(0) })
|
|
348
|
+
return
|
|
349
|
+
}
|
|
350
|
+
if (e === null) {
|
|
351
|
+
return
|
|
352
|
+
}
|
|
353
|
+
if (entries.length >= MAX_ENTRIES) {
|
|
354
|
+
grants.add(TOO_LARGE)
|
|
355
|
+
return
|
|
356
|
+
}
|
|
357
|
+
const file = path.join(at, e.name)
|
|
358
|
+
const name = rel === "" ? e.name : `${rel}/${e.name}`
|
|
359
|
+
if (e.isDirectory()) {
|
|
360
|
+
entries.push({ name, kind: "dir", data: Buffer.alloc(0) })
|
|
361
|
+
walk(file, name, depth + 1)
|
|
362
|
+
if (grants.has(TOO_LARGE)) {
|
|
363
|
+
return
|
|
364
|
+
}
|
|
365
|
+
continue
|
|
366
|
+
}
|
|
367
|
+
let kind = "other"
|
|
368
|
+
let data = Buffer.alloc(0)
|
|
369
|
+
try {
|
|
370
|
+
if (e.isFile()) {
|
|
371
|
+
kind = "file"
|
|
372
|
+
const read = readBounded(file)
|
|
373
|
+
if (read === null) {
|
|
374
|
+
grants.add(TOO_LARGE)
|
|
375
|
+
return
|
|
376
|
+
}
|
|
377
|
+
data = read
|
|
378
|
+
bytes += data.length
|
|
379
|
+
} else if (e.isSymbolicLink()) {
|
|
380
|
+
kind = "link"
|
|
381
|
+
data = Buffer.from(fs.readlinkSync(file))
|
|
382
|
+
grants.add("contains a link")
|
|
383
|
+
} else {
|
|
384
|
+
grants.add("contains a special file")
|
|
385
|
+
}
|
|
386
|
+
} catch {
|
|
387
|
+
kind = "unreadable"
|
|
388
|
+
data = Buffer.alloc(0)
|
|
389
|
+
grants.add("contains an unreadable entry")
|
|
390
|
+
}
|
|
391
|
+
entries.push({ name, kind, data })
|
|
392
|
+
}
|
|
393
|
+
} finally {
|
|
394
|
+
handle.closeSync()
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
walk(dir, "", 0)
|
|
398
|
+
const hash = crypto.createHash("sha256")
|
|
399
|
+
for (const { name, kind, data } of entries.sort((x, y) => byCodeUnit(x.name, y.name))) {
|
|
400
|
+
const head = Buffer.from(name)
|
|
401
|
+
hash.update(`${kind} ${head.length} `).update(head).update(` ${data.length} `).update(data)
|
|
402
|
+
}
|
|
403
|
+
if (grants.size > 0) {
|
|
404
|
+
hash.update(crypto.randomBytes(32))
|
|
405
|
+
}
|
|
406
|
+
const skillMd = entries.find((e) => e.name === "SKILL.md" && e.kind === "file")?.data ?? null
|
|
407
|
+
return { hash: `sha256-${hash.digest("hex")}`, grants: [...grants], skillMd }
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
/** What a skill grants when its frontmatter could not be read: it counts as a grant. */
|
|
411
|
+
const UNREADABLE = "unreadable frontmatter"
|
|
412
|
+
|
|
413
|
+
/**
|
|
414
|
+
* The top-level frontmatter keys Claude Code documents as granting nothing.
|
|
415
|
+
* Every other key -- `allowed-tools`, `hooks`, `context`, `agent`,
|
|
416
|
+
* `background`, or one added after this list was written -- counts as a grant,
|
|
417
|
+
* so a key Claude Code learns later is refused by `--yes` until a person names
|
|
418
|
+
* the skill.
|
|
419
|
+
*/
|
|
420
|
+
const INERT = new Set([
|
|
421
|
+
"name",
|
|
422
|
+
"description",
|
|
423
|
+
"when_to_use",
|
|
424
|
+
"argument-hint",
|
|
425
|
+
"arguments",
|
|
426
|
+
"metadata",
|
|
427
|
+
"license",
|
|
428
|
+
"compatibility",
|
|
429
|
+
"model",
|
|
430
|
+
"effort",
|
|
431
|
+
"disable-model-invocation",
|
|
432
|
+
"user-invocable",
|
|
433
|
+
"paths",
|
|
434
|
+
"disallowed-tools",
|
|
435
|
+
"shell",
|
|
436
|
+
])
|
|
437
|
+
|
|
438
|
+
/** Keys Claude Code documents as granting something, named as they are rather than as unknown. */
|
|
439
|
+
const GRANTING = new Set(["hooks", "context", "agent", "background"])
|
|
440
|
+
|
|
441
|
+
/**
|
|
442
|
+
* A `SKILL.md` body or frontmatter that runs a shell command when the skill
|
|
443
|
+
* loads: an inline `` !`cmd` ``, or a fence of three or more backticks or
|
|
444
|
+
* tildes followed by `!`. The fence counts anywhere on a line -- after
|
|
445
|
+
* indentation, a list or quote marker, or any text -- and with any spaces,
|
|
446
|
+
* tabs and non-breaking spaces included, between it and the `!` on that line. An inline `` !` ``
|
|
447
|
+
* counts after anything but a letter, digit or `_`: that one is code such as
|
|
448
|
+
* TypeScript's `` `x!` `` (non-null assertion) inside a code span. Either way
|
|
449
|
+
* the check errs towards asking.
|
|
450
|
+
*/
|
|
451
|
+
const SHELL_AT_LOAD = /(?<![\p{L}\p{N}_])!`|(?:`{3,}|~{3,})[^\S\r\n]*!/u
|
|
452
|
+
|
|
453
|
+
/** A YAML scalar with its quotes taken off. */
|
|
454
|
+
const unquote = (value) => (/^"[^"]*"$|^'[^']*'$/.test(value) ? value.slice(1, -1) : value)
|
|
455
|
+
|
|
456
|
+
/**
|
|
457
|
+
* One thing a skill grants: a line to show, or an `allowed-tools` key with
|
|
458
|
+
* every entry it lists, kept apart so the display can count and dedupe them
|
|
459
|
+
* rather than re-split a joined string.
|
|
460
|
+
*
|
|
461
|
+
* @typedef {string | { key: string, tools: string[] }} Grant
|
|
462
|
+
*/
|
|
463
|
+
|
|
464
|
+
/** The tools an `allowed-tools` key lists, with `<unreadable>` for a form this file does not read. */
|
|
465
|
+
const toolsOf = ({ value, under }) => {
|
|
466
|
+
if (value === "" && under.every((item) => item.startsWith("- "))) {
|
|
467
|
+
return under.flatMap((item) => unquote(item.slice(2).trim()).split(/[,\s]+/))
|
|
468
|
+
}
|
|
469
|
+
if (under.length > 0 || (value.startsWith("[") && !value.endsWith("]"))) {
|
|
470
|
+
return ["<unreadable>"]
|
|
471
|
+
}
|
|
472
|
+
if (value.startsWith("[")) {
|
|
473
|
+
return value
|
|
474
|
+
.slice(1, -1)
|
|
475
|
+
.split(",")
|
|
476
|
+
.flatMap((t) => unquote(t.trim()).split(/[,\s]+/))
|
|
477
|
+
}
|
|
478
|
+
return unquote(value).split(/[,\s]+/)
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
/**
|
|
482
|
+
* The description of a `SKILL.md` and everything it grants, read from its
|
|
483
|
+
* leading `---` block and its body. It reads only top-level `key: value`
|
|
484
|
+
* scalars, inline `[a, b]` lists and `- item` block lists -- no YAML
|
|
485
|
+
* dependency -- and it fails closed: a block it cannot read, a top-level key
|
|
486
|
+
* not in `INERT`, or a load-time shell command adds to `grants`. Only a block
|
|
487
|
+
* that parsed, holds inert keys alone, and a text with no `!` command yields
|
|
488
|
+
* an empty `grants`.
|
|
489
|
+
*
|
|
490
|
+
* @param {string} text The whole `SKILL.md`.
|
|
491
|
+
* @returns {{ description: string, grants: Grant[] }} Each grant unsanitised.
|
|
492
|
+
*/
|
|
493
|
+
const frontmatter = (text) => {
|
|
494
|
+
const shell = SHELL_AT_LOAD.test(text) ? ["runs shell at load"] : []
|
|
495
|
+
const unreadable = { description: "", grants: [UNREADABLE, ...shell] }
|
|
496
|
+
const lines = text.replace(/^\uFEFF/, "").split(/\r?\n/)
|
|
497
|
+
// The opener and the closer are `---` exactly, and no other line in the
|
|
498
|
+
// block looks like a document marker, so a reader that ends the block at a
|
|
499
|
+
// looser `---` or at `...` cannot end it sooner than this one does.
|
|
500
|
+
if (lines[0] !== "---") {
|
|
501
|
+
return unreadable
|
|
502
|
+
}
|
|
503
|
+
const end = lines.findIndex((line, i) => i > 0 && line === "---")
|
|
504
|
+
if (end === -1) {
|
|
505
|
+
return unreadable
|
|
506
|
+
}
|
|
507
|
+
const block = lines.slice(1, end)
|
|
508
|
+
// A YAML reader may break a line at a lone CR, NEL or a Unicode line or
|
|
509
|
+
// paragraph separator, or read a vertical tab or form feed as space, where
|
|
510
|
+
// this one does not, so a block holding one is not read.
|
|
511
|
+
if (
|
|
512
|
+
block.some((line) => /[\r\v\f\u0085\u2028\u2029]/.test(line) || /^\s*(?:-{3}|\.{3})(?:\s|$)/.test(line))
|
|
513
|
+
) {
|
|
514
|
+
return unreadable
|
|
515
|
+
}
|
|
516
|
+
/** Each top-level key with its inline value and the indented lines under it. */
|
|
517
|
+
const keys = []
|
|
518
|
+
for (const line of block) {
|
|
519
|
+
if (/^[ \t]*$/.test(line) || line.startsWith("#")) {
|
|
520
|
+
continue
|
|
521
|
+
}
|
|
522
|
+
// Only a space indents. A line led by a tab, a no-break space or any
|
|
523
|
+
// other whitespace is one a reader might take as top-level, or reject,
|
|
524
|
+
// so the whole block counts as unreadable.
|
|
525
|
+
if (line.startsWith(" ")) {
|
|
526
|
+
if (keys.length === 0) {
|
|
527
|
+
return unreadable
|
|
528
|
+
}
|
|
529
|
+
keys[keys.length - 1].under.push(line.trim())
|
|
530
|
+
continue
|
|
531
|
+
}
|
|
532
|
+
// A quoted key, a merge key, a flow mapping: anything else at the top could
|
|
533
|
+
// hide a grant, so the whole block counts as unreadable. Only a space or a
|
|
534
|
+
// tab separates a key from its value.
|
|
535
|
+
const m = /^([A-Za-z0-9_.-]+):(?:[ \t]+(.*))?$/.exec(line)
|
|
536
|
+
if (m === null) {
|
|
537
|
+
return unreadable
|
|
538
|
+
}
|
|
539
|
+
keys.push({ key: m[1], value: (m[2] ?? "").trim(), under: [] })
|
|
540
|
+
}
|
|
541
|
+
const description = keys
|
|
542
|
+
.filter((k) => k.key === "description")
|
|
543
|
+
.map((k) => [unquote(k.value.replace(/^[>|][-+]?$/, "")), ...k.under].join(" ").trim())
|
|
544
|
+
.join(" ")
|
|
545
|
+
const grants = []
|
|
546
|
+
for (const k of keys) {
|
|
547
|
+
if (INERT.has(k.key)) {
|
|
548
|
+
continue
|
|
549
|
+
}
|
|
550
|
+
if (/^allowed[-_]?tools$/i.test(k.key)) {
|
|
551
|
+
// Any spelling a reader might honour is shown as what it is, so a near-miss reads as a grant.
|
|
552
|
+
const tools = toolsOf(k).filter((t) => t !== "")
|
|
553
|
+
grants.push(tools.length === 0 ? `${k.key} (present, empty)` : { key: k.key, tools })
|
|
554
|
+
} else {
|
|
555
|
+
grants.push(GRANTING.has(k.key) ? k.key : `unknown key ${k.key}`)
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
return { description, grants: [...grants, ...shell] }
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
/** A package's `version`, or `?` when it has none to show. */
|
|
562
|
+
const versionOf = (dir) => {
|
|
563
|
+
const version = packageJson(dir)?.version
|
|
564
|
+
return typeof version === "string" ? version : "?"
|
|
565
|
+
}
|
|
566
|
+
|
|
567
|
+
/**
|
|
568
|
+
* One skill a Nish package ships, as `findSkills` found it.
|
|
569
|
+
*
|
|
570
|
+
* @typedef {object} Skill
|
|
571
|
+
* @property {string} pkg The package that ships it.
|
|
572
|
+
* @property {string} version That package's version, or `?`.
|
|
573
|
+
* @property {string} name The skill's name: its directory under `skills/`.
|
|
574
|
+
* @property {string} dir The skill directory's absolute path.
|
|
575
|
+
* @property {string} hash `sha256-<hex>` over the whole skill directory.
|
|
576
|
+
* @property {string} description The frontmatter's `description`, unsanitised.
|
|
577
|
+
* @property {Grant[]} grants What it grants, as `frontmatter` and `readSkill` read it, unsanitised; empty when it grants nothing.
|
|
578
|
+
*/
|
|
579
|
+
|
|
580
|
+
/**
|
|
581
|
+
* Every skill the project's Nish packages ship. The first package in order to
|
|
582
|
+
* claim a name wins it -- `nish` first, so no library can shadow its skills --
|
|
583
|
+
* and a later claimant is reported as skipped, as is a directory whose name is
|
|
584
|
+
* not a `NAME`.
|
|
585
|
+
*
|
|
586
|
+
* @param {string} project The project root, the directory holding `node_modules/`.
|
|
587
|
+
* @returns {{ skills: Skill[], skipped: { name: string, reason: string }[] }}
|
|
588
|
+
*/
|
|
589
|
+
const findSkills = (project) => {
|
|
590
|
+
const skills = []
|
|
591
|
+
const skipped = []
|
|
592
|
+
for (const pkg of nishPackages(path.join(path.resolve(project), "node_modules"))) {
|
|
593
|
+
for (const name of skillsOf(pkg, skipped)) {
|
|
594
|
+
if (!NAME.test(name)) {
|
|
595
|
+
skipped.push({ name, reason: `in ${pkg.name} is not a valid skill name, so it is not linked` })
|
|
596
|
+
continue
|
|
597
|
+
}
|
|
598
|
+
const owner = skills.find((s) => s.name === name)
|
|
599
|
+
if (owner !== undefined) {
|
|
600
|
+
skipped.push({ name, reason: `${owner.pkg} already provides it, so ${pkg.name}'s is not linked` })
|
|
601
|
+
continue
|
|
602
|
+
}
|
|
603
|
+
const dir = path.join(pkg.dir, "skills", name)
|
|
604
|
+
// The text is the bytes the hash covers, never a second read that could differ.
|
|
605
|
+
const tree = readSkill(dir)
|
|
606
|
+
const meta =
|
|
607
|
+
tree.skillMd === null
|
|
608
|
+
? { description: "", grants: ["unreadable SKILL.md"] }
|
|
609
|
+
: frontmatter(tree.skillMd.toString("utf8"))
|
|
610
|
+
skills.push({
|
|
611
|
+
pkg: pkg.name,
|
|
612
|
+
version: versionOf(pkg.dir),
|
|
613
|
+
name,
|
|
614
|
+
dir,
|
|
615
|
+
hash: tree.hash,
|
|
616
|
+
description: meta.description,
|
|
617
|
+
grants: [...meta.grants, ...tree.grants],
|
|
618
|
+
})
|
|
619
|
+
}
|
|
620
|
+
}
|
|
621
|
+
return { skills, skipped }
|
|
622
|
+
}
|
|
623
|
+
|
|
624
|
+
/** The record of accepted skills, beside the links it governs. */
|
|
625
|
+
const RECORD = ".nish-skills.json"
|
|
626
|
+
|
|
627
|
+
/** The record's format version; a record with any other is read as accepting nothing. */
|
|
628
|
+
const RECORD_VERSION = 1
|
|
629
|
+
|
|
630
|
+
/**
|
|
631
|
+
* The accepted skills the record holds, by name. A missing, unreadable or
|
|
632
|
+
* malformed record, or one of an unknown version, accepts nothing: consent
|
|
633
|
+
* that cannot be read is consent not given, and asking again is the cost.
|
|
634
|
+
*
|
|
635
|
+
* @param {string} project The project root.
|
|
636
|
+
* @returns {Map<string, { package: string, hash: string }>}
|
|
637
|
+
*/
|
|
638
|
+
const readRecord = (project) => {
|
|
639
|
+
const accepted = new Map()
|
|
640
|
+
const file = path.join(path.resolve(project), ".claude", "skills", RECORD)
|
|
641
|
+
let parsed
|
|
642
|
+
try {
|
|
643
|
+
if (!fs.lstatSync(file).isFile()) {
|
|
644
|
+
return accepted
|
|
645
|
+
}
|
|
646
|
+
parsed = JSON.parse(fs.readFileSync(file, "utf8"))
|
|
647
|
+
} catch {
|
|
648
|
+
return accepted
|
|
649
|
+
}
|
|
650
|
+
const skills = parsed?.version === RECORD_VERSION ? parsed.skills : null
|
|
651
|
+
if (skills === null || typeof skills !== "object" || Array.isArray(skills)) {
|
|
652
|
+
return accepted
|
|
653
|
+
}
|
|
654
|
+
for (const [name, entry] of Object.entries(skills)) {
|
|
655
|
+
if (typeof entry?.package === "string" && typeof entry?.hash === "string") {
|
|
656
|
+
accepted.set(name, { package: entry.package, hash: entry.hash })
|
|
657
|
+
}
|
|
658
|
+
}
|
|
659
|
+
return accepted
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
/** Whether the record accepts this exact skill: the same package and the same hash. */
|
|
663
|
+
const isAccepted = (record, skill) => {
|
|
664
|
+
const entry = record.get(skill.name)
|
|
665
|
+
return entry !== undefined && entry.package === skill.pkg && entry.hash === skill.hash
|
|
666
|
+
}
|
|
667
|
+
|
|
668
|
+
/** Write `data` to `file` through a temporary name and a rename, so a reader never sees half of it. */
|
|
669
|
+
const writeAtomic = (file, data) => {
|
|
670
|
+
let temp = `${file}.${process.pid}.tmp`
|
|
671
|
+
// A leftover of a killed run with this pid goes first. What cannot be
|
|
672
|
+
// removed, such as a directory, is left alone for a fresh random name; `wx`
|
|
673
|
+
// then refuses anything that appears in its place, a link above all, rather
|
|
674
|
+
// than write through it.
|
|
675
|
+
try {
|
|
676
|
+
fs.rmSync(temp, { force: true })
|
|
677
|
+
} catch {
|
|
678
|
+
temp = `${file}.${process.pid}.${crypto.randomBytes(8).toString("hex")}.tmp`
|
|
679
|
+
}
|
|
680
|
+
// `wx` either creates the file or throws, so once it opens the file is this
|
|
681
|
+
// call's own: a failed write or rename removes it, and a refusal removes nothing.
|
|
682
|
+
const fd = fs.openSync(temp, "wx")
|
|
683
|
+
try {
|
|
684
|
+
try {
|
|
685
|
+
fs.writeFileSync(fd, data)
|
|
686
|
+
} finally {
|
|
687
|
+
fs.closeSync(fd)
|
|
688
|
+
}
|
|
689
|
+
fs.renameSync(temp, file)
|
|
690
|
+
} catch (err) {
|
|
691
|
+
fs.rmSync(temp, { force: true })
|
|
692
|
+
throw err
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
/**
|
|
697
|
+
* Make `<project>/.claude/skills/` match what is accepted: link every accepted
|
|
698
|
+
* skill, unlink every other linker-owned link (to a skill not accepted at its
|
|
699
|
+
* current hash, or one no installed Nish package ships any more), and write
|
|
700
|
+
* the record of what is accepted.
|
|
701
|
+
*
|
|
702
|
+
* A skill in `accepted` counts only if it is in `found` from the same package
|
|
703
|
+
* at the same hash. The check is against `found`, not the disk: a caller that
|
|
704
|
+
* asked a question about a skill passes the same `found` it asked about, and a
|
|
705
|
+
* caller that wants the disk's current state passes a fresh `findSkills`.
|
|
706
|
+
* Nothing is created under `.claude/` when nothing
|
|
707
|
+
* is accepted. Running it twice changes nothing the second time. A write that
|
|
708
|
+
* fails throws, after cleaning up its temporary entry.
|
|
709
|
+
*
|
|
710
|
+
* @param {string} project The project root, the directory holding `node_modules/`.
|
|
711
|
+
* @param {{ accepted?: { name: string, pkg: string, hash: string }[], platform?: string, found?: ReturnType<typeof findSkills> }} [options]
|
|
712
|
+
* `accepted` is every skill to link, already-accepted ones included; `platform` chooses a junction (`win32`) or a relative symlink;
|
|
713
|
+
* `found` is a `findSkills` result to reuse.
|
|
714
|
+
* @returns {{ linked: string[], kept: string[], unlinked: { name: string, reason: string }[], pruned: string[], skipped: { name: string, reason: string }[] }}
|
|
715
|
+
* What happened to each skill name: linked or relinked, already right, unlinked and why, removed because its target is gone, or left alone and why.
|
|
716
|
+
*/
|
|
717
|
+
export const linkSkills = (project, { accepted = [], platform = process.platform, found } = {}) => {
|
|
718
|
+
const root = path.resolve(project)
|
|
719
|
+
const { skills: all, skipped } = found ?? findSkills(root)
|
|
720
|
+
const result = { linked: [], kept: [], unlinked: [], pruned: [], skipped: [...skipped] }
|
|
721
|
+
const nodeModules = path.join(root, "node_modules")
|
|
722
|
+
const yes = all.filter((s) =>
|
|
723
|
+
accepted.some((a) => a.name === s.name && a.pkg === s.pkg && a.hash === s.hash)
|
|
724
|
+
)
|
|
725
|
+
const previous = readRecord(root)
|
|
726
|
+
|
|
727
|
+
const claude = path.join(root, ".claude")
|
|
728
|
+
const skills = path.join(claude, "skills")
|
|
729
|
+
for (const dir of [claude, skills]) {
|
|
730
|
+
const st = lstatOrNull(dir)
|
|
731
|
+
if (st === null) {
|
|
732
|
+
if (yes.length === 0) {
|
|
733
|
+
return result
|
|
734
|
+
}
|
|
735
|
+
fs.mkdirSync(dir)
|
|
736
|
+
} else if (st.isSymbolicLink() || !st.isDirectory()) {
|
|
737
|
+
result.skipped.push({
|
|
738
|
+
name: path.relative(root, dir),
|
|
739
|
+
reason: `${st.isSymbolicLink() ? "is a link" : "is not a directory"}, so nothing is written`,
|
|
740
|
+
})
|
|
741
|
+
return result
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
|
|
745
|
+
/** Whether the entry is one of the linker's own: a link that resolves inside `node_modules/`. */
|
|
746
|
+
const owned = (entry, st) => st !== null && st.isSymbolicLink() && inside(targetOf(entry), nodeModules)
|
|
747
|
+
|
|
748
|
+
for (const skill of all) {
|
|
749
|
+
const { name } = skill
|
|
750
|
+
const entry = path.join(skills, name)
|
|
751
|
+
const st = lstatOrNull(entry)
|
|
752
|
+
if (!yes.includes(skill)) {
|
|
753
|
+
// Removing needs no consent, so a link the user never accepted, or
|
|
754
|
+
// accepted at another hash, goes whatever made it.
|
|
755
|
+
if (owned(entry, st)) {
|
|
756
|
+
fs.unlinkSync(entry)
|
|
757
|
+
const was = previous.get(name)
|
|
758
|
+
result.unlinked.push({
|
|
759
|
+
name,
|
|
760
|
+
reason: was?.package === skill.pkg ? "changed since it was accepted" : "not accepted",
|
|
761
|
+
})
|
|
762
|
+
}
|
|
763
|
+
continue
|
|
764
|
+
}
|
|
765
|
+
if (st !== null && !owned(entry, st)) {
|
|
766
|
+
result.skipped.push({
|
|
767
|
+
name,
|
|
768
|
+
reason: `.claude/skills/${name} is the project's own, so it is left alone`,
|
|
769
|
+
})
|
|
770
|
+
continue
|
|
771
|
+
}
|
|
772
|
+
if (st !== null && sameDir(targetOf(entry), skill.dir)) {
|
|
773
|
+
result.kept.push(name)
|
|
774
|
+
continue
|
|
775
|
+
}
|
|
776
|
+
const junction = platform === "win32"
|
|
777
|
+
const target = junction ? skill.dir : path.relative(skills, skill.dir)
|
|
778
|
+
const temp = path.join(skills, tempName(name))
|
|
779
|
+
// win32's rename does not replace an existing directory entry, so the old
|
|
780
|
+
// link is removed first, and put back if the rename then fails.
|
|
781
|
+
const replaced = st !== null && junction ? fs.readlinkSync(entry) : null
|
|
782
|
+
try {
|
|
783
|
+
fs.symlinkSync(target, temp, junction ? "junction" : "dir")
|
|
784
|
+
if (replaced !== null) {
|
|
785
|
+
fs.unlinkSync(entry)
|
|
786
|
+
}
|
|
787
|
+
fs.renameSync(temp, entry)
|
|
788
|
+
} catch (err) {
|
|
789
|
+
fs.rmSync(temp, { force: true })
|
|
790
|
+
if (replaced !== null && lstatOrNull(entry) === null) {
|
|
791
|
+
fs.symlinkSync(replaced, entry, "junction")
|
|
792
|
+
}
|
|
793
|
+
throw err
|
|
794
|
+
}
|
|
795
|
+
result.linked.push(name)
|
|
796
|
+
}
|
|
797
|
+
|
|
798
|
+
const names = new Set(all.map((s) => s.name))
|
|
799
|
+
// Every other owned link goes: a temporary one a killed run left behind, one
|
|
800
|
+
// whose target is gone, and one to a skill that no longer qualifies (its
|
|
801
|
+
// package dropped `exports.nish`, or the name is no longer valid), which
|
|
802
|
+
// would otherwise keep serving whatever the package now ships.
|
|
803
|
+
for (const name of fs.readdirSync(skills).sort()) {
|
|
804
|
+
const entry = path.join(skills, name)
|
|
805
|
+
if (names.has(name) || !owned(entry, lstatOrNull(entry))) {
|
|
806
|
+
continue
|
|
807
|
+
}
|
|
808
|
+
const gone = !fs.existsSync(targetOf(entry))
|
|
809
|
+
fs.unlinkSync(entry)
|
|
810
|
+
if (TEMP.test(name)) {
|
|
811
|
+
// Never a skill, whatever it points at: nothing to report.
|
|
812
|
+
} else if (gone) {
|
|
813
|
+
result.pruned.push(name)
|
|
814
|
+
} else {
|
|
815
|
+
result.unlinked.push({ name, reason: "no installed Nish package ships it" })
|
|
816
|
+
}
|
|
817
|
+
}
|
|
818
|
+
|
|
819
|
+
const file = path.join(skills, RECORD)
|
|
820
|
+
const record = `${JSON.stringify(
|
|
821
|
+
{
|
|
822
|
+
version: RECORD_VERSION,
|
|
823
|
+
skills: Object.fromEntries(yes.map((s) => [s.name, { package: s.pkg, hash: s.hash }])),
|
|
824
|
+
},
|
|
825
|
+
null,
|
|
826
|
+
2
|
|
827
|
+
)}\n`
|
|
828
|
+
let current = null
|
|
829
|
+
try {
|
|
830
|
+
// Only a regular file is read, so a FIFO in its place cannot hang the run.
|
|
831
|
+
current = fs.lstatSync(file).isFile() ? fs.readFileSync(file, "utf8") : ""
|
|
832
|
+
} catch {
|
|
833
|
+
// No record yet, or one that cannot be read: either way it is rewritten below.
|
|
834
|
+
}
|
|
835
|
+
if (current !== record && (current !== null || yes.length > 0)) {
|
|
836
|
+
writeAtomic(file, record)
|
|
837
|
+
}
|
|
838
|
+
return result
|
|
839
|
+
}
|
|
840
|
+
|
|
841
|
+
/**
|
|
842
|
+
* What `clean` replaces: every control (`Cc`), format character (`Cf`: the
|
|
843
|
+
* bidirectional marks and overrides, the zero-width characters, the tag
|
|
844
|
+
* characters), private-use, unassigned and surrogate code point, the line and
|
|
845
|
+
* paragraph separators, and the characters that draw nothing yet are not in
|
|
846
|
+
* those classes -- the combining grapheme joiner, the Hangul fillers, the
|
|
847
|
+
* braille blank and the variation selectors.
|
|
848
|
+
*/
|
|
849
|
+
const INVISIBLE =
|
|
850
|
+
/͏|[\p{Cc}\p{Cf}\p{Co}\p{Cn}\p{Cs}\p{Zl}\p{Zp}\u115f\u1160\u3164\uffa0\u2800]|[\ufe00-\ufe0f]|[\u180b-\u180d\u180f]|[\u17b4\u17b5]|[\u{e0100}-\u{e01ef}]/gu
|
|
851
|
+
|
|
852
|
+
/**
|
|
853
|
+
* A package-controlled string made safe for a terminal: every `INVISIBLE`
|
|
854
|
+
* character becomes `?` (tab, newline and carriage return a space), and
|
|
855
|
+
* anything past `max` code points is cut, so a
|
|
856
|
+
* `SKILL.md` cannot move the cursor, recolour or redraw the prompt it is shown
|
|
857
|
+
* in, or hide text inside what it shows.
|
|
858
|
+
*
|
|
859
|
+
* @param {unknown} text The string to show.
|
|
860
|
+
* @param {number} [max] The most code points to keep.
|
|
861
|
+
* @returns {string} The text, safe to print.
|
|
862
|
+
*/
|
|
863
|
+
export const clean = (text, max = 300) => {
|
|
864
|
+
const safe = Array.from(
|
|
865
|
+
String(text)
|
|
866
|
+
.replace(/[\t\n\r]/g, " ")
|
|
867
|
+
.replace(INVISIBLE, "?")
|
|
868
|
+
)
|
|
869
|
+
return safe.length > max ? `${safe.slice(0, max).join("")}...` : safe.join("")
|
|
870
|
+
}
|
|
871
|
+
|
|
872
|
+
/**
|
|
873
|
+
* The order grants are shown in: the ones that act first, so a long list of
|
|
874
|
+
* unknown keys can never push `allowed-tools` out of what the user reads.
|
|
875
|
+
*/
|
|
876
|
+
const GRANT_ORDER = [
|
|
877
|
+
/^allowed[-_]?tools\b/i,
|
|
878
|
+
/^hooks$/,
|
|
879
|
+
/^runs shell at load$/,
|
|
880
|
+
/^contains a link$/,
|
|
881
|
+
/^unreadable |^contains an unreadable |^contains a special |^too large /,
|
|
882
|
+
/^(context|agent|background)$/,
|
|
883
|
+
]
|
|
884
|
+
|
|
885
|
+
/** The prefix `frontmatter` gives a key it does not know. */
|
|
886
|
+
const UNKNOWN_KEY = "unknown key "
|
|
887
|
+
|
|
888
|
+
/** Tools that run commands, write files or reach out, shown before the rest. */
|
|
889
|
+
const ACTING_TOOL =
|
|
890
|
+
/^(<unreadable>|Bash|PowerShell|Write|Edit|MultiEdit|NotebookEdit|WebFetch|WebSearch|Task|Agent|Skill|KillShell|mcp__)/
|
|
891
|
+
|
|
892
|
+
/** The most code points of one tool or one unknown key shown. */
|
|
893
|
+
const ITEM_MAX = 80
|
|
894
|
+
|
|
895
|
+
/**
|
|
896
|
+
* A heading and one indented line per distinct item, the acting ones first,
|
|
897
|
+
* so no cap on a line can drop an item: each is cut on its own line only.
|
|
898
|
+
*/
|
|
899
|
+
const listed = (head, items, acting = () => false) => {
|
|
900
|
+
const distinct = [...new Set(items)].sort(
|
|
901
|
+
(x, y) => Number(acting(y)) - Number(acting(x)) || byCodeUnit(x, y)
|
|
902
|
+
)
|
|
903
|
+
return [head(items.length, distinct.length), ...distinct.map((item) => ` - ${clean(item, ITEM_MAX)}`)]
|
|
904
|
+
}
|
|
905
|
+
|
|
906
|
+
/**
|
|
907
|
+
* What a skill grants, for the terminal, each line starting with its `- `
|
|
908
|
+
* bullet: one grant to a line, those that act first in `GRANT_ORDER`. No cap
|
|
909
|
+
* may remove a distinct grant from what the user sees, so a list is never
|
|
910
|
+
* joined onto one line: an `allowed-tools` key with more than one entry shows
|
|
911
|
+
* its count and then each distinct tool on a line of its own, acting tools
|
|
912
|
+
* first, and the unknown keys come last the same way. Only the text of a
|
|
913
|
+
* single tool or key is cut, at `ITEM_MAX`; how many are shown never is.
|
|
914
|
+
*
|
|
915
|
+
* @param {Skill} skill
|
|
916
|
+
* @returns {string[]} The lines, cleaned; empty when it grants nothing.
|
|
917
|
+
*/
|
|
918
|
+
const grantLines = (skill) => {
|
|
919
|
+
const label = (g) => (typeof g === "string" ? g : g.key)
|
|
920
|
+
const rank = (g) => {
|
|
921
|
+
const i = GRANT_ORDER.findIndex((re) => re.test(label(g)))
|
|
922
|
+
return i === -1 ? GRANT_ORDER.length : i
|
|
923
|
+
}
|
|
924
|
+
const known = skill.grants.filter((g) => typeof g !== "string" || !g.startsWith(UNKNOWN_KEY))
|
|
925
|
+
const unknown = skill.grants
|
|
926
|
+
.filter((g) => typeof g === "string" && g.startsWith(UNKNOWN_KEY))
|
|
927
|
+
.map((g) => String(g).slice(UNKNOWN_KEY.length))
|
|
928
|
+
const lines = known
|
|
929
|
+
.map((g, i) => ({ g, i }))
|
|
930
|
+
.sort((x, y) => rank(x.g) - rank(y.g) || x.i - y.i)
|
|
931
|
+
.flatMap(({ g }) => {
|
|
932
|
+
if (typeof g === "string") {
|
|
933
|
+
return [`- ${clean(g, ITEM_MAX)}`]
|
|
934
|
+
}
|
|
935
|
+
const key = clean(g.key, ITEM_MAX)
|
|
936
|
+
if (g.tools.length === 1) {
|
|
937
|
+
return [`- ${key}: ${clean(g.tools[0], ITEM_MAX)}`]
|
|
938
|
+
}
|
|
939
|
+
return listed(
|
|
940
|
+
(n, d) => `- ${key} (${n} entries, ${d} distinct):`,
|
|
941
|
+
g.tools,
|
|
942
|
+
(t) => ACTING_TOOL.test(t)
|
|
943
|
+
)
|
|
944
|
+
})
|
|
945
|
+
if (unknown.length === 1) {
|
|
946
|
+
lines.push(`- unknown key ${clean(unknown[0], ITEM_MAX)}`)
|
|
947
|
+
} else if (unknown.length > 1) {
|
|
948
|
+
lines.push(...listed((n, d) => `- ${n} unknown keys (${d} distinct):`, unknown))
|
|
949
|
+
}
|
|
950
|
+
return lines
|
|
951
|
+
}
|
|
952
|
+
|
|
953
|
+
/**
|
|
954
|
+
* The `nish-skills` command, without its argument parsing: find the project's
|
|
955
|
+
* skills, decide which are accepted, link exactly those, and report.
|
|
956
|
+
*
|
|
957
|
+
* A skill the record accepts at its current package and hash is kept without
|
|
958
|
+
* asking. Otherwise, with `ask` (an interactive run), each skill is shown and
|
|
959
|
+
* asked about, and only `y` or `yes` accepts; with names or `yes` (a run that
|
|
960
|
+
* cannot ask), a named skill is accepted whatever it grants, `yes` accepts
|
|
961
|
+
* every skill that grants nothing, and a skill that grants anything is linked
|
|
962
|
+
* only when named. Declines are not recorded, so an interactive run asks again.
|
|
963
|
+
*
|
|
964
|
+
* @param {string} project The project root.
|
|
965
|
+
* @param {{ names?: string[], yes?: boolean, ask?: ((question: string, name: string) => Promise<string | null>) | null, write?: (text: string) => void, platform?: string }} [options]
|
|
966
|
+
* `ask` is given the question and the skill's name, and returns the answer line, or
|
|
967
|
+
* null at end of input; `write` receives the output.
|
|
968
|
+
* @returns {Promise<{ unknown: string[], result: ReturnType<typeof linkSkills> | null }>}
|
|
969
|
+
* `unknown` holds the names no found skill has, and then nothing was written and `result` is null.
|
|
970
|
+
*/
|
|
971
|
+
export const review = async (
|
|
972
|
+
project,
|
|
973
|
+
{ names = [], yes = false, ask = null, write = (t) => process.stdout.write(t), platform } = {}
|
|
974
|
+
) => {
|
|
975
|
+
const say = (line) => write(`${clean(line, 1000)}\n`)
|
|
976
|
+
const found = findSkills(project)
|
|
977
|
+
const unknown = names.filter((n) => !found.skills.some((s) => s.name === n))
|
|
978
|
+
if (unknown.length > 0) {
|
|
979
|
+
return { unknown, result: null }
|
|
980
|
+
}
|
|
981
|
+
const record = readRecord(project)
|
|
982
|
+
const accepted = []
|
|
983
|
+
const waiting = []
|
|
984
|
+
for (const skill of found.skills) {
|
|
985
|
+
if (isAccepted(record, skill) || names.includes(skill.name)) {
|
|
986
|
+
accepted.push(skill)
|
|
987
|
+
} else if (ask !== null) {
|
|
988
|
+
say(`${clean(skill.name, 100)} from ${clean(skill.pkg, 214)}@${clean(skill.version, 40)}`)
|
|
989
|
+
say(` ${clean(skill.description) || "(no description)"}`)
|
|
990
|
+
const lines = grantLines(skill)
|
|
991
|
+
say(lines.length === 0 ? " grants nothing" : " grants:")
|
|
992
|
+
for (const line of lines) {
|
|
993
|
+
say(` ${line}`)
|
|
994
|
+
}
|
|
995
|
+
const answer = await ask(`Link ${clean(skill.name, 100)}? [y/N] `, skill.name)
|
|
996
|
+
if (answer !== null && /^y(es)?$/i.test(answer.trim())) {
|
|
997
|
+
accepted.push(skill)
|
|
998
|
+
}
|
|
999
|
+
} else if (yes && skill.grants.length === 0) {
|
|
1000
|
+
accepted.push(skill)
|
|
1001
|
+
} else {
|
|
1002
|
+
waiting.push(skill)
|
|
1003
|
+
}
|
|
1004
|
+
}
|
|
1005
|
+
const result = linkSkills(project, { accepted, platform, found })
|
|
1006
|
+
for (const skill of waiting) {
|
|
1007
|
+
const name = clean(skill.name, 100)
|
|
1008
|
+
say(
|
|
1009
|
+
`found ${name} from ${clean(skill.pkg, 214)}@${clean(skill.version, 40)}: ${clean(skill.description) || "(no description)"}`
|
|
1010
|
+
)
|
|
1011
|
+
// The name is a `NAME`, so the command below is never cut.
|
|
1012
|
+
if (skill.grants.length === 0) {
|
|
1013
|
+
say(" not linked; accept it with 'npx nish-skills --yes' or:")
|
|
1014
|
+
} else {
|
|
1015
|
+
say(" not linked, since it grants:")
|
|
1016
|
+
for (const line of grantLines(skill)) {
|
|
1017
|
+
say(` ${line}`)
|
|
1018
|
+
}
|
|
1019
|
+
say(" only naming it accepts it:")
|
|
1020
|
+
}
|
|
1021
|
+
say(` npx nish-skills ${name}`)
|
|
1022
|
+
}
|
|
1023
|
+
for (const name of result.linked) {
|
|
1024
|
+
say(`linked ${name}`)
|
|
1025
|
+
}
|
|
1026
|
+
for (const { name, reason } of result.unlinked) {
|
|
1027
|
+
say(`unlinked ${name}: ${reason}`)
|
|
1028
|
+
}
|
|
1029
|
+
for (const name of result.pruned) {
|
|
1030
|
+
say(`pruned ${name}`)
|
|
1031
|
+
}
|
|
1032
|
+
for (const { name, reason } of result.skipped) {
|
|
1033
|
+
say(`skipped ${name}: ${reason}`)
|
|
1034
|
+
}
|
|
1035
|
+
say(
|
|
1036
|
+
`nish-skills: ${result.linked.length} linked, ${result.kept.length} unchanged, ${result.unlinked.length} unlinked, ${result.pruned.length} pruned, ${waiting.length} not accepted, ${result.skipped.length} skipped in ${project}`
|
|
1037
|
+
)
|
|
1038
|
+
return { unknown: [], result }
|
|
1039
|
+
}
|