insightfulpipe 0.4.1 → 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.
package/src/cli/errors.js CHANGED
@@ -1,4 +1,4 @@
1
- import { printable } from '../output.js';
1
+ import { jsonText, printable } from '../output.js';
2
2
 
3
3
  /** Anything meant for reading is cut here; the marker says how much the server actually sent. */
4
4
  const MAX_TEXT_CHARS = 2000;
@@ -31,7 +31,7 @@ export function fail(message, tip, details = {}) {
31
31
  const text = (value) => printable(value, { lines: true });
32
32
  writeStderr(tip ? `Error: ${text(message)}\nTip: ${text(tip)}` : `Error: ${text(message)}`);
33
33
  } else {
34
- writeStderr(JSON.stringify({ status: 'error', message, ...(tip ? { tip } : {}), ...details }, null, 2));
34
+ writeStderr(jsonText({ status: 'error', message, ...(tip ? { tip } : {}), ...details }));
35
35
  }
36
36
  process.exit(1);
37
37
  }
@@ -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
@@ -1,5 +1,20 @@
1
+ const escapeChar = (ch) => `\\u${ch.charCodeAt(0).toString(16).padStart(4, '0')}`;
2
+
3
+ // What JSON.stringify leaves raw but a terminal acts on: DEL, the C1 controls and the bidi overrides.
4
+ const RAW_IN_JSON = /[\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g;
5
+
6
+ /** JSON text with those characters escaped: still valid JSON that parses to the same values. */
7
+ export function jsonText(data, space = 2) {
8
+ return JSON.stringify(data, null, space).replace(RAW_IN_JSON, escapeChar);
9
+ }
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
+
1
16
  export function printJson(data) {
2
- console.log(JSON.stringify(data, null, 2));
17
+ console.log(jsonText(data));
3
18
  }
4
19
 
5
20
  /** JSON is the CLI's default output: it is read by scripts and agents far more than by eyes.
@@ -11,14 +26,15 @@ export function wantsJson(command) {
11
26
  }
12
27
 
13
28
  // C0/C1 controls, DEL and the bidi overrides: a terminal acts on them instead of showing them.
14
- const UNPRINTABLE = /[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g;
29
+ export const UNPRINTABLE = /[\u0000-\u001f\u007f-\u009f\u202a-\u202e\u2066-\u2069]/g;
15
30
 
16
31
  /** Text as the terminal will show it: control characters become visible \uXXXX escapes, so data from a
17
32
  * connected platform can never move the cursor, clear the screen or write to the clipboard. `lines`
18
- * keeps line breaks, for multi-line text such as pretty-printed JSON or an error sentence. */
33
+ * keeps line breaks and tabs, for multi-line text such as pretty-printed JSON or an error sentence. */
19
34
  export function printable(value, { lines = false } = {}) {
20
- return String(value ?? '').replace(UNPRINTABLE, (ch) =>
21
- (lines && ch === '\n' ? ch : `\\u${ch.charCodeAt(0).toString(16).padStart(4, '0')}`));
35
+ const text = String(value ?? '');
36
+ return (lines ? text.replace(/\r\n/g, '\n') : text).replace(UNPRINTABLE, (ch) =>
37
+ (lines && (ch === '\n' || ch === '\t') ? ch : escapeChar(ch)));
22
38
  }
23
39
 
24
40
  /** JSON shown under `--table` when a result has no table form. The escapes keep it valid JSON with the
@@ -60,11 +76,23 @@ const ENVELOPE_FIELDS = new Set(['status', 'data', 'meta', 'next_step', 'request
60
76
  // Where platforms put paging: on meta itself, or in one of these objects inside it.
61
77
  const PAGING_PLACES = ['paging', 'pagination', 'page_info'];
62
78
  // Every way a platform marks a list as cut short; they differ (Meta's has_next, X's next_cursor, …).
63
- const MORE_MARKERS = [
64
- 'next', 'has_next', 'has_next_page', 'has_more', 'row_limit_applied', 'page_limit_applied',
65
- 'next_cursor', 'next_page_token', 'nextPageToken', 'next_pagination_token', 'next_token', 'cursor',
79
+ // A yes/no answer outranks a token beside it, since TikTok keeps its cursor on the last page; a limit
80
+ // that cut the rows always means more.
81
+ const MORE_ANSWERS = ['has_more', 'has_next', 'has_next_page'];
82
+ const MORE_TOKENS = [
83
+ 'next', 'next_cursor', 'next_page_token', 'nextPageToken', 'next_pagination_token', 'next_token', 'cursor',
84
+ 'next_page_info', 'bookmark', 'after',
85
+ ];
86
+ const CUT_MARKERS = ['row_limit_applied', 'page_limit_applied', 'row_limit_exceeded'];
87
+ const MORE_MARKERS = [...MORE_ANSWERS, ...MORE_TOKENS, ...CUT_MARKERS];
88
+ const TOTAL_FIELDS = ['total_available', 'total_documents', 'total_count', 'total', 'rowCount'];
89
+ // What a paging object carries besides markers and totals. One holding anything else is named under the
90
+ // table, never read as complete.
91
+ const PAGING_DETAILS = [
92
+ 'previous', 'has_previous', 'before', 'cursors', 'row_limit', 'page_limit', 'pages_fetched', 'total_fetched',
93
+ 'auto_paginate', 'last_page', 'size', 'rows_fetched', 'stopped_by', 'total_rows_fetched', 'rows_deduplicated',
94
+ 'max_rows_per_page',
66
95
  ];
67
- const TOTAL_FIELDS = ['total_available', 'total_documents', 'total_count', 'total'];
68
96
  const PROBLEM_FIELDS = ['partial_errors', 'errors', 'failed_count', 'missing_metrics'];
69
97
  const NOTE_FIELDS = ['warnings', 'notes'];
70
98
  // meta fields that only describe the request or the reply. Anything else is named under the table,
@@ -100,26 +128,44 @@ function resultRows(result, listField) {
100
128
  .map(([field, value]) => ({ field, value }));
101
129
  }
102
130
 
103
- /** What meta says the table cannot show. A "more" marker wins over any count; a total proves a list
104
- * complete only without one. Every meta field left over that is not descriptive is named. */
131
+ /** Whether one place in meta says the list goes on. */
132
+ function saysMore(place) {
133
+ if (CUT_MARKERS.some((key) => place[key])) return true;
134
+ const answers = MORE_ANSWERS.filter((key) => typeof place[key] === 'boolean');
135
+ if (answers.length) return answers.some((key) => place[key]);
136
+ return [...MORE_ANSWERS, ...MORE_TOKENS].some((key) => place[key]);
137
+ }
138
+
139
+ const PAGING_KEYS = new Set([...MORE_MARKERS, ...TOTAL_FIELDS, ...PAGING_DETAILS]);
140
+
141
+ /** A paging object the table has fully read: every field known, and either a total counts the rows or a
142
+ * yes/no answer says the list ends. A row limit that was reached is not always flagged, so nothing less. */
143
+ function readToTheEnd(place, counted) {
144
+ if (!Object.keys(place).every((key) => PAGING_KEYS.has(key))) return false;
145
+ return counted || MORE_ANSWERS.some((key) => typeof place[key] === 'boolean');
146
+ }
147
+
148
+ /** What meta says the table cannot show. A "more" marker wins over any count; paging that is not read to
149
+ * the end is named. Every meta field left over that is not descriptive is named too. */
105
150
  function metaFooters(meta, shown) {
106
151
  if (meta === undefined || meta === null) return [];
107
152
  if (!isRecord(meta)) return hasContent(meta) ? ['More in meta (drop --table to read it).'] : [];
108
153
  const places = [meta, ...PAGING_PLACES.map((key) => meta[key]).filter(isRecord)];
109
154
  const total = places.flatMap((place) => TOTAL_FIELDS.map((key) => place[key])).find(Number.isInteger);
110
- const more = places.some((place) => MORE_MARKERS.some((marker) => place[marker]));
155
+ const more = places.some(saysMore);
111
156
  const footers = [];
112
- const told = new Set();
113
- const pagingTold = () => [...PAGING_PLACES, ...MORE_MARKERS, ...TOTAL_FIELDS].forEach((key) => told.add(key));
157
+ const told = new Set(MORE_MARKERS);
114
158
  if (more) {
115
159
  const of = shown !== null && total > shown ? ` of ${total}` : '';
116
160
  footers.push(shown === null
117
161
  ? 'The server has more (drop --table for its paging details).'
118
162
  : `Showing ${shown}${of} rows; the server has more (drop --table for its paging details).`);
119
- pagingTold();
120
- } else if (shown !== null && total !== undefined) {
121
- if (total > shown) footers.push(`Showing ${shown} of ${total} rows.`);
122
- pagingTold();
163
+ [...PAGING_PLACES, ...TOTAL_FIELDS].forEach((key) => told.add(key));
164
+ } else {
165
+ const counted = shown !== null && total !== undefined;
166
+ if (counted && total > shown) footers.push(`Showing ${shown} of ${total} rows.`);
167
+ if (counted) TOTAL_FIELDS.forEach((key) => told.add(key));
168
+ PAGING_PLACES.filter((key) => isRecord(meta[key]) && readToTheEnd(meta[key], counted)).forEach((key) => told.add(key));
123
169
  }
124
170
  const problems = PROBLEM_FIELDS.filter((key) => hasContent(meta[key]));
125
171
  if (problems.length) footers.push(`Some items failed or were left out: see meta ${problems.join(', ')} (drop --table to read it).`);
@@ -135,9 +181,9 @@ function metaFooters(meta, shown) {
135
181
  function resultFooters(result, listField, fromWholeResult) {
136
182
  const footers = [];
137
183
  if (result.partial_failure === true) {
138
- footers.push(`Partial failure: ${printable(result.message || 'some items were refused')}`);
184
+ footers.push(`Partial failure: ${printable(result.message || 'some items were refused', { lines: true })}`);
139
185
  } else if (!fromWholeResult && typeof result.message === 'string' && result.message) {
140
- footers.push(`Message: ${printable(result.message)}`);
186
+ footers.push(`Message: ${printable(result.message, { lines: true })}`);
141
187
  }
142
188
  if (!fromWholeResult) {
143
189
  const others = Object.keys(result).filter((field) => field !== listField && !ENVELOPE_FIELDS.has(field));
@@ -1,7 +1,9 @@
1
- import { existsSync, lstatSync, realpathSync } from 'node:fs';
1
+ import { existsSync, lstatSync } from 'node:fs';
2
2
  import { homedir } from 'node:os';
3
3
  import { basename, dirname, join, resolve, sep } from 'node:path';
4
4
 
5
+ import { realPath } from './paths.js';
6
+
5
7
  /** Where each agent looks for skills. Global folders hold skills for every project; project folders
6
8
  * sit inside the current directory. Paths follow each agent's own conventions, including their
7
9
  * home-directory environment overrides. */
@@ -61,7 +63,7 @@ function realFolder(path) {
61
63
  existing = dirname(existing);
62
64
  }
63
65
  try {
64
- return join(realpathSync.native(existing), ...missing);
66
+ return join(realPath(existing), ...missing);
65
67
  } catch (error) {
66
68
  throw new Error(`Could not resolve the skills folder ${path}: ${error.message}`);
67
69
  }
@@ -81,7 +83,7 @@ export function resolveSkillsDir({ agent = DEFAULT_AGENT, project = false, dir }
81
83
  }
82
84
 
83
85
  if (project) {
84
- const root = realpathSync.native(process.cwd());
86
+ const root = realPath(process.cwd());
85
87
  const projectDir = realFolder(resolve(root, config.project));
86
88
  if (!projectDir.startsWith(root.endsWith(sep) ? root : root + sep)) {
87
89
  throw new Error(
@@ -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
 
@@ -203,8 +190,15 @@ function writeFiles(root, files, marker) {
203
190
  writeFileSync(join(root, MARKER_FILE), `${JSON.stringify(marker, null, 2)}\n`);
204
191
  }
205
192
 
193
+ // A marker read from disk may have been planted, so its text is shown only when it is a plain name or version.
194
+ const markerVersion = (marker) => (PLAIN_VERSION.test(String(marker.version)) ? marker.version : 'unreadable');
195
+
196
+ /** A workspace skill here is either recorded as the user's or about to be installed, so its key is plain. */
206
197
  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}`;
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';
208
202
  }
209
203
 
210
204
  /** Whether a marker belongs to the skill about to be installed, so replacing it is an update, not a swap. */
@@ -216,7 +210,9 @@ function sameSkill(marker, incoming) {
216
210
  : marker.category === incoming.category;
217
211
  }
218
212
 
219
- 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) {
220
216
  const marker = readMarker(dest);
221
217
  if (!marker) {
222
218
  return `${dest} already exists and was not installed by InsightfulPipe. Add --force to replace it.`;
@@ -225,15 +221,21 @@ function refuseExisting(dest, skill, incoming) {
225
221
  return `${dest} already exists and was not installed by you here. Add --force to replace it.`;
226
222
  }
227
223
  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.`;
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.`;
229
225
  }
230
- return `${skill.slug} is already installed at ${dest} (version ${marker.version}). 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}`;
231
228
  }
232
229
 
233
230
  /** Writes the skill into `<skillsDir>/<slug>`. The files land in a temporary folder first and are
234
231
  * swapped in with a rename, so a failure never leaves a half-written skill behind. The marker records
235
232
  * 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 } = {}) {
233
+ export function installSkill(
234
+ skillsDir,
235
+ skill,
236
+ validated,
237
+ { force = false, source, origin = 'public', key, workspaceId, updateHint = null } = {},
238
+ ) {
237
239
  const dest = join(skillsDir, String(skill.slug));
238
240
  if (!isSafeName(skill.slug) || !isSafeName(skill.category) || dirname(resolve(dest)) !== resolve(skillsDir)) {
239
241
  throw new Error(`Refusing to install ${JSON.stringify(skill.slug)}: it is not a plain skill name.`);
@@ -246,7 +248,7 @@ export function installSkill(skillsDir, skill, validated, { force = false, sourc
246
248
  };
247
249
  const replacing = lexists(dest);
248
250
  if (replacing && !force) {
249
- throw new Error(refuseExisting(dest, skill, identity));
251
+ throw new Error(refuseExisting(dest, skill, identity, updateHint));
250
252
  }
251
253
 
252
254
  mkdirSync(skillsDir, { recursive: true });
@@ -264,15 +266,16 @@ export function installSkill(skillsDir, skill, validated, { force = false, sourc
264
266
 
265
267
  try {
266
268
  writeFiles(staging, validated.files, marker);
267
- if (replacing) renameSync(dest, old);
269
+ if (replacing) moveSkillFolder(dest, old, skill.slug);
268
270
  try {
269
- renameSync(staging, dest);
271
+ moveSkillFolder(staging, dest, skill.slug);
270
272
  } catch (error) {
271
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`);
272
275
  throw error;
273
276
  }
274
277
  } catch (error) {
275
- 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)}`);
276
279
  }
277
280
 
278
281
  const warning = replacing ? removeLeftover(old).trim() : '';
@@ -338,6 +341,9 @@ function fileDigest(path) {
338
341
  }
339
342
  }
340
343
 
344
+ // Listed in place of a marker path that is not a plain relative path: it counts as an edit but is never shown.
345
+ const UNSAFE_RECORDED_PATH = '(a path in the marker that is not safe to show)';
346
+
341
347
  /** Files changed, deleted or added since install, compared with the digests in the marker. Only
342
348
  * entries found by `walk` are read, so a marker path with `..` or a linked folder is never followed;
343
349
  * a marker that records more than any install could counts as edited. */
@@ -352,7 +358,7 @@ export function localChanges(skillDir, marker) {
352
358
  for (const [path, digest] of Object.entries(recorded)) {
353
359
  const entry = onDisk.get(path);
354
360
  if (!isSafeRelativePath(path)) {
355
- changed.push(path);
361
+ changed.push(UNSAFE_RECORDED_PATH);
356
362
  } else if (!entry) {
357
363
  missing.push(path);
358
364
  } else if (!entry.file || fileDigest(join(skillDir, ...path.split('/'))) !== digest) {
@@ -363,10 +369,13 @@ export function localChanges(skillDir, marker) {
363
369
  return { changed, missing, added, edited: changed.length + missing.length + added.length > 0 };
364
370
  }
365
371
 
366
- /** 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). */
367
374
  export function removeInstalled(skillDir) {
368
375
  if (!readMarker(skillDir)) {
369
376
  throw new Error(`${skillDir} was not installed by InsightfulPipe, so it was left alone.`);
370
377
  }
371
- 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();
372
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
+ }
@@ -0,0 +1,12 @@
1
+ import { realpathSync } from 'node:fs';
2
+
3
+ /** The path as the disk spells it. The native call fails on some Windows virtual drives where the
4
+ * JavaScript one still answers, so a failure other than a missing path falls back to it. */
5
+ export function realPath(path) {
6
+ try {
7
+ return realpathSync.native(path);
8
+ } catch (error) {
9
+ if (error?.code === 'ENOENT') throw error;
10
+ return realpathSync(path);
11
+ }
12
+ }