insightfulpipe 0.2.0 → 0.3.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.
@@ -1,16 +1,11 @@
1
- import { readFileSync } from 'fs';
2
- import { dirname, join } from 'path';
3
- import { fileURLToPath } from 'url';
4
-
5
1
  import { Command } from 'commander';
6
2
 
7
- const PACKAGE_VERSION = JSON.parse(
8
- readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', '..', 'package.json'), 'utf-8'),
9
- ).version;
3
+ import { PACKAGE_VERSION } from '../http.js';
10
4
  import { registerAuthCommand } from './commands/auth.js';
11
5
  import { registerConfigCommand } from './commands/config.js';
12
6
  import { registerContextCommand, registerDiscoveryCommands } from './commands/discovery.js';
13
7
  import { registerExecutionCommands } from './commands/execution.js';
8
+ import { registerSkillsCommand } from './commands/skills.js';
14
9
 
15
10
  export function buildProgram() {
16
11
  const program = new Command();
@@ -44,6 +39,10 @@ export function buildProgram() {
44
39
  ' insightfulpipe brands --workspace ID Brand metadata\n' +
45
40
  ' insightfulpipe whoami Current authenticated user\n' +
46
41
  ' insightfulpipe doctor Check auth and connectivity\n\n' +
42
+ 'Skills (no login needed):\n' +
43
+ ' insightfulpipe skills search [words] Browse InsightfulPipe skills\n' +
44
+ ' insightfulpipe skills install <name> Install one for Claude Code (or --agent openclaw|codex|cursor|gemini-cli)\n' +
45
+ ' insightfulpipe skills list Installed skills and available updates\n\n' +
47
46
  'Authentication:\n' +
48
47
  ' insightfulpipe auth Save your API token (starts with ip_sk_)\n' +
49
48
  ' Or set INSIGHTFULPIPE_TOKEN env var.'
@@ -58,6 +57,7 @@ export function buildProgram() {
58
57
  registerContextCommand(program);
59
58
  registerExecutionCommands(program);
60
59
  registerConfigCommand(program);
60
+ registerSkillsCommand(program);
61
61
 
62
62
  return program;
63
63
  }
@@ -79,7 +79,7 @@ export async function fetchConnectedSources(platform, prod = false) {
79
79
  payload.prod = true;
80
80
  }
81
81
 
82
- return handleApiError(await apiPost('/connected-sources/', payload));
82
+ return handleApiError(await apiPost('/connected-sources/', payload), { platform });
83
83
  }
84
84
 
85
85
  export async function fetchBrandMetadata(workspaceId, brandIds) {
@@ -100,7 +100,8 @@ export async function fetchHelperPayload(platform, actions) {
100
100
  platform,
101
101
  actions: actions && actions.length > 0 ? actions.join(',') : undefined,
102
102
  })}`
103
- )
103
+ ),
104
+ { platform },
104
105
  );
105
106
 
106
107
  // Rewrite next_step from MCP language to CLI commands
package/src/http.js ADDED
@@ -0,0 +1,39 @@
1
+ import { readFileSync } from 'node:fs';
2
+ import { dirname, join } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+
5
+ export const PACKAGE_VERSION = JSON.parse(
6
+ readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'package.json'), 'utf-8'),
7
+ ).version;
8
+
9
+ /** Sent on every request, so the app's logs and the catalogue can tell CLI calls from MCP ones. */
10
+ export const USER_AGENT = `insightfulpipe-cli/${PACKAGE_VERSION}`;
11
+
12
+ /** The whole body as a Buffer. Past `maxBytes` it returns null (leaving the loop cancels the rest of
13
+ * the download); with `idleMs`, `onIdle` fires when no chunk arrives for that long, so a stalled body
14
+ * ends without putting a cap on how long or how large a steady one may be. */
15
+ export async function readBody(res, { maxBytes = Infinity, idleMs = 0, onIdle } = {}) {
16
+ const chunks = [];
17
+ let total = 0;
18
+ let timer;
19
+ const arm = () => {
20
+ if (idleMs) {
21
+ clearTimeout(timer);
22
+ timer = setTimeout(onIdle, idleMs);
23
+ }
24
+ };
25
+ arm();
26
+ try {
27
+ for await (const chunk of res.body ?? []) {
28
+ total += chunk.length;
29
+ if (total > maxBytes) {
30
+ return null;
31
+ }
32
+ chunks.push(chunk);
33
+ arm();
34
+ }
35
+ } finally {
36
+ clearTimeout(timer);
37
+ }
38
+ return Buffer.concat(chunks);
39
+ }
@@ -0,0 +1,94 @@
1
+ import { existsSync, lstatSync, realpathSync } from 'node:fs';
2
+ import { homedir } from 'node:os';
3
+ import { basename, dirname, join, resolve, sep } from 'node:path';
4
+
5
+ /** Where each agent looks for skills. Global folders hold skills for every project; project folders
6
+ * sit inside the current directory. Paths follow each agent's own conventions, including their
7
+ * home-directory environment overrides. */
8
+
9
+ function openClawGlobalDir(home) {
10
+ // OpenClaw was previously named Clawdbot and then Moltbot; use whichever state folder exists.
11
+ for (const name of ['.openclaw', '.clawdbot', '.moltbot']) {
12
+ if (existsSync(join(home, name))) {
13
+ return join(home, name, 'skills');
14
+ }
15
+ }
16
+ return join(home, '.openclaw', 'skills');
17
+ }
18
+
19
+ const envDir = (name) => process.env[name]?.trim() || null;
20
+
21
+ export const AGENTS = {
22
+ 'claude-code': {
23
+ label: 'Claude Code',
24
+ global: () => join(envDir('CLAUDE_CONFIG_DIR') || join(homedir(), '.claude'), 'skills'),
25
+ project: join('.claude', 'skills'),
26
+ },
27
+ openclaw: {
28
+ label: 'OpenClaw',
29
+ global: () => envDir('OPENCLAW_SKILLS_DIR') || openClawGlobalDir(homedir()),
30
+ project: 'skills',
31
+ },
32
+ codex: {
33
+ label: 'Codex',
34
+ global: () => join(envDir('CODEX_HOME') || join(homedir(), '.codex'), 'skills'),
35
+ project: join('.agents', 'skills'),
36
+ },
37
+ cursor: {
38
+ label: 'Cursor',
39
+ global: () => join(homedir(), '.cursor', 'skills'),
40
+ project: join('.agents', 'skills'),
41
+ },
42
+ 'gemini-cli': {
43
+ label: 'Gemini CLI',
44
+ global: () => join(homedir(), '.gemini', 'skills'),
45
+ project: join('.agents', 'skills'),
46
+ },
47
+ };
48
+
49
+ export const DEFAULT_AGENT = 'claude-code';
50
+
51
+ export const AGENT_NAMES = Object.keys(AGENTS);
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. */
55
+ function realFolder(path) {
56
+ const missing = [];
57
+ let existing = path;
58
+ while (!lstatSync(existing, { throwIfNoEntry: false }) && dirname(existing) !== existing) {
59
+ missing.unshift(basename(existing));
60
+ existing = dirname(existing);
61
+ }
62
+ try {
63
+ return join(realpathSync(existing), ...missing);
64
+ } catch (error) {
65
+ throw new Error(`Could not resolve the skills folder ${path}: ${error.message}`);
66
+ }
67
+ }
68
+
69
+ /** The skills folder a command works on: `--dir` wins, then `--project` (current directory), then the
70
+ * agent's global folder. Always the real path; a project's folder must stay inside the project, since a
71
+ * cloned repo could plant a symlink that points it at any other folder. */
72
+ export function resolveSkillsDir({ agent = DEFAULT_AGENT, project = false, dir } = {}) {
73
+ if (dir) {
74
+ return { dir: realFolder(resolve(dir)), agent: null, scope: 'custom' };
75
+ }
76
+
77
+ const config = AGENTS[agent];
78
+ if (!config) {
79
+ throw new Error(`Unknown agent "${agent}". Use one of: ${AGENT_NAMES.join(', ')}.`);
80
+ }
81
+
82
+ if (project) {
83
+ const root = realpathSync(process.cwd());
84
+ const projectDir = realFolder(resolve(root, config.project));
85
+ if (!projectDir.startsWith(root.endsWith(sep) ? root : root + sep)) {
86
+ throw new Error(
87
+ `This project's skills folder ${resolve(process.cwd(), config.project)} leads to ${projectDir}, outside the project. Refusing to follow it.`,
88
+ );
89
+ }
90
+ return { dir: projectDir, agent, scope: 'project' };
91
+ }
92
+
93
+ return { dir: realFolder(config.global()), agent, scope: 'global' };
94
+ }
@@ -0,0 +1,177 @@
1
+ import { normalizeTimeoutMs } from '../config.js';
2
+ import { readBody, USER_AGENT } from '../http.js';
3
+ import { isSafeName } from './installer.js';
4
+
5
+ /** The public skills catalogue on insightfulpipe.com. Skills are free to download, so these requests
6
+ * carry no API token: the token is only ever sent to the API host in config. */
7
+
8
+ const DEFAULT_CATALOG_URL = 'https://insightfulpipe.com';
9
+ const ENV_CATALOG_URL = 'INSIGHTFULPIPE_SKILLS_URL';
10
+ const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);
11
+ // Only our own domain may serve public skills. A catalogue somewhere else could hand out skills with
12
+ // self-consistent checksums, so the override exists for local testing, not for other hosts.
13
+ const OUR_DOMAIN = /(^|\.)insightfulpipe\.com$/;
14
+ const ENV_TIMEOUT_MS = 'INSIGHTFULPIPE_TIMEOUT_MS';
15
+ const DEFAULT_TIMEOUT_MS = 30000;
16
+ // Far above any real catalogue or skill bundle; a response this large is not one of ours.
17
+ const MAX_RESPONSE_BYTES = 10 * 1024 * 1024;
18
+
19
+ export function getCatalogUrl() {
20
+ const raw = process.env[ENV_CATALOG_URL]?.trim() || DEFAULT_CATALOG_URL;
21
+ let url;
22
+ try {
23
+ url = new URL(raw);
24
+ } catch {
25
+ throw new Error(`${ENV_CATALOG_URL} is not a valid URL: ${raw}`);
26
+ }
27
+ const local = LOCAL_HOSTS.has(url.hostname);
28
+ const ours = url.protocol === 'https:' && OUR_DOMAIN.test(url.hostname);
29
+ if (!ours && !(local && (url.protocol === 'http:' || url.protocol === 'https:'))) {
30
+ throw new Error(
31
+ `${ENV_CATALOG_URL} must be https://insightfulpipe.com or one of its subdomains (localhost is allowed for testing).`,
32
+ );
33
+ }
34
+ return url.toString().replace(/\/+$/, '');
35
+ }
36
+
37
+ /** Public skills need no login, so the timeout comes from the environment alone, never the saved
38
+ * config: reading that would touch the keychain for a command that must not need the API key. */
39
+ function requestTimeoutMs() {
40
+ const raw = process.env[ENV_TIMEOUT_MS];
41
+ return raw ? normalizeTimeoutMs(raw, `environment variable ${ENV_TIMEOUT_MS}`) : DEFAULT_TIMEOUT_MS;
42
+ }
43
+
44
+ /** Redirects are refused, so every byte comes from the host `getCatalogUrl` allowed. The timeout covers
45
+ * the whole body, and an error answer's body is cancelled unread, so a server can never hold us open. */
46
+ async function request(path, { binary = false } = {}) {
47
+ const url = `${getCatalogUrl()}${path}`;
48
+ const timeoutMs = requestTimeoutMs();
49
+ const controller = new AbortController();
50
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
51
+
52
+ let res;
53
+ let body;
54
+ try {
55
+ res = await fetch(url, {
56
+ headers: {
57
+ Accept: binary ? 'application/zip' : 'application/json',
58
+ 'User-Agent': USER_AGENT,
59
+ },
60
+ redirect: 'error',
61
+ signal: controller.signal,
62
+ });
63
+ body = res.ok ? await readBody(res, { maxBytes: MAX_RESPONSE_BYTES }) : null;
64
+ } catch (error) {
65
+ const cause = error?.cause?.message ? ` (${error.cause.message})` : '';
66
+ throw new Error(
67
+ error?.name === 'AbortError'
68
+ ? `The skills catalogue did not answer within ${timeoutMs} ms.`
69
+ : `Could not reach the skills catalogue: ${error.message}${cause}`,
70
+ );
71
+ } finally {
72
+ clearTimeout(timer);
73
+ controller.abort();
74
+ }
75
+
76
+ if (res.status === 404) {
77
+ return null;
78
+ }
79
+ if (!res.ok) {
80
+ throw new Error(`The skills catalogue returned HTTP ${res.status} for ${path}.`);
81
+ }
82
+ if (!body) {
83
+ throw new Error(`The skills catalogue sent more than ${MAX_RESPONSE_BYTES} bytes for ${path}.`);
84
+ }
85
+ if (binary) {
86
+ return body;
87
+ }
88
+
89
+ try {
90
+ return JSON.parse(new TextDecoder().decode(body));
91
+ } catch {
92
+ throw new Error(`The skills catalogue sent something that is not JSON for ${path}.`);
93
+ }
94
+ }
95
+
96
+ /** Every published skill, without file contents. The slug and category become folder and file names,
97
+ * so an entry whose names are not plain lowercase words is dropped rather than offered. */
98
+ export async function fetchCatalog() {
99
+ const data = await request('/api/skills');
100
+ if (!data || !Array.isArray(data.skills)) {
101
+ throw new Error('The skills catalogue response has no skills list.');
102
+ }
103
+ return { ...data, skills: data.skills.filter((skill) => isSafeName(skill?.slug) && isSafeName(skill?.category)) };
104
+ }
105
+
106
+ /** One skill's exact files, with a sha256 per file and the skill's content version. */
107
+ export async function fetchSkillFiles(category, slug) {
108
+ return request(`/api/skills/${encodeURIComponent(category)}/${encodeURIComponent(slug)}/files`);
109
+ }
110
+
111
+ /** The ZIP the website offers, for uploading in Claude.ai or Claude Desktop. */
112
+ export async function fetchSkillZip(category, slug) {
113
+ return request(`/api/skills/download/${encodeURIComponent(category)}/${encodeURIComponent(slug)}`, { binary: true });
114
+ }
115
+
116
+ export function skillKey(skill) {
117
+ return `${skill.category}/${skill.slug}`;
118
+ }
119
+
120
+ export function pageUrl(skill) {
121
+ return `${getCatalogUrl()}/marketing-claude-skills/${skill.category}/${skill.slug}`;
122
+ }
123
+
124
+ /** Accepts `slug`, `category/slug` or `@insightfulpipe/slug`. A bare slug that exists in two
125
+ * categories is an error that lists both, never a guess. */
126
+ export function resolveSkill(name, skills) {
127
+ const wanted = String(name).trim().toLowerCase().replace(/^@insightfulpipe\//, '');
128
+ if (!wanted) {
129
+ return { error: 'Give a skill name.' };
130
+ }
131
+
132
+ const matches = wanted.includes('/')
133
+ ? skills.filter((skill) => skillKey(skill) === wanted)
134
+ : skills.filter((skill) => skill.slug === wanted);
135
+
136
+ if (matches.length === 1) {
137
+ return { skill: matches[0] };
138
+ }
139
+ if (matches.length > 1) {
140
+ return {
141
+ error: `"${name}" matches more than one skill. Use one of: ${matches.map(skillKey).join(', ')}.`,
142
+ };
143
+ }
144
+
145
+ const slugPart = wanted.split('/').pop();
146
+ const suggestions = skills
147
+ .map((skill) => ({ skill, score: similarity(slugPart, skill.slug) }))
148
+ .filter(({ skill, score }) => score <= 3 || skill.slug.includes(slugPart) || slugPart.includes(skill.slug))
149
+ .sort((a, b) => a.score - b.score)
150
+ .slice(0, 5)
151
+ .map(({ skill }) => skillKey(skill));
152
+
153
+ return {
154
+ error: suggestions.length
155
+ ? `No skill named "${name}". Did you mean: ${suggestions.join(', ')}?`
156
+ : `No skill named "${name}". Run "insightfulpipe skills search" to browse them.`,
157
+ };
158
+ }
159
+
160
+ /** Levenshtein distance, small and enough for suggesting near-miss names. */
161
+ function similarity(a, b) {
162
+ const rows = a.length + 1;
163
+ const cols = b.length + 1;
164
+ let previous = Array.from({ length: cols }, (_, j) => j);
165
+ for (let i = 1; i < rows; i++) {
166
+ const current = [i];
167
+ for (let j = 1; j < cols; j++) {
168
+ current[j] = Math.min(
169
+ previous[j] + 1,
170
+ current[j - 1] + 1,
171
+ previous[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1),
172
+ );
173
+ }
174
+ previous = current;
175
+ }
176
+ return previous[cols - 1];
177
+ }