insightfulpipe 0.4.2 → 0.5.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.
@@ -44,6 +44,8 @@ export function buildProgram() {
44
44
  ' insightfulpipe skills search [words] Browse InsightfulPipe skills\n' +
45
45
  ' insightfulpipe skills install <name> Install one for Claude Code (or --agent openclaw|codex|cursor|gemini-cli)\n' +
46
46
  ' insightfulpipe skills list Installed skills and available updates\n\n' +
47
+ 'Your workspace\'s skills, Public and Custom (after insightfulpipe auth):\n' +
48
+ ' insightfulpipe skills install <name> --workspace <id>\n\n' +
47
49
  'Authentication:\n' +
48
50
  ' insightfulpipe auth Save your API token (starts with ip_sk_)\n' +
49
51
  ' Or set INSIGHTFULPIPE_TOKEN env var.'
package/src/output.js CHANGED
@@ -8,6 +8,11 @@ export function jsonText(data, space = 2) {
8
8
  return JSON.stringify(data, null, space).replace(RAW_IN_JSON, escapeChar);
9
9
  }
10
10
 
11
+ /** A message set inside a longer sentence, without its own full stop. */
12
+ export function clause(message) {
13
+ return String(message).replace(/\.$/, '');
14
+ }
15
+
11
16
  export function printJson(data) {
12
17
  console.log(jsonText(data));
13
18
  }
@@ -21,7 +26,7 @@ export function wantsJson(command) {
21
26
  }
22
27
 
23
28
  // C0/C1 controls, DEL and the bidi overrides: a terminal acts on them instead of showing them.
24
- const UNPRINTABLE = /[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g;
29
+ export const UNPRINTABLE = /[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g;
25
30
 
26
31
  /** Text as the terminal will show it: control characters become visible \uXXXX escapes, so data from a
27
32
  * connected platform can never move the cursor, clear the screen or write to the clipboard. `lines`
@@ -0,0 +1,129 @@
1
+ import { isAbsolute, resolve } from 'node:path';
2
+
3
+ import { isWorkspaceKey, keyType } from './keys.js';
4
+ import { markerLabel, markerOrigin } from './sources.js';
5
+
6
+ /** How a typed name reaches one installed skill folder in `update` and `remove`. Entries are `listInstalled` rows
7
+ * plus `ours` (the install record names the folder). A word that names a key never acts on a folder holding
8
+ * another key, a folder's absolute path reaches it alone, and every name the CLI prints reaches its folder alone. */
9
+
10
+ /** Said in place of a command whose path would not paste back into a shell as the same path. */
11
+ export const UNPRINTED = 'no command is printed, since a shell could misread the path';
12
+
13
+ /** A command no quotes can wrap, since it holds both kinds. A message prints it last on its line, after a colon, so no
14
+ * comma or full stop is pasted as part of its last word. */
15
+ export function printsBare(command) {
16
+ return command.includes('"') && command.includes("'");
17
+ }
18
+
19
+ /** A command as a message quotes it: in the quote kind it does not hold, double first, or bare when it holds both,
20
+ * so the outer quotes never mix with the quotes around its path. */
21
+ export function quotedCommand(command) {
22
+ if (!command.includes('"')) return `"${command}"`;
23
+ return printsBare(command) ? command : `'${command}'`;
24
+ }
25
+
26
+ function normalized(name) {
27
+ return String(name).toLowerCase().replace(/^@insightfulpipe\//, '');
28
+ }
29
+
30
+ /** The key a word names, as in `install`: a bare key, or `private/` or `public/` before a key of that type. */
31
+ function keyNamed(wanted) {
32
+ const labelled = wanted.match(/^(private|public)\/(.+)$/);
33
+ if (!labelled) return isWorkspaceKey(wanted) ? wanted : null;
34
+ return keyType(labelled[2]) === (labelled[1] === 'public' ? 'public' : 'custom') ? labelled[2] : null;
35
+ }
36
+
37
+ /** A path spelled one way without touching the disk, so no link is followed: in NFC, as macOS finds a name in either
38
+ * form, and without case on Windows. A `.` or `..` part, which a link would make mean another folder, spells none. */
39
+ function pathKey(path) {
40
+ const parts = String(path).split(process.platform === 'win32' ? /[\\/]/ : '/');
41
+ if (parts.some((part) => part === '.' || part === '..')) return null;
42
+ const plain = resolve(String(path)).normalize('NFC');
43
+ return process.platform === 'win32' ? plain.toLowerCase() : plain;
44
+ }
45
+
46
+ /** Every folder a word points at: by folder name or `list` label, by key when the word names one, or by its
47
+ * absolute path. */
48
+ export function installedMatches(installed, name) {
49
+ if (isAbsolute(String(name))) {
50
+ const wanted = pathKey(name);
51
+ return wanted === null ? [] : installed.filter((entry) => pathKey(entry.dir) === wanted);
52
+ }
53
+ const wanted = normalized(name);
54
+ const key = keyNamed(wanted);
55
+ return installed.filter(
56
+ ({ marker }) =>
57
+ marker.slug === wanted ||
58
+ markerLabel(marker) === wanted ||
59
+ (key !== null && markerOrigin(marker) === 'private' && marker.key === key),
60
+ );
61
+ }
62
+
63
+ /** The one folder a word reaches, or undefined. A word that names a key reaches only a folder holding it, and
64
+ * `update` (`forUpdate`) never reaches a folder not installed by you here by its path. */
65
+ export function resolveInstalled(installed, name, { forUpdate = false } = {}) {
66
+ const matches = installedMatches(installed, name);
67
+ if (matches.length !== 1) return undefined;
68
+ if (isAbsolute(String(name))) return matches[0].ours || !forUpdate ? matches[0] : undefined;
69
+ const key = keyNamed(normalized(name));
70
+ return key === null || matches[0].marker.key === key ? matches[0] : undefined;
71
+ }
72
+
73
+ /** The two folders a key reaches when they may be a renamed old copy and its reinstalled new copy: both recorded
74
+ * installs of that key from one workspace. Null for any other match. */
75
+ export function keyPair(installed, name) {
76
+ const key = keyNamed(normalized(name));
77
+ const matches = installedMatches(installed, name);
78
+ if (key === null || matches.length !== 2) return null;
79
+ const held = matches.every((one) => one.ours && one.marker.key === key && markerOrigin(one.marker) === 'private');
80
+ return held && matches[0].marker.workspace_id === matches[1].marker.workspace_id ? matches : null;
81
+ }
82
+
83
+ /** The first of the `list` label, the folder name, the key and the folder's path that reaches only this folder, else
84
+ * null. The key is offered only when the install record names the folder: any other may come from a cloned repo. */
85
+ export function nameForInstalled(entry, installed, how = {}) {
86
+ const key = entry.ours && markerOrigin(entry.marker) === 'private' ? [entry.marker.key] : [];
87
+ const forms = [markerLabel(entry.marker), entry.slug, ...key, entry.dir];
88
+ return forms.find((form) => resolveInstalled(installed, form, how) === entry) ?? null;
89
+ }
90
+
91
+ /** What a folder holds, shown next to it: its key when the install record names the folder. */
92
+ export function installedNote(entry) {
93
+ if (markerOrigin(entry.marker) === 'public') return '';
94
+ return entry.ours ? entry.marker.key : 'not installed by you here';
95
+ }
96
+
97
+ /** A folder as `list` names it, with its key, so a folder named after another key is not mistaken for it. Given a
98
+ * `workspace`, your own copy from another one also names its workspace; no other marker's claim is shown. */
99
+ export function installedLabel(entry, { workspace } = {}) {
100
+ const note = installedNote(entry);
101
+ const elsewhere = entry.ours && note && workspace !== undefined && entry.marker.workspace_id !== workspace;
102
+ const full = elsewhere ? `${note}, workspace ${entry.marker.workspace_id}` : note;
103
+ return full ? `${markerLabel(entry.marker)} (${full})` : markerLabel(entry.marker);
104
+ }
105
+
106
+ /** Why a word reaches no single folder, naming each folder it points at by a name that reaches only it, or by the
107
+ * command `how.run` prints for its path, a bare one each ending a line. Only `update` meets a folder with neither. */
108
+ export function refuseInstalled(installed, name, matches, how) {
109
+ if (isAbsolute(String(name))) return `"${name}" was not installed by you here, so update never changes it.`;
110
+ const why =
111
+ matches.length > 1
112
+ ? `"${name}" matches more than one installed skill.`
113
+ : `"${name}" names the key ${keyNamed(normalized(name))}, which the folder ${matches[0].slug} does not hold.`;
114
+ const named = [];
115
+ const byPath = [];
116
+ const bare = [];
117
+ for (const entry of matches) {
118
+ const form = nameForInstalled(entry, installed, how);
119
+ const note = form !== null && form === entry.marker.key ? `folder ${entry.slug}` : installedNote(entry);
120
+ const shown = note ? ` (${note})` : '';
121
+ if (form === null) byPath.push(`No name reaches the folder ${entry.dir}${shown}; update never changes it.`);
122
+ else if (form === entry.dir && how.run(form) === null) byPath.push(`For the folder ${entry.dir}${shown}, run ${how.unprinted(form, entry)} (${UNPRINTED}).`);
123
+ else if (form === entry.dir && printsBare(how.run(form))) bare.push(`For the folder ${entry.slug}${shown}, run: ${how.run(form)}`);
124
+ else if (form === entry.dir) byPath.push(`For the folder ${entry.slug}${shown}, run ${quotedCommand(how.run(form))}.`);
125
+ else named.push(`${form}${shown}`);
126
+ }
127
+ const text = [why, named.length ? `Use one of: ${named.join(', ')}.` : '', ...byPath].filter(Boolean).join(' ');
128
+ return bare.length ? `${text} ${bare.join('\n')}` : text;
129
+ }
@@ -9,12 +9,13 @@ import {
9
9
  readdirSync,
10
10
  readFileSync,
11
11
  readSync,
12
- renameSync,
13
- rmSync,
14
12
  writeFileSync,
15
13
  } from 'node:fs';
16
- import { dirname, isAbsolute, join, resolve } from 'node:path';
14
+ import { basename, dirname, isAbsolute, join, resolve } from 'node:path';
17
15
 
16
+ import { keyType, TYPE_LABEL } from './keys.js';
17
+ import { clause } from '../output.js';
18
+ import { lexists, moveFolder, moveSkillFolder, removeLeftover } from './moves.js';
18
19
  import { isRecordedInstall } from './records.js';
19
20
 
20
21
  /** Installs skills into an agent's skills folder and keeps a small marker in each one, so the CLI can
@@ -77,7 +78,7 @@ function isSafeSegment(part) {
77
78
  * inner spaces are allowed. */
78
79
  export function isSafeRelativePath(path) {
79
80
  if (typeof path !== 'string' || !path || path.length > 200) return false;
80
- if (isAbsolute(path) || path.includes('\\')) return false;
81
+ if (isAbsolute(path)) return false;
81
82
  return path.split('/').every(isSafeSegment);
82
83
  }
83
84
 
@@ -171,26 +172,12 @@ export function readMarker(skillDir) {
171
172
  }
172
173
  }
173
174
 
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
175
  /** Puts the previous copy back after a failed swap; if even that fails, says where it was kept. */
189
176
  function restorePrevious(old, dest, cause) {
190
177
  try {
191
- renameSync(old, dest);
178
+ moveFolder(old, dest);
192
179
  } catch {
193
- throw new Error(`${cause.message}. Your previous copy is kept at ${old}`);
180
+ throw new Error(`${clause(cause.message)}. Your previous copy is kept at ${old}`);
194
181
  }
195
182
  }
196
183
 
@@ -206,9 +193,12 @@ function writeFiles(root, files, marker) {
206
193
  // A marker read from disk may have been planted, so its text is shown only when it is a plain name or version.
207
194
  const markerVersion = (marker) => (PLAIN_VERSION.test(String(marker.version)) ? marker.version : 'unreadable');
208
195
 
196
+ /** A workspace skill here is either recorded as the user's or about to be installed, so its key is plain. */
209
197
  function describeInstalled({ origin, key, workspace_id: workspaceId, category, slug }) {
210
- if (origin === 'private') return `the private skill ${key} of workspace ${workspaceId}`;
211
- return isSafeName(category) && isSafeName(slug) ? `the public skill ${category}/${slug}` : 'a public skill with an unreadable name';
198
+ if (origin === 'private') return `the ${TYPE_LABEL[keyType(key)] ?? 'workspace'} skill ${key} of workspace ${workspaceId}`;
199
+ return isSafeName(category) && isSafeName(slug)
200
+ ? `the insightfulpipe.com skill ${category}/${slug}`
201
+ : 'an insightfulpipe.com skill with an unreadable name';
212
202
  }
213
203
 
214
204
  /** Whether a marker belongs to the skill about to be installed, so replacing it is an update, not a swap. */
@@ -220,7 +210,9 @@ function sameSkill(marker, incoming) {
220
210
  : marker.category === incoming.category;
221
211
  }
222
212
 
223
- function refuseExisting(dest, skill, incoming) {
213
+ /** `updateHint` is the caller's sentence on updating this folder instead of reinstalling it, which names --force too,
214
+ * or null when it has none. */
215
+ function refuseExisting(dest, skill, incoming, updateHint) {
224
216
  const marker = readMarker(dest);
225
217
  if (!marker) {
226
218
  return `${dest} already exists and was not installed by InsightfulPipe. Add --force to replace it.`;
@@ -231,13 +223,19 @@ function refuseExisting(dest, skill, incoming) {
231
223
  if (!sameSkill(marker, incoming)) {
232
224
  return `${dest} holds ${describeInstalled(marker)} (version ${markerVersion(marker)}). Installing ${describeInstalled(incoming)} would replace it: add --force to do that, or use --dir to install into another folder.`;
233
225
  }
234
- return `${skill.slug} is already installed at ${dest} (version ${markerVersion(marker)}). Run "insightfulpipe skills update ${skill.slug}", or add --force to reinstall.`;
226
+ const next = updateHint ?? 'Add --force to reinstall.';
227
+ return `${skill.slug} is already installed at ${dest} (version ${markerVersion(marker)}). ${next}`;
235
228
  }
236
229
 
237
230
  /** Writes the skill into `<skillsDir>/<slug>`. The files land in a temporary folder first and are
238
231
  * swapped in with a rename, so a failure never leaves a half-written skill behind. The marker records
239
232
  * the origin (public, or private with its key and workspace) that list and update go back to. */
240
- export function installSkill(skillsDir, skill, validated, { force = false, source, origin = 'public', key, workspaceId } = {}) {
233
+ export function installSkill(
234
+ skillsDir,
235
+ skill,
236
+ validated,
237
+ { force = false, source, origin = 'public', key, workspaceId, updateHint = null } = {},
238
+ ) {
241
239
  const dest = join(skillsDir, String(skill.slug));
242
240
  if (!isSafeName(skill.slug) || !isSafeName(skill.category) || dirname(resolve(dest)) !== resolve(skillsDir)) {
243
241
  throw new Error(`Refusing to install ${JSON.stringify(skill.slug)}: it is not a plain skill name.`);
@@ -250,7 +248,7 @@ export function installSkill(skillsDir, skill, validated, { force = false, sourc
250
248
  };
251
249
  const replacing = lexists(dest);
252
250
  if (replacing && !force) {
253
- throw new Error(refuseExisting(dest, skill, identity));
251
+ throw new Error(refuseExisting(dest, skill, identity, updateHint));
254
252
  }
255
253
 
256
254
  mkdirSync(skillsDir, { recursive: true });
@@ -268,15 +266,16 @@ export function installSkill(skillsDir, skill, validated, { force = false, sourc
268
266
 
269
267
  try {
270
268
  writeFiles(staging, validated.files, marker);
271
- if (replacing) renameSync(dest, old);
269
+ if (replacing) moveSkillFolder(dest, old, skill.slug);
272
270
  try {
273
- renameSync(staging, dest);
271
+ moveSkillFolder(staging, dest, skill.slug);
274
272
  } catch (error) {
275
273
  if (replacing) restorePrevious(old, dest, error);
274
+ if (!replacing && lexists(dest)) throw new Error(`${skill.slug} appeared at ${dest} while installing; run the command again`);
276
275
  throw error;
277
276
  }
278
277
  } catch (error) {
279
- throw new Error(`Could not install ${skill.slug}: ${error.message}.${removeLeftover(staging)}`);
278
+ throw new Error(`Could not install ${skill.slug}: ${clause(error.message)}.${removeLeftover(staging)}`);
280
279
  }
281
280
 
282
281
  const warning = replacing ? removeLeftover(old).trim() : '';
@@ -370,10 +369,13 @@ export function localChanges(skillDir, marker) {
370
369
  return { changed, missing, added, edited: changed.length + missing.length + added.length > 0 };
371
370
  }
372
371
 
373
- /** Deletes a skill folder, but only one this CLI installed. */
372
+ /** Deletes a skill folder, but only one this CLI installed. It is moved aside first, so a failure either touches
373
+ * nothing or leaves only the moved copy, which the returned sentence names (empty when it is gone). */
374
374
  export function removeInstalled(skillDir) {
375
375
  if (!readMarker(skillDir)) {
376
376
  throw new Error(`${skillDir} was not installed by InsightfulPipe, so it was left alone.`);
377
377
  }
378
- rmSync(skillDir, { recursive: true, force: true });
378
+ const aside = join(dirname(skillDir), `.${basename(skillDir)}.removing-${randomBytes(4).toString('hex')}`);
379
+ moveSkillFolder(skillDir, aside, basename(skillDir));
380
+ return removeLeftover(aside).trim();
379
381
  }
@@ -0,0 +1,21 @@
1
+ /** Workspace skill keys as the app's raw skills endpoints send them. `custom-<id>` is a workspace's own
2
+ * skill and `public-<id>` comes with the app. The key alone decides the type. */
3
+
4
+ /** `\d` is ASCII only here, and `$` does not match before a trailing newline. */
5
+ const KEY_RE = /^(custom|public)-\d{1,10}$/;
6
+
7
+ export const TYPE_LABEL = { custom: 'Custom', public: 'Public' };
8
+
9
+ export function isWorkspaceKey(value) {
10
+ return typeof value === 'string' && KEY_RE.test(value);
11
+ }
12
+
13
+ /** `custom` or `public` for a valid key, else null. */
14
+ export function keyType(value) {
15
+ return isWorkspaceKey(value) ? value.slice(0, value.indexOf('-')) : null;
16
+ }
17
+
18
+ /** Custom skills keep 0.4's `private` category, so their markers and the app's files answer are unchanged. */
19
+ export function categoryFor(type) {
20
+ return type === 'public' ? 'public' : 'private';
21
+ }
@@ -0,0 +1,87 @@
1
+ import { lstatSync, renameSync, rmSync } from 'node:fs';
2
+
3
+ import { clause } from '../output.js';
4
+
5
+ /** Moving skill folders and just-written files, and deleting leftovers. On Windows, antivirus and indexers hold a
6
+ * new or opened file for a moment, so a refused move is tried again briefly there; macOS and Linux never block one. */
7
+
8
+ // The waits between tries on Windows, about 2 s in all.
9
+ const WAITS_MS = [25, 50, 100, 200, 400, 600, 625];
10
+ // The codes Windows gives a rename that a file held open blocks; EACCES too, though it is not named as such.
11
+ const RETRIED = new Set(['EBUSY', 'EPERM', 'EACCES']);
12
+ const PAUSE = new Int32Array(new SharedArrayBuffer(4));
13
+
14
+ const onWindows = () => process.platform === 'win32';
15
+
16
+ export function lexists(path) {
17
+ return Boolean(lstatSync(path, { throwIfNoEntry: false }));
18
+ }
19
+
20
+ /** What no wait can move a rename past: Windows never moves a folder onto anything that exists, nor a file onto a
21
+ * folder. */
22
+ function inTheWay(to, folder) {
23
+ const stat = lstatSync(to, { throwIfNoEntry: false });
24
+ return Boolean(stat) && (folder || stat.isDirectory());
25
+ }
26
+
27
+ /** renameSync, tried again on Windows after each wait while the move is refused as if a file were held open, until
28
+ * something is in the way. */
29
+ function retriedRename(from, to, folder) {
30
+ for (const wait of onWindows() ? WAITS_MS : []) {
31
+ try {
32
+ return renameSync(from, to);
33
+ } catch (error) {
34
+ if (!RETRIED.has(error?.code) || inTheWay(to, folder)) throw error;
35
+ Atomics.wait(PAUSE, 0, 0, wait);
36
+ }
37
+ }
38
+ return renameSync(from, to);
39
+ }
40
+
41
+ export function moveFolder(from, to) {
42
+ return retriedRename(from, to, true);
43
+ }
44
+
45
+ /** On Windows a move refused with EBUSY or EPERM most likely meets a file another program holds open. Elsewhere,
46
+ * for any other code, or with something in the way (another run's folder), the rename's own error is kept. */
47
+ function movedError(error, name, held, to, folder) {
48
+ if (!onWindows() || (error?.code !== 'EBUSY' && error?.code !== 'EPERM') || inTheWay(to, folder)) return error;
49
+ return new Error(`${name} could not be moved (${error.code}), most likely because a program has ${held} open. Close that program and try again.`);
50
+ }
51
+
52
+ /** moveFolder for the skill folder `name`, failing with the sentence movedError gives. */
53
+ export function moveSkillFolder(from, to, name) {
54
+ try {
55
+ moveFolder(from, to);
56
+ } catch (error) {
57
+ throw movedError(error, name, 'a file in it', to, true);
58
+ }
59
+ }
60
+
61
+ /** A just-written file moved into place, perhaps over an older one, tried again on Windows like a folder; a refusal
62
+ * that outlasts the tries names the file as the user knows it, `name`. */
63
+ export function moveFile(from, to, name) {
64
+ try {
65
+ retriedRename(from, to, false);
66
+ } catch (error) {
67
+ throw movedError(error, name, 'it', to, false);
68
+ }
69
+ }
70
+
71
+ /** Empty when the leftover folder or file is gone, otherwise a sentence telling the user where it is. On Windows
72
+ * rmSync's own retries ride out a file held open. */
73
+ export function removeLeftover(path) {
74
+ try {
75
+ rmSync(path, { recursive: true, force: true, ...(onWindows() ? { maxRetries: 5, retryDelay: 100 } : {}) });
76
+ return '';
77
+ } catch (error) {
78
+ return ` ${path} could not be removed (${error.message}); delete it by hand.`;
79
+ }
80
+ }
81
+
82
+ /** The error a failed move left, after deleting the temporary file `path`; if that delete fails too, the message also
83
+ * says where the file is, so the delete never hides why the move failed. */
84
+ export function withLeftover(error, path) {
85
+ const leftover = removeLeftover(path);
86
+ return leftover ? new Error(`${clause(error.message)}.${leftover}`) : error;
87
+ }
@@ -0,0 +1,40 @@
1
+ import { categoryFor, isWorkspaceKey, keyType, TYPE_LABEL } from './keys.js';
2
+
3
+ /** How a typed name reaches one workspace skill. A Custom skill's name may equal another skill's name or key,
4
+ * so a name that matches more than one skill is refused, never guessed, and every printed command uses a
5
+ * form that reaches exactly its own skill. */
6
+
7
+ /** Every listed skill an input points at. A bare input is a name or a key. `private/` or `public/` keeps that
8
+ * type, and before a key of that type it means the key alone, so `<label>/<own key>` reaches exactly its skill. */
9
+ function matchesFor(wanted, skills) {
10
+ const labelled = wanted.match(/^(private|public)\/(.+)$/);
11
+ if (!labelled) return skills.filter((skill) => skill.slug === wanted || skill.key === wanted);
12
+ const [, label, name] = labelled;
13
+ const type = label === 'public' ? 'public' : 'custom';
14
+ const byKey = keyType(name) === type;
15
+ return skills.filter((skill) => skill.type === type && (byKey ? skill.key === name : skill.slug === name));
16
+ }
17
+
18
+ /** The first of name, key and `<label>/<name>` that reaches only this skill, else `<label>/<key>`, which always
19
+ * does. A name shaped like another key is skipped: update and remove read such a word as that key. */
20
+ export function installNameFor(skill, skills) {
21
+ const label = categoryFor(skill.type);
22
+ const reachesOnly = (form) => {
23
+ const matches = matchesFor(form, skills);
24
+ return matches.length === 1 && matches[0] === skill;
25
+ };
26
+ const name = isWorkspaceKey(skill.slug) && skill.slug !== skill.key ? [] : [skill.slug];
27
+ return [...name, skill.key, `${label}/${skill.slug}`].find(reachesOnly) ?? `${label}/${skill.key}`;
28
+ }
29
+
30
+ /** Exactly one listed skill, or a sentence that gives each match its working name; that name reaches one
31
+ * skill, so it is never the input just refused. */
32
+ export function resolveWorkspaceSkill(name, skills, workspaceId) {
33
+ const matches = matchesFor(String(name).trim().toLowerCase(), skills);
34
+ if (matches.length === 1) return { skill: matches[0] };
35
+ if (!matches.length) {
36
+ return { error: `No skill named "${name}" in workspace ${workspaceId}. Run: insightfulpipe skills search --workspace ${workspaceId}` };
37
+ }
38
+ const forms = matches.map((skill) => `${installNameFor(skill, skills)} (${TYPE_LABEL[skill.type]})`);
39
+ return { error: `"${name}" matches more than one skill in workspace ${workspaceId}. Use one of: ${forms.join(', ')}.` };
40
+ }
@@ -2,21 +2,19 @@ import { apiGet } from '../api.js';
2
2
  import { errorMessage } from '../cli/errors.js';
3
3
  import { getApiUrl, getContext, getToken, tokenProblem } from '../config.js';
4
4
  import { isSafeName, validateBundle } from './installer.js';
5
+ import { categoryFor, isWorkspaceKey, keyType } from './keys.js';
5
6
 
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. */
7
+ /** Workspace skills: a workspace's Custom skills and the app's Public skills, served by the app API with the
8
+ * user's API key. This is the only skills module that may use the key. insightfulpipe.com skills come from
9
+ * catalog.js without it, and the two never fall back to each other. */
9
10
 
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.";
11
+ // A workspace skill is fixed where it was written: the CLI can refuse it but not repair it.
12
+ const FIX_BY_TYPE = {
13
+ custom: "Fix the skill in the app's Skills Library (for example, rename the file), then try again.",
14
+ public: 'Public skills cannot be edited in the app; please report this to InsightfulPipe support.',
15
+ };
14
16
 
15
- export function isPrivateKey(value) {
16
- return typeof value === 'string' && KEY_RE.test(value);
17
- }
18
-
19
- function workspaceIdFrom(value, where) {
17
+ export function parseWorkspaceId(value, where) {
20
18
  const id = Number(value);
21
19
  if (!Number.isInteger(id) || id < 1) {
22
20
  throw new Error(`${where} must be a positive integer workspace id, not ${JSON.stringify(value)}.`);
@@ -25,17 +23,17 @@ function workspaceIdFrom(value, where) {
25
23
  }
26
24
 
27
25
  /** `--workspace` wins, then the saved scope from `insightfulpipe use`. */
28
- export function privateWorkspaceId(opts) {
29
- if (opts.workspace !== undefined) return workspaceIdFrom(opts.workspace, '--workspace');
26
+ export function workspaceIdFor(opts) {
27
+ if (opts.workspace !== undefined) return parseWorkspaceId(opts.workspace, '--workspace');
30
28
  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>".');
29
+ if (saved != null) return parseWorkspaceId(saved, 'The saved workspace');
30
+ throw new Error('Workspace skills belong to a workspace. Add --workspace <id>, or save one with "insightfulpipe use -w <id>".');
33
31
  }
34
32
 
35
33
  /** Refuses before any request when there is no key to send, so a missing key is a sentence, not an exit. */
36
34
  function requireKey() {
37
35
  const token = getToken();
38
- if (!token) throw new Error('Private skills need your API key. Run: insightfulpipe auth');
36
+ if (!token) throw new Error('Workspace skills need your API key. Run: insightfulpipe auth');
39
37
  const problem = tokenProblem(token);
40
38
  if (problem) throw new Error(problem);
41
39
  }
@@ -48,53 +46,42 @@ function failure(data, what) {
48
46
  return error;
49
47
  }
50
48
 
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) {
49
+ /** The workspace's skills, without file contents. The slug becomes a folder name and the key part of a
50
+ * command, so an entry whose slug or key is not plain is dropped. Type and category come from the key
51
+ * alone, over anything the entry says. */
52
+ export async function fetchWorkspaceCatalog(workspaceId) {
54
53
  requireKey();
55
54
  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 }));
55
+ if (data?.error) throw failure(data, `list the skills of workspace ${workspaceId}`);
56
+ if (!Array.isArray(data?.skills)) throw new Error('The app did not return a list of workspace skills.');
57
+ const listed = data.skills.filter((skill) => isWorkspaceKey(skill?.key) && isSafeName(skill.slug));
58
+ return listed
59
+ .filter((skill) => listed.filter((other) => other.key === skill.key).length === 1)
60
+ .map((skill) => ({ ...skill, type: keyType(skill.key), category: categoryFor(keyType(skill.key)) }));
61
61
  }
62
62
 
63
- /** One private skill's exact files, or null when the workspace no longer has it. */
64
- export async function fetchPrivateSkillFiles(workspaceId, key) {
63
+ /** One workspace skill's exact files, or null when the workspace no longer has it. */
64
+ export async function fetchWorkspaceSkillFiles(workspaceId, key) {
65
65
  requireKey();
66
66
  const data = await apiGet(`/skills/files/?workspace_id=${encodeURIComponent(workspaceId)}&key=${encodeURIComponent(key)}`);
67
67
  if (data?.error && data.status === 404) return null;
68
- if (data?.error) throw failure(data, `download the private skill ${key}`);
68
+ if (data?.error) throw failure(data, `download the skill ${key}`);
69
69
  return data;
70
70
  }
71
71
 
72
72
  /** The installer's checks, plus that the files are the skill that was asked for. */
73
- export function validatePrivateBundle(bundle, skill) {
73
+ export function validateWorkspaceBundle(bundle, skill) {
74
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}.`);
75
+ throw new Error(`Refusing to install ${skill.category}/${skill.slug}: the app sent the files of ${bundle?.key ?? 'another skill'}, not ${skill.key}.`);
76
76
  }
77
77
  try {
78
78
  return validateBundle(bundle, skill);
79
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(', ')}.` };
80
+ throw new Error(`${error.message} ${FIX_BY_TYPE[skill.type]}`);
93
81
  }
94
- return { error: `No private skill named "${name}" in this workspace. Run: insightfulpipe skills search --private` };
95
82
  }
96
83
 
97
- /** Recorded in the marker as where a private skill came from. */
98
- export function privateSourceUrl() {
84
+ /** Recorded in the marker as where a workspace skill came from. */
85
+ export function workspaceSourceUrl() {
99
86
  return getApiUrl();
100
87
  }
@@ -1,8 +1,9 @@
1
1
  import { createHash, randomBytes } from 'node:crypto';
2
- import { lstatSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { lstatSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
3
3
  import { join } from 'node:path';
4
4
 
5
5
  import { getConfigDir } from '../config.js';
6
+ import { lexists, moveFile, withLeftover } from './moves.js';
6
7
  import { realPath } from './paths.js';
7
8
 
8
9
  /** The private skills this user installed, and where. It lives next to the config, never in a skills
@@ -51,6 +52,16 @@ export function isRecordedInstall(dir, marker) {
51
52
  return Boolean(entry) && entry.key === marker.key && entry.workspace_id === marker.workspace_id && entry.slug === marker.slug;
52
53
  }
53
54
 
55
+ /** Whether an entry for this real folder path is there; false when there is none or the record folder cannot be
56
+ * read. */
57
+ export function recordExists(path) {
58
+ try {
59
+ return Boolean(path) && lexists(entryFile(path));
60
+ } catch {
61
+ return false;
62
+ }
63
+ }
64
+
54
65
  /** Written to a private temporary file and renamed into place, readable by this user only. */
55
66
  export function recordInstall(dir, { key, workspaceId, slug }) {
56
67
  const path = realFolderPath(dir);
@@ -60,10 +71,9 @@ export function recordInstall(dir, { key, workspaceId, slug }) {
60
71
  const entry = { schema: 'insightfulpipe.private-install.v1', path, key, workspace_id: workspaceId, slug };
61
72
  try {
62
73
  writeFileSync(temp, `${JSON.stringify(entry, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
63
- renameSync(temp, entryFile(path));
74
+ moveFile(temp, entryFile(path), 'the install record');
64
75
  } catch (error) {
65
- rmSync(temp, { force: true });
66
- throw error;
76
+ throw withLeftover(error, temp);
67
77
  }
68
78
  }
69
79