insightfulpipe 0.1.4 → 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.
- package/CHANGELOG.md +71 -0
- package/README.md +65 -2
- package/SKILL.md +8 -5
- package/bin/cli.js +4 -1
- package/package.json +7 -3
- package/skills/insightfulpipe/SKILL.md +8 -5
- package/src/api.js +88 -75
- package/src/cli/commands/discovery.js +80 -19
- package/src/cli/commands/execution.js +58 -17
- package/src/cli/commands/skills.js +454 -0
- package/src/cli/errors.js +167 -13
- package/src/cli/input.js +6 -0
- package/src/cli/program.js +18 -3
- package/src/cli/query-contexts.js +3 -2
- package/src/config.js +54 -2
- package/src/http.js +39 -0
- package/src/output.js +5 -1
- package/src/skills/agents.js +94 -0
- package/src/skills/catalog.js +177 -0
- package/src/skills/installer.js +331 -0
package/src/cli/program.js
CHANGED
|
@@ -1,8 +1,11 @@
|
|
|
1
1
|
import { Command } from 'commander';
|
|
2
|
+
|
|
3
|
+
import { PACKAGE_VERSION } from '../http.js';
|
|
2
4
|
import { registerAuthCommand } from './commands/auth.js';
|
|
3
5
|
import { registerConfigCommand } from './commands/config.js';
|
|
4
|
-
import { registerDiscoveryCommands } from './commands/discovery.js';
|
|
6
|
+
import { registerContextCommand, registerDiscoveryCommands } from './commands/discovery.js';
|
|
5
7
|
import { registerExecutionCommands } from './commands/execution.js';
|
|
8
|
+
import { registerSkillsCommand } from './commands/skills.js';
|
|
6
9
|
|
|
7
10
|
export function buildProgram() {
|
|
8
11
|
const program = new Command();
|
|
@@ -11,7 +14,12 @@ export function buildProgram() {
|
|
|
11
14
|
.name('insightfulpipe')
|
|
12
15
|
.description(
|
|
13
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' +
|
|
14
18
|
'Run "insightfulpipe platforms" to see all supported platforms.\n\n' +
|
|
19
|
+
'Set your scope once and stop passing ids:\n' +
|
|
20
|
+
' insightfulpipe use Adopt your only workspace\n' +
|
|
21
|
+
' insightfulpipe use -w <id> -b <id> Pick a workspace and brand\n' +
|
|
22
|
+
' insightfulpipe brands Brand ids and names\n\n' +
|
|
15
23
|
'Query workflow:\n' +
|
|
16
24
|
' 1. insightfulpipe accounts --platform <platform>\n' +
|
|
17
25
|
' Get workspace_id, brand_id, and source identifiers (e.g. property_id, site_url).\n\n' +
|
|
@@ -31,18 +39,25 @@ export function buildProgram() {
|
|
|
31
39
|
' insightfulpipe brands --workspace ID Brand metadata\n' +
|
|
32
40
|
' insightfulpipe whoami Current authenticated user\n' +
|
|
33
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' +
|
|
34
46
|
'Authentication:\n' +
|
|
35
47
|
' insightfulpipe auth Save your API token (starts with ip_sk_)\n' +
|
|
36
48
|
' Or set INSIGHTFULPIPE_TOKEN env var.'
|
|
37
49
|
)
|
|
38
|
-
.version(
|
|
39
|
-
.option('--json', 'Print JSON
|
|
50
|
+
.version(PACKAGE_VERSION)
|
|
51
|
+
.option('--json', 'Print JSON (default; kept for compatibility)')
|
|
52
|
+
.option('--table', 'Print a human-readable table instead of JSON')
|
|
40
53
|
.showHelpAfterError();
|
|
41
54
|
|
|
42
55
|
registerAuthCommand(program);
|
|
43
56
|
registerDiscoveryCommands(program);
|
|
57
|
+
registerContextCommand(program);
|
|
44
58
|
registerExecutionCommands(program);
|
|
45
59
|
registerConfigCommand(program);
|
|
60
|
+
registerSkillsCommand(program);
|
|
46
61
|
|
|
47
62
|
return program;
|
|
48
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/config.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'fs';
|
|
2
2
|
import { homedir } from 'os';
|
|
3
3
|
import { join } from 'path';
|
|
4
|
+
import { fail } from './cli/errors.js';
|
|
4
5
|
import { getTokenFromKeyring, saveTokenToKeyring, isKeyringAvailable } from './keyring.js';
|
|
5
6
|
|
|
6
7
|
const ENV_API_URL = 'INSIGHTFULPIPE_API_URL';
|
|
@@ -11,6 +12,10 @@ const DEFAULT_CONFIG = {
|
|
|
11
12
|
api_url: 'https://app.insightfulpipe.com',
|
|
12
13
|
token: null,
|
|
13
14
|
timeout_ms: 30000,
|
|
15
|
+
// Saved scope: set once with `insightfulpipe use`, then every query fills these in so nobody has
|
|
16
|
+
// to carry ids around by hand. A body that names them explicitly always wins.
|
|
17
|
+
workspace_id: null,
|
|
18
|
+
brand_id: null,
|
|
14
19
|
};
|
|
15
20
|
|
|
16
21
|
function getConfigDir() {
|
|
@@ -29,8 +34,7 @@ function ensureConfigDir() {
|
|
|
29
34
|
}
|
|
30
35
|
|
|
31
36
|
function configError(message) {
|
|
32
|
-
|
|
33
|
-
process.exit(1);
|
|
37
|
+
fail(message);
|
|
34
38
|
}
|
|
35
39
|
|
|
36
40
|
function normalizeConfig(rawConfig, sourceLabel) {
|
|
@@ -58,6 +62,21 @@ function normalizeConfig(rawConfig, sourceLabel) {
|
|
|
58
62
|
normalized.timeout_ms = normalizeTimeoutMs(rawConfig.timeout_ms, `${sourceLabel} field "timeout_ms"`);
|
|
59
63
|
}
|
|
60
64
|
|
|
65
|
+
for (const key of ['workspace_id', 'brand_id']) {
|
|
66
|
+
if (key in rawConfig) {
|
|
67
|
+
const value = rawConfig[key];
|
|
68
|
+
if (value === null) {
|
|
69
|
+
normalized[key] = null;
|
|
70
|
+
continue;
|
|
71
|
+
}
|
|
72
|
+
const parsed = Number(value);
|
|
73
|
+
if (!Number.isInteger(parsed) || parsed < 1) {
|
|
74
|
+
configError(`${sourceLabel} field "${key}" must be a positive integer or null.`);
|
|
75
|
+
}
|
|
76
|
+
normalized[key] = parsed;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
|
|
61
80
|
return normalized;
|
|
62
81
|
}
|
|
63
82
|
|
|
@@ -101,6 +120,8 @@ function buildConfigSnapshot() {
|
|
|
101
120
|
api_url: Object.hasOwn(stored, 'api_url') ? sourceLabel('file') : sourceLabel('default'),
|
|
102
121
|
token: Object.hasOwn(stored, 'token') && stored.token ? sourceLabel('file') : sourceLabel('default'),
|
|
103
122
|
timeout_ms: Object.hasOwn(stored, 'timeout_ms') ? sourceLabel('file') : sourceLabel('default'),
|
|
123
|
+
workspace_id: Object.hasOwn(stored, 'workspace_id') ? sourceLabel('file') : sourceLabel('default'),
|
|
124
|
+
brand_id: Object.hasOwn(stored, 'brand_id') ? sourceLabel('file') : sourceLabel('default'),
|
|
104
125
|
};
|
|
105
126
|
|
|
106
127
|
// Token priority: env var > keyring > config file
|
|
@@ -192,3 +213,34 @@ export function getApiUrl() {
|
|
|
192
213
|
export function getRequestTimeoutMs() {
|
|
193
214
|
return loadConfig().timeout_ms;
|
|
194
215
|
}
|
|
216
|
+
|
|
217
|
+
/** The saved workspace/brand scope (`insightfulpipe use`). */
|
|
218
|
+
export function getContext() {
|
|
219
|
+
const config = loadConfig();
|
|
220
|
+
return { workspace_id: config.workspace_id ?? null, brand_id: config.brand_id ?? null };
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
/** Merge the saved scope into a request body WITHOUT overriding anything the caller stated. */
|
|
224
|
+
export function applyContextToBody(body, overrides = {}) {
|
|
225
|
+
const context = getContext();
|
|
226
|
+
const next = { ...body };
|
|
227
|
+
const workspaceId = overrides.workspace_id ?? context.workspace_id;
|
|
228
|
+
const brandId = overrides.brand_id ?? context.brand_id;
|
|
229
|
+
if (next.workspace_id === undefined && workspaceId != null) {
|
|
230
|
+
next.workspace_id = workspaceId;
|
|
231
|
+
}
|
|
232
|
+
if (next.brand_id === undefined && brandId != null) {
|
|
233
|
+
next.brand_id = brandId;
|
|
234
|
+
}
|
|
235
|
+
return next;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** Persist (or clear, with null) the saved scope, keeping the rest of the config untouched. */
|
|
239
|
+
export function saveContext({ workspaceId, brandId }) {
|
|
240
|
+
const stored = readStoredConfig();
|
|
241
|
+
const next = { ...stored };
|
|
242
|
+
if (workspaceId !== undefined) next.workspace_id = workspaceId;
|
|
243
|
+
if (brandId !== undefined) next.brand_id = brandId;
|
|
244
|
+
saveConfig(next);
|
|
245
|
+
return getContext();
|
|
246
|
+
}
|
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
|
+
}
|
package/src/output.js
CHANGED
|
@@ -2,8 +2,12 @@ export function printJson(data) {
|
|
|
2
2
|
console.log(JSON.stringify(data, null, 2));
|
|
3
3
|
}
|
|
4
4
|
|
|
5
|
+
/** JSON is the CLI's default output: it is read by scripts and agents far more than by eyes.
|
|
6
|
+
* `--table` opts into the human view; `--json` is accepted and does nothing, so every documented
|
|
7
|
+
* command and existing script keeps working unchanged. */
|
|
5
8
|
export function wantsJson(command) {
|
|
6
|
-
|
|
9
|
+
const opts = command?.optsWithGlobals?.() ?? {};
|
|
10
|
+
return !opts.table;
|
|
7
11
|
}
|
|
8
12
|
|
|
9
13
|
export function printTable(rows, columns) {
|
|
@@ -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
|
+
}
|