skill-autoroute 0.0.0-stage → 0.2.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/LICENSE +21 -0
- package/README.md +279 -2
- package/bin/cli.js +81 -0
- package/hook/route.js +251 -0
- package/package.json +41 -4
- package/skill/SKILL.md +59 -0
- package/src/dedupe.js +91 -0
- package/src/discover.js +113 -0
- package/src/flow.js +422 -0
- package/src/models.js +13 -0
- package/src/paths.js +8 -0
- package/src/scan/ai.js +114 -0
- package/src/scan/static.js +210 -0
- package/src/table.js +29 -0
- package/src/tools/claude.js +62 -0
- package/src/tools/codex-models.js +28 -0
- package/src/tools/codex.js +56 -0
- package/src/tools/hookconfig.js +108 -0
- package/src/tools/run.js +59 -0
- package/src/triggers.js +134 -0
- package/src/usage.js +96 -0
- package/src/validate-worker.js +33 -0
- package/src/validate.js +90 -0
|
@@ -0,0 +1,210 @@
|
|
|
1
|
+
import { statSync, readFileSync } from 'node:fs';
|
|
2
|
+
import { relative, sep } from 'node:path';
|
|
3
|
+
import { parseFrontmatter } from '../discover.js';
|
|
4
|
+
|
|
5
|
+
const MAX_BYTES = 1024 * 1024; // larger files are never read line by line
|
|
6
|
+
const LONG_LINE = 20000;
|
|
7
|
+
|
|
8
|
+
// Every regex below avoids nested quantifiers, so matching stays linear in line length.
|
|
9
|
+
const BIDI_OR_TAG = /[\u202a-\u202e\u2066-\u2069]|[\u{E0000}-\u{E007F}]/u;
|
|
10
|
+
const ZERO_RUN = /[\u200b-\u200d\u2060\ufeff]{2}/;
|
|
11
|
+
const LONE_INVISIBLE = /[\u200b-\u200f\u2060\ufeff]/;
|
|
12
|
+
const EMOJI_ZWJ = /(\p{Extended_Pictographic}[\ufe0f\u{1F3FB}-\u{1F3FF}]?)\u200d(?=\p{Extended_Pictographic})/gu;
|
|
13
|
+
const BASE64_RUN = /(?<![A-Za-z0-9+/])[A-Za-z0-9+/]{300,}/g;
|
|
14
|
+
const DATA_URI_TAIL = /data:image\/[\w.+-]+;base64,$/;
|
|
15
|
+
const INJECTION = [
|
|
16
|
+
/\b(?:ignore|disregard|forget|override)\b[^.\n]{0,40}\b(?:previous|prior|above|earlier)\b[^.\n]{0,20}\b(?:instructions?|rules|prompts?|directions|guidelines)\b/i,
|
|
17
|
+
/\b(?:ignore|disregard|forget)\s+(?:(?:all|any|your|the|these|those)\s+)*instructions?\b/i,
|
|
18
|
+
/\b(?:do not|don['\u2019]t|never)\s+(?:tell|inform|reveal)\s+(?:the\s+)?(?:user|human)\b/i,
|
|
19
|
+
/\bwithout\s+(?:telling|informing|notifying)\s+(?:the\s+)?(?:user|human)\b/i,
|
|
20
|
+
/\b(?:reveal|print|output|show)\s+(?:your\s+)?system\s+prompt\b/i,
|
|
21
|
+
/\byou are now (?:in )?(?:dan|developer mode|jailbroken)\b/i,
|
|
22
|
+
];
|
|
23
|
+
// Pipes into an interpreter. Shells run whatever they are given; python/node/perl/ruby only count
|
|
24
|
+
// when they read the script from stdin (bare, or `-`), so `| python3 -m json.tool` is fine.
|
|
25
|
+
const PIPE_TO_INTERPRETER = /(?<!\|)\|\s*(?:sudo\s+(?:-\S+\s+)?)?(?:(?:\/usr)?\/bin\/env\s+|env\s+|xargs\s+(?:-\S+\s+)*)?(?:\/(?:usr\/)?(?:local\/)?bin\/)?(?:(?:ba|z|da|k)?sh\b|(?:python3?|perl|ruby|node)(?:\s+-)?\s*(?=$|[;&|)]))/g;
|
|
26
|
+
const DOWNLOADER = /\b(?:curl|wget)\b/;
|
|
27
|
+
const SHELL_SUBST = /(?:\b(?:ba|z|da|k)?sh|\bsource|\beval|(?:^|[\s;&(])\.)\s+(?:-c\s+)?["']?(?:\$\(|<\(|`)\s*(?:curl|wget)\b/;
|
|
28
|
+
// shortcut: remote-exec misses two-step download-then-run, PowerShell iwr | iex and uppercase CURL; add if seen in the wild.
|
|
29
|
+
const SECRET_SSH = /\.ssh(?![\w.-])(\/[^\s'"`;|&<>)]*)?/g;
|
|
30
|
+
const SECRET_OTHER = /\bid_(?:rsa|ed25519|ecdsa|dsa)\b(?!\.pub)|\.aws\/credentials|\.gnupg\b|\.netrc\b|\.npmrc\b|\.git-credentials|\.pypirc|\.docker\/config\.json|\.config\/gcloud|\.config\/gh\/hosts\.yml|\.kube\/config|\/etc\/shadow|Login Data/;
|
|
31
|
+
const NETWORK_CALL = /\b(?:curl|wget|nc|ncat|socat|telnet|scp|rsync|Invoke-RestMethod|Invoke-WebRequest)\b|\/dev\/tcp\/|\bfetch\s*\(|\bhttps?\.request|requests\.(?:get|post|put|patch|delete)|\burllib|\baxios\b|XMLHttpRequest/;
|
|
32
|
+
const PERSIST_PATH = /\.(?:bashrc|zshrc|bash_profile|zprofile|profile|zshenv)\b|\.(?:claude|codex)\/(?:settings(?:\.local)?\.json|config\.toml)|\/etc\/(?:cron|systemd|profile\.d|rc\.local)|LaunchAgents|\.config\/(?:autostart|systemd)/;
|
|
33
|
+
const WRITE_SIGNAL = />|\btee\b|\bsed\s+-i|\b(?:echo|cp|mv|write|writes|append|appends|modify|modifies|edit|edits|overwrite|patch)\b/i;
|
|
34
|
+
const SCHEDULER = /\bcrontab\s+-(?!l\b)|\blaunchctl\s+load\b|\bsystemctl\s+(?:--user\s+)?enable\b/;
|
|
35
|
+
const RM_ROOT = /\brm\s+(?:-[a-zA-Z-]+\s+)+(?:--no-preserve-root\s+)?["']?(?:\/|~|\$HOME|\$\{HOME\})(?:\*|\/\*?)?(?=["'\s;|&]|$)/;
|
|
36
|
+
const WIPE = /\bmkfs(?:\.\w+)?\s|\bdd\s+[^\n]{0,80}\bof=\/dev\/(?:sd|nvme|disk)/;
|
|
37
|
+
const WIDE_TOOLS = /(?:^|[,\s[])(?:\*|Bash(?:\(\s*:?\*?\s*\))?)(?=$|[,\s\]])/;
|
|
38
|
+
|
|
39
|
+
const anyOf = (res, s) => res.some((re) => re.test(s));
|
|
40
|
+
|
|
41
|
+
function pipesToInterpreter(line) {
|
|
42
|
+
const first = line.search(DOWNLOADER);
|
|
43
|
+
if (first < 0) return false;
|
|
44
|
+
PIPE_TO_INTERPRETER.lastIndex = 0;
|
|
45
|
+
for (let m; (m = PIPE_TO_INTERPRETER.exec(line));) if (m.index > first) return true;
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function hasBase64(line) {
|
|
50
|
+
BASE64_RUN.lastIndex = 0;
|
|
51
|
+
for (let m; (m = BASE64_RUN.exec(line));) {
|
|
52
|
+
if (!DATA_URI_TAIL.test(line.slice(Math.max(0, m.index - 80), m.index))) return true;
|
|
53
|
+
}
|
|
54
|
+
return false;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// A secret path that is not a public key or authorized_keys; bare `.ssh` (whole dir) counts.
|
|
58
|
+
function hasSecretPath(line) {
|
|
59
|
+
if (SECRET_OTHER.test(line)) return true;
|
|
60
|
+
SECRET_SSH.lastIndex = 0;
|
|
61
|
+
for (let m; (m = SECRET_SSH.exec(line));) {
|
|
62
|
+
const p = m[1] || '';
|
|
63
|
+
if (!p.endsWith('.pub') && !/\/authorized_keys$/.test(p)) return true;
|
|
64
|
+
}
|
|
65
|
+
return false;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
export const RULES = [
|
|
69
|
+
{ id: 'remote-exec', severity: 'high', reason: 'pipes a downloaded script into a shell',
|
|
70
|
+
test: (line) => pipesToInterpreter(line) || SHELL_SUBST.test(line) },
|
|
71
|
+
{ id: 'remote-instructions', severity: 'high', reason: 'fetches a web page and follows its instructions',
|
|
72
|
+
test: (line) => /https?:\/\//i.test(line) && /\b(?:fetch|download|load|read|curl|wget)\b/i.test(line)
|
|
73
|
+
&& /\b(?:follow|obey|execute|comply with|adhere to)\b/i.test(line)
|
|
74
|
+
&& /\b(?:instructions?|rules|directives?|guidelines|commands|prompt)\b/i.test(line) },
|
|
75
|
+
{ id: 'hidden-text', severity: 'high', reason: 'hides text from the reader (invisible characters, comments or encoded data)',
|
|
76
|
+
test: (line, ctx) => BIDI_OR_TAG.test(line) || ZERO_RUN.test(line) || hasBase64(line)
|
|
77
|
+
|| (ctx.comment !== '' && anyOf(INJECTION, ctx.comment)) },
|
|
78
|
+
{ id: 'hidden-char', severity: 'medium', reason: 'contains an invisible character',
|
|
79
|
+
test: (line) => {
|
|
80
|
+
const plain = line.replace(EMOJI_ZWJ, '$1'); // emoji joiners are normal text
|
|
81
|
+
return LONE_INVISIBLE.test(plain) && !ZERO_RUN.test(plain);
|
|
82
|
+
} },
|
|
83
|
+
{ id: 'injection-phrase', severity: 'high', reason: 'tells the AI to ignore its instructions or hide things from you',
|
|
84
|
+
test: (line) => anyOf(INJECTION, line) },
|
|
85
|
+
{ id: 'secret-theft', severity: 'high', reason: 'reads private keys or credentials and also sends data over the network',
|
|
86
|
+
// shortcut: needs the path and the network call in one file; read in one file, send in another is not caught.
|
|
87
|
+
test: (line, ctx) => ctx.network && hasSecretPath(line) },
|
|
88
|
+
{ id: 'persistence', severity: 'medium', reason: 'changes shell startup, scheduled jobs or agent settings',
|
|
89
|
+
test: (line) => SCHEDULER.test(line) || (PERSIST_PATH.test(line) && WRITE_SIGNAL.test(line)) },
|
|
90
|
+
{ id: 'destructive', severity: 'medium', reason: 'deletes or wipes whole folders or disks',
|
|
91
|
+
test: (line) => RM_ROOT.test(line) || WIPE.test(line) },
|
|
92
|
+
{ id: 'wide-permissions', severity: 'medium', reason: 'asks for unrestricted tool permissions',
|
|
93
|
+
test: (line, ctx) => ctx.lineNo === ctx.allowedLine && WIDE_TOOLS.test(ctx.allowedTools) },
|
|
94
|
+
{ id: 'opaque', severity: 'info', reason: 'contains binary or minified code that cannot be reviewed',
|
|
95
|
+
test: (line) => line.length > LONG_LINE && 'contains a minified or very long single-line file that cannot be reviewed' },
|
|
96
|
+
// Emitted by scanStatic once per skill.outside entry; never matches a line.
|
|
97
|
+
{ id: 'outside-link', severity: 'medium', reason: 'links to a file outside the skill folder', test: () => false },
|
|
98
|
+
];
|
|
99
|
+
const byId = Object.fromEntries(RULES.map((r) => [r.id, r]));
|
|
100
|
+
|
|
101
|
+
const isBinary = (buf) => {
|
|
102
|
+
const head = buf.subarray(0, 8000);
|
|
103
|
+
return head.includes(0) || (head.length > 3 && head[0] === 0x7f && head.toString('latin1', 1, 4) === 'ELF');
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
const FENCE = /^\s*(?:```|~~~)/;
|
|
107
|
+
const MAX_PER_RULE = 5; // per rule per file, so one noisy file cannot flood the picker
|
|
108
|
+
|
|
109
|
+
// Physical lines, with backslash-continued lines joined; `no` is the first physical line.
|
|
110
|
+
function logicalLines(text) {
|
|
111
|
+
const physical = text.split(/\r?\n/);
|
|
112
|
+
const out = [];
|
|
113
|
+
for (let i = 0; i < physical.length; i++) {
|
|
114
|
+
const no = i + 1;
|
|
115
|
+
const parts = [];
|
|
116
|
+
while (physical[i].endsWith('\\') && i + 1 < physical.length) parts.push(physical[i++].slice(0, -1));
|
|
117
|
+
parts.push(physical[i]);
|
|
118
|
+
out.push({ text: parts.length > 1 ? parts.join(' ') : parts[0], no });
|
|
119
|
+
}
|
|
120
|
+
return out;
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Network calls only count on code: every line of a script, fenced blocks of markdown.
|
|
124
|
+
function hasNetworkCall(lines, isMarkdown) {
|
|
125
|
+
let fenced = false;
|
|
126
|
+
for (const { text } of lines) {
|
|
127
|
+
if (isMarkdown && FENCE.test(text)) { fenced = !fenced; continue; }
|
|
128
|
+
if ((!isMarkdown || fenced) && NETWORK_CALL.test(text)) return true;
|
|
129
|
+
}
|
|
130
|
+
return false;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
function* commentParts(lines) {
|
|
134
|
+
let open = false;
|
|
135
|
+
for (const { text: line } of lines) {
|
|
136
|
+
let out = '';
|
|
137
|
+
let i = 0;
|
|
138
|
+
for (;;) {
|
|
139
|
+
const j = line.indexOf(open ? '-->' : '<!--', i);
|
|
140
|
+
if (j < 0) { if (open) out += line.slice(i); break; }
|
|
141
|
+
if (open) out += line.slice(i, j) + ' ';
|
|
142
|
+
open = !open;
|
|
143
|
+
i = j + (open ? 4 : 3);
|
|
144
|
+
}
|
|
145
|
+
yield out;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
export function scanStatic(skill) {
|
|
150
|
+
const findings = [];
|
|
151
|
+
const counts = new Map();
|
|
152
|
+
let partial = false;
|
|
153
|
+
const add = (id, file, line, reason) => {
|
|
154
|
+
const key = `${id}\0${file}`;
|
|
155
|
+
const n = counts.get(key) || 0;
|
|
156
|
+
if (n >= MAX_PER_RULE) return;
|
|
157
|
+
counts.set(key, n + 1);
|
|
158
|
+
findings.push({ rule: id, severity: byId[id].severity, file, line, reason: reason || byId[id].reason });
|
|
159
|
+
};
|
|
160
|
+
|
|
161
|
+
for (const abs of skill.files) {
|
|
162
|
+
const file = relative(skill.dir, abs).split(sep).join('/');
|
|
163
|
+
let buf;
|
|
164
|
+
try {
|
|
165
|
+
const size = statSync(abs).size;
|
|
166
|
+
if (size > MAX_BYTES) {
|
|
167
|
+
partial = true;
|
|
168
|
+
add('opaque', file, 0, `larger than 1 MB (${(size / MAX_BYTES).toFixed(1)} MB), not read`);
|
|
169
|
+
continue;
|
|
170
|
+
}
|
|
171
|
+
buf = readFileSync(abs);
|
|
172
|
+
} catch { partial = true; continue; }
|
|
173
|
+
if (isBinary(buf)) { add('opaque', file, 0, 'binary file that cannot be reviewed'); continue; }
|
|
174
|
+
|
|
175
|
+
const text = buf.toString('utf8').replace(/^\ufeff/, '');
|
|
176
|
+
const lines = logicalLines(text);
|
|
177
|
+
const ctx = {
|
|
178
|
+
network: hasNetworkCall(lines, /\.(?:md|markdown|mdx)$/i.test(file)),
|
|
179
|
+
comment: '', lineNo: 0, allowedLine: -1, allowedTools: '',
|
|
180
|
+
};
|
|
181
|
+
if (abs === skill.skillPath) {
|
|
182
|
+
const fm = parseFrontmatter(text);
|
|
183
|
+
if (fm.allowedTools) {
|
|
184
|
+
ctx.allowedTools = fm.allowedTools;
|
|
185
|
+
ctx.allowedLine = Math.max(1, lines.find((l) => /^allowed-tools:/.test(l.text))?.no ?? 1);
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
const comments = commentParts(lines);
|
|
189
|
+
for (const { text: line, no } of lines) {
|
|
190
|
+
ctx.lineNo = no;
|
|
191
|
+
ctx.comment = comments.next().value;
|
|
192
|
+
for (const rule of RULES) {
|
|
193
|
+
const hit = rule.test(line, ctx);
|
|
194
|
+
if (hit) add(rule.id, file, no, typeof hit === 'string' ? hit : undefined);
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
}
|
|
198
|
+
for (const rel of skill.outside) { partial = true; add('outside-link', rel, 0); }
|
|
199
|
+
if (skill.skipped?.length) partial = true; // node_modules and .git are never read
|
|
200
|
+
|
|
201
|
+
const verdict = findings.some((f) => f.severity === 'high') ? 'block'
|
|
202
|
+
: findings.some((f) => f.severity === 'medium') ? 'warn' : 'ok';
|
|
203
|
+
return { verdict, partial, findings };
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
export function label(result) {
|
|
207
|
+
const f = result.findings.find((x) => x.severity === 'high') || result.findings.find((x) => x.severity === 'medium');
|
|
208
|
+
if (f) return f.reason;
|
|
209
|
+
return result.partial ? 'no issues found (partial scan)' : 'no issues found';
|
|
210
|
+
}
|
package/src/table.js
ADDED
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import { readFileSync, writeFileSync, renameSync, mkdirSync, unlinkSync } from 'node:fs';
|
|
2
|
+
import { dirname } from 'node:path';
|
|
3
|
+
import { merge } from '../hook/route.js';
|
|
4
|
+
|
|
5
|
+
export function readTable(path) {
|
|
6
|
+
try {
|
|
7
|
+
const t = JSON.parse(readFileSync(path, 'utf8'));
|
|
8
|
+
return t && Array.isArray(t.skills) ? t : null;
|
|
9
|
+
} catch {
|
|
10
|
+
return null;
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
export function writeTable(path, table) {
|
|
15
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
16
|
+
const tmp = `${path}.${process.pid}.tmp`;
|
|
17
|
+
try {
|
|
18
|
+
writeFileSync(tmp, JSON.stringify(table, null, 2) + '\n');
|
|
19
|
+
renameSync(tmp, path);
|
|
20
|
+
} catch (e) {
|
|
21
|
+
try { unlinkSync(tmp); } catch { /* nothing to clean */ }
|
|
22
|
+
throw e;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
export function mergeTables(user, project) {
|
|
27
|
+
const m = merge(user, project) ?? { generatedAt: '', skills: [] };
|
|
28
|
+
return { version: 1, generator: (project ?? user)?.generator, ...m };
|
|
29
|
+
}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import { readFileSync, existsSync } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { addHook, removeHook as removeHookFrom, hasHook as hasHookIn } from './hookconfig.js';
|
|
5
|
+
import { runCli, parseJson, onPath, checkPrompt } from './run.js';
|
|
6
|
+
|
|
7
|
+
export const name = 'claude';
|
|
8
|
+
|
|
9
|
+
const settings = (scope) => (scope === 'project' ? join(process.cwd(), '.claude', 'settings.json') : join(homedir(), '.claude', 'settings.json'));
|
|
10
|
+
const readJson = (p) => { try { return JSON.parse(readFileSync(p, 'utf8')); } catch { return null; } };
|
|
11
|
+
|
|
12
|
+
export const detect = () => ({ cli: onPath('claude'), configDir: existsSync(join(homedir(), '.claude')) });
|
|
13
|
+
|
|
14
|
+
// Plugin skill dirs come from installed_plugins.json, limited to plugins enabled in `settingsFile`.
|
|
15
|
+
function pluginDirs(settingsFile) {
|
|
16
|
+
const enabled = readJson(settingsFile)?.enabledPlugins;
|
|
17
|
+
const installed = readJson(join(homedir(), '.claude', 'plugins', 'installed_plugins.json'))?.plugins;
|
|
18
|
+
if (!enabled || typeof enabled !== 'object' || !installed || typeof installed !== 'object') return [];
|
|
19
|
+
const out = [];
|
|
20
|
+
for (const [key, on] of Object.entries(enabled)) {
|
|
21
|
+
if (on !== true || !Array.isArray(installed[key])) continue;
|
|
22
|
+
for (const e of installed[key]) {
|
|
23
|
+
const dir = typeof e?.installPath === 'string' && join(e.installPath, 'skills');
|
|
24
|
+
if (dir && existsSync(dir)) out.push({ dir, tool: 'claude', source: `plugin:${key}` });
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return out;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// Each scope lists only its own dirs; the hook merges the user and project tables at run time.
|
|
31
|
+
export function skillDirs(scope) {
|
|
32
|
+
const base = scope === 'project' ? join(process.cwd(), '.claude') : join(homedir(), '.claude');
|
|
33
|
+
return [{ dir: join(base, 'skills'), tool: 'claude', source: scope === 'project' ? 'project' : 'user' }, ...pluginDirs(settings(scope))];
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export const installHook = (scope, command) => addHook(settings(scope), command);
|
|
37
|
+
export const removeHook = (scope) => removeHookFrom(settings(scope));
|
|
38
|
+
export const hasHook = (scope) => hasHookIn(settings(scope));
|
|
39
|
+
export const hookConfig = (scope) => settings(scope);
|
|
40
|
+
|
|
41
|
+
// loadUserSettings (bench only): keep the user's settings, hooks and MCP so the routing hook fires.
|
|
42
|
+
export async function headless({ prompt, schema, model, effort, timeoutMs, loadUserSettings = false, env }) {
|
|
43
|
+
checkPrompt(prompt);
|
|
44
|
+
const { stdout, stderr } = await runCli('claude', () => [
|
|
45
|
+
'-p', prompt, '--model', model, '--effort', effort, '--tools', '', '--output-format', 'json',
|
|
46
|
+
'--json-schema', typeof schema === 'string' ? schema : JSON.stringify(schema), '--no-session-persistence',
|
|
47
|
+
...(loadUserSettings ? [] : ['--setting-sources', '', '--strict-mcp-config', '--disable-slash-commands']),
|
|
48
|
+
], timeoutMs, env);
|
|
49
|
+
const r = parseJson('claude', stdout, stderr);
|
|
50
|
+
if (r.is_error) throw new Error(`claude reported an error: ${String(r.result).slice(0, 200)}`);
|
|
51
|
+
if (r.structured_output === undefined) throw new Error('claude result has no structured_output');
|
|
52
|
+
const u = r.usage ?? {};
|
|
53
|
+
return {
|
|
54
|
+
json: r.structured_output,
|
|
55
|
+
usage: {
|
|
56
|
+
input: (u.input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0),
|
|
57
|
+
cacheRead: u.cache_read_input_tokens ?? 0,
|
|
58
|
+
output: u.output_tokens ?? 0,
|
|
59
|
+
model: Object.keys(r.modelUsage ?? {})[0] ?? model,
|
|
60
|
+
},
|
|
61
|
+
};
|
|
62
|
+
}
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { readFileSync } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
|
|
5
|
+
// Codex reads CODEX_HOME when it is set, so every Codex file lives there.
|
|
6
|
+
export const codexHome = () => process.env.CODEX_HOME || join(homedir(), '.codex');
|
|
7
|
+
|
|
8
|
+
export const CODEX_TIERS = { small: ['gpt-6-luna', 'gpt-5.6-luna'], mid: ['gpt-6.1-sol', 'gpt-6-sol'] };
|
|
9
|
+
|
|
10
|
+
// The user's own top-level `model = "..."` from config.toml (keys before the first [section]), or null.
|
|
11
|
+
function configuredModel() {
|
|
12
|
+
try {
|
|
13
|
+
const top = readFileSync(join(codexHome(), 'config.toml'), 'utf8').split(/^\s*\[/m)[0];
|
|
14
|
+
return /^\s*model\s*=\s*"([^"]+)"/m.exec(top)?.[1] ?? null;
|
|
15
|
+
} catch { return null; }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
// First tier slug that Codex lists. On fallback the model is the user's configured one, or null
|
|
19
|
+
// (omit -m).
|
|
20
|
+
export function resolveCodexModel(tier) {
|
|
21
|
+
try {
|
|
22
|
+
const cache = JSON.parse(readFileSync(join(codexHome(), 'models_cache.json'), 'utf8'));
|
|
23
|
+
const listed = new Set(cache.models.filter((m) => m.visibility === 'list').map((m) => m.slug));
|
|
24
|
+
const model = (CODEX_TIERS[tier] ?? []).find((s) => listed.has(s));
|
|
25
|
+
if (model) return { model, fallback: false };
|
|
26
|
+
} catch { /* no cache: fall through */ }
|
|
27
|
+
return { model: configuredModel(), fallback: true };
|
|
28
|
+
}
|
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
import { existsSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { addHook, removeHook as removeHookFrom, hasHook as hasHookIn } from './hookconfig.js';
|
|
5
|
+
import { runCli, parseJson, onPath, checkPrompt } from './run.js';
|
|
6
|
+
import { codexHome } from './codex-models.js';
|
|
7
|
+
|
|
8
|
+
export const name = 'codex';
|
|
9
|
+
|
|
10
|
+
const NO_PROJECT = { changed: false, note: 'codex uses the user-level hook; it reads the project table' };
|
|
11
|
+
const hooksFile = () => join(codexHome(), 'hooks.json');
|
|
12
|
+
|
|
13
|
+
export const detect = () => ({ cli: onPath('codex'), configDir: existsSync(codexHome()) });
|
|
14
|
+
|
|
15
|
+
export function skillDirs(scope) {
|
|
16
|
+
if (scope === 'project') return [{ dir: join(process.cwd(), '.agents', 'skills'), tool: 'codex', source: 'project' }];
|
|
17
|
+
return [
|
|
18
|
+
{ dir: join(homedir(), '.agents', 'skills'), tool: 'codex', source: 'user' },
|
|
19
|
+
{ dir: join(codexHome(), 'skills'), tool: 'codex', source: 'user' },
|
|
20
|
+
];
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export function installHook(scope, command) {
|
|
24
|
+
if (scope === 'project') return { ...NO_PROJECT };
|
|
25
|
+
const r = addHook(hooksFile(), command);
|
|
26
|
+
return r.changed ? { ...r, note: 'run /hooks once in Codex to trust the new hook' } : r;
|
|
27
|
+
}
|
|
28
|
+
export const removeHook = (scope) => (scope === 'project' ? { ...NO_PROJECT } : removeHookFrom(hooksFile()));
|
|
29
|
+
export const hasHook = () => hasHookIn(hooksFile()); // codex has only the user-level hook
|
|
30
|
+
export const hookConfig = (scope) => (scope === 'project' ? null : hooksFile());
|
|
31
|
+
|
|
32
|
+
export async function headless({ prompt, schema, model, effort, timeoutMs, loadUserSettings = false, env }) {
|
|
33
|
+
checkPrompt(prompt);
|
|
34
|
+
const { stdout, stderr } = await runCli('codex', (dir) => {
|
|
35
|
+
const schemaFile = join(dir, 'schema.json');
|
|
36
|
+
writeFileSync(schemaFile, typeof schema === 'string' ? schema : JSON.stringify(schema));
|
|
37
|
+
return [
|
|
38
|
+
'exec', '--skip-git-repo-check', '--json', ...(loadUserSettings ? [] : ['--ignore-user-config']), '-s', 'read-only',
|
|
39
|
+
'--disable', 'shell_tool', '--disable', 'unified_exec', // shell features off by flag; the read-only sandbox is the backstop
|
|
40
|
+
...(model ? ['-m', model] : []), '-c', `model_reasoning_effort=${effort}`,
|
|
41
|
+
'--output-schema', schemaFile, prompt,
|
|
42
|
+
];
|
|
43
|
+
}, timeoutMs, env);
|
|
44
|
+
let text, usage;
|
|
45
|
+
for (const line of stdout.split('\n')) {
|
|
46
|
+
let ev;
|
|
47
|
+
try { ev = JSON.parse(line); } catch { continue; }
|
|
48
|
+
if (ev.type === 'item.completed' && ev.item?.type === 'agent_message') text = ev.item.text;
|
|
49
|
+
else if (ev.type === 'turn.completed') usage = ev.usage;
|
|
50
|
+
}
|
|
51
|
+
if (text === undefined) throw new Error(`codex output had no agent_message: ${(stderr.trim() || stdout.trim()).slice(0, 200)}`);
|
|
52
|
+
return {
|
|
53
|
+
json: parseJson('codex agent_message', text, stderr),
|
|
54
|
+
usage: { input: usage?.input_tokens ?? 0, cacheRead: usage?.cached_input_tokens ?? 0, output: usage?.output_tokens ?? 0, model: model ?? null },
|
|
55
|
+
};
|
|
56
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
import { readFileSync, writeFileSync, renameSync, copyFileSync, mkdirSync, existsSync, realpathSync, statSync, chmodSync, unlinkSync } from 'node:fs';
|
|
2
|
+
import { dirname } from 'node:path';
|
|
3
|
+
import { fileURLToPath } from 'node:url';
|
|
4
|
+
import { hookCopyPath } from '../paths.js';
|
|
5
|
+
|
|
6
|
+
const MARK = 'skill-autoroute/route.mjs';
|
|
7
|
+
const EVENT = 'UserPromptSubmit';
|
|
8
|
+
const isObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
9
|
+
const ours = (h) => isObj(h) && typeof h.command === 'string' && h.command.includes(MARK);
|
|
10
|
+
|
|
11
|
+
// Returns {cfg, existed}. Throws (never overwrites) on invalid JSON or an unexpected shape.
|
|
12
|
+
function load(path) {
|
|
13
|
+
let text;
|
|
14
|
+
try { text = readFileSync(path, 'utf8'); } catch (e) {
|
|
15
|
+
if (e.code === 'ENOENT') return { cfg: {}, existed: false };
|
|
16
|
+
throw e;
|
|
17
|
+
}
|
|
18
|
+
if (!text.trim()) return { cfg: {}, existed: true };
|
|
19
|
+
let cfg;
|
|
20
|
+
try { cfg = JSON.parse(text); } catch (e) {
|
|
21
|
+
throw new Error(`${path} is not valid JSON (${e.message}); fix or remove it, nothing was changed`);
|
|
22
|
+
}
|
|
23
|
+
const groups = isObj(cfg) && (cfg.hooks === undefined || (isObj(cfg.hooks) && (cfg.hooks[EVENT] === undefined || Array.isArray(cfg.hooks[EVENT]))));
|
|
24
|
+
if (!groups) throw new Error(`${path} has an unexpected shape (hooks.${EVENT} must be an array); nothing was changed`);
|
|
25
|
+
return { cfg, existed: true };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
// Writes next to the real target (a symlinked config stays a symlink) and keeps the file mode.
|
|
29
|
+
function save(path, cfg) {
|
|
30
|
+
mkdirSync(dirname(path), { recursive: true });
|
|
31
|
+
const target = existsSync(path) ? realpathSync(path) : path;
|
|
32
|
+
const tmp = `${target}.tmp-${process.pid}`;
|
|
33
|
+
const mode = existsSync(target) ? statSync(target).mode & 0o7777 : null;
|
|
34
|
+
try {
|
|
35
|
+
// created with the target's mode, so a private config is never world-readable, not even briefly
|
|
36
|
+
writeFileSync(tmp, JSON.stringify(cfg, null, 2) + '\n', mode === null ? undefined : { mode });
|
|
37
|
+
if (mode !== null) chmodSync(tmp, mode); // the umask may have narrowed it
|
|
38
|
+
renameSync(tmp, target);
|
|
39
|
+
} catch (e) {
|
|
40
|
+
try { unlinkSync(tmp); } catch { /* nothing to clean */ }
|
|
41
|
+
throw e;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const groupHooks = (g) => (isObj(g) && Array.isArray(g.hooks) ? g.hooks : []);
|
|
46
|
+
|
|
47
|
+
export function addHook(configPath, command) {
|
|
48
|
+
if (!command.includes(MARK)) throw new Error(`hook command must contain "${MARK}"`);
|
|
49
|
+
const { cfg, existed } = load(configPath);
|
|
50
|
+
const groups = cfg.hooks?.[EVENT] ?? [];
|
|
51
|
+
const mine = groups.flatMap(groupHooks).filter(ours);
|
|
52
|
+
if (mine.length && mine.every((h) => h.command === command)) return { changed: false };
|
|
53
|
+
const bak = `${configPath}.bak-skill-autoroute`;
|
|
54
|
+
if (existed && !existsSync(bak)) copyFileSync(configPath, bak);
|
|
55
|
+
if (mine.length) for (const h of mine) h.command = command; // an older install (other node, no tool argument): update in place
|
|
56
|
+
else {
|
|
57
|
+
cfg.hooks ??= {};
|
|
58
|
+
cfg.hooks[EVENT] = [...groups, { hooks: [{ type: 'command', command }] }];
|
|
59
|
+
}
|
|
60
|
+
save(configPath, cfg);
|
|
61
|
+
return { changed: true };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export function removeHook(configPath) {
|
|
65
|
+
const { cfg, existed } = load(configPath);
|
|
66
|
+
const groups = cfg.hooks?.[EVENT];
|
|
67
|
+
if (!existed || !groups?.some((g) => groupHooks(g).some(ours))) return { changed: false };
|
|
68
|
+
const kept = [];
|
|
69
|
+
for (const g of groups) {
|
|
70
|
+
const rest = groupHooks(g).filter((h) => !ours(h));
|
|
71
|
+
if (rest.length === groupHooks(g).length) kept.push(g);
|
|
72
|
+
else if (rest.length) kept.push({ ...g, hooks: rest });
|
|
73
|
+
}
|
|
74
|
+
if (kept.length) cfg.hooks[EVENT] = kept;
|
|
75
|
+
else delete cfg.hooks[EVENT];
|
|
76
|
+
if (!Object.keys(cfg.hooks).length) delete cfg.hooks;
|
|
77
|
+
save(configPath, cfg);
|
|
78
|
+
return { changed: true };
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// Throws (naming the file) when addHook would refuse it; used to check every config before any write.
|
|
82
|
+
export const checkConfig = (configPath) => { load(configPath); };
|
|
83
|
+
|
|
84
|
+
// False when the file is missing or unreadable.
|
|
85
|
+
export function hasHook(configPath) {
|
|
86
|
+
try { return (load(configPath).cfg.hooks?.[EVENT] ?? []).some((g) => groupHooks(g).some(ours)); } catch { return false; }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
// The npx cache can vanish after install, so the hook runs from a copy in the data folder. Returns the copy's path.
|
|
90
|
+
export function installHookCopy(scope) {
|
|
91
|
+
const dest = hookCopyPath(scope);
|
|
92
|
+
mkdirSync(dirname(dest), { recursive: true });
|
|
93
|
+
const tmp = `${dest}.tmp-${process.pid}`;
|
|
94
|
+
try {
|
|
95
|
+
copyFileSync(fileURLToPath(new URL('../../hook/route.js', import.meta.url)), tmp);
|
|
96
|
+
renameSync(tmp, dest);
|
|
97
|
+
} catch (e) {
|
|
98
|
+
try { unlinkSync(tmp); } catch { /* nothing to clean */ }
|
|
99
|
+
throw e;
|
|
100
|
+
}
|
|
101
|
+
return dest;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// The hook command for one tool; the tool argument makes the hook hint only that tool's skills.
|
|
105
|
+
// User scope runs the installing node by absolute path; project settings are shared in git, so they name `node`.
|
|
106
|
+
export const hookCommand = (scope, tool) => (scope === 'project'
|
|
107
|
+
? `node "$CLAUDE_PROJECT_DIR/.skill-autoroute/route.mjs" ${tool}`
|
|
108
|
+
: `"${process.execPath}" "${hookCopyPath(scope)}" ${tool}`);
|
package/src/tools/run.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { mkdtempSync, rmSync, accessSync, statSync, constants } from 'node:fs';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { join, delimiter } from 'node:path';
|
|
5
|
+
|
|
6
|
+
const head = (s) => s.trim().slice(0, 200);
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
// Runs `cmd` with no shell, stdin ignored, in a fresh temp cwd that is removed afterwards.
|
|
10
|
+
// `buildArgs(dir)` may write helper files into that dir. Resolves {stdout, stderr}; rejects on
|
|
11
|
+
// spawn error, non-zero exit or timeout.
|
|
12
|
+
// `env` (optional) is merged over process.env; a key set to undefined removes it.
|
|
13
|
+
export function runCli(cmd, buildArgs, timeoutMs = 180000, env) {
|
|
14
|
+
const dir = mkdtempSync(join(tmpdir(), 'skill-autoroute-run-'));
|
|
15
|
+
return new Promise((resolve, reject) => {
|
|
16
|
+
let out = '', err = '', done = false, timer;
|
|
17
|
+
const finish = (fn, v) => {
|
|
18
|
+
if (done) return;
|
|
19
|
+
done = true;
|
|
20
|
+
clearTimeout(timer);
|
|
21
|
+
rmSync(dir, { recursive: true, force: true });
|
|
22
|
+
fn(v);
|
|
23
|
+
};
|
|
24
|
+
let child;
|
|
25
|
+
try {
|
|
26
|
+
child = spawn(cmd, buildArgs(dir), { cwd: dir, stdio: ['ignore', 'pipe', 'pipe'], env: env && { ...process.env, ...env } });
|
|
27
|
+
} catch (e) { return finish(reject, e); }
|
|
28
|
+
child.stdout.setEncoding('utf8');
|
|
29
|
+
child.stderr.setEncoding('utf8');
|
|
30
|
+
child.stdout.on('data', (d) => { out += d; });
|
|
31
|
+
child.stderr.on('data', (d) => { err += d; });
|
|
32
|
+
child.on('error', (e) => finish(reject, new Error(`could not run ${cmd}: ${e.message}`)));
|
|
33
|
+
child.on('close', (code) => (code === 0
|
|
34
|
+
? finish(resolve, { stdout: out, stderr: err })
|
|
35
|
+
: finish(reject, new Error(`${cmd} exited with code ${code}: ${head(err) || head(out)}`))));
|
|
36
|
+
timer = setTimeout(() => { child.kill('SIGKILL'); finish(reject, new Error(`${cmd} timed out after ${timeoutMs} ms`)); }, timeoutMs);
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export const parseJson = (cmd, text, stderr = '') => {
|
|
41
|
+
try { return JSON.parse(text); } catch { throw new Error(`${cmd} output was not JSON: ${head(stderr) || head(text)}`); }
|
|
42
|
+
};
|
|
43
|
+
export const checkPrompt = (prompt) => {
|
|
44
|
+
if (typeof prompt !== 'string' || prompt.startsWith('-')) throw new Error('prompt must be a string that does not start with "-"');
|
|
45
|
+
};
|
|
46
|
+
|
|
47
|
+
// Searches PATH itself (no `which` subprocess).
|
|
48
|
+
export function onPath(name) {
|
|
49
|
+
const exts = process.platform === 'win32' ? (process.env.PATHEXT || '.EXE;.CMD').split(';') : [''];
|
|
50
|
+
for (const d of (process.env.PATH || '').split(delimiter).filter(Boolean)) {
|
|
51
|
+
for (const x of exts) {
|
|
52
|
+
try {
|
|
53
|
+
const f = join(d, name + x);
|
|
54
|
+
if (statSync(f).isFile()) { accessSync(f, constants.X_OK); return true; }
|
|
55
|
+
} catch { /* not here */ }
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
return false;
|
|
59
|
+
}
|