skill-autoroute 0.4.1 → 0.6.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/README.md +18 -2
- package/hook/route.js +75 -11
- package/package.json +1 -1
- package/src/discover.js +5 -2
- package/src/flow.js +4 -1
- package/src/tools/claude.js +44 -5
package/README.md
CHANGED
|
@@ -45,6 +45,19 @@ No match means no output and **0 extra tokens**. No AI runs at prompt time. The
|
|
|
45
45
|
|
|
46
46
|

|
|
47
47
|
|
|
48
|
+
### 3 · During the work (agent loops)
|
|
49
|
+
|
|
50
|
+
The hook fires only when a prompt arrives, not on every step of an agent loop. So the first prompt of each session
|
|
51
|
+
also tells the agent how to ask for skills itself before a new sub-task:
|
|
52
|
+
|
|
53
|
+
```bash
|
|
54
|
+
node ~/.config/skill-autoroute/route.mjs claude suggest <session-id> "write the migration for the orders table"
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
The hook remembers which skills it already named in a session (in `~/.config/skill-autoroute/sessions/`, pruned
|
|
58
|
+
after 7 days). A later prompt, or a resumed round of a headless run (`claude -p --resume`), does not hint them again.
|
|
59
|
+
`suggest` always answers and adds what it names to that memory.
|
|
60
|
+
|
|
48
61
|
---
|
|
49
62
|
|
|
50
63
|
## Quick start
|
|
@@ -151,8 +164,10 @@ The router **adds** tokens. It does not save them. It pays off when a hint makes
|
|
|
151
164
|
|
|
152
165
|
| When | Cost |
|
|
153
166
|
| ------------------------------------------ | -------------------------------------------------------------- |
|
|
154
|
-
| A prompt matches nothing | **0 tokens**
|
|
167
|
+
| A prompt matches nothing | **0 tokens** (the first prompt of a session: the `suggest` line, about 40 tokens) |
|
|
155
168
|
| A prompt matches | one line, about 50–70 tokens per skill, at most 3 skills |
|
|
169
|
+
| A skill already named in this session | **0 tokens**: not hinted again |
|
|
170
|
+
| The agent runs `suggest` | one tool call plus the same hint line |
|
|
156
171
|
| Install (example: 7 skills, `--ai claude`) | 58,350 input tokens against an estimate of 58,200, in 11 calls |
|
|
157
172
|
|
|
158
173
|
|
|
@@ -276,7 +291,8 @@ When your skills change, the hint line tells you so. Run `regenerate`.
|
|
|
276
291
|
|
|
277
292
|

|
|
278
293
|
|
|
279
|
-
- **User level** works in every folder.
|
|
294
|
+
- **User level** works in every folder. It also picks up the skills that only one project loads (its own
|
|
295
|
+
`.claude/skills` and plugins enabled only in that project's settings) and hints them only inside that project.
|
|
280
296
|
- **Project level** goes into the repository, so teammates get it on clone. It adds a hook to `.claude/settings.json`.
|
|
281
297
|
Paths are stored relative to the project, and entries that point outside the project are skipped.
|
|
282
298
|
- **Codex** has a user-level hook only. That hook still reads the project table of the folder you run Codex in.
|
package/hook/route.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// Per-prompt hook for Claude Code and Codex. Node built-ins only; any error means no output, exit 0.
|
|
2
2
|
// argv[2] names the tool (claude or codex): only that tool's skills are hinted; no argument hints all.
|
|
3
|
-
import { readFileSync, statSync, readdirSync, realpathSync, appendFileSync, mkdirSync, existsSync } from 'node:fs';
|
|
3
|
+
import { readFileSync, statSync, readdirSync, realpathSync, appendFileSync, mkdirSync, existsSync, unlinkSync } from 'node:fs';
|
|
4
4
|
import { join, dirname, resolve, sep } from 'node:path';
|
|
5
5
|
import { homedir } from 'node:os';
|
|
6
6
|
import { pathToFileURL } from 'node:url';
|
|
@@ -157,24 +157,44 @@ export function staleCount(table, fs = FS) {
|
|
|
157
157
|
// Names come from skill files and go into model context: short, plain characters only.
|
|
158
158
|
const shownName = (v) => v.slice(0, MAX_NAME).replace(/[^A-Za-z0-9._:@/ -]/g, '?');
|
|
159
159
|
|
|
160
|
-
|
|
160
|
+
// Where a prompt runs: the base folder and, for a git worktree, its main checkout (from the `gitdir:` line of base/.git).
|
|
161
|
+
function places(base, fs) {
|
|
162
|
+
if (typeof base !== 'string' || !base) return [];
|
|
163
|
+
const out = [fs.real(base)];
|
|
164
|
+
try {
|
|
165
|
+
const m = /^gitdir:\s*(.+?)\s*$/m.exec(readFileSync(join(base, '.git'), 'utf8'));
|
|
166
|
+
const i = m ? m[1].lastIndexOf(`${sep}.git${sep}worktrees${sep}`) : -1;
|
|
167
|
+
if (i > 0) out.push(fs.real(m[1].slice(0, i)));
|
|
168
|
+
} catch { /* not a worktree */ }
|
|
169
|
+
return out;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// An entry with `projects` belongs to those project folders only; without a base it is never hinted.
|
|
173
|
+
const inProject = (s, here, fs) => !Array.isArray(s.projects) || s.projects.some((p) => {
|
|
174
|
+
if (typeof p !== 'string' || !p) return false;
|
|
175
|
+
const root = fs.real(p);
|
|
176
|
+
return here.some((h) => h === root || h.startsWith(root + sep));
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
function pick(prompt, table, { tool, base, skip, fs = FS } = {}) {
|
|
161
180
|
const text = String(prompt).slice(0, MAX_PROMPT);
|
|
181
|
+
const here = places(base, fs);
|
|
162
182
|
const ok = (v) => typeof v === 'string' && v !== '';
|
|
163
183
|
const seen = new Set();
|
|
164
184
|
const hits = table.skills
|
|
165
|
-
.filter((s) => s && s.enabled && ok(s.name) && ok(s.path) && /[\\/]SKILL\.md$/.test(s.path) && (!tool || (Array.isArray(s.tools) ? s.tools : [s.tool]).includes(tool)))
|
|
185
|
+
.filter((s) => s && s.enabled && ok(s.name) && ok(s.path) && /[\\/]SKILL\.md$/.test(s.path) && (!tool || (Array.isArray(s.tools) ? s.tools : [s.tool]).includes(tool)) && inProject(s, here, fs))
|
|
166
186
|
.map((s) => ({ s, own: ownFits(s, text) }))
|
|
167
187
|
.filter(({ s, own }) => (own || fits(s.patterns, text)) && fs.mtime(s.path) !== null)
|
|
168
188
|
.sort((a, b) => (b.own - a.own) || ((a.s.priority ?? 1e9) - (b.s.priority ?? 1e9)))
|
|
169
189
|
.map(({ s }) => s)
|
|
170
|
-
.filter((s) => !seen.has(s.name) && seen.add(s.name))
|
|
190
|
+
.filter((s) => !seen.has(s.name) && seen.add(s.name) && !skip?.has(s.name))
|
|
171
191
|
.slice(0, MAX_HINTS);
|
|
172
192
|
if (!hits.length) return null;
|
|
173
193
|
const safe = (v) => v.replace(/[\u0000-\u001f\u007f-\u009f]/g, '');
|
|
174
194
|
let out = 'Skills that fit this work (read each SKILL.md before you start): ' + hits.map((s) => `${shownName(s.name)} (${safe(s.path)})`).join('; ') + '.';
|
|
175
195
|
const n = staleCount(table, fs);
|
|
176
196
|
if (n) out += `\n${n} skill${n === 1 ? '' : 's'} changed since the last generate. Run: npx skill-autoroute regenerate`;
|
|
177
|
-
return { out, count: hits.length };
|
|
197
|
+
return { out, count: hits.length, names: hits.map((s) => s.name) };
|
|
178
198
|
}
|
|
179
199
|
|
|
180
200
|
export const route = (prompt, table, opts) => pick(prompt, table, opts)?.out ?? null;
|
|
@@ -230,26 +250,70 @@ const userClaudeHook = (udir) => {
|
|
|
230
250
|
} catch { return false; }
|
|
231
251
|
};
|
|
232
252
|
|
|
253
|
+
// Skills already named in a session, one name per line, so a resumed or repeated prompt does not hint (and the agent
|
|
254
|
+
// does not re-read) them again. An id that is not a plain token gets no memory: it is never used as a file name.
|
|
255
|
+
function sessionFile(udir, tool, sid) {
|
|
256
|
+
return typeof sid === 'string' && /^[A-Za-z0-9_-]{1,128}$/.test(sid) ? join(udir, 'sessions', `${tool || 'any'}-${sid}`) : null;
|
|
257
|
+
}
|
|
258
|
+
const remembered = (file) => {
|
|
259
|
+
try { return new Set(readFileSync(file, 'utf8').split('\n').filter(Boolean)); } catch { return null; }
|
|
260
|
+
};
|
|
261
|
+
function remember(file, names) {
|
|
262
|
+
if (!file) return;
|
|
263
|
+
try {
|
|
264
|
+
const dir = dirname(file);
|
|
265
|
+
if (!existsSync(file)) {
|
|
266
|
+
mkdirSync(dir, { recursive: true });
|
|
267
|
+
// shortcut: prune old sessions only when a new one starts; fine for a few hundred sessions a week.
|
|
268
|
+
for (const f of readdirSync(dir)) if ((FS.mtime(join(dir, f)) ?? Infinity) < Date.now() - 7 * 864e5) unlinkSync(join(dir, f));
|
|
269
|
+
}
|
|
270
|
+
appendFileSync(file, names.map((n) => `${n}\n`).join(''));
|
|
271
|
+
} catch { /* a read-only sandbox only loses the memory */ }
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
const loadTable = (udir, base) => merge(load(join(udir, 'routes.json')), resolveProject(load(join(base, '.skill-autoroute', 'routes.json')), base));
|
|
275
|
+
|
|
276
|
+
// `route.mjs [tool] suggest <session|-> <text...>`: the agent asks for skills in the middle of its work.
|
|
277
|
+
function suggest(udir, args, i) {
|
|
278
|
+
const tool = i === 1 ? args[0] : undefined;
|
|
279
|
+
const base = process.env.CLAUDE_PROJECT_DIR || process.cwd();
|
|
280
|
+
const table = loadTable(udir, base);
|
|
281
|
+
const hit = table && pick(args.slice(i + 2).join(' '), table, { tool, base });
|
|
282
|
+
process.stdout.write(`${hit ? hit.out : 'No skill fits.'}\n`);
|
|
283
|
+
if (hit) remember(sessionFile(udir, tool, args[i + 1]), hit.names);
|
|
284
|
+
}
|
|
285
|
+
|
|
233
286
|
function main(self) {
|
|
234
287
|
if (process.env.SKILL_AUTOROUTE_DISABLE === '1') return;
|
|
235
288
|
const udir = join(homedir(), '.config', 'skill-autoroute');
|
|
289
|
+
const args = process.argv.slice(2);
|
|
290
|
+
const at = args.indexOf('suggest');
|
|
291
|
+
if (at === 0 || at === 1) return suggest(udir, args, at);
|
|
236
292
|
// The user Claude hook already merges the project table; the project copy beside it would hint twice.
|
|
237
293
|
// Only a Claude user hook counts: a Codex-only user install must not silence the Claude project hook.
|
|
238
294
|
if (self.endsWith(`${sep}.skill-autoroute${sep}route.mjs`) && userClaudeHook(udir)) return;
|
|
239
295
|
try {
|
|
240
|
-
const { prompt } = JSON.parse(readFileSync(0, 'utf8'));
|
|
296
|
+
const { prompt, session_id: sid } = JSON.parse(readFileSync(0, 'utf8'));
|
|
241
297
|
if (typeof prompt !== 'string') return;
|
|
242
298
|
const base = process.env.CLAUDE_PROJECT_DIR || process.cwd();
|
|
243
|
-
const table =
|
|
299
|
+
const table = loadTable(udir, base);
|
|
244
300
|
if (!table) return;
|
|
245
|
-
const
|
|
246
|
-
|
|
247
|
-
const
|
|
301
|
+
const tool = args[0];
|
|
302
|
+
const file = sessionFile(udir, tool, sid);
|
|
303
|
+
const known = file && remembered(file);
|
|
304
|
+
const hit = pick(prompt, table, { tool, base, skip: known ?? undefined });
|
|
305
|
+
// Told once per session: later prompts and resumed rounds already have this line in context.
|
|
306
|
+
const tell = file && !known
|
|
307
|
+
? `To find skills for a new sub-task later in this session, run: node ${JSON.stringify(self)}${tool ? ` ${tool}` : ''} suggest ${sid} "<what you will do next>"`
|
|
308
|
+
: '';
|
|
309
|
+
if (!hit && !tell) return;
|
|
310
|
+
remember(file, hit ? hit.names : []);
|
|
311
|
+
const ctx = [hit?.out, tell].filter(Boolean).join('\n');
|
|
248
312
|
process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: 'UserPromptSubmit', additionalContext: ctx } }) + '\n');
|
|
249
313
|
if (process.env.SKILL_AUTOROUTE_LOG === '1' || table.log === true) {
|
|
250
314
|
try {
|
|
251
315
|
mkdirSync(udir, { recursive: true });
|
|
252
|
-
appendFileSync(join(udir, 'usage.log'), `${new Date().toISOString()}\t${hit
|
|
316
|
+
appendFileSync(join(udir, 'usage.log'), `${new Date().toISOString()}\t${hit?.count ?? 0}\t${ctx.length}\n`);
|
|
253
317
|
} catch { /* logging must never break a prompt */ }
|
|
254
318
|
}
|
|
255
319
|
} catch (e) {
|
package/package.json
CHANGED
package/src/discover.js
CHANGED
|
@@ -66,9 +66,10 @@ function walk(root, realDir, rel, seen, found, outside, skipped) {
|
|
|
66
66
|
export function discover(dirs) {
|
|
67
67
|
const skills = [];
|
|
68
68
|
const done = new Map(); // real dir -> skill, so a folder shared by two tools lists both
|
|
69
|
-
for (const { dir, tool, source } of dirs) {
|
|
69
|
+
for (const { dir, tool, source, projects, only } of dirs) {
|
|
70
70
|
let names;
|
|
71
71
|
try { names = readdirSync(dir).sort(); } catch { continue; }
|
|
72
|
+
if (Array.isArray(only)) names = names.filter((n) => only.includes(n));
|
|
72
73
|
for (const folder of names) {
|
|
73
74
|
let real;
|
|
74
75
|
try {
|
|
@@ -78,6 +79,8 @@ export function discover(dirs) {
|
|
|
78
79
|
if (done.has(real)) {
|
|
79
80
|
const prev = done.get(real);
|
|
80
81
|
if (prev && !prev.tools.includes(tool)) prev.tools.push(tool);
|
|
82
|
+
// A skill stays scoped only while every dir that lists it is scoped; one global listing makes it global.
|
|
83
|
+
if (prev?.projects) prev.projects = projects ? [...new Set([...prev.projects, ...projects])] : undefined;
|
|
81
84
|
continue;
|
|
82
85
|
}
|
|
83
86
|
const skillPath = join(real, 'SKILL.md');
|
|
@@ -99,7 +102,7 @@ export function discover(dirs) {
|
|
|
99
102
|
const skill = {
|
|
100
103
|
name: fm.name || folder,
|
|
101
104
|
description: fm.description || '',
|
|
102
|
-
tool, tools: [tool], source, dir: real, skillPath,
|
|
105
|
+
tool, tools: [tool], source, ...(projects ? { projects: [...projects] } : {}), dir: real, skillPath,
|
|
103
106
|
hash: `sha256:${h.digest('hex')}`,
|
|
104
107
|
files: found.map((f) => f.real),
|
|
105
108
|
outside: outside.sort(),
|
package/src/flow.js
CHANGED
|
@@ -191,6 +191,7 @@ const entry = (r, gen, scope) => {
|
|
|
191
191
|
const g = r.enabled ? gen.bySkill.get(r.skill.name) : null;
|
|
192
192
|
return {
|
|
193
193
|
name: r.skill.name, tool: r.skill.tool, tools: r.skill.tools ?? [r.skill.tool], path: keyOf(scope)(r.skill.skillPath), hash: r.skill.hash, enabled: r.enabled,
|
|
194
|
+
...(r.skill.projects ? { projects: r.skill.projects } : {}),
|
|
194
195
|
priority: g?.priority ?? 50, patterns: g?.rules ?? [],
|
|
195
196
|
scan: { verdict: r.scan.verdict, partial: r.scan.partial, findings: tableFindings(scope, r.skill, r.scan.findings) }, duplicateOf: r.dup?.of ?? null,
|
|
196
197
|
};
|
|
@@ -346,7 +347,9 @@ export async function regenerate(o, ui) {
|
|
|
346
347
|
if (was(s).patterns?.length && (!g || gen.fellBack.includes(s.name))) continue;
|
|
347
348
|
byPath.set(s.skillPath, { ...was(s), priority: g?.priority ?? 50, patterns: g?.rules ?? [] });
|
|
348
349
|
}
|
|
349
|
-
|
|
350
|
+
// Scope comes from this discovery, not the old entry: enabling a plugin in another project changes no skill file.
|
|
351
|
+
const scoped = ({ projects, ...e }, s) => (s.projects ? { ...e, projects: s.projects } : e);
|
|
352
|
+
const table = tableOf(ctx, skills.map((s) => scoped(byPath.get(s.skillPath) ?? was(s), s)), roots.map(key), old.log);
|
|
350
353
|
keepWords(table, old);
|
|
351
354
|
// unchanged rules still come from the old generator; after a full rebuild the new model wrote them all
|
|
352
355
|
if (!o.ai && old.generator) table.generator = { ...old.generator, rules: RULES_VERSION, ...(outdated && ctx.ai ? { model: table.generator.model } : {}) };
|
package/src/tools/claude.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { readFileSync, existsSync } from 'node:fs';
|
|
2
2
|
import { homedir } from 'node:os';
|
|
3
|
-
import { join } from 'node:path';
|
|
3
|
+
import { join, resolve, dirname, basename, sep } from 'node:path';
|
|
4
4
|
import { addHook, removeHook as removeHookFrom, hasHook as hasHookIn } from './hookconfig.js';
|
|
5
5
|
import { runCli, parseJson, onPath, checkPrompt } from './run.js';
|
|
6
6
|
|
|
@@ -20,8 +20,46 @@ function pluginDirs(settingsFile) {
|
|
|
20
20
|
for (const [key, on] of Object.entries(enabled)) {
|
|
21
21
|
if (on !== true || !Array.isArray(installed[key])) continue;
|
|
22
22
|
for (const e of installed[key]) {
|
|
23
|
-
|
|
24
|
-
|
|
23
|
+
if (typeof e?.installPath !== 'string') continue;
|
|
24
|
+
const source = `plugin:${key}`;
|
|
25
|
+
const listed = readJson(join(e.installPath, '.claude-plugin', 'plugin.json'))?.skills;
|
|
26
|
+
if (!Array.isArray(listed)) {
|
|
27
|
+
const dir = join(e.installPath, 'skills');
|
|
28
|
+
if (existsSync(dir)) out.push({ dir, tool: 'claude', source });
|
|
29
|
+
continue;
|
|
30
|
+
}
|
|
31
|
+
// A manifest names its skill folders, which may sit deeper than skills/<name>: scan each parent for those names only.
|
|
32
|
+
const byParent = new Map();
|
|
33
|
+
for (const rel of listed) {
|
|
34
|
+
const p = typeof rel === 'string' && resolve(e.installPath, rel);
|
|
35
|
+
if (!p || !p.startsWith(e.installPath + sep) || !existsSync(p)) continue;
|
|
36
|
+
byParent.set(dirname(p), [...(byParent.get(dirname(p)) ?? []), basename(p)]);
|
|
37
|
+
}
|
|
38
|
+
for (const [dir, only] of byParent) out.push({ dir, tool: 'claude', source, only });
|
|
39
|
+
}
|
|
40
|
+
}
|
|
41
|
+
return out;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// Projects Claude Code has opened (~/.claude.json) or installed a plugin for (projectPath in installed_plugins.json). Their own skills and the plugins only they enable live outside
|
|
45
|
+
// the user dirs; the user table lists them with `projects`, and the hook hints them only inside that project.
|
|
46
|
+
function projectDirs(userDirs) {
|
|
47
|
+
const seen = new Set(userDirs.map((d) => d.dir));
|
|
48
|
+
const out = [];
|
|
49
|
+
const installed = Object.values(readJson(join(homedir(), '.claude', 'plugins', 'installed_plugins.json'))?.plugins ?? {});
|
|
50
|
+
const roots = new Set([
|
|
51
|
+
...Object.keys(readJson(join(homedir(), '.claude.json'))?.projects ?? {}),
|
|
52
|
+
...installed.flatMap((list) => (Array.isArray(list) ? list : [])).map((e) => e?.projectPath).filter((p) => typeof p === 'string'),
|
|
53
|
+
]);
|
|
54
|
+
for (const root of roots) {
|
|
55
|
+
if (root === homedir() || !existsSync(root)) continue;
|
|
56
|
+
const projects = [root];
|
|
57
|
+
const own = join(root, '.claude', 'skills');
|
|
58
|
+
if (existsSync(own)) out.push({ dir: own, tool: 'claude', source: 'project', projects });
|
|
59
|
+
for (const f of ['settings.json', 'settings.local.json']) {
|
|
60
|
+
for (const d of pluginDirs(join(root, '.claude', f))) {
|
|
61
|
+
if (!seen.has(d.dir) && !out.some((o) => o.dir === d.dir && o.projects === projects)) out.push({ ...d, projects });
|
|
62
|
+
}
|
|
25
63
|
}
|
|
26
64
|
}
|
|
27
65
|
return out;
|
|
@@ -29,8 +67,9 @@ function pluginDirs(settingsFile) {
|
|
|
29
67
|
|
|
30
68
|
// Each scope lists only its own dirs; the hook merges the user and project tables at run time.
|
|
31
69
|
export function skillDirs(scope) {
|
|
32
|
-
|
|
33
|
-
|
|
70
|
+
if (scope === 'project') return [{ dir: join(process.cwd(), '.claude', 'skills'), tool: 'claude', source: 'project' }, ...pluginDirs(settings(scope))];
|
|
71
|
+
const user = [{ dir: join(homedir(), '.claude', 'skills'), tool: 'claude', source: 'user' }, ...pluginDirs(settings(scope))];
|
|
72
|
+
return [...user, ...projectDirs(user)];
|
|
34
73
|
}
|
|
35
74
|
|
|
36
75
|
export const installHook = (scope, command) => addHook(settings(scope), command);
|