insightfulpipe 0.2.0 → 0.4.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 +101 -0
- package/README.md +61 -1
- package/package.json +2 -2
- package/src/api.js +112 -73
- package/src/cli/commands/auth.js +7 -2
- package/src/cli/commands/discovery.js +8 -7
- package/src/cli/commands/execution.js +3 -3
- package/src/cli/commands/skills.js +554 -0
- package/src/cli/errors.js +159 -15
- package/src/cli/input.js +6 -0
- package/src/cli/program.js +7 -7
- package/src/cli/query-contexts.js +3 -2
- package/src/config.js +16 -3
- package/src/http.js +39 -0
- package/src/skills/agents.js +95 -0
- package/src/skills/catalog.js +177 -0
- package/src/skills/installer.js +372 -0
- package/src/skills/private.js +100 -0
- package/src/skills/records.js +72 -0
- package/src/skills/sources.js +108 -0
|
@@ -0,0 +1,372 @@
|
|
|
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
|
+
import { isRecordedInstall } from './records.js';
|
|
19
|
+
|
|
20
|
+
/** Installs skills into an agent's skills folder and keeps a small marker in each one, so the CLI can
|
|
21
|
+
* list, update and remove only what it installed, and tell when a user edited the files. */
|
|
22
|
+
|
|
23
|
+
export const MARKER_FILE = '.insightfulpipe-skill.json';
|
|
24
|
+
const MAX_TOTAL_BYTES = 1024 * 1024;
|
|
25
|
+
const MAX_FILES = 50;
|
|
26
|
+
const MAX_MARKER_BYTES = 256 * 1024;
|
|
27
|
+
const MAX_WALK_ENTRIES = 1000;
|
|
28
|
+
|
|
29
|
+
function sha256(buffer) {
|
|
30
|
+
return createHash('sha256').update(buffer).digest('hex');
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** The same version the website computes: a sha256 over every file's path and digest, sorted. */
|
|
34
|
+
export function computeVersion(files) {
|
|
35
|
+
const hash = createHash('sha256');
|
|
36
|
+
const sorted = [...files].sort((a, b) => (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
|
|
37
|
+
for (const file of sorted) {
|
|
38
|
+
hash.update(`${file.path}\0${file.sha256}\n`);
|
|
39
|
+
}
|
|
40
|
+
return hash.digest('hex').slice(0, 12);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Frontmatter as the website's manifest builder reads it: `key: value` lines between `---` fences. */
|
|
44
|
+
export function parseFrontmatter(text) {
|
|
45
|
+
const normalized = String(text).replace(/^/, '').replace(/\r\n/g, '\n');
|
|
46
|
+
const match = normalized.match(/^---\n([\s\S]*?)\n---/);
|
|
47
|
+
if (!match) {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
const fields = {};
|
|
51
|
+
for (const line of match[1].split('\n')) {
|
|
52
|
+
const colon = line.indexOf(':');
|
|
53
|
+
if (colon <= 0) continue;
|
|
54
|
+
fields[line.slice(0, colon).trim()] = line.slice(colon + 1).trim().replace(/^(["'])(.*)\1$/, '$2');
|
|
55
|
+
}
|
|
56
|
+
return fields;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const SAFE_NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;
|
|
60
|
+
// ASCII only: a disk folds case and look-alike letters (`ſ` is `S` on macOS) in ways no check can mirror.
|
|
61
|
+
// Single spaces may sit between characters ("Brand guide.md"); none at either end, where Windows drops them.
|
|
62
|
+
const SAFE_SEGMENT = /^[A-Za-z0-9_](?:[A-Za-z0-9._-]| (?=[A-Za-z0-9._-]))*$/;
|
|
63
|
+
// Windows ignores spaces after a device name, so `con .txt` is the console too.
|
|
64
|
+
const WINDOWS_DEVICE = /^(con|prn|aux|nul|com[0-9]|lpt[0-9]) *(\.|$)/i;
|
|
65
|
+
|
|
66
|
+
/** A skill slug or category: it becomes a folder name, so plain lowercase words and dashes only. */
|
|
67
|
+
export function isSafeName(name) {
|
|
68
|
+
return typeof name === 'string' && SAFE_NAME.test(name) && !WINDOWS_DEVICE.test(name);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function isSafeSegment(part) {
|
|
72
|
+
return SAFE_SEGMENT.test(part) && !part.endsWith('.') && !WINDOWS_DEVICE.test(part);
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/** A relative path of plain ASCII segments that mean the same file on macOS, Linux and Windows: no
|
|
76
|
+
* `..`, no absolute paths, no hidden files, nothing Windows would rename or treat as a device. Single
|
|
77
|
+
* inner spaces are allowed. */
|
|
78
|
+
export function isSafeRelativePath(path) {
|
|
79
|
+
if (typeof path !== 'string' || !path || path.length > 200) return false;
|
|
80
|
+
if (isAbsolute(path) || path.includes('\\')) return false;
|
|
81
|
+
return path.split('/').every(isSafeSegment);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Two paths a case-insensitive disk (macOS, Windows) would store as one file. */
|
|
85
|
+
function sameFileKey(path) {
|
|
86
|
+
return path.toLowerCase();
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Checks a downloaded skill before anything is written. Returns the decoded files, or throws with
|
|
90
|
+
* every problem found. */
|
|
91
|
+
export function validateBundle(bundle, expected) {
|
|
92
|
+
const problems = [];
|
|
93
|
+
if (!bundle || typeof bundle !== 'object') {
|
|
94
|
+
throw new Error('The skill download is empty.');
|
|
95
|
+
}
|
|
96
|
+
if (bundle.slug !== expected.slug || bundle.category !== expected.category) {
|
|
97
|
+
problems.push(`the download is for ${bundle.category}/${bundle.slug}, not ${expected.category}/${expected.slug}`);
|
|
98
|
+
}
|
|
99
|
+
const files = Array.isArray(bundle.files) ? bundle.files : [];
|
|
100
|
+
if (!files.length) problems.push('it has no files');
|
|
101
|
+
if (files.length > MAX_FILES) problems.push(`it has ${files.length} files (the limit is ${MAX_FILES})`);
|
|
102
|
+
|
|
103
|
+
const decoded = [];
|
|
104
|
+
const seen = new Set();
|
|
105
|
+
let total = 0;
|
|
106
|
+
for (const file of files) {
|
|
107
|
+
if (!isSafeRelativePath(file?.path)) {
|
|
108
|
+
problems.push(`unsafe file path ${JSON.stringify(file?.path)}`);
|
|
109
|
+
continue;
|
|
110
|
+
}
|
|
111
|
+
if (seen.has(sameFileKey(file.path))) {
|
|
112
|
+
problems.push(`${file.path} appears twice`);
|
|
113
|
+
continue;
|
|
114
|
+
}
|
|
115
|
+
seen.add(sameFileKey(file.path));
|
|
116
|
+
if (file.encoding !== 'utf8' && file.encoding !== 'base64') {
|
|
117
|
+
problems.push(`${file.path} has an unknown encoding`);
|
|
118
|
+
continue;
|
|
119
|
+
}
|
|
120
|
+
const buffer = Buffer.from(String(file.content ?? ''), file.encoding === 'base64' ? 'base64' : 'utf8');
|
|
121
|
+
total += buffer.length;
|
|
122
|
+
if (typeof file.sha256 !== 'string' || sha256(buffer) !== file.sha256) {
|
|
123
|
+
problems.push(`${file.path} does not match its checksum`);
|
|
124
|
+
continue;
|
|
125
|
+
}
|
|
126
|
+
decoded.push({ path: file.path, buffer, sha256: file.sha256 });
|
|
127
|
+
}
|
|
128
|
+
if (total > MAX_TOTAL_BYTES) problems.push(`it is ${total} bytes (the limit is ${MAX_TOTAL_BYTES})`);
|
|
129
|
+
|
|
130
|
+
const skillMd = decoded.find((file) => file.path === 'SKILL.md');
|
|
131
|
+
if (!skillMd) {
|
|
132
|
+
problems.push('it has no SKILL.md');
|
|
133
|
+
} else {
|
|
134
|
+
const frontmatter = parseFrontmatter(skillMd.buffer.toString('utf8'));
|
|
135
|
+
if (!frontmatter) problems.push('SKILL.md has no frontmatter');
|
|
136
|
+
else {
|
|
137
|
+
if (frontmatter.name !== expected.slug) problems.push(`SKILL.md is named "${frontmatter.name}", not "${expected.slug}"`);
|
|
138
|
+
if (!frontmatter.description) problems.push('SKILL.md has no description');
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const version = computeVersion(decoded);
|
|
143
|
+
if (bundle.version !== version) {
|
|
144
|
+
problems.push(
|
|
145
|
+
bundle.version ? `its files add up to version ${version}, not the ${bundle.version} it claims` : 'it does not state its version',
|
|
146
|
+
);
|
|
147
|
+
}
|
|
148
|
+
if (expected.version && expected.version !== version) {
|
|
149
|
+
problems.push(`the catalogue lists version ${expected.version}, but the files add up to ${version}`);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
if (problems.length) {
|
|
153
|
+
throw new Error(`Refusing to install ${expected.category}/${expected.slug}: ${problems.join('; ')}.`);
|
|
154
|
+
}
|
|
155
|
+
return { files: decoded, version };
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
/** The marker, read only from a small regular file: a cloned project could plant a symlink to a
|
|
159
|
+
* device or pipe that would block or never end. */
|
|
160
|
+
export function readMarker(skillDir) {
|
|
161
|
+
const path = join(skillDir, MARKER_FILE);
|
|
162
|
+
try {
|
|
163
|
+
const stat = lstatSync(path);
|
|
164
|
+
if (!stat.isFile() || stat.size > MAX_MARKER_BYTES) {
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
const marker = JSON.parse(readFileSync(path, 'utf-8'));
|
|
168
|
+
return marker && typeof marker === 'object' && marker.slug ? marker : null;
|
|
169
|
+
} catch {
|
|
170
|
+
return null;
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
export function lexists(path) {
|
|
175
|
+
return Boolean(lstatSync(path, { throwIfNoEntry: false }));
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** Empty when the leftover is gone, otherwise a sentence telling the user where it is. */
|
|
179
|
+
function removeLeftover(path) {
|
|
180
|
+
try {
|
|
181
|
+
rmSync(path, { recursive: true, force: true });
|
|
182
|
+
return '';
|
|
183
|
+
} catch (error) {
|
|
184
|
+
return ` ${path} could not be removed (${error.message}); delete it by hand.`;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** Puts the previous copy back after a failed swap; if even that fails, says where it was kept. */
|
|
189
|
+
function restorePrevious(old, dest, cause) {
|
|
190
|
+
try {
|
|
191
|
+
renameSync(old, dest);
|
|
192
|
+
} catch {
|
|
193
|
+
throw new Error(`${cause.message}. Your previous copy is kept at ${old}`);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function writeFiles(root, files, marker) {
|
|
198
|
+
for (const file of files) {
|
|
199
|
+
const target = join(root, ...file.path.split('/'));
|
|
200
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
201
|
+
writeFileSync(target, file.buffer);
|
|
202
|
+
}
|
|
203
|
+
writeFileSync(join(root, MARKER_FILE), `${JSON.stringify(marker, null, 2)}\n`);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
function describeInstalled({ origin, key, workspace_id: workspaceId, category, slug }) {
|
|
207
|
+
return origin === 'private' ? `the private skill ${key} of workspace ${workspaceId}` : `the public skill ${category}/${slug}`;
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Whether a marker belongs to the skill about to be installed, so replacing it is an update, not a swap. */
|
|
211
|
+
function sameSkill(marker, incoming) {
|
|
212
|
+
const origin = marker.origin === 'private' ? 'private' : 'public';
|
|
213
|
+
if (origin !== incoming.origin) return false;
|
|
214
|
+
return origin === 'private'
|
|
215
|
+
? marker.key === incoming.key && marker.workspace_id === incoming.workspace_id
|
|
216
|
+
: marker.category === incoming.category;
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
function refuseExisting(dest, skill, incoming) {
|
|
220
|
+
const marker = readMarker(dest);
|
|
221
|
+
if (!marker) {
|
|
222
|
+
return `${dest} already exists and was not installed by InsightfulPipe. Add --force to replace it.`;
|
|
223
|
+
}
|
|
224
|
+
if (marker.origin === 'private' && !isRecordedInstall(dest, marker)) {
|
|
225
|
+
return `${dest} already exists and was not installed by you here. Add --force to replace it.`;
|
|
226
|
+
}
|
|
227
|
+
if (!sameSkill(marker, incoming)) {
|
|
228
|
+
return `${dest} holds ${describeInstalled(marker)} (version ${marker.version}). Installing ${describeInstalled(incoming)} would replace it: add --force to do that, or use --dir to install into another folder.`;
|
|
229
|
+
}
|
|
230
|
+
return `${skill.slug} is already installed at ${dest} (version ${marker.version}). Run "insightfulpipe skills update ${skill.slug}", or add --force to reinstall.`;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/** Writes the skill into `<skillsDir>/<slug>`. The files land in a temporary folder first and are
|
|
234
|
+
* swapped in with a rename, so a failure never leaves a half-written skill behind. The marker records
|
|
235
|
+
* the origin (public, or private with its key and workspace) that list and update go back to. */
|
|
236
|
+
export function installSkill(skillsDir, skill, validated, { force = false, source, origin = 'public', key, workspaceId } = {}) {
|
|
237
|
+
const dest = join(skillsDir, String(skill.slug));
|
|
238
|
+
if (!isSafeName(skill.slug) || !isSafeName(skill.category) || dirname(resolve(dest)) !== resolve(skillsDir)) {
|
|
239
|
+
throw new Error(`Refusing to install ${JSON.stringify(skill.slug)}: it is not a plain skill name.`);
|
|
240
|
+
}
|
|
241
|
+
const identity = {
|
|
242
|
+
origin,
|
|
243
|
+
...(origin === 'private' ? { key, workspace_id: workspaceId } : {}),
|
|
244
|
+
category: skill.category,
|
|
245
|
+
slug: skill.slug,
|
|
246
|
+
};
|
|
247
|
+
const replacing = lexists(dest);
|
|
248
|
+
if (replacing && !force) {
|
|
249
|
+
throw new Error(refuseExisting(dest, skill, identity));
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
mkdirSync(skillsDir, { recursive: true });
|
|
253
|
+
const suffix = randomBytes(4).toString('hex');
|
|
254
|
+
const staging = join(skillsDir, `.${skill.slug}.installing-${suffix}`);
|
|
255
|
+
const old = join(skillsDir, `.${skill.slug}.replaced-${suffix}`);
|
|
256
|
+
const marker = {
|
|
257
|
+
schema: 'insightfulpipe.installed-skill.v1',
|
|
258
|
+
source,
|
|
259
|
+
...identity,
|
|
260
|
+
version: validated.version,
|
|
261
|
+
installed_at: new Date().toISOString(),
|
|
262
|
+
files: Object.fromEntries(validated.files.map((file) => [file.path, file.sha256])),
|
|
263
|
+
};
|
|
264
|
+
|
|
265
|
+
try {
|
|
266
|
+
writeFiles(staging, validated.files, marker);
|
|
267
|
+
if (replacing) renameSync(dest, old);
|
|
268
|
+
try {
|
|
269
|
+
renameSync(staging, dest);
|
|
270
|
+
} catch (error) {
|
|
271
|
+
if (replacing) restorePrevious(old, dest, error);
|
|
272
|
+
throw error;
|
|
273
|
+
}
|
|
274
|
+
} catch (error) {
|
|
275
|
+
throw new Error(`Could not install ${skill.slug}: ${error.message}.${removeLeftover(staging)}`);
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
const warning = replacing ? removeLeftover(old).trim() : '';
|
|
279
|
+
return { path: dest, marker, ...(warning ? { warning } : {}) };
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
const PLAIN_VERSION = /^[0-9a-f]{1,64}$/;
|
|
283
|
+
|
|
284
|
+
/** Skills in a folder that this CLI installed: they carry the marker, in the folder named after it.
|
|
285
|
+
* A copied or renamed folder keeps a marker for another name, and is the user's, not ours. A marker
|
|
286
|
+
* may come with a cloned repository, so only plain names are taken from it, and a version that is not
|
|
287
|
+
* plain hex is dropped rather than printed. */
|
|
288
|
+
export function listInstalled(skillsDir) {
|
|
289
|
+
if (!existsSync(skillsDir)) {
|
|
290
|
+
return [];
|
|
291
|
+
}
|
|
292
|
+
return readdirSync(skillsDir, { withFileTypes: true })
|
|
293
|
+
.filter((entry) => entry.isDirectory() && isSafeName(entry.name))
|
|
294
|
+
.map((entry) => {
|
|
295
|
+
const dir = join(skillsDir, entry.name);
|
|
296
|
+
return { slug: entry.name, dir, marker: readMarker(dir) };
|
|
297
|
+
})
|
|
298
|
+
.filter(({ slug, marker }) => marker && marker.slug === slug && (marker.origin === 'private' || isSafeName(marker.category)))
|
|
299
|
+
.map((item) => ({
|
|
300
|
+
...item,
|
|
301
|
+
marker: { ...item.marker, version: PLAIN_VERSION.test(item.marker.version) ? item.marker.version : null },
|
|
302
|
+
}))
|
|
303
|
+
.sort((a, b) => a.slug.localeCompare(b.slug));
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
/** Every entry under a skill folder without following links: hidden files, symlinks and empty
|
|
307
|
+
* folders included, only our marker and the Finder's .DS_Store skipped. Stops past the cap. */
|
|
308
|
+
function walk(root, base = '', out = []) {
|
|
309
|
+
for (const entry of readdirSync(join(root, base), { withFileTypes: true })) {
|
|
310
|
+
if ((!base && entry.name === MARKER_FILE) || entry.name === '.DS_Store') continue;
|
|
311
|
+
if (out.length > MAX_WALK_ENTRIES) break;
|
|
312
|
+
const rel = base ? `${base}/${entry.name}` : entry.name;
|
|
313
|
+
if (entry.isDirectory()) {
|
|
314
|
+
const before = out.length;
|
|
315
|
+
walk(root, rel, out);
|
|
316
|
+
if (out.length === before) out.push({ path: `${rel}/`, file: false });
|
|
317
|
+
} else {
|
|
318
|
+
out.push({ path: rel, file: entry.isFile() });
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
return out;
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
/** sha256 of a regular file, or null past the install size cap, so a huge or endless file is never
|
|
325
|
+
* read whole; the last path part is never followed as a link. */
|
|
326
|
+
function fileDigest(path) {
|
|
327
|
+
const buffer = Buffer.alloc(MAX_TOTAL_BYTES + 1);
|
|
328
|
+
const fd = openSync(path, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
|
|
329
|
+
try {
|
|
330
|
+
let total = 0;
|
|
331
|
+
let read;
|
|
332
|
+
while (total < buffer.length && (read = readSync(fd, buffer, total, buffer.length - total, null)) > 0) {
|
|
333
|
+
total += read;
|
|
334
|
+
}
|
|
335
|
+
return total > MAX_TOTAL_BYTES ? null : sha256(buffer.subarray(0, total));
|
|
336
|
+
} finally {
|
|
337
|
+
closeSync(fd);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
/** Files changed, deleted or added since install, compared with the digests in the marker. Only
|
|
342
|
+
* entries found by `walk` are read, so a marker path with `..` or a linked folder is never followed;
|
|
343
|
+
* a marker that records more than any install could counts as edited. */
|
|
344
|
+
export function localChanges(skillDir, marker) {
|
|
345
|
+
const recorded = marker?.files && typeof marker.files === 'object' ? marker.files : {};
|
|
346
|
+
if (Object.keys(recorded).length > MAX_FILES) {
|
|
347
|
+
return { changed: [], missing: [], added: [], edited: true };
|
|
348
|
+
}
|
|
349
|
+
const onDisk = new Map(walk(skillDir).map((entry) => [entry.path, entry]));
|
|
350
|
+
const changed = [];
|
|
351
|
+
const missing = [];
|
|
352
|
+
for (const [path, digest] of Object.entries(recorded)) {
|
|
353
|
+
const entry = onDisk.get(path);
|
|
354
|
+
if (!isSafeRelativePath(path)) {
|
|
355
|
+
changed.push(path);
|
|
356
|
+
} else if (!entry) {
|
|
357
|
+
missing.push(path);
|
|
358
|
+
} else if (!entry.file || fileDigest(join(skillDir, ...path.split('/'))) !== digest) {
|
|
359
|
+
changed.push(path);
|
|
360
|
+
}
|
|
361
|
+
}
|
|
362
|
+
const added = [...onDisk.keys()].filter((path) => !Object.hasOwn(recorded, path));
|
|
363
|
+
return { changed, missing, added, edited: changed.length + missing.length + added.length > 0 };
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
/** Deletes a skill folder, but only one this CLI installed. */
|
|
367
|
+
export function removeInstalled(skillDir) {
|
|
368
|
+
if (!readMarker(skillDir)) {
|
|
369
|
+
throw new Error(`${skillDir} was not installed by InsightfulPipe, so it was left alone.`);
|
|
370
|
+
}
|
|
371
|
+
rmSync(skillDir, { recursive: true, force: true });
|
|
372
|
+
}
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
import { apiGet } from '../api.js';
|
|
2
|
+
import { errorMessage } from '../cli/errors.js';
|
|
3
|
+
import { getApiUrl, getContext, getToken, tokenProblem } from '../config.js';
|
|
4
|
+
import { isSafeName, validateBundle } from './installer.js';
|
|
5
|
+
|
|
6
|
+
/** Private skills: a workspace's own (custom) skills, served by the app API with the user's API key.
|
|
7
|
+
* This is the only skills module that may use the key. Public skills come from the website
|
|
8
|
+
* (catalog.js) without it, and the two never fall back to each other. */
|
|
9
|
+
|
|
10
|
+
export const PRIVATE_CATEGORY = 'private';
|
|
11
|
+
const KEY_RE = /^custom-\d{1,10}$/;
|
|
12
|
+
// A private skill is fixed where it was written: the CLI can refuse it but not repair it.
|
|
13
|
+
const FIX_IN_LIBRARY = "Fix the skill in the app's Skills Library (for example, rename the file), then try again.";
|
|
14
|
+
|
|
15
|
+
export function isPrivateKey(value) {
|
|
16
|
+
return typeof value === 'string' && KEY_RE.test(value);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function workspaceIdFrom(value, where) {
|
|
20
|
+
const id = Number(value);
|
|
21
|
+
if (!Number.isInteger(id) || id < 1) {
|
|
22
|
+
throw new Error(`${where} must be a positive integer workspace id, not ${JSON.stringify(value)}.`);
|
|
23
|
+
}
|
|
24
|
+
return id;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** `--workspace` wins, then the saved scope from `insightfulpipe use`. */
|
|
28
|
+
export function privateWorkspaceId(opts) {
|
|
29
|
+
if (opts.workspace !== undefined) return workspaceIdFrom(opts.workspace, '--workspace');
|
|
30
|
+
const saved = getContext().workspace_id;
|
|
31
|
+
if (saved != null) return workspaceIdFrom(saved, 'The saved workspace');
|
|
32
|
+
throw new Error('Private skills belong to a workspace. Add --workspace <id>, or save one with "insightfulpipe use -w <id>".');
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Refuses before any request when there is no key to send, so a missing key is a sentence, not an exit. */
|
|
36
|
+
function requireKey() {
|
|
37
|
+
const token = getToken();
|
|
38
|
+
if (!token) throw new Error('Private skills need your API key. Run: insightfulpipe auth');
|
|
39
|
+
const problem = tokenProblem(token);
|
|
40
|
+
if (problem) throw new Error(problem);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** The app's own message and HTTP status; the status also rides on the error as `httpStatus`. */
|
|
44
|
+
function failure(data, what) {
|
|
45
|
+
const status = typeof data.status === 'number' ? data.status : undefined;
|
|
46
|
+
const error = new Error(`Could not ${what}: ${errorMessage(data)}${status ? ` (HTTP ${status})` : ''}`);
|
|
47
|
+
if (status) error.httpStatus = status;
|
|
48
|
+
return error;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** The workspace's private skills, without file contents. The slug becomes a folder name and the key part
|
|
52
|
+
* of a command, so an entry whose slug or key is not plain is dropped, as the public catalogue does. */
|
|
53
|
+
export async function fetchPrivateCatalog(workspaceId) {
|
|
54
|
+
requireKey();
|
|
55
|
+
const data = await apiGet(`/skills/?workspace_id=${encodeURIComponent(workspaceId)}`);
|
|
56
|
+
if (data?.error) throw failure(data, `list the private skills of workspace ${workspaceId}`);
|
|
57
|
+
if (!Array.isArray(data?.skills)) throw new Error('The app did not return a list of private skills.');
|
|
58
|
+
return data.skills
|
|
59
|
+
.filter((skill) => isPrivateKey(skill?.key) && isSafeName(skill.slug))
|
|
60
|
+
.map((skill) => ({ ...skill, category: PRIVATE_CATEGORY }));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** One private skill's exact files, or null when the workspace no longer has it. */
|
|
64
|
+
export async function fetchPrivateSkillFiles(workspaceId, key) {
|
|
65
|
+
requireKey();
|
|
66
|
+
const data = await apiGet(`/skills/files/?workspace_id=${encodeURIComponent(workspaceId)}&key=${encodeURIComponent(key)}`);
|
|
67
|
+
if (data?.error && data.status === 404) return null;
|
|
68
|
+
if (data?.error) throw failure(data, `download the private skill ${key}`);
|
|
69
|
+
return data;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/** The installer's checks, plus that the files are the skill that was asked for. */
|
|
73
|
+
export function validatePrivateBundle(bundle, skill) {
|
|
74
|
+
if (bundle?.key !== skill.key) {
|
|
75
|
+
throw new Error(`Refusing to install ${PRIVATE_CATEGORY}/${skill.slug}: the app sent the files of ${bundle?.key ?? 'another skill'}, not ${skill.key}.`);
|
|
76
|
+
}
|
|
77
|
+
try {
|
|
78
|
+
return validateBundle(bundle, skill);
|
|
79
|
+
} catch (error) {
|
|
80
|
+
throw new Error(`${error.message} ${FIX_IN_LIBRARY}`);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** Accepts the skill key (`custom-12`) or its name. A name two private skills share must be given by key. */
|
|
85
|
+
export function resolvePrivateSkill(name, skills) {
|
|
86
|
+
const wanted = String(name).trim().toLowerCase().replace(/^private\//, '');
|
|
87
|
+
const matches = isPrivateKey(wanted)
|
|
88
|
+
? skills.filter((skill) => skill.key === wanted)
|
|
89
|
+
: skills.filter((skill) => skill.slug === wanted);
|
|
90
|
+
if (matches.length === 1) return { skill: matches[0] };
|
|
91
|
+
if (matches.length > 1) {
|
|
92
|
+
return { error: `"${name}" matches more than one private skill. Use its key: ${matches.map((skill) => skill.key).join(', ')}.` };
|
|
93
|
+
}
|
|
94
|
+
return { error: `No private skill named "${name}" in this workspace. Run: insightfulpipe skills search --private` };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Recorded in the marker as where a private skill came from. */
|
|
98
|
+
export function privateSourceUrl() {
|
|
99
|
+
return getApiUrl();
|
|
100
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { createHash, randomBytes } from 'node:crypto';
|
|
2
|
+
import { lstatSync, mkdirSync, readFileSync, realpathSync, renameSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
|
|
5
|
+
import { getConfigDir } from '../config.js';
|
|
6
|
+
|
|
7
|
+
/** The private skills this user installed, and where. It lives next to the config, never in a skills
|
|
8
|
+
* folder, so a cloned repository cannot add to it: a private marker is trusted only when this record
|
|
9
|
+
* names its real folder, key, workspace and slug, and the CLI never sends the key on behalf of any other.
|
|
10
|
+
* One small file per installed folder, so installs running at the same time never undo each other. */
|
|
11
|
+
|
|
12
|
+
const RECORD_DIR = 'private-skills';
|
|
13
|
+
const MAX_ENTRY_BYTES = 64 * 1024;
|
|
14
|
+
|
|
15
|
+
function recordDir() {
|
|
16
|
+
return join(getConfigDir(), RECORD_DIR);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
function entryFile(path) {
|
|
20
|
+
return join(recordDir(), `${createHash('sha256').update(path).digest('hex').slice(0, 40)}.json`);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** The folder's real path as the disk spells it (`--dir ./Skills` and `./skills` are one folder on
|
|
24
|
+
* macOS and Windows), or null when it does not exist. */
|
|
25
|
+
export function realFolderPath(dir) {
|
|
26
|
+
try {
|
|
27
|
+
return realpathSync.native(dir);
|
|
28
|
+
} catch {
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** Read only from a small regular file; anything unreadable counts as absent, which only trusts less. */
|
|
34
|
+
function readEntry(path) {
|
|
35
|
+
try {
|
|
36
|
+
const file = entryFile(path);
|
|
37
|
+
const stat = lstatSync(file);
|
|
38
|
+
if (!stat.isFile() || stat.size > MAX_ENTRY_BYTES) return null;
|
|
39
|
+
const entry = JSON.parse(readFileSync(file, 'utf-8'));
|
|
40
|
+
return entry?.path === path ? entry : null;
|
|
41
|
+
} catch {
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Whether this user installed this very private skill (key, workspace and slug) in this very folder. */
|
|
47
|
+
export function isRecordedInstall(dir, marker) {
|
|
48
|
+
const path = realFolderPath(dir);
|
|
49
|
+
const entry = path && readEntry(path);
|
|
50
|
+
return Boolean(entry) && entry.key === marker.key && entry.workspace_id === marker.workspace_id && entry.slug === marker.slug;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Written to a private temporary file and renamed into place, readable by this user only. */
|
|
54
|
+
export function recordInstall(dir, { key, workspaceId, slug }) {
|
|
55
|
+
const path = realFolderPath(dir);
|
|
56
|
+
if (!path) return;
|
|
57
|
+
mkdirSync(recordDir(), { recursive: true, mode: 0o700 });
|
|
58
|
+
const temp = join(recordDir(), `.${randomBytes(6).toString('hex')}.tmp`);
|
|
59
|
+
const entry = { schema: 'insightfulpipe.private-install.v1', path, key, workspace_id: workspaceId, slug };
|
|
60
|
+
try {
|
|
61
|
+
writeFileSync(temp, `${JSON.stringify(entry, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
|
|
62
|
+
renameSync(temp, entryFile(path));
|
|
63
|
+
} catch (error) {
|
|
64
|
+
rmSync(temp, { force: true });
|
|
65
|
+
throw error;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Drops the entry for a folder, by the real path taken before the folder was removed or replaced. */
|
|
70
|
+
export function forgetInstall(path) {
|
|
71
|
+
if (path) rmSync(entryFile(path), { force: true });
|
|
72
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { fetchCatalog, fetchSkillFiles, getCatalogUrl, pageUrl, resolveSkill, skillKey } from './catalog.js';
|
|
2
|
+
import { validateBundle } from './installer.js';
|
|
3
|
+
import {
|
|
4
|
+
fetchPrivateCatalog,
|
|
5
|
+
fetchPrivateSkillFiles,
|
|
6
|
+
privateSourceUrl,
|
|
7
|
+
privateWorkspaceId,
|
|
8
|
+
resolvePrivateSkill,
|
|
9
|
+
validatePrivateBundle,
|
|
10
|
+
} from './private.js';
|
|
11
|
+
|
|
12
|
+
/** Where skills come from: the public library on the website, with no key, or a workspace's private
|
|
13
|
+
* skills from the app API, with the user's key. A command uses exactly one source and never falls back
|
|
14
|
+
* to the other; an installed skill goes back to the source its marker names. */
|
|
15
|
+
|
|
16
|
+
/** Markers written before 0.4.0 have no origin, and every one of those is public. */
|
|
17
|
+
export function markerOrigin(marker) {
|
|
18
|
+
return marker?.origin === 'private' ? 'private' : 'public';
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** A private marker's own category is never shown: it may have come with a cloned repository. */
|
|
22
|
+
export function markerLabel(marker) {
|
|
23
|
+
return markerOrigin(marker) === 'private' ? `private/${marker.slug}` : `${marker.category}/${marker.slug}`;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
function publicSource(catalog) {
|
|
27
|
+
const installName = (skill) =>
|
|
28
|
+
catalog.skills.filter((other) => other.slug === skill.slug).length > 1 ? skillKey(skill) : skill.slug;
|
|
29
|
+
return {
|
|
30
|
+
origin: 'public',
|
|
31
|
+
skills: catalog.skills,
|
|
32
|
+
resolve: (name) => resolveSkill(name, catalog.skills),
|
|
33
|
+
find: (marker) => catalog.skills.find((skill) => skill.category === marker.category && skill.slug === marker.slug),
|
|
34
|
+
files: (skill) => fetchSkillFiles(skill.category, skill.slug),
|
|
35
|
+
validate: validateBundle,
|
|
36
|
+
installOptions: () => ({ origin: 'public', source: getCatalogUrl() }),
|
|
37
|
+
summarize: (skill) => ({
|
|
38
|
+
skill: skill.slug,
|
|
39
|
+
category: skill.category,
|
|
40
|
+
name: skill.displayName,
|
|
41
|
+
description: skill.description,
|
|
42
|
+
version: skill.version ?? null,
|
|
43
|
+
install: `insightfulpipe skills install ${installName(skill)}`,
|
|
44
|
+
page: pageUrl(skill),
|
|
45
|
+
}),
|
|
46
|
+
};
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function privateSourceFor(workspaceId, skills) {
|
|
50
|
+
const installName = (skill) => (skills.filter((other) => other.slug === skill.slug).length > 1 ? skill.key : skill.slug);
|
|
51
|
+
return {
|
|
52
|
+
origin: 'private',
|
|
53
|
+
workspaceId,
|
|
54
|
+
skills,
|
|
55
|
+
resolve: (name) => resolvePrivateSkill(name, skills),
|
|
56
|
+
find: (marker) => skills.find((skill) => skill.key === marker.key),
|
|
57
|
+
files: (skill) => fetchPrivateSkillFiles(workspaceId, skill.key),
|
|
58
|
+
validate: validatePrivateBundle,
|
|
59
|
+
installOptions: (skill) => ({ origin: 'private', source: privateSourceUrl(), key: skill.key, workspaceId }),
|
|
60
|
+
summarize: (skill) => ({
|
|
61
|
+
skill: skill.slug,
|
|
62
|
+
key: skill.key,
|
|
63
|
+
category: skill.category,
|
|
64
|
+
name: skill.name,
|
|
65
|
+
description: skill.description ?? '',
|
|
66
|
+
data_source: skill.data_source || null,
|
|
67
|
+
version: skill.version ?? null,
|
|
68
|
+
install: `insightfulpipe skills install ${installName(skill)} --private --workspace ${workspaceId}`,
|
|
69
|
+
page: null,
|
|
70
|
+
}),
|
|
71
|
+
};
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
async function openPrivate(workspaceId) {
|
|
75
|
+
return privateSourceFor(workspaceId, await fetchPrivateCatalog(workspaceId));
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/** The source a command was asked for: `--private` (with `--workspace` or the saved scope), else public. */
|
|
79
|
+
export async function openSource(opts) {
|
|
80
|
+
return opts.private ? openPrivate(privateWorkspaceId(opts)) : publicSource(await fetchCatalog());
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
function markerWorkspace(marker) {
|
|
84
|
+
const id = marker.workspace_id;
|
|
85
|
+
return Number.isInteger(id) && id > 0 ? id : null;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function openForMarker(marker) {
|
|
89
|
+
if (markerOrigin(marker) === 'public') return openSource({});
|
|
90
|
+
const workspaceId = markerWorkspace(marker);
|
|
91
|
+
return workspaceId
|
|
92
|
+
? openPrivate(workspaceId)
|
|
93
|
+
: Promise.reject(new Error('Its marker names no workspace. Install it again with --private.'));
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Opens each installed skill's own source once per command; a source that failed fails each of its skills. */
|
|
97
|
+
export function sourcesForMarkers() {
|
|
98
|
+
const opened = new Map();
|
|
99
|
+
return (marker) => {
|
|
100
|
+
const id = markerOrigin(marker) === 'private' ? `private:${markerWorkspace(marker) ?? 'none'}` : 'public';
|
|
101
|
+
if (!opened.has(id)) {
|
|
102
|
+
const pending = openForMarker(marker);
|
|
103
|
+
pending.catch(() => {});
|
|
104
|
+
opened.set(id, pending);
|
|
105
|
+
}
|
|
106
|
+
return opened.get(id);
|
|
107
|
+
};
|
|
108
|
+
}
|