insightfulpipe 0.3.0 → 0.4.1

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,3 +1,5 @@
1
+ import { printable } from '../output.js';
2
+
1
3
  /** Anything meant for reading is cut here; the marker says how much the server actually sent. */
2
4
  const MAX_TEXT_CHARS = 2000;
3
5
  const TRUNCATION_MARKER = /\.\.\. \[truncated, \d+ more characters\]$/;
@@ -26,7 +28,8 @@ function writeStderr(text) {
26
28
 
27
29
  export function fail(message, tip, details = {}) {
28
30
  if (humanOutput()) {
29
- writeStderr(tip ? `Error: ${message}\nTip: ${tip}` : `Error: ${message}`);
31
+ const text = (value) => printable(value, { lines: true });
32
+ writeStderr(tip ? `Error: ${text(message)}\nTip: ${text(tip)}` : `Error: ${text(message)}`);
30
33
  } else {
31
34
  writeStderr(JSON.stringify({ status: 'error', message, ...(tip ? { tip } : {}), ...details }, null, 2));
32
35
  }
@@ -14,7 +14,8 @@ export function buildProgram() {
14
14
  .name('insightfulpipe')
15
15
  .description(
16
16
  'InsightfulPipe CLI — query your marketing data from the terminal.\n\n' +
17
- 'Output is JSON by default; add --table for a human-readable view.\n\n' +
17
+ 'Output is JSON by default; add --table for a human-readable view\n' +
18
+ '(helper --actions request templates stay JSON, to copy into -b).\n\n' +
18
19
  'Run "insightfulpipe platforms" to see all supported platforms.\n\n' +
19
20
  'Set your scope once and stop passing ids:\n' +
20
21
  ' insightfulpipe use Adopt your only workspace\n' +
package/src/config.js CHANGED
@@ -18,7 +18,7 @@ const DEFAULT_CONFIG = {
18
18
  brand_id: null,
19
19
  };
20
20
 
21
- function getConfigDir() {
21
+ export function getConfigDir() {
22
22
  return join(homedir(), '.insightfulpipe');
23
23
  }
24
24
 
@@ -200,9 +200,22 @@ export function getConfigSnapshot() {
200
200
  return buildConfigSnapshot();
201
201
  }
202
202
 
203
+ // What an Authorization header can carry. Real keys are ip_sk_ plus hex; other bearer tokens can come in through the env var.
204
+ const TOKEN_RE = /^[\x21-\x7e]+$/;
205
+
206
+ /** The token without the whitespace a pasted or file-read value often carries at its ends: the same
207
+ * characters the app's header parser (Python's str.split) drops, so 0.3.0 sent such a token as if clean. */
208
+ export function cleanToken(value) {
209
+ return typeof value === 'string' ? value.replace(/^[\s\x85]+|[\s\x85]+$/g, '') || null : null;
210
+ }
211
+
212
+ /** Why a token cannot be sent, or null when it can. */
213
+ export function tokenProblem(token) {
214
+ return TOKEN_RE.test(token) ? null : 'The API token contains spaces, line breaks or other characters an API token never has.';
215
+ }
216
+
203
217
  export function getToken() {
204
- const config = loadConfig();
205
- return config.token;
218
+ return cleanToken(loadConfig().token);
206
219
  }
207
220
 
208
221
  export function getApiUrl() {
package/src/http.js CHANGED
@@ -6,7 +6,7 @@ export const PACKAGE_VERSION = JSON.parse(
6
6
  readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'package.json'), 'utf-8'),
7
7
  ).version;
8
8
 
9
- /** Sent on every request, so the app's logs and the catalogue can tell CLI calls from MCP ones. */
9
+ /** Sent on every request. The app's Activity log labels key-authenticated calls carrying it as CLI. */
10
10
  export const USER_AGENT = `insightfulpipe-cli/${PACKAGE_VERSION}`;
11
11
 
12
12
  /** The whole body as a Buffer. Past `maxBytes` it returns null (leaving the loop cancels the rest of
package/src/output.js CHANGED
@@ -10,28 +10,175 @@ export function wantsJson(command) {
10
10
  return !opts.table;
11
11
  }
12
12
 
13
+ // 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;
15
+
16
+ /** Text as the terminal will show it: control characters become visible \uXXXX escapes, so data from a
17
+ * 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. */
19
+ 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')}`));
22
+ }
23
+
24
+ /** JSON shown under `--table` when a result has no table form. The escapes keep it valid JSON with the
25
+ * same values; the default JSON output is never passed through here. */
26
+ export function printJsonForHumans(data) {
27
+ console.log(printable(JSON.stringify(data, null, 2), { lines: true }));
28
+ }
29
+
30
+ /** Lines of the human view that carry text from the server (names, descriptions, errors). */
31
+ export const say = (text) => console.log(printable(text, { lines: true }));
32
+ export const warn = (text) => console.error(printable(text, { lines: true }));
33
+
13
34
  export function printTable(rows, columns) {
14
35
  if (!rows || rows.length === 0) {
15
36
  console.log('No data.');
16
37
  return;
17
38
  }
18
39
 
19
- const widths = {};
20
- for (const col of columns) {
21
- widths[col.key] = col.label.length;
22
- for (const row of rows) {
23
- const val = String(row[col.key] ?? '');
24
- widths[col.key] = Math.max(widths[col.key], val.length);
25
- }
40
+ const labels = columns.map((c) => printable(c.label));
41
+ const lines = rows.map((row) => columns.map((c) => printable(row[c.key])));
42
+ const widths = labels.map((label) => label.length);
43
+ for (const line of lines) {
44
+ line.forEach((text, i) => {
45
+ widths[i] = Math.max(widths[i], text.length);
46
+ });
47
+ }
48
+
49
+ console.log(labels.map((label, i) => label.padEnd(widths[i])).join(' '));
50
+ console.log(widths.map((width) => '-'.repeat(width)).join(' '));
51
+ for (const line of lines) {
52
+ console.log(line.map((text, i) => text.padEnd(widths[i])).join(' '));
53
+ }
54
+ }
55
+
56
+ const CELL_MAX_CHARS = 60;
57
+ const MAX_COLUMNS = 40;
58
+ // Fields that frame a result rather than carry its data; anything else beside the rows is named.
59
+ const ENVELOPE_FIELDS = new Set(['status', 'data', 'meta', 'next_step', 'request', 'partial_failure', 'message']);
60
+ // Where platforms put paging: on meta itself, or in one of these objects inside it.
61
+ const PAGING_PLACES = ['paging', 'pagination', 'page_info'];
62
+ // 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',
66
+ ];
67
+ const TOTAL_FIELDS = ['total_available', 'total_documents', 'total_count', 'total'];
68
+ const PROBLEM_FIELDS = ['partial_errors', 'errors', 'failed_count', 'missing_metrics'];
69
+ const NOTE_FIELDS = ['warnings', 'notes'];
70
+ // meta fields that only describe the request or the reply. Anything else is named under the table,
71
+ // so a platform's new way of saying "there is more" can never pass as a complete result.
72
+ const DESCRIPTIVE_META = new Set([
73
+ 'resource', 'path', 'endpoint', 'http_method', 'method', 'label', 'category', 'slug', 'query', 'report',
74
+ 'request_id', 'request_config', 'task_id', 'task_cost', 'token_type', 'timeout', 'wait_for_load', 'includes',
75
+ 'is_read_only', 'is_write_operation', 'readback_action', 'auto_paginate', 'incremental_field',
76
+ 'supports_incremental', 'content_type', 'row_count', 'result_count', 'count', 'response_aggregation_type',
77
+ 'api_dimensions', 'dimension_mapping', 'calculated_dimensions',
78
+ ]);
79
+
80
+ const isRecord = (value) => value !== null && typeof value === 'object' && !Array.isArray(value);
81
+ const hasContent = (value) => (Array.isArray(value) ? value.length > 0 : isRecord(value) ? Object.keys(value).length > 0 : Boolean(value));
82
+
83
+ /** One cell of the human view: one line, nested values as compact JSON, long text cut. */
84
+ function cell(value) {
85
+ if (value === null || value === undefined) return { text: '', cut: false };
86
+ const text = (typeof value === 'object' ? JSON.stringify(value) : String(value)).replace(/\s+/g, ' ');
87
+ const chars = Array.from(text);
88
+ if (chars.length <= CELL_MAX_CHARS) return { text, cut: false };
89
+ return { text: `${chars.slice(0, CELL_MAX_CHARS - 1).join('')}…`, cut: true };
90
+ }
91
+
92
+ /** The rows a result carries: its list (`data`, or a helper's `actions`), else one record as
93
+ * field/value pairs (`data` when it is an object, the whole result otherwise). */
94
+ function resultRows(result, listField) {
95
+ const list = result[listField];
96
+ if (Array.isArray(list)) return list.map((item) => (isRecord(item) ? item : { value: item }));
97
+ const record = isRecord(result.data) ? result.data : result;
98
+ return Object.entries(record)
99
+ .filter(([field]) => record !== result || field !== 'next_step')
100
+ .map(([field, value]) => ({ field, value }));
101
+ }
102
+
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. */
105
+ function metaFooters(meta, shown) {
106
+ if (meta === undefined || meta === null) return [];
107
+ if (!isRecord(meta)) return hasContent(meta) ? ['More in meta (drop --table to read it).'] : [];
108
+ const places = [meta, ...PAGING_PLACES.map((key) => meta[key]).filter(isRecord)];
109
+ 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]));
111
+ const footers = [];
112
+ const told = new Set();
113
+ const pagingTold = () => [...PAGING_PLACES, ...MORE_MARKERS, ...TOTAL_FIELDS].forEach((key) => told.add(key));
114
+ if (more) {
115
+ const of = shown !== null && total > shown ? ` of ${total}` : '';
116
+ footers.push(shown === null
117
+ ? 'The server has more (drop --table for its paging details).'
118
+ : `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();
26
123
  }
124
+ const problems = PROBLEM_FIELDS.filter((key) => hasContent(meta[key]));
125
+ if (problems.length) footers.push(`Some items failed or were left out: see meta ${problems.join(', ')} (drop --table to read it).`);
126
+ if (NOTE_FIELDS.some((key) => hasContent(meta[key]))) footers.push('The server sent warnings or notes; drop --table to read them.');
127
+ [...PROBLEM_FIELDS, ...NOTE_FIELDS].forEach((key) => told.add(key));
128
+ const rest = Object.keys(meta).filter((key) => !told.has(key) && !DESCRIPTIVE_META.has(key) && hasContent(meta[key]));
129
+ if (rest.length) footers.push(`More in meta: ${rest.map((key) => printable(key)).join(', ')} (drop --table to read it).`);
130
+ return footers;
131
+ }
27
132
 
28
- const header = columns.map(c => c.label.padEnd(widths[c.key])).join(' ');
29
- const separator = columns.map(c => '-'.repeat(widths[c.key])).join(' ');
133
+ /** What the table leaves out of the result itself: a partial failure and its message, the server's
134
+ * message, and the names of any other fields beside the rows. */
135
+ function resultFooters(result, listField, fromWholeResult) {
136
+ const footers = [];
137
+ if (result.partial_failure === true) {
138
+ footers.push(`Partial failure: ${printable(result.message || 'some items were refused')}`);
139
+ } else if (!fromWholeResult && typeof result.message === 'string' && result.message) {
140
+ footers.push(`Message: ${printable(result.message)}`);
141
+ }
142
+ if (!fromWholeResult) {
143
+ const others = Object.keys(result).filter((field) => field !== listField && !ENVELOPE_FIELDS.has(field));
144
+ if (others.length) footers.push(`Also in the result: ${others.map((field) => printable(field)).join(', ')} (drop --table to read them).`);
145
+ }
146
+ return footers;
147
+ }
30
148
 
31
- console.log(header);
32
- console.log(separator);
33
- for (const row of rows) {
34
- const line = columns.map(c => String(row[c.key] ?? '').padEnd(widths[c.key])).join(' ');
35
- console.log(line);
149
+ /** Results of query, action, raw and helper: JSON by default, a table under `--table`. A result with
150
+ * no table form (not an object, or rows with too many different fields) stays JSON, with a note. */
151
+ export function printResult(result, command, listField = 'data') {
152
+ if (wantsJson(command)) {
153
+ printJson(result);
154
+ return;
155
+ }
156
+ if (!isRecord(result)) {
157
+ console.error('This result has no table view; showing JSON.');
158
+ printJsonForHumans(result);
159
+ return;
160
+ }
161
+ const rows = resultRows(result, listField);
162
+ const keys = [...new Set(rows.flatMap((row) => Object.keys(row)))];
163
+ if (keys.length > MAX_COLUMNS) {
164
+ console.error('These rows have too many different fields for a table; showing JSON.');
165
+ printJsonForHumans(result);
166
+ return;
36
167
  }
168
+ let cut = false;
169
+ const cells = rows.map((row) => Object.fromEntries(keys.map((key) => {
170
+ const one = cell(Object.hasOwn(row, key) ? row[key] : undefined);
171
+ cut ||= one.cut;
172
+ return [key, one.text];
173
+ })));
174
+ if (rows.length && !keys.length) console.log(`${rows.length} rows, all empty.`);
175
+ else printTable(cells, keys.map((key) => ({ key, label: key })));
176
+ const isList = Array.isArray(result[listField]);
177
+ const fromWholeResult = !isList && !isRecord(result.data);
178
+ const footers = [
179
+ ...metaFooters(result.meta, isList ? rows.length : null),
180
+ ...(cut ? ['Long values are shortened; drop --table for the full JSON.'] : []),
181
+ ...resultFooters(result, listField, fromWholeResult),
182
+ ];
183
+ if (footers.length) console.log(`\n${footers.join('\n')}`);
37
184
  }
@@ -50,8 +50,9 @@ export const DEFAULT_AGENT = 'claude-code';
50
50
 
51
51
  export const AGENT_NAMES = Object.keys(AGENTS);
52
52
 
53
- /** The folder's real path with every symlink followed: its own when it exists, otherwise its nearest
54
- * existing parent's with the missing names added back. */
53
+ /** The folder's real path with every symlink followed and spelled as the disk spells it (case included,
54
+ * on macOS and Windows): its own when it exists, otherwise its nearest existing parent's with the
55
+ * missing names added back. */
55
56
  function realFolder(path) {
56
57
  const missing = [];
57
58
  let existing = path;
@@ -60,7 +61,7 @@ function realFolder(path) {
60
61
  existing = dirname(existing);
61
62
  }
62
63
  try {
63
- return join(realpathSync(existing), ...missing);
64
+ return join(realpathSync.native(existing), ...missing);
64
65
  } catch (error) {
65
66
  throw new Error(`Could not resolve the skills folder ${path}: ${error.message}`);
66
67
  }
@@ -80,7 +81,7 @@ export function resolveSkillsDir({ agent = DEFAULT_AGENT, project = false, dir }
80
81
  }
81
82
 
82
83
  if (project) {
83
- const root = realpathSync(process.cwd());
84
+ const root = realpathSync.native(process.cwd());
84
85
  const projectDir = realFolder(resolve(root, config.project));
85
86
  if (!projectDir.startsWith(root.endsWith(sep) ? root : root + sep)) {
86
87
  throw new Error(
@@ -15,6 +15,8 @@ import {
15
15
  } from 'node:fs';
16
16
  import { dirname, isAbsolute, join, resolve } from 'node:path';
17
17
 
18
+ import { isRecordedInstall } from './records.js';
19
+
18
20
  /** Installs skills into an agent's skills folder and keeps a small marker in each one, so the CLI can
19
21
  * list, update and remove only what it installed, and tell when a user edited the files. */
20
22
 
@@ -56,8 +58,10 @@ export function parseFrontmatter(text) {
56
58
 
57
59
  const SAFE_NAME = /^[a-z0-9][a-z0-9-]{0,63}$/;
58
60
  // ASCII only: a disk folds case and look-alike letters (`ſ` is `S` on macOS) in ways no check can mirror.
59
- const SAFE_SEGMENT = /^[A-Za-z0-9_][A-Za-z0-9._-]*$/;
60
- const WINDOWS_DEVICE = /^(con|prn|aux|nul|com[0-9]|lpt[0-9])(\.|$)/i;
61
+ // 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;
61
65
 
62
66
  /** A skill slug or category: it becomes a folder name, so plain lowercase words and dashes only. */
63
67
  export function isSafeName(name) {
@@ -69,7 +73,8 @@ function isSafeSegment(part) {
69
73
  }
70
74
 
71
75
  /** A relative path of plain ASCII segments that mean the same file on macOS, Linux and Windows: no
72
- * `..`, no absolute paths, no hidden files, nothing Windows would rename or treat as a device. */
76
+ * `..`, no absolute paths, no hidden files, nothing Windows would rename or treat as a device. Single
77
+ * inner spaces are allowed. */
73
78
  export function isSafeRelativePath(path) {
74
79
  if (typeof path !== 'string' || !path || path.length > 200) return false;
75
80
  if (isAbsolute(path) || path.includes('\\')) return false;
@@ -198,21 +203,50 @@ function writeFiles(root, files, marker) {
198
203
  writeFileSync(join(root, MARKER_FILE), `${JSON.stringify(marker, null, 2)}\n`);
199
204
  }
200
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
+
201
233
  /** Writes the skill into `<skillsDir>/<slug>`. The files land in a temporary folder first and are
202
- * swapped in with a rename, so a failure never leaves a half-written skill behind. */
203
- export function installSkill(skillsDir, skill, validated, { force = false, source } = {}) {
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 } = {}) {
204
237
  const dest = join(skillsDir, String(skill.slug));
205
238
  if (!isSafeName(skill.slug) || !isSafeName(skill.category) || dirname(resolve(dest)) !== resolve(skillsDir)) {
206
239
  throw new Error(`Refusing to install ${JSON.stringify(skill.slug)}: it is not a plain skill name.`);
207
240
  }
241
+ const identity = {
242
+ origin,
243
+ ...(origin === 'private' ? { key, workspace_id: workspaceId } : {}),
244
+ category: skill.category,
245
+ slug: skill.slug,
246
+ };
208
247
  const replacing = lexists(dest);
209
248
  if (replacing && !force) {
210
- const marker = readMarker(dest);
211
- throw new Error(
212
- marker
213
- ? `${skill.slug} is already installed at ${dest} (version ${marker.version}). Run "insightfulpipe skills update ${skill.slug}", or add --force to reinstall.`
214
- : `${dest} already exists and was not installed by InsightfulPipe. Add --force to replace it.`,
215
- );
249
+ throw new Error(refuseExisting(dest, skill, identity));
216
250
  }
217
251
 
218
252
  mkdirSync(skillsDir, { recursive: true });
@@ -222,8 +256,7 @@ export function installSkill(skillsDir, skill, validated, { force = false, sourc
222
256
  const marker = {
223
257
  schema: 'insightfulpipe.installed-skill.v1',
224
258
  source,
225
- category: skill.category,
226
- slug: skill.slug,
259
+ ...identity,
227
260
  version: validated.version,
228
261
  installed_at: new Date().toISOString(),
229
262
  files: Object.fromEntries(validated.files.map((file) => [file.path, file.sha256])),
@@ -246,19 +279,27 @@ export function installSkill(skillsDir, skill, validated, { force = false, sourc
246
279
  return { path: dest, marker, ...(warning ? { warning } : {}) };
247
280
  }
248
281
 
282
+ const PLAIN_VERSION = /^[0-9a-f]{1,64}$/;
283
+
249
284
  /** Skills in a folder that this CLI installed: they carry the marker, in the folder named after it.
250
- * A copied or renamed folder keeps a marker for another name, and is the user's, not ours. */
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. */
251
288
  export function listInstalled(skillsDir) {
252
289
  if (!existsSync(skillsDir)) {
253
290
  return [];
254
291
  }
255
292
  return readdirSync(skillsDir, { withFileTypes: true })
256
- .filter((entry) => entry.isDirectory() && !entry.name.startsWith('.'))
293
+ .filter((entry) => entry.isDirectory() && isSafeName(entry.name))
257
294
  .map((entry) => {
258
295
  const dir = join(skillsDir, entry.name);
259
296
  return { slug: entry.name, dir, marker: readMarker(dir) };
260
297
  })
261
- .filter((item) => item.marker && item.marker.slug === item.slug)
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
+ }))
262
303
  .sort((a, b) => a.slug.localeCompare(b.slug));
263
304
  }
264
305
 
@@ -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
+ }