insightfulpipe 0.2.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.
- package/CHANGELOG.md +101 -0
- package/README.md +61 -1
- package/package.json +2 -2
- package/src/api.js +112 -73
- package/src/cli/commands/auth.js +7 -2
- package/src/cli/commands/discovery.js +8 -7
- package/src/cli/commands/execution.js +3 -3
- package/src/cli/commands/skills.js +554 -0
- package/src/cli/errors.js +159 -15
- package/src/cli/input.js +6 -0
- package/src/cli/program.js +7 -7
- package/src/cli/query-contexts.js +3 -2
- package/src/config.js +16 -3
- package/src/http.js +39 -0
- package/src/skills/agents.js +95 -0
- package/src/skills/catalog.js +177 -0
- package/src/skills/installer.js +372 -0
- package/src/skills/private.js +100 -0
- package/src/skills/records.js +72 -0
- package/src/skills/sources.js +108 -0
package/src/cli/errors.js
CHANGED
|
@@ -1,32 +1,176 @@
|
|
|
1
|
+
/** Anything meant for reading is cut here; the marker says how much the server actually sent. */
|
|
2
|
+
const MAX_TEXT_CHARS = 2000;
|
|
3
|
+
const TRUNCATION_MARKER = /\.\.\. \[truncated, \d+ more characters\]$/;
|
|
4
|
+
|
|
5
|
+
/** Idempotent: text that is already a full head plus the marker passes through, so a string cut
|
|
6
|
+
* once in api.js is not cut again on its way out. */
|
|
7
|
+
export function bounded(text) {
|
|
8
|
+
if (text.length <= MAX_TEXT_CHARS || text.replace(TRUNCATION_MARKER, '').length === MAX_TEXT_CHARS) {
|
|
9
|
+
return text;
|
|
10
|
+
}
|
|
11
|
+
return `${text.slice(0, MAX_TEXT_CHARS)}... [truncated, ${text.length - MAX_TEXT_CHARS} more characters]`;
|
|
12
|
+
}
|
|
13
|
+
|
|
1
14
|
/** Failures follow the same contract as results: JSON by default, a sentence under `--table`.
|
|
2
15
|
* Always on stderr, so `insightfulpipe ... | jq` never sees them either way. */
|
|
3
16
|
function humanOutput() {
|
|
4
17
|
return process.argv.includes('--table');
|
|
5
18
|
}
|
|
6
19
|
|
|
7
|
-
|
|
20
|
+
/** A piped stderr is written asynchronously on macOS, and `process.exit` drops whatever has not
|
|
21
|
+
* drained yet (a 64 KB cut); blocking mode makes the write finish before the exit. */
|
|
22
|
+
function writeStderr(text) {
|
|
23
|
+
process.stderr._handle?.setBlocking?.(true);
|
|
24
|
+
process.stderr.write(`${text}\n`);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function fail(message, tip, details = {}) {
|
|
8
28
|
if (humanOutput()) {
|
|
9
|
-
|
|
10
|
-
if (tip) {
|
|
11
|
-
console.error(`Tip: ${tip}`);
|
|
12
|
-
}
|
|
29
|
+
writeStderr(tip ? `Error: ${message}\nTip: ${tip}` : `Error: ${message}`);
|
|
13
30
|
} else {
|
|
14
|
-
|
|
31
|
+
writeStderr(JSON.stringify({ status: 'error', message, ...(tip ? { tip } : {}), ...details }, null, 2));
|
|
15
32
|
}
|
|
16
33
|
process.exit(1);
|
|
17
34
|
}
|
|
18
35
|
|
|
19
|
-
|
|
36
|
+
/** What the server sent next to its message rides along in the JSON output, so a script can branch
|
|
37
|
+
* on the platform's own code, sleep for `retry_after`, or see that a write may have landed. */
|
|
38
|
+
const PASSTHROUGH_FIELDS = ['api_status_code', 'api_error', 'details', 'error_type', 'retry_after'];
|
|
39
|
+
// The app's own write-outcome fields (apps/raw_apis/error_text.py), so a retrying script never double-writes.
|
|
40
|
+
const WRITE_OUTCOME_FIELDS = [
|
|
41
|
+
'status_code',
|
|
42
|
+
'write_state',
|
|
43
|
+
'outcome',
|
|
44
|
+
'needs_reconciliation',
|
|
45
|
+
'may_have_written',
|
|
46
|
+
'ambiguous',
|
|
47
|
+
'ambiguous_write',
|
|
48
|
+
'outcome_unknown',
|
|
49
|
+
'created_resource_names',
|
|
50
|
+
];
|
|
51
|
+
|
|
52
|
+
/** Slug words whose brand spelling title-casing gets wrong; every other word is simply capitalised. */
|
|
53
|
+
const BRAND_WORDS = {
|
|
54
|
+
api: 'API',
|
|
55
|
+
bigquery: 'BigQuery',
|
|
56
|
+
callrail: 'CallRail',
|
|
57
|
+
dataforseo: 'DataForSEO',
|
|
58
|
+
linkedin: 'LinkedIn',
|
|
59
|
+
mssql: 'MSSQL',
|
|
60
|
+
mysql: 'MySQL',
|
|
61
|
+
openai: 'OpenAI',
|
|
62
|
+
pagespeed: 'PageSpeed',
|
|
63
|
+
postgresql: 'PostgreSQL',
|
|
64
|
+
rest: 'REST',
|
|
65
|
+
tiktok: 'TikTok',
|
|
66
|
+
woocommerce: 'WooCommerce',
|
|
67
|
+
wordpress: 'WordPress',
|
|
68
|
+
youtube: 'YouTube',
|
|
69
|
+
};
|
|
70
|
+
|
|
71
|
+
/** The platform named in the response wins, then the one the command was run for: "tiktok-ads"
|
|
72
|
+
* reads as "TikTok Ads". With neither, or a slug with no words in it, the label is just "API". */
|
|
73
|
+
function platformLabel(data, context) {
|
|
74
|
+
const slug = [data.platform, context.platform].find((value) => typeof value === 'string' && value.trim());
|
|
75
|
+
const label = (slug || '')
|
|
76
|
+
.toLowerCase()
|
|
77
|
+
.split(/[-_\s]+/)
|
|
78
|
+
.filter(Boolean)
|
|
79
|
+
.map((word) => BRAND_WORDS[word] || word[0].toUpperCase() + word.slice(1))
|
|
80
|
+
.join(' ');
|
|
81
|
+
return label || 'API';
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
/** A string is itself and an object or array is compact JSON; anything else (the boolean error
|
|
85
|
+
* flag, a bare number) is not a message. */
|
|
86
|
+
function asText(value) {
|
|
87
|
+
if (typeof value === 'string') {
|
|
88
|
+
return value || undefined;
|
|
89
|
+
}
|
|
90
|
+
if (value && typeof value === 'object') {
|
|
91
|
+
return JSON.stringify(value);
|
|
92
|
+
}
|
|
93
|
+
return undefined;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** Providers send `api_error` as a string, as `{code, message}` (Pinterest) or as
|
|
97
|
+
* `{error: {code, message}}` (Meta); anything else is shown as JSON rather than dropped. */
|
|
98
|
+
function apiErrorParts(apiError) {
|
|
99
|
+
if (typeof apiError === 'string') {
|
|
100
|
+
return apiError ? { message: apiError } : undefined;
|
|
101
|
+
}
|
|
102
|
+
if (!apiError || typeof apiError !== 'object') {
|
|
103
|
+
return undefined;
|
|
104
|
+
}
|
|
105
|
+
const inner = apiError.error && typeof apiError.error === 'object' ? apiError.error : apiError;
|
|
106
|
+
if (typeof inner.message !== 'string' || !inner.message) {
|
|
107
|
+
return { message: JSON.stringify(apiError) };
|
|
108
|
+
}
|
|
109
|
+
return { code: inner.code, message: inner.message };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/** A code is normally a number or a short string; a structured one is shown compact, never as
|
|
113
|
+
* "[object Object]". */
|
|
114
|
+
function codeText(code) {
|
|
115
|
+
if (code === undefined || code === null || code === '') {
|
|
116
|
+
return '';
|
|
117
|
+
}
|
|
118
|
+
return ` ${typeof code === 'object' ? JSON.stringify(code) : code}`;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** `Pinterest Pages error 50 (HTTP 404): Pin not found.` keeps the platform's code, its message and
|
|
122
|
+
* the status it answered with, so the sentence under --table says as much as the JSON does. */
|
|
123
|
+
function describeApiError(data, context) {
|
|
124
|
+
const parts = apiErrorParts(data.api_error);
|
|
125
|
+
if (!parts) {
|
|
126
|
+
return undefined;
|
|
127
|
+
}
|
|
128
|
+
const http = data.api_status_code === undefined || data.api_status_code === null ? '' : ` (HTTP ${data.api_status_code})`;
|
|
129
|
+
return `${platformLabel(data, context)} error${codeText(parts.code)}${http}: ${parts.message}`;
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/** The one sentence for a failed response, in precedence order: the server's own message, then the
|
|
133
|
+
* platform's `api_error`, then `details`, then a string `error`; the boolean `error` flag never shows. */
|
|
134
|
+
export function errorMessage(data, context = {}) {
|
|
135
|
+
return bounded(
|
|
136
|
+
asText(data.message) ||
|
|
137
|
+
describeApiError(data, context) ||
|
|
138
|
+
asText(data.details) ||
|
|
139
|
+
(typeof data.error === 'string' ? data.error : undefined) ||
|
|
140
|
+
(typeof data.status === 'number' ? `Request failed with status ${data.status}` : 'Request failed'),
|
|
141
|
+
);
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
/** A field passes through as sent while it is small; past the cap it becomes a truncated string,
|
|
145
|
+
* so a 2 MB upstream body (an HTML error page in `api_error`, say) never lands in the output whole. */
|
|
146
|
+
function boundedField(value) {
|
|
147
|
+
if (typeof value === 'string') {
|
|
148
|
+
return bounded(value);
|
|
149
|
+
}
|
|
150
|
+
const serialized = JSON.stringify(value);
|
|
151
|
+
return serialized === undefined || serialized.length <= MAX_TEXT_CHARS ? value : bounded(serialized);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function retryTip(data) {
|
|
155
|
+
const seconds = Number(data.retry_after);
|
|
156
|
+
return Number.isFinite(seconds) && seconds > 0 ? `Retry after ${seconds} seconds.` : undefined;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** `context.platform` is the slug the command was run for (`query pinterest-pages ...`), so the
|
|
160
|
+
* sentence can name the platform even when the response does not. */
|
|
161
|
+
export function handleApiError(data, context = {}) {
|
|
20
162
|
if (!data || !data.error) {
|
|
21
163
|
return data;
|
|
22
164
|
}
|
|
23
165
|
|
|
24
|
-
const
|
|
25
|
-
|
|
26
|
-
data
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
166
|
+
const passthrough = {};
|
|
167
|
+
for (const field of [...PASSTHROUGH_FIELDS, ...WRITE_OUTCOME_FIELDS]) {
|
|
168
|
+
if (data[field] !== undefined) {
|
|
169
|
+
passthrough[field] = boundedField(data[field]);
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
if (typeof data.status === 'number') {
|
|
173
|
+
passthrough.http_status = data.status;
|
|
174
|
+
}
|
|
175
|
+
fail(errorMessage(data, context), data.tip || retryTip(data), passthrough);
|
|
32
176
|
}
|
package/src/cli/input.js
CHANGED
|
@@ -122,6 +122,12 @@ export async function promptSecret(promptText) {
|
|
|
122
122
|
});
|
|
123
123
|
}
|
|
124
124
|
|
|
125
|
+
/** Ask a yes/no question on the terminal; anything but y/yes is a no. */
|
|
126
|
+
export async function confirm(question) {
|
|
127
|
+
const answer = await promptInput(question);
|
|
128
|
+
return /^(y|yes)$/i.test(answer);
|
|
129
|
+
}
|
|
130
|
+
|
|
125
131
|
export async function confirmWriteAction(platform, body, skipConfirmation) {
|
|
126
132
|
if (skipConfirmation) {
|
|
127
133
|
return;
|
package/src/cli/program.js
CHANGED
|
@@ -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
|
-
|
|
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/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
|
-
|
|
205
|
-
return config.token;
|
|
218
|
+
return cleanToken(loadConfig().token);
|
|
206
219
|
}
|
|
207
220
|
|
|
208
221
|
export function getApiUrl() {
|
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. The app's Activity log labels key-authenticated calls carrying it as CLI. */
|
|
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,95 @@
|
|
|
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 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. */
|
|
56
|
+
function realFolder(path) {
|
|
57
|
+
const missing = [];
|
|
58
|
+
let existing = path;
|
|
59
|
+
while (!lstatSync(existing, { throwIfNoEntry: false }) && dirname(existing) !== existing) {
|
|
60
|
+
missing.unshift(basename(existing));
|
|
61
|
+
existing = dirname(existing);
|
|
62
|
+
}
|
|
63
|
+
try {
|
|
64
|
+
return join(realpathSync.native(existing), ...missing);
|
|
65
|
+
} catch (error) {
|
|
66
|
+
throw new Error(`Could not resolve the skills folder ${path}: ${error.message}`);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
/** The skills folder a command works on: `--dir` wins, then `--project` (current directory), then the
|
|
71
|
+
* agent's global folder. Always the real path; a project's folder must stay inside the project, since a
|
|
72
|
+
* cloned repo could plant a symlink that points it at any other folder. */
|
|
73
|
+
export function resolveSkillsDir({ agent = DEFAULT_AGENT, project = false, dir } = {}) {
|
|
74
|
+
if (dir) {
|
|
75
|
+
return { dir: realFolder(resolve(dir)), agent: null, scope: 'custom' };
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
const config = AGENTS[agent];
|
|
79
|
+
if (!config) {
|
|
80
|
+
throw new Error(`Unknown agent "${agent}". Use one of: ${AGENT_NAMES.join(', ')}.`);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
if (project) {
|
|
84
|
+
const root = realpathSync.native(process.cwd());
|
|
85
|
+
const projectDir = realFolder(resolve(root, config.project));
|
|
86
|
+
if (!projectDir.startsWith(root.endsWith(sep) ? root : root + sep)) {
|
|
87
|
+
throw new Error(
|
|
88
|
+
`This project's skills folder ${resolve(process.cwd(), config.project)} leads to ${projectDir}, outside the project. Refusing to follow it.`,
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
return { dir: projectDir, agent, scope: 'project' };
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
return { dir: realFolder(config.global()), agent, scope: 'global' };
|
|
95
|
+
}
|
|
@@ -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
|
+
}
|