insightfulpipe 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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
+ }
@@ -0,0 +1,108 @@
1
+ import { fetchCatalog, fetchSkillFiles, getCatalogUrl, pageUrl, resolveSkill, skillKey } from './catalog.js';
2
+ import { validateBundle } from './installer.js';
3
+ import {
4
+ fetchPrivateCatalog,
5
+ fetchPrivateSkillFiles,
6
+ privateSourceUrl,
7
+ privateWorkspaceId,
8
+ resolvePrivateSkill,
9
+ validatePrivateBundle,
10
+ } from './private.js';
11
+
12
+ /** Where skills come from: the public library on the website, with no key, or a workspace's private
13
+ * skills from the app API, with the user's key. A command uses exactly one source and never falls back
14
+ * to the other; an installed skill goes back to the source its marker names. */
15
+
16
+ /** Markers written before 0.4.0 have no origin, and every one of those is public. */
17
+ export function markerOrigin(marker) {
18
+ return marker?.origin === 'private' ? 'private' : 'public';
19
+ }
20
+
21
+ /** A private marker's own category is never shown: it may have come with a cloned repository. */
22
+ export function markerLabel(marker) {
23
+ return markerOrigin(marker) === 'private' ? `private/${marker.slug}` : `${marker.category}/${marker.slug}`;
24
+ }
25
+
26
+ function publicSource(catalog) {
27
+ const installName = (skill) =>
28
+ catalog.skills.filter((other) => other.slug === skill.slug).length > 1 ? skillKey(skill) : skill.slug;
29
+ return {
30
+ origin: 'public',
31
+ skills: catalog.skills,
32
+ resolve: (name) => resolveSkill(name, catalog.skills),
33
+ find: (marker) => catalog.skills.find((skill) => skill.category === marker.category && skill.slug === marker.slug),
34
+ files: (skill) => fetchSkillFiles(skill.category, skill.slug),
35
+ validate: validateBundle,
36
+ installOptions: () => ({ origin: 'public', source: getCatalogUrl() }),
37
+ summarize: (skill) => ({
38
+ skill: skill.slug,
39
+ category: skill.category,
40
+ name: skill.displayName,
41
+ description: skill.description,
42
+ version: skill.version ?? null,
43
+ install: `insightfulpipe skills install ${installName(skill)}`,
44
+ page: pageUrl(skill),
45
+ }),
46
+ };
47
+ }
48
+
49
+ function privateSourceFor(workspaceId, skills) {
50
+ const installName = (skill) => (skills.filter((other) => other.slug === skill.slug).length > 1 ? skill.key : skill.slug);
51
+ return {
52
+ origin: 'private',
53
+ workspaceId,
54
+ skills,
55
+ resolve: (name) => resolvePrivateSkill(name, skills),
56
+ find: (marker) => skills.find((skill) => skill.key === marker.key),
57
+ files: (skill) => fetchPrivateSkillFiles(workspaceId, skill.key),
58
+ validate: validatePrivateBundle,
59
+ installOptions: (skill) => ({ origin: 'private', source: privateSourceUrl(), key: skill.key, workspaceId }),
60
+ summarize: (skill) => ({
61
+ skill: skill.slug,
62
+ key: skill.key,
63
+ category: skill.category,
64
+ name: skill.name,
65
+ description: skill.description ?? '',
66
+ data_source: skill.data_source || null,
67
+ version: skill.version ?? null,
68
+ install: `insightfulpipe skills install ${installName(skill)} --private --workspace ${workspaceId}`,
69
+ page: null,
70
+ }),
71
+ };
72
+ }
73
+
74
+ async function openPrivate(workspaceId) {
75
+ return privateSourceFor(workspaceId, await fetchPrivateCatalog(workspaceId));
76
+ }
77
+
78
+ /** The source a command was asked for: `--private` (with `--workspace` or the saved scope), else public. */
79
+ export async function openSource(opts) {
80
+ return opts.private ? openPrivate(privateWorkspaceId(opts)) : publicSource(await fetchCatalog());
81
+ }
82
+
83
+ function markerWorkspace(marker) {
84
+ const id = marker.workspace_id;
85
+ return Number.isInteger(id) && id > 0 ? id : null;
86
+ }
87
+
88
+ function openForMarker(marker) {
89
+ if (markerOrigin(marker) === 'public') return openSource({});
90
+ const workspaceId = markerWorkspace(marker);
91
+ return workspaceId
92
+ ? openPrivate(workspaceId)
93
+ : Promise.reject(new Error('Its marker names no workspace. Install it again with --private.'));
94
+ }
95
+
96
+ /** Opens each installed skill's own source once per command; a source that failed fails each of its skills. */
97
+ export function sourcesForMarkers() {
98
+ const opened = new Map();
99
+ return (marker) => {
100
+ const id = markerOrigin(marker) === 'private' ? `private:${markerWorkspace(marker) ?? 'none'}` : 'public';
101
+ if (!opened.has(id)) {
102
+ const pending = openForMarker(marker);
103
+ pending.catch(() => {});
104
+ opened.set(id, pending);
105
+ }
106
+ return opened.get(id);
107
+ };
108
+ }