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.
@@ -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,10 @@
1
1
  import { createHash, randomBytes } from 'node:crypto';
2
- import { lstatSync, mkdirSync, readFileSync, realpathSync, 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';
7
+ import { realPath } from './paths.js';
6
8
 
7
9
  /** The private skills this user installed, and where. It lives next to the config, never in a skills
8
10
  * folder, so a cloned repository cannot add to it: a private marker is trusted only when this record
@@ -24,7 +26,7 @@ function entryFile(path) {
24
26
  * macOS and Windows), or null when it does not exist. */
25
27
  export function realFolderPath(dir) {
26
28
  try {
27
- return realpathSync.native(dir);
29
+ return realPath(dir);
28
30
  } catch {
29
31
  return null;
30
32
  }
@@ -50,6 +52,16 @@ export function isRecordedInstall(dir, marker) {
50
52
  return Boolean(entry) && entry.key === marker.key && entry.workspace_id === marker.workspace_id && entry.slug === marker.slug;
51
53
  }
52
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
+
53
65
  /** Written to a private temporary file and renamed into place, readable by this user only. */
54
66
  export function recordInstall(dir, { key, workspaceId, slug }) {
55
67
  const path = realFolderPath(dir);
@@ -59,10 +71,9 @@ export function recordInstall(dir, { key, workspaceId, slug }) {
59
71
  const entry = { schema: 'insightfulpipe.private-install.v1', path, key, workspace_id: workspaceId, slug };
60
72
  try {
61
73
  writeFileSync(temp, `${JSON.stringify(entry, null, 2)}\n`, { mode: 0o600, flag: 'wx' });
62
- renameSync(temp, entryFile(path));
74
+ moveFile(temp, entryFile(path), 'the install record');
63
75
  } catch (error) {
64
- rmSync(temp, { force: true });
65
- throw error;
76
+ throw withLeftover(error, temp);
66
77
  }
67
78
  }
68
79
 
@@ -1,26 +1,41 @@
1
1
  import { fetchCatalog, fetchSkillFiles, getCatalogUrl, pageUrl, resolveSkill, skillKey } from './catalog.js';
2
2
  import { validateBundle } from './installer.js';
3
+ import { categoryFor, keyType } from './keys.js';
4
+ import { installNameFor, resolveWorkspaceSkill } from './names.js';
3
5
  import {
4
- fetchPrivateCatalog,
5
- fetchPrivateSkillFiles,
6
- privateSourceUrl,
7
- privateWorkspaceId,
8
- resolvePrivateSkill,
9
- validatePrivateBundle,
6
+ fetchWorkspaceCatalog,
7
+ fetchWorkspaceSkillFiles,
8
+ validateWorkspaceBundle,
9
+ workspaceIdFor,
10
+ workspaceSourceUrl,
10
11
  } from './private.js';
11
12
 
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. */
13
+ /** Where skills come from: insightfulpipe.com with no key, or a workspace (its Public and Custom skills)
14
+ * from the app API with the user's key. A command uses exactly one source and never falls back to the
15
+ * other; an installed skill goes back to the source its marker names. */
15
16
 
16
17
  /** Markers written before 0.4.0 have no origin, and every one of those is public. */
17
18
  export function markerOrigin(marker) {
18
19
  return marker?.origin === 'private' ? 'private' : 'public';
19
20
  }
20
21
 
21
- /** A private marker's own category is never shown: it may have come with a cloned repository. */
22
+ /** A workspace marker's own category is never shown: it may have come with a cloned repository. The prefix
23
+ * comes from the key's form alone, a fixed word; nothing else the marker claims is shown. */
22
24
  export function markerLabel(marker) {
23
- return markerOrigin(marker) === 'private' ? `private/${marker.slug}` : `${marker.category}/${marker.slug}`;
25
+ return markerOrigin(marker) === 'private'
26
+ ? `${categoryFor(keyType(marker.key))}/${marker.slug}`
27
+ : `${marker.category}/${marker.slug}`;
28
+ }
29
+
30
+ /** `public` or `custom` for a workspace marker with a valid key, else null. */
31
+ export function markerType(marker) {
32
+ return markerOrigin(marker) === 'private' ? keyType(marker.key) : null;
33
+ }
34
+
35
+ /** What `list` calls a skill's origin: a Public workspace skill is never called private. */
36
+ export function listedOrigin(marker) {
37
+ if (markerOrigin(marker) === 'public') return 'public';
38
+ return markerType(marker) === 'public' ? 'workspace' : 'private';
24
39
  }
25
40
 
26
41
  function publicSource(catalog) {
@@ -28,6 +43,7 @@ function publicSource(catalog) {
28
43
  catalog.skills.filter((other) => other.slug === skill.slug).length > 1 ? skillKey(skill) : skill.slug;
29
44
  return {
30
45
  origin: 'public',
46
+ noFiles: 'The public source has no files for this skill.',
31
47
  skills: catalog.skills,
32
48
  resolve: (name) => resolveSkill(name, catalog.skills),
33
49
  find: (marker) => catalog.skills.find((skill) => skill.category === marker.category && skill.slug === marker.slug),
@@ -46,38 +62,50 @@ function publicSource(catalog) {
46
62
  };
47
63
  }
48
64
 
49
- function privateSourceFor(workspaceId, skills) {
50
- const installName = (skill) => (skills.filter((other) => other.slug === skill.slug).length > 1 ? skill.key : skill.slug);
65
+ /** `sourceName` is what the JSON calls the source: `private` when the user typed `--private`, as in 0.4. */
66
+ function workspaceSourceFor(workspaceId, skills, sourceName) {
67
+ const installName = (skill) => installNameFor(skill, skills);
51
68
  return {
52
69
  origin: 'private',
70
+ sourceName,
53
71
  workspaceId,
72
+ noFiles: `Workspace ${workspaceId} has no files for this skill.`,
54
73
  skills,
55
- resolve: (name) => resolvePrivateSkill(name, skills),
74
+ resolve: (name) => resolveWorkspaceSkill(name, skills, workspaceId),
56
75
  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
- }),
76
+ files: (skill) => fetchWorkspaceSkillFiles(workspaceId, skill.key),
77
+ validate: validateWorkspaceBundle,
78
+ installName,
79
+ installOptions: (skill) => ({ origin: 'private', source: workspaceSourceUrl(), key: skill.key, workspaceId }),
80
+ summarize: (skill) => summarizeWorkspaceSkill(skill, installName(skill), workspaceId),
81
+ };
82
+ }
83
+
84
+ function summarizeWorkspaceSkill(skill, name, workspaceId) {
85
+ return {
86
+ skill: skill.slug,
87
+ key: skill.key,
88
+ type: skill.type,
89
+ category: skill.category,
90
+ name: skill.name,
91
+ description: skill.description ?? '',
92
+ data_source: skill.data_source || null,
93
+ version: skill.version ?? null,
94
+ install: `insightfulpipe skills install ${name} --workspace ${workspaceId}`,
95
+ page: null,
71
96
  };
72
97
  }
73
98
 
74
- async function openPrivate(workspaceId) {
75
- return privateSourceFor(workspaceId, await fetchPrivateCatalog(workspaceId));
99
+ async function openWorkspace(workspaceId, sourceName = 'workspace') {
100
+ return workspaceSourceFor(workspaceId, await fetchWorkspaceCatalog(workspaceId), sourceName);
76
101
  }
77
102
 
78
- /** The source a command was asked for: `--private` (with `--workspace` or the saved scope), else public. */
103
+ /** The source a command was asked for: `--workspace`, or `--private` with it or the saved scope, else
104
+ * insightfulpipe.com. The saved scope alone never switches the source. */
79
105
  export async function openSource(opts) {
80
- return opts.private ? openPrivate(privateWorkspaceId(opts)) : publicSource(await fetchCatalog());
106
+ return opts.private || opts.workspace !== undefined
107
+ ? openWorkspace(workspaceIdFor(opts), opts.private ? 'private' : 'workspace')
108
+ : publicSource(await fetchCatalog());
81
109
  }
82
110
 
83
111
  function markerWorkspace(marker) {
@@ -89,8 +117,8 @@ function openForMarker(marker) {
89
117
  if (markerOrigin(marker) === 'public') return openSource({});
90
118
  const workspaceId = markerWorkspace(marker);
91
119
  return workspaceId
92
- ? openPrivate(workspaceId)
93
- : Promise.reject(new Error('Its marker names no workspace. Install it again with --private.'));
120
+ ? openWorkspace(workspaceId)
121
+ : Promise.reject(new Error('Its marker names no workspace. Install it again with --workspace <id>.'));
94
122
  }
95
123
 
96
124
  /** Opens each installed skill's own source once per command; a source that failed fails each of its skills. */