insightfulpipe 0.1.4 → 0.3.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/CHANGELOG.md +71 -0
- package/README.md +65 -2
- package/SKILL.md +8 -5
- package/bin/cli.js +4 -1
- package/package.json +7 -3
- package/skills/insightfulpipe/SKILL.md +8 -5
- package/src/api.js +88 -75
- package/src/cli/commands/discovery.js +80 -19
- package/src/cli/commands/execution.js +58 -17
- package/src/cli/commands/skills.js +454 -0
- package/src/cli/errors.js +167 -13
- package/src/cli/input.js +6 -0
- package/src/cli/program.js +18 -3
- package/src/cli/query-contexts.js +3 -2
- package/src/config.js +54 -2
- package/src/http.js +39 -0
- package/src/output.js +5 -1
- package/src/skills/agents.js +94 -0
- package/src/skills/catalog.js +177 -0
- package/src/skills/installer.js +331 -0
|
@@ -0,0 +1,331 @@
|
|
|
1
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
2
|
+
import {
|
|
3
|
+
closeSync,
|
|
4
|
+
constants,
|
|
5
|
+
existsSync,
|
|
6
|
+
lstatSync,
|
|
7
|
+
mkdirSync,
|
|
8
|
+
openSync,
|
|
9
|
+
readdirSync,
|
|
10
|
+
readFileSync,
|
|
11
|
+
readSync,
|
|
12
|
+
renameSync,
|
|
13
|
+
rmSync,
|
|
14
|
+
writeFileSync,
|
|
15
|
+
} from 'node:fs';
|
|
16
|
+
import { dirname, isAbsolute, join, resolve } from 'node:path';
|
|
17
|
+
|
|
18
|
+
/** Installs skills into an agent's skills folder and keeps a small marker in each one, so the CLI can
|
|
19
|
+
* list, update and remove only what it installed, and tell when a user edited the files. */
|
|
20
|
+
|
|
21
|
+
export const MARKER_FILE = '.insightfulpipe-skill.json';
|
|
22
|
+
const MAX_TOTAL_BYTES = 1024 * 1024;
|
|
23
|
+
const MAX_FILES = 50;
|
|
24
|
+
const MAX_MARKER_BYTES = 256 * 1024;
|
|
25
|
+
const MAX_WALK_ENTRIES = 1000;
|
|
26
|
+
|
|
27
|
+
function sha256(buffer) {
|
|
28
|
+
return createHash('sha256').update(buffer).digest('hex');
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** The same version the website computes: a sha256 over every file's path and digest, sorted. */
|
|
32
|
+
export function computeVersion(files) {
|
|
33
|
+
const hash = createHash('sha256');
|
|
34
|
+
const sorted = [...files].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
|
|
35
|
+
for (const file of sorted) {
|
|
36
|
+
hash.update(`${file.path}\0${file.sha256}\n`);
|
|
37
|
+
}
|
|
38
|
+
return hash.digest('hex').slice(0, 12);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Frontmatter as the website's manifest builder reads it: `key: value` lines between `---` fences. */
|
|
42
|
+
export function parseFrontmatter(text) {
|
|
43
|
+
const normalized = String(text).replace(/^/, '').replace(/\r\n/g, '\n');
|
|
44
|
+
const match = normalized.match(/^---\n([\s\S]*?)\n---/);
|
|
45
|
+
if (!match) {
|
|
46
|
+
return null;
|
|
47
|
+
}
|
|
48
|
+
const fields = {};
|
|
49
|
+
for (const line of match[1].split('\n')) {
|
|
50
|
+
const colon = line.indexOf(':');
|
|
51
|
+
if (colon <= 0) continue;
|
|
52
|
+
fields[line.slice(0, colon).trim()] = line.slice(colon + 1).trim().replace(/^(["'])(.*)\1$/, '$2');
|
|
53
|
+
}
|
|
54
|
+
return fields;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
const SAFE_NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
|
58
|
+
// ASCII only: a disk folds case and look-alike letters (`ſ` is `S` on macOS) in ways no check can mirror.
|
|
59
|
+
const SAFE_SEGMENT = /^[A-Za-z0-9_][A-Za-z0-9._-]*$/;
|
|
60
|
+
const WINDOWS_DEVICE = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\.|$)/i;
|
|
61
|
+
|
|
62
|
+
/** A skill slug or category: it becomes a folder name, so plain lowercase words and dashes only. */
|
|
63
|
+
export function isSafeName(name) {
|
|
64
|
+
return typeof name === 'string' && SAFE_NAME.test(name) && !WINDOWS_DEVICE.test(name);
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function isSafeSegment(part) {
|
|
68
|
+
return SAFE_SEGMENT.test(part) && !part.endsWith('.') && !WINDOWS_DEVICE.test(part);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** A relative path of plain ASCII segments that mean the same file on macOS, Linux and Windows: no
|
|
72
|
+
* `..`, no absolute paths, no hidden files, nothing Windows would rename or treat as a device. */
|
|
73
|
+
export function isSafeRelativePath(path) {
|
|
74
|
+
if (typeof path !== 'string' || !path || path.length > 200) return false;
|
|
75
|
+
if (isAbsolute(path) || path.includes('\\')) return false;
|
|
76
|
+
return path.split('/').every(isSafeSegment);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Two paths a case-insensitive disk (macOS, Windows) would store as one file. */
|
|
80
|
+
function sameFileKey(path) {
|
|
81
|
+
return path.toLowerCase();
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Checks a downloaded skill before anything is written. Returns the decoded files, or throws with
|
|
85
|
+
* every problem found. */
|
|
86
|
+
export function validateBundle(bundle, expected) {
|
|
87
|
+
const problems = [];
|
|
88
|
+
if (!bundle || typeof bundle !== 'object') {
|
|
89
|
+
throw new Error('The skill download is empty.');
|
|
90
|
+
}
|
|
91
|
+
if (bundle.slug !== expected.slug || bundle.category !== expected.category) {
|
|
92
|
+
problems.push(`the download is for ${bundle.category}/${bundle.slug}, not ${expected.category}/${expected.slug}`);
|
|
93
|
+
}
|
|
94
|
+
const files = Array.isArray(bundle.files) ? bundle.files : [];
|
|
95
|
+
if (!files.length) problems.push('it has no files');
|
|
96
|
+
if (files.length > MAX_FILES) problems.push(`it has ${files.length} files (the limit is ${MAX_FILES})`);
|
|
97
|
+
|
|
98
|
+
const decoded = [];
|
|
99
|
+
const seen = new Set();
|
|
100
|
+
let total = 0;
|
|
101
|
+
for (const file of files) {
|
|
102
|
+
if (!isSafeRelativePath(file?.path)) {
|
|
103
|
+
problems.push(`unsafe file path ${JSON.stringify(file?.path)}`);
|
|
104
|
+
continue;
|
|
105
|
+
}
|
|
106
|
+
if (seen.has(sameFileKey(file.path))) {
|
|
107
|
+
problems.push(`${file.path} appears twice`);
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
seen.add(sameFileKey(file.path));
|
|
111
|
+
if (file.encoding !== 'utf8' && file.encoding !== 'base64') {
|
|
112
|
+
problems.push(`${file.path} has an unknown encoding`);
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
const buffer = Buffer.from(String(file.content ?? ''), file.encoding === 'base64' ? 'base64' : 'utf8');
|
|
116
|
+
total += buffer.length;
|
|
117
|
+
if (typeof file.sha256 !== 'string' || sha256(buffer) !== file.sha256) {
|
|
118
|
+
problems.push(`${file.path} does not match its checksum`);
|
|
119
|
+
continue;
|
|
120
|
+
}
|
|
121
|
+
decoded.push({ path: file.path, buffer, sha256: file.sha256 });
|
|
122
|
+
}
|
|
123
|
+
if (total > MAX_TOTAL_BYTES) problems.push(`it is ${total} bytes (the limit is ${MAX_TOTAL_BYTES})`);
|
|
124
|
+
|
|
125
|
+
const skillMd = decoded.find((file) => file.path === 'SKILL.md');
|
|
126
|
+
if (!skillMd) {
|
|
127
|
+
problems.push('it has no SKILL.md');
|
|
128
|
+
} else {
|
|
129
|
+
const frontmatter = parseFrontmatter(skillMd.buffer.toString('utf8'));
|
|
130
|
+
if (!frontmatter) problems.push('SKILL.md has no frontmatter');
|
|
131
|
+
else {
|
|
132
|
+
if (frontmatter.name !== expected.slug) problems.push(`SKILL.md is named "${frontmatter.name}", not "${expected.slug}"`);
|
|
133
|
+
if (!frontmatter.description) problems.push('SKILL.md has no description');
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
const version = computeVersion(decoded);
|
|
138
|
+
if (bundle.version !== version) {
|
|
139
|
+
problems.push(
|
|
140
|
+
bundle.version ? `its files add up to version ${version}, not the ${bundle.version} it claims` : 'it does not state its version',
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
if (expected.version && expected.version !== version) {
|
|
144
|
+
problems.push(`the catalogue lists version ${expected.version}, but the files add up to ${version}`);
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
if (problems.length) {
|
|
148
|
+
throw new Error(`Refusing to install ${expected.category}/${expected.slug}: ${problems.join('; ')}.`);
|
|
149
|
+
}
|
|
150
|
+
return { files: decoded, version };
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** The marker, read only from a small regular file: a cloned project could plant a symlink to a
|
|
154
|
+
* device or pipe that would block or never end. */
|
|
155
|
+
export function readMarker(skillDir) {
|
|
156
|
+
const path = join(skillDir, MARKER_FILE);
|
|
157
|
+
try {
|
|
158
|
+
const stat = lstatSync(path);
|
|
159
|
+
if (!stat.isFile() || stat.size > MAX_MARKER_BYTES) {
|
|
160
|
+
return null;
|
|
161
|
+
}
|
|
162
|
+
const marker = JSON.parse(readFileSync(path, 'utf-8'));
|
|
163
|
+
return marker && typeof marker === 'object' && marker.slug ? marker : null;
|
|
164
|
+
} catch {
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
export function lexists(path) {
|
|
170
|
+
return Boolean(lstatSync(path, { throwIfNoEntry: false }));
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Empty when the leftover is gone, otherwise a sentence telling the user where it is. */
|
|
174
|
+
function removeLeftover(path) {
|
|
175
|
+
try {
|
|
176
|
+
rmSync(path, { recursive: true, force: true });
|
|
177
|
+
return '';
|
|
178
|
+
} catch (error) {
|
|
179
|
+
return ` ${path} could not be removed (${error.message}); delete it by hand.`;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/** Puts the previous copy back after a failed swap; if even that fails, says where it was kept. */
|
|
184
|
+
function restorePrevious(old, dest, cause) {
|
|
185
|
+
try {
|
|
186
|
+
renameSync(old, dest);
|
|
187
|
+
} catch {
|
|
188
|
+
throw new Error(`${cause.message}. Your previous copy is kept at ${old}`);
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
function writeFiles(root, files, marker) {
|
|
193
|
+
for (const file of files) {
|
|
194
|
+
const target = join(root, ...file.path.split('/'));
|
|
195
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
196
|
+
writeFileSync(target, file.buffer);
|
|
197
|
+
}
|
|
198
|
+
writeFileSync(join(root, MARKER_FILE), `${JSON.stringify(marker, null, 2)}\n`);
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/** Writes the skill into `<skillsDir>/<slug>`. The files land in a temporary folder first and are
|
|
202
|
+
* swapped in with a rename, so a failure never leaves a half-written skill behind. */
|
|
203
|
+
export function installSkill(skillsDir, skill, validated, { force = false, source } = {}) {
|
|
204
|
+
const dest = join(skillsDir, String(skill.slug));
|
|
205
|
+
if (!isSafeName(skill.slug) || !isSafeName(skill.category) || dirname(resolve(dest)) !== resolve(skillsDir)) {
|
|
206
|
+
throw new Error(`Refusing to install ${JSON.stringify(skill.slug)}: it is not a plain skill name.`);
|
|
207
|
+
}
|
|
208
|
+
const replacing = lexists(dest);
|
|
209
|
+
if (replacing && !force) {
|
|
210
|
+
const marker = readMarker(dest);
|
|
211
|
+
throw new Error(
|
|
212
|
+
marker
|
|
213
|
+
? `${skill.slug} is already installed at ${dest} (version ${marker.version}). Run "insightfulpipe skills update ${skill.slug}", or add --force to reinstall.`
|
|
214
|
+
: `${dest} already exists and was not installed by InsightfulPipe. Add --force to replace it.`,
|
|
215
|
+
);
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
mkdirSync(skillsDir, { recursive: true });
|
|
219
|
+
const suffix = randomBytes(4).toString('hex');
|
|
220
|
+
const staging = join(skillsDir, `.${skill.slug}.installing-${suffix}`);
|
|
221
|
+
const old = join(skillsDir, `.${skill.slug}.replaced-${suffix}`);
|
|
222
|
+
const marker = {
|
|
223
|
+
schema: 'insightfulpipe.installed-skill.v1',
|
|
224
|
+
source,
|
|
225
|
+
category: skill.category,
|
|
226
|
+
slug: skill.slug,
|
|
227
|
+
version: validated.version,
|
|
228
|
+
installed_at: new Date().toISOString(),
|
|
229
|
+
files: Object.fromEntries(validated.files.map((file) => [file.path, file.sha256])),
|
|
230
|
+
};
|
|
231
|
+
|
|
232
|
+
try {
|
|
233
|
+
writeFiles(staging, validated.files, marker);
|
|
234
|
+
if (replacing) renameSync(dest, old);
|
|
235
|
+
try {
|
|
236
|
+
renameSync(staging, dest);
|
|
237
|
+
} catch (error) {
|
|
238
|
+
if (replacing) restorePrevious(old, dest, error);
|
|
239
|
+
throw error;
|
|
240
|
+
}
|
|
241
|
+
} catch (error) {
|
|
242
|
+
throw new Error(`Could not install ${skill.slug}: ${error.message}.${removeLeftover(staging)}`);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const warning = replacing ? removeLeftover(old).trim() : '';
|
|
246
|
+
return { path: dest, marker, ...(warning ? { warning } : {}) };
|
|
247
|
+
}
|
|
248
|
+
|
|
249
|
+
/** Skills in a folder that this CLI installed: they carry the marker, in the folder named after it.
|
|
250
|
+
* A copied or renamed folder keeps a marker for another name, and is the user's, not ours. */
|
|
251
|
+
export function listInstalled(skillsDir) {
|
|
252
|
+
if (!existsSync(skillsDir)) {
|
|
253
|
+
return [];
|
|
254
|
+
}
|
|
255
|
+
return readdirSync(skillsDir, { withFileTypes: true })
|
|
256
|
+
.filter((entry) => entry.isDirectory() && !entry.name.startsWith('.'))
|
|
257
|
+
.map((entry) => {
|
|
258
|
+
const dir = join(skillsDir, entry.name);
|
|
259
|
+
return { slug: entry.name, dir, marker: readMarker(dir) };
|
|
260
|
+
})
|
|
261
|
+
.filter((item) => item.marker && item.marker.slug === item.slug)
|
|
262
|
+
.sort((a, b) => a.slug.localeCompare(b.slug));
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/** Every entry under a skill folder without following links: hidden files, symlinks and empty
|
|
266
|
+
* folders included, only our marker and the Finder's .DS_Store skipped. Stops past the cap. */
|
|
267
|
+
function walk(root, base = '', out = []) {
|
|
268
|
+
for (const entry of readdirSync(join(root, base), { withFileTypes: true })) {
|
|
269
|
+
if ((!base && entry.name === MARKER_FILE) || entry.name === '.DS_Store') continue;
|
|
270
|
+
if (out.length > MAX_WALK_ENTRIES) break;
|
|
271
|
+
const rel = base ? `${base}/${entry.name}` : entry.name;
|
|
272
|
+
if (entry.isDirectory()) {
|
|
273
|
+
const before = out.length;
|
|
274
|
+
walk(root, rel, out);
|
|
275
|
+
if (out.length === before) out.push({ path: `${rel}/`, file: false });
|
|
276
|
+
} else {
|
|
277
|
+
out.push({ path: rel, file: entry.isFile() });
|
|
278
|
+
}
|
|
279
|
+
}
|
|
280
|
+
return out;
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
/** sha256 of a regular file, or null past the install size cap, so a huge or endless file is never
|
|
284
|
+
* read whole; the last path part is never followed as a link. */
|
|
285
|
+
function fileDigest(path) {
|
|
286
|
+
const buffer = Buffer.alloc(MAX_TOTAL_BYTES + 1);
|
|
287
|
+
const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
288
|
+
try {
|
|
289
|
+
let total = 0;
|
|
290
|
+
let read;
|
|
291
|
+
while (total < buffer.length && (read = readSync(fd, buffer, total, buffer.length - total, null)) > 0) {
|
|
292
|
+
total += read;
|
|
293
|
+
}
|
|
294
|
+
return total > MAX_TOTAL_BYTES ? null : sha256(buffer.subarray(0, total));
|
|
295
|
+
} finally {
|
|
296
|
+
closeSync(fd);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** Files changed, deleted or added since install, compared with the digests in the marker. Only
|
|
301
|
+
* entries found by `walk` are read, so a marker path with `..` or a linked folder is never followed;
|
|
302
|
+
* a marker that records more than any install could counts as edited. */
|
|
303
|
+
export function localChanges(skillDir, marker) {
|
|
304
|
+
const recorded = marker?.files && typeof marker.files === 'object' ? marker.files : {};
|
|
305
|
+
if (Object.keys(recorded).length > MAX_FILES) {
|
|
306
|
+
return { changed: [], missing: [], added: [], edited: true };
|
|
307
|
+
}
|
|
308
|
+
const onDisk = new Map(walk(skillDir).map((entry) => [entry.path, entry]));
|
|
309
|
+
const changed = [];
|
|
310
|
+
const missing = [];
|
|
311
|
+
for (const [path, digest] of Object.entries(recorded)) {
|
|
312
|
+
const entry = onDisk.get(path);
|
|
313
|
+
if (!isSafeRelativePath(path)) {
|
|
314
|
+
changed.push(path);
|
|
315
|
+
} else if (!entry) {
|
|
316
|
+
missing.push(path);
|
|
317
|
+
} else if (!entry.file || fileDigest(join(skillDir, ...path.split('/'))) !== digest) {
|
|
318
|
+
changed.push(path);
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
const added = [...onDisk.keys()].filter((path) => !Object.hasOwn(recorded, path));
|
|
322
|
+
return { changed, missing, added, edited: changed.length + missing.length + added.length > 0 };
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** Deletes a skill folder, but only one this CLI installed. */
|
|
326
|
+
export function removeInstalled(skillDir) {
|
|
327
|
+
if (!readMarker(skillDir)) {
|
|
328
|
+
throw new Error(`${skillDir} was not installed by InsightfulPipe, so it was left alone.`);
|
|
329
|
+
}
|
|
330
|
+
rmSync(skillDir, { recursive: true, force: true });
|
|
331
|
+
}
|