@originkit/skillrouter 0.1.0 → 0.1.2

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/data/skills.json CHANGED
@@ -2420,7 +2420,8 @@
2420
2420
  "warnings": [
2421
2421
  "no longer in coreyhaines31/marketingskills under this name; loads from a pinned older commit"
2422
2422
  ],
2423
- "source": "https://raw.githubusercontent.com/coreyhaines31/marketingskills/f3990f7f99ae63b9e26eaa61114f60e0408742ff/skills/schema-markup/SKILL.md"
2423
+ "source": "https://raw.githubusercontent.com/coreyhaines31/marketingskills/f3990f7f99ae63b9e26eaa61114f60e0408742ff/skills/schema-markup/SKILL.md",
2424
+ "replacedBy": "coreyhaines31/marketingskills/schema"
2424
2425
  },
2425
2426
  {
2426
2427
  "id": "coreyhaines31/marketingskills/ai-seo",
@@ -3008,46 +3009,6 @@
3008
3009
  "install": "npx skills add https://github.com/giuseppe-trisciuoglio/developer-kit --skill nextjs-performance",
3009
3010
  "source": "https://raw.githubusercontent.com/giuseppe-trisciuoglio/developer-kit/fe73fb33a09ee6562eeec7415a3f9a3bcf795177/plugins/developer-kit-typescript/skills/nextjs-performance/SKILL.md"
3010
3011
  },
3011
- {
3012
- "id": "local/cursor-build",
3013
- "name": "cursor-build",
3014
- "description": "Sections build themselves as they scroll in: a crew of live multiplayer cursors rebuilds each one, then hands back the real section. 5 intros, 5 appears.",
3015
- "summary": "Sections build themselves as they scroll in: a crew of live multiplayer cursors rebuilds each one, then hands back the real section. 5 intros, 5 appears.",
3016
- "placements": [
3017
- {
3018
- "category": "interactive-showpieces",
3019
- "tier": "main"
3020
- }
3021
- ]
3022
- },
3023
- {
3024
- "id": "local/anatomy",
3025
- "name": "anatomy",
3026
- "description": "Build crafted, highly detailed, interactive isometric SVG figures that explain a technical idea as a real physical object (a test rig, a dial gauge, a cabinet of drawers, a plotter, a lock), with many small precise solid parts, four-tone shading, correct painter's order, a framed card with title, hint and live readout, and calm eased motion. Use this whenever someone wants an isometric illustration, an explanatory diagram or figure for docs, a blog post, a landing page or an article, a \"Linear-style\" or \"premium\" technical drawing, an interactive explainer, or an SVG that shows how a system, algorithm or component works, even if they never say \"isometric\". Works framework-free (TypeScript/JS that writes SVG and HTML) and in React/Next.js, and can add realistic WebGL shaders (fire, exhaust, water, caustics, lamp light) that live inside the drawing in the same isometric perspective.",
3027
- "summary": "Name an idea in one line and Claude draws a live, isometric machine that does it: drag, press and read it. 35.6K installs on skills.sh, one audit warning there.",
3028
- "placements": [
3029
- {
3030
- "category": "interactive-showpieces",
3031
- "tier": "main"
3032
- }
3033
- ],
3034
- "warnings": [
3035
- "1 audit warning"
3036
- ],
3037
- "path": "~/.claude/skills/anatomy/SKILL.md"
3038
- },
3039
- {
3040
- "id": "local/teardown",
3041
- "name": "teardown",
3042
- "description": "Interactive 3D simulators of real machines you can take apart, with live panels and a recorded 60 fps video.",
3043
- "summary": "Interactive 3D simulators of real machines you can take apart, with live panels and a recorded 60 fps video.",
3044
- "placements": [
3045
- {
3046
- "category": "interactive-showpieces",
3047
- "tier": "main"
3048
- }
3049
- ]
3050
- },
3051
3012
  {
3052
3013
  "id": "mengto/skills/cinematic-scroll-storytelling",
3053
3014
  "name": "cinematic-scroll-storytelling",
package/dist/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { homedir } from "node:os";
3
- import { join } from "node:path";
3
+ import { dirname, join } from "node:path";
4
4
  import { text } from "node:stream/consumers";
5
5
  import { parseArgs } from "node:util";
6
6
  import { createRouter, discoverSkills, loadPack, loadSkillsDir, loadSkillBody } from "./index.js";
@@ -42,6 +42,8 @@ if (!cmd || values.help) {
42
42
  process.exit(cmd || values.help ? 0 : 1);
43
43
  }
44
44
  const CACHE = join(homedir(), ".cache", "skill-router");
45
+ // Below this RouteResult.confidence the hook stays silent.
46
+ const HOOK_MIN = 0.15;
45
47
  if (cmd === "mcp") {
46
48
  const { serve } = await import("./mcp.js");
47
49
  await serve(loadAll, CACHE);
@@ -51,25 +53,36 @@ else if (cmd === "hook") {
51
53
  // Never blocks the prompt: any failure means no context, not an error.
52
54
  try {
53
55
  const { prompt } = JSON.parse(await text(process.stdin));
54
- const res = prompt ? await createRouter(loadAll()).route(prompt, { k: values.k ? Number(values.k) : 3 }) : null;
55
- if (res && !res.none) {
56
+ // Recall over precision: a list Claude doesn't need costs ~300 tokens and gets ignored (0 false loads on
57
+ // 9 off-topic prompts in bench/), while a missing skill is a miss. 8 lines at confidence >= 0.15 listed
58
+ // the right skill for 89% of blind tasks (was 77% at 5 lines, 0.25).
59
+ const res = prompt ? await createRouter(loadAll()).route(prompt, { k: values.k ? Number(values.k) : 8, relative: 0, minCoverage: 0.1 }) : null;
60
+ // Unsolicited, so stricter than route_skill: weak matches stay silent.
61
+ if (res && !res.none && res.confidence >= HOOK_MIN) {
56
62
  const parts = [];
63
+ const how = (s) => (s.path ? `use the installed ${s.name} skill` : `load it with the get_skill tool, id "${s.id}"`);
64
+ const caution = (s) => (s.warnings?.length ? ` Caution: ${s.warnings.join("; ")}; tell the user before relying on it.` : "");
57
65
  // Named by the user: load the instructions now instead of suggesting them.
58
66
  for (const { skill: s } of res.matches.filter((m) => m.mentioned)) {
59
67
  const body = await loadSkillBody(s, { cacheDir: CACHE }).catch(() => null);
60
- const warn = s.warnings?.length ? `\nCaution: ${s.warnings.join("; ")}. Tell the user before relying on it.` : "";
68
+ const files = s.path
69
+ ? `Files it refers to are next to it in ${dirname(s.path)}.`
70
+ : `Files it refers to (e.g. references/…): the get_skill tool with id "${s.id}" and file "<path>".`;
61
71
  parts.push(body
62
- ? `skill-router: the user asked for the ${s.name} skill (${s.id}). Follow these instructions for this request:${warn}\n<skill id="${s.id}">\n${clip(body, 30_000)}\n</skill>`
63
- : `skill-router: the user asked for the ${s.name} skill (${s.id}); load it with skill-router get_skill.${warn}`);
72
+ ? `skill-router: the user asked for the ${s.name} skill (${s.id}). Follow these instructions for this request. ${files}${caution(s)}\n<skill id="${s.id}">\n${clip(body, 30_000)}\n</skill>`
73
+ : `skill-router: the user asked for the ${s.name} skill (${s.id}); ${how(s)}.${caution(s)}`);
64
74
  }
75
+ // Otherwise a short list for Claude to judge. Word matching alone is right first only about half the time on
76
+ // unseen prompts, but a model picking from its list gets ~3 in 4 (data/eval-holdout.json), so ask Claude to
77
+ // check actively: a bare "may fit" was skipped even when right, in live runs.
65
78
  const suggested = res.matches.filter((m) => !m.mentioned);
66
- if (suggested.length) {
79
+ if (suggested.length && !parts.length) {
80
+ // No "strong match" tag here: on unseen prompts word matching's first pick is wrong ~1 in 3, and a tag biases Claude toward it.
67
81
  const lines = suggested.map(({ skill: s }) => {
68
- const how = s.path ? "installed" : `load with skill-router get_skill id="${s.id}"`;
69
- const warn = s.warnings?.length ? ` Caution: ${s.warnings.join("; ")}.` : "";
70
- return `- ${s.id}: ${s.summary ?? s.description.slice(0, 160)} (${how})${warn}`;
82
+ const about = (s.summary ?? s.description).replace(/\s+/g, " ").slice(0, 160);
83
+ return `- ${s.id}: ${about}${s.path ? " [installed]" : ""}${caution(s)}`;
71
84
  });
72
- parts.push(`skill-router: skills that may fit this request. Use one only if it genuinely fits; otherwise ignore this.\n${lines.join("\n")}`);
85
+ parts.push(`skill-router: these skills match this request (already routed, so route_skill isn't needed). As your first step, before reading or searching any files, pick the one that best fits the task (not necessarily the first; the list is ranked by word overlap) and load it: an installed one by using the skill, any other with the get_skill tool (id = its id below). Then follow it. Skip this only if none of them is about this task.\n${lines.join("\n")}`);
73
86
  }
74
87
  const additionalContext = parts.join("\n\n");
75
88
  console.log(JSON.stringify({ hookSpecificOutput: { hookEventName: "UserPromptSubmit", additionalContext } }));
@@ -106,5 +119,5 @@ else {
106
119
  }
107
120
  }
108
121
  function clip(s, n) {
109
- return s.length > n ? `${s.slice(0, n)}\n[truncated: read the rest with skill-router get_skill]` : s;
122
+ return s.length > n ? `${s.slice(0, n)}\n[truncated: read the rest with the get_skill tool]` : s;
110
123
  }
package/dist/index.d.ts CHANGED
@@ -22,7 +22,7 @@ export interface RouteOptions {
22
22
  relative?: number;
23
23
  /** When given, a model picks from the top `candidates` lexical hits. */
24
24
  complete?: Complete;
25
- /** How many lexical hits the model sees. Default 12. */
25
+ /** How many lexical hits the model sees. Default 40: the right skill can rank low lexically when the task names its page ("pricing page", "landing page") more than its problem. */
26
26
  candidates?: number;
27
27
  }
28
28
  export interface Router {
@@ -38,7 +38,14 @@ export interface Router {
38
38
  * with `node test/eval.ts --sweep`. Relative, so it holds from 2 skills to 2,000.
39
39
  */
40
40
  export declare const DEFAULT_MIN_COVERAGE = 0.25;
41
- export declare function createRouter(skills: Skill[]): Router;
41
+ export interface RouterOptions {
42
+ /**
43
+ * Weight of problem keywords ("cramped", "janky") against the description (1). Default 2: on the
44
+ * blind holdout it took the right skill from 83% to 98% inside the top 40, and 14% to 38% first on symptom-only tasks.
45
+ */
46
+ keywordBoost?: number;
47
+ }
48
+ export declare function createRouter(skills: Skill[], { keywordBoost }?: RouterOptions): Router;
42
49
  export declare function rerankPrompt(task: string, hits: Match[], k: number): string;
43
50
  export interface BodyOptions {
44
51
  /** A file next to SKILL.md, e.g. "references/rules.md". Default "SKILL.md". */
package/dist/index.js CHANGED
@@ -8,8 +8,11 @@ import { parse as parseYaml } from "yaml";
8
8
  /** The bundled web-design pack (data/skills.json). */
9
9
  export const PACK_PATH = fileURLToPath(new URL("../data/skills.json", import.meta.url));
10
10
  export function loadPack(path = PACK_PATH) {
11
+ // Problem keywords (data/keywords.json beside the pack) are optional: index them when present.
12
+ const kwPath = join(dirname(path), "keywords.json");
13
+ const keywords = existsSync(kwPath) ? JSON.parse(readFileSync(kwPath, "utf8")) : {};
11
14
  // A catalog describes skills; where one is installed is this machine's business (discoverSkills).
12
- return JSON.parse(readFileSync(path, "utf8")).map(({ path: _, ...s }) => s);
15
+ return JSON.parse(readFileSync(path, "utf8")).map(({ path: _, ...s }) => keywords[s.id] && !s.keywords ? { ...s, keywords: keywords[s.id] } : s);
13
16
  }
14
17
  /** Parse a SKILL.md file. Returns null when it has no usable frontmatter. */
15
18
  export function parseSkillFile(path, id) {
@@ -100,7 +103,7 @@ const processTerm = (t) => {
100
103
  const w = t.toLowerCase();
101
104
  return STOP.has(w) || w.length < 2 ? null : w;
102
105
  };
103
- export function createRouter(skills) {
106
+ export function createRouter(skills, { keywordBoost = 2 } = {}) {
104
107
  // Same id twice: merge, later fields win (an installed copy keeps the catalog's categories).
105
108
  const byId = new Map();
106
109
  for (const s of skills)
@@ -123,6 +126,17 @@ export function createRouter(skills) {
123
126
  byId.delete(id);
124
127
  aliases.set(id, twin.id);
125
128
  }
129
+ // A skill renamed upstream resolves to its successor, which inherits its catalog placements.
130
+ for (const [id, s] of byId) {
131
+ const next = s.replacedBy ? byId.get(s.replacedBy) : undefined;
132
+ if (!next)
133
+ continue;
134
+ const placements = [...(next.placements ?? []), ...(s.placements ?? [])];
135
+ // The old entry's summary describes the skill; the successor's may only point back at it ("…under its newer name").
136
+ byId.set(next.id, { ...next, summary: s.summary ?? next.summary, placements: placements.filter((p, i) => placements.findIndex((q) => q.category === p.category) === i) });
137
+ byId.delete(id);
138
+ aliases.set(id, next.id);
139
+ }
126
140
  // The same skill synced into several folders is one skill.
127
141
  const seen = new Set();
128
142
  for (const [id, s] of byId) {
@@ -134,12 +148,12 @@ export function createRouter(skills) {
134
148
  const all = [...byId.values()];
135
149
  const get = (id) => byId.get(id) ?? byId.get(aliases.get(id) ?? "");
136
150
  const index = new MiniSearch({
137
- fields: ["name", "summary", "description", "categories"],
151
+ fields: ["name", "summary", "description", "categories", "keywords"],
138
152
  idField: "id",
139
153
  processTerm,
140
154
  tokenize,
141
155
  searchOptions: {
142
- boost: { name: 3, summary: 1.5, categories: 1.2, description: 1 },
156
+ boost: { name: 3, summary: 1.5, categories: 1.2, description: 1, keywords: keywordBoost },
143
157
  prefix: (t) => t.length > 3,
144
158
  fuzzy: (t) => (t.length > 5 ? 0.15 : false),
145
159
  combineWith: "OR",
@@ -150,12 +164,13 @@ export function createRouter(skills) {
150
164
  summary: s.summary ?? "",
151
165
  name: s.name.replace(/-/g, " "),
152
166
  categories: (s.placements ?? []).map((p) => p.category.replace(/-/g, " ")).join(" "),
167
+ keywords: (s.keywords ?? []).join(" "),
153
168
  }));
154
169
  index.addAll(docs);
155
170
  // Document frequency per term, for weighting the task's words by rarity.
156
171
  const df = new Map();
157
172
  for (const doc of docs) {
158
- const terms = new Set(tokenize([doc.name, doc.summary, doc.description, doc.categories].join(" ")).map(processTerm));
173
+ const terms = new Set(tokenize([doc.name, doc.summary, doc.description, doc.categories, doc.keywords].join(" ")).map(processTerm));
159
174
  for (const t of terms)
160
175
  if (t)
161
176
  df.set(t, (df.get(t) ?? 0) + 1);
@@ -197,20 +212,21 @@ export function createRouter(skills) {
197
212
  [...g].sort((a, b) => pos(a) - pos(b) || prior(b) - prior(a))[0]);
198
213
  }
199
214
  async function route(task, opts = {}) {
200
- const { k = 3, minScore = 0, minCoverage = DEFAULT_MIN_COVERAGE, relative = 0.5, complete, candidates = 12, } = opts;
215
+ const { k = 3, minScore = 0, minCoverage = DEFAULT_MIN_COVERAGE, relative = 0.5, complete, candidates = 40, } = opts;
201
216
  // Small catalogs: let the model see everything, lexical overlap or not.
202
- const hits = rank(task, candidates);
217
+ // Enough hits for both the rerank pool and the k results asked for.
218
+ const hits = rank(task, Math.max(candidates, k));
203
219
  // Named skills always come first and skip the no-fit check: the user chose them.
204
220
  const pinned = named(task, hits).map((skill) => ({ skill, score: 1, reason: "named in the task", mentioned: true }));
205
- const withPinned = (rest, via) => {
221
+ const withPinned = (rest, via, confidence = 0) => {
206
222
  const matches = [...pinned, ...rest.filter((m) => !pinned.some((p) => p.skill === m.skill))].slice(0, Math.max(k, pinned.length));
207
- return { matches, none: matches.length === 0, via };
223
+ return { matches, none: matches.length === 0, via, confidence: pinned.length ? 1 : +confidence.toFixed(3) };
208
224
  };
209
225
  if (complete) {
210
226
  const pool = all.length <= candidates ? all.map((skill) => ({ skill, score: 0 })) : hits;
211
227
  const picked = pool.length ? await rerank(task, pool, complete, k) : [];
212
228
  if (picked)
213
- return withPinned(picked, "llm");
229
+ return withPinned(picked, "llm", Math.max(0, ...picked.map((m) => m.score)));
214
230
  // Unparseable model output: fall through to lexical rather than fail.
215
231
  }
216
232
  const top = hits[0]?.score ?? 0;
@@ -222,11 +238,13 @@ export function createRouter(skills) {
222
238
  const got = words.filter((t) => lead.has(t)).reduce((sum, t) => sum + weight(t), 0);
223
239
  if (!hits.length || !total || top < minScore || got / total < minCoverage)
224
240
  return withPinned([], "lexical");
241
+ // How much of the task the best skill covers on its own: one skill that owns the task is a strong match.
242
+ const own = words.filter((t) => hits[0].matched.has(t)).reduce((sum, t) => sum + weight(t), 0) / total;
225
243
  const matches = hits
226
244
  .filter((h) => h.score >= top * relative)
227
245
  .slice(0, k)
228
246
  .map((h) => ({ skill: h.skill, score: +(h.score / top).toFixed(3) }));
229
- return withPinned(matches, "lexical");
247
+ return withPinned(matches, "lexical", own);
230
248
  }
231
249
  return { skills: all, get, search, route };
232
250
  }
package/dist/mcp.js CHANGED
@@ -10,30 +10,29 @@ const text = (t) => ({ content: [{ type: "text", text: t }] });
10
10
  export async function serve(load, cacheDir) {
11
11
  // Rebuilt per call (tens of ms) so skills installed while the server runs are seen at once.
12
12
  const router = () => createRouter(load());
13
- const server = new McpServer({ name: "skill-router", version: "0.1.0" }, {
13
+ const server = new McpServer({ name: "skill-router", version: "0.1.2" }, {
14
14
  instructions: "Before starting a substantial task, call route_skill with the user's task to see whether a specialised skill covers it. If a returned skill genuinely fits, load it with get_skill and follow it. If none fits, carry on without one.",
15
15
  });
16
16
  server.registerTool("route_skill", {
17
- description: "Call before starting a task to find which agent skills apply. Returns a shortlist of skills (id, description, cautions) ranked for the task; pick the ones that genuinely fit, or none. Then load a pick with get_skill or install it.",
17
+ description: "Call before starting a task to find which agent skills apply. Returns up to 40 candidate skills, best lexical match first, one line each. Word matching ranks the page a task mentions (\"pricing page\") as highly as its problem (\"buttons feel flat\"), so read the whole list and judge: pick the skills that genuinely fit, or none. Then load a pick with get_skill.",
18
18
  inputSchema: {
19
19
  task: z.string().describe("The user's task, in their words plus any useful context"),
20
- limit: z.number().int().min(1).max(25).optional().describe("Shortlist size, default 8"),
20
+ limit: z.number().int().min(1).max(60).optional().describe("Candidates to list, default 40"),
21
21
  },
22
22
  annotations: { readOnlyHint: true },
23
+ // Claude Code defers MCP tools behind a ToolSearch step; this loads them up front (saves a turn per skill load).
24
+ _meta: { "anthropic/alwaysLoad": true },
23
25
  }, async ({ task, limit }) => {
24
- const res = await router().route(task, { k: limit ?? 8, relative: 0.3 });
26
+ // A long list of one-liners: the right skill can rank 30th lexically, and the agent is the better judge.
27
+ const res = await router().route(task, { k: limit ?? 40, relative: 0 });
25
28
  if (res.none)
26
29
  return text("No skill matches this task. Proceed without one.");
27
- return text(res.matches
28
- .map(({ skill: s, score, mentioned }) => [
29
- `## ${s.id} (${mentioned ? "named in the task" : `match ${score.toFixed(2)}`}${s.path ? ", installed" : ""})`,
30
- s.description,
31
- s.warnings?.length ? `Caution: ${s.warnings.join("; ")}` : "",
32
- s.path || s.source ? "Load: get_skill" : s.install ? `Install: ${s.install}` : "",
33
- ]
34
- .filter(Boolean)
35
- .join("\n"))
36
- .join("\n\n"));
30
+ const lines = res.matches.map(({ skill: s, mentioned }, i) => {
31
+ const tags = [mentioned ? "named in the task" : i === 0 && res.confidence >= 0.5 ? "strong match" : "", s.path ? "installed" : "", s.warnings?.length ? `caution: ${s.warnings.join("; ")}` : ""].filter(Boolean);
32
+ const about = (s.summary ?? s.description).replace(/\s+/g, " ");
33
+ return `- ${s.id}: ${about.length > 200 ? `${about.slice(0, 199)}…` : about}${tags.length ? ` [${tags.join(", ")}]` : ""}`;
34
+ });
35
+ return text(`${lines.join("\n")}\n\nLoad a pick's full instructions with get_skill.`);
37
36
  });
38
37
  server.registerTool("get_skill", {
39
38
  description: "Return a skill's instructions (its SKILL.md), or a file it references such as references/rules.md. Fetched once, then cached.",
@@ -42,6 +41,8 @@ export async function serve(load, cacheDir) {
42
41
  file: z.string().optional().describe("A file the skill's instructions point to, relative to SKILL.md"),
43
42
  },
44
43
  annotations: { readOnlyHint: true },
44
+ // Claude Code defers MCP tools behind a ToolSearch step; this loads them up front (saves a turn per skill load).
45
+ _meta: { "anthropic/alwaysLoad": true },
45
46
  }, async ({ id, file }) => {
46
47
  const s = router().get(id);
47
48
  if (!s)
package/dist/types.d.ts CHANGED
@@ -14,6 +14,10 @@ export interface Skill {
14
14
  install?: string;
15
15
  /** Raw SKILL.md URL pinned to a commit, so the body can be fetched on demand and cached forever. */
16
16
  source?: string;
17
+ /** Words users type when they need this skill ("cramped", "janky hover"). Indexed, never shown. */
18
+ keywords?: string[];
19
+ /** The id this skill was renamed to upstream; the router routes to that one instead. */
20
+ replacedBy?: string;
17
21
  /** Path to SKILL.md when installed on this machine. */
18
22
  path?: string;
19
23
  }
@@ -36,6 +40,11 @@ export interface RouteResult {
36
40
  /** True when nothing cleared the threshold: the router's honest "no skill fits". */
37
41
  none: boolean;
38
42
  via: "lexical" | "llm";
43
+ /**
44
+ * 0..1, how sure the top pick is. Lexical: rarity-weighted share of the task the best skill covers
45
+ * on its own. LLM: the model's top confidence. 1 when the task names a skill.
46
+ */
47
+ confidence: number;
39
48
  }
40
49
  /** Any text-completion function. Keeps the router free of provider SDKs. */
41
50
  export type Complete = (prompt: string) => Promise<string>;
@@ -0,0 +1,234 @@
1
+ # Integrating skill-router into an app or agent
2
+
3
+ This guide is written so that a person, or a coding agent (Claude Code, Cursor, Codex, …) handed this file, can add skill routing to an app that runs an AI agent. Follow it top to bottom. Every step ends with a check.
4
+
5
+ > **Agents:** do the steps in order and run each check before moving on. Don't skip the bundling step (step 5) if the app bundles its server.
6
+
7
+ ## What you're adding
8
+
9
+ Your agent gets the right skill, meaning expert instructions in a `SKILL.md`, for the task at hand. You don't install every skill or paste them all into the prompt. The router keeps a small index of skill names, descriptions and problem keywords. It ships with 256 web-design skills, and you can add your own. For each task, it does three things:
10
+
11
+ 1. **Shortlists** candidates with offline word matching (BM25 plus problem keywords). Building the index takes about 11 ms at startup, and each query takes about 0.1 ms.
12
+ 2. **Lets a model pick** from the shortlist: either your agent itself, or a cheap model you plug in.
13
+ 3. **Loads only the picked skill's instructions**, fetched once from a commit-pinned URL and cached.
14
+
15
+ **Step 2 is not optional for quality.** On a blind test of 101 realistic prompts:
16
+
17
+ | | Word matching alone | Model picks from top 40 |
18
+ |---|---|---|
19
+ | Right skill first | 48% | **73%** |
20
+ | Symptom prompts ("people bounce in 3 s") | 33% | **76%** |
21
+ | Off-topic correctly rejected | 5/20 | **19/20** |
22
+ | Right skill somewhere in the top 40 | 98% | — |
23
+
24
+ Word matching is good at getting the right skill *into* the list, and a model is good at picking it *out*. Design your integration so a model makes the final pick from a wide list.
25
+
26
+ ## Step 1: Install
27
+
28
+ ```sh
29
+ npm i @originkit/skillrouter # Node ≥ 22, ESM (CommonJS require() also works)
30
+ ```
31
+
32
+ Use version **0.1.1 or later**: it has the problem keywords, `confidence`, and the 40-candidate default.
33
+
34
+ ✅ Check: `node -e 'import("@originkit/skillrouter").then(m => console.log(Object.keys(m)))'` lists `createRouter`, `loadPack` and `loadSkillBody`.
35
+
36
+ ## Step 2: Build one router at startup
37
+
38
+ ```ts
39
+ import { createRouter, loadPack, loadSkillsDir, loadSkillBody } from "@originkit/skillrouter";
40
+
41
+ // Once per process, not per request.
42
+ export const router = createRouter([
43
+ ...loadPack(), // the bundled 256 web-design skills (+ their keywords)
44
+ // ...loadSkillsDir("./skills"), // optional: your own SKILL.md folders
45
+ // ...skillsFromDb, // optional: { id, name, description, source?, keywords? }[]
46
+ ]);
47
+ ```
48
+
49
+ Choose which skills the router knows:
50
+ - **Server or multi-user app:** the catalog plus your own skills only. **Don't** call `discoverSkills()`, which reads `~/.claude/skills` and similar folders on the machine it runs on. That's right for a personal CLI tool and wrong for a server, because every user would see whatever happens to be installed on the host.
51
+ - **Your own catalog instead of the pack:** pass `Skill` objects. `id` must be unique; use `owner/repo/skill`, because names collide (`seo` exists in 4 repos). Add `source` (a raw `SKILL.md` URL **pinned to a commit**) so `loadSkillBody` can fetch it. Add `keywords` (the words users type when they need the skill: "cramped", "janky", "nobody clicks") for much better recall.
52
+
53
+ ✅ Check: `(await router.route("our pricing page buttons feel flat", { k: 40, relative: 0 })).matches.some(m => m.skill.name === "make-interfaces-feel-better")` is `true`.
54
+
55
+ ## Step 3: Choose an integration pattern
56
+
57
+ | Your app… | Use |
58
+ |---|---|
59
+ | runs an agent with tools (Claude Agent SDK, Vercel AI SDK, OpenAI tools, LangChain, MCP) | **Pattern A: two tools.** The agent picks. Recommended. |
60
+ | builds one prompt per request with no tool calls | **Pattern B: route before the call.** A cheap model picks, and you inject the instructions. |
61
+ | is a user's own coding agent (Claude Code, Cursor, Desktop, Codex) | Not this guide: use the plugin or MCP server ([README](../README.md#install)). |
62
+
63
+ ### Pattern A: two tools, the agent picks (recommended)
64
+
65
+ Give the agent a **wide, cheap list** (40 one-line candidates, about 1.3k tokens) and a way to load one. Don't pre-filter to 3: the right skill often isn't first by word matching, because tasks name their page ("pricing page") as loudly as their problem ("buttons feel flat").
66
+
67
+ The tool logic is shared by every framework:
68
+
69
+ ```ts
70
+ import type { Skill } from "@originkit/skillrouter";
71
+
72
+ const CACHE_DIR = "/var/cache/my-app/skills"; // writable; on serverless use os.tmpdir() or omit (memory only)
73
+
74
+ export async function findSkill(task: string): Promise<string> {
75
+ const res = await router.route(task, { k: 40, relative: 0 });
76
+ if (res.none) return "No skill fits this task. Go ahead without one.";
77
+ const lines = res.matches.map(({ skill: s, mentioned }, i) => {
78
+ const tags = [
79
+ mentioned ? "named in the task" : i === 0 && res.confidence >= 0.5 ? "strong match" : "",
80
+ s.warnings?.length ? `caution: ${s.warnings.join("; ")}` : "",
81
+ ].filter(Boolean);
82
+ const about = (s.summary ?? s.description).replace(/\s+/g, " ").slice(0, 200);
83
+ return `- ${s.id}: ${about}${tags.length ? ` [${tags.join(", ")}]` : ""}`;
84
+ });
85
+ return `${lines.join("\n")}\n\nRead the whole list and judge: word matching ranks the page a task mentions as highly as its problem, so the best skill may be far down. Load a pick with use_skill.`;
86
+ }
87
+
88
+ export async function useSkill(id: string, file?: string): Promise<string> {
89
+ const skill = router.get(id);
90
+ if (!skill) return `Unknown skill id: ${id}`;
91
+ // file: a reference the instructions point to, e.g. "references/rules.md". Paths outside the skill are refused.
92
+ const body = await loadSkillBody(skill, { file, cacheDir: CACHE_DIR }).catch((e: Error) => `Error: ${e.message}`);
93
+ return body ?? `${id} has no ${file ?? "instructions"} available.`;
94
+ }
95
+ ```
96
+
97
+ Then register them in your framework.
98
+
99
+ **Claude Agent SDK** (`@anthropic-ai/claude-agent-sdk`):
100
+ ```ts
101
+ import { createSdkMcpServer, tool } from "@anthropic-ai/claude-agent-sdk";
102
+ import { z } from "zod";
103
+
104
+ const text = (t: string) => ({ content: [{ type: "text" as const, text: t }] });
105
+ export const skillTools = createSdkMcpServer({
106
+ name: "skills",
107
+ alwaysLoad: true, // no ToolSearch turn before the first use
108
+ version: "1.0.0",
109
+ tools: [
110
+ tool("find_skill", "Find expert skills for the current task. Returns ~40 candidates, one line each.", { task: z.string() },
111
+ async ({ task }) => text(await findSkill(task)), { annotations: { readOnlyHint: true } }),
112
+ tool("use_skill", "Load a skill's instructions (SKILL.md) or a file they reference.", { id: z.string(), file: z.string().optional() },
113
+ async ({ id, file }) => text(await useSkill(id, file)), { annotations: { readOnlyHint: true } }),
114
+ ],
115
+ });
116
+ // query({ prompt, options: { mcpServers: { skills: skillTools }, ... } })
117
+ ```
118
+
119
+ **Vercel AI SDK** (`ai` v5+):
120
+ ```ts
121
+ import { tool, stepCountIs, generateText } from "ai";
122
+ import { z } from "zod";
123
+
124
+ const tools = {
125
+ find_skill: tool({ description: "Find expert skills for the current task (~40 candidates, one line each).",
126
+ inputSchema: z.object({ task: z.string() }), execute: async ({ task }) => findSkill(task) }),
127
+ use_skill: tool({ description: "Load a skill's instructions (SKILL.md) or a file they reference.",
128
+ inputSchema: z.object({ id: z.string(), file: z.string().optional() }), execute: async ({ id, file }) => useSkill(id, file) }),
129
+ };
130
+ // generateText({ model, system, prompt, tools, stopWhen: stepCountIs(10) })
131
+ ```
132
+
133
+ **Any function-calling API** (OpenAI, Anthropic Messages, Gemini, …): declare `find_skill { task: string }` and `use_skill { id: string, file?: string }` as JSON-schema tools, and call `findSkill` / `useSkill` when the model invokes them.
134
+
135
+ **System prompt:** add this line, or the agent will rarely call the tools:
136
+ ```
137
+ Before design, copy, SEO, accessibility, performance or motion work, call find_skill with the task. If a skill fits, load it with use_skill and follow it; if none fits, go ahead without one.
138
+ ```
139
+ Adapt the list of work types to your catalog.
140
+
141
+ ✅ Check: ask your agent "our pricing page buttons feel flat". Its trace should show `find_skill`, then `use_skill("jakubkrehel/make-interfaces-feel-better/make-interfaces-feel-better")`, then work that follows those instructions. Ask "write a bash one-liner to rename .jpeg files": it should either not call `find_skill` or get "No skill fits".
142
+
143
+ ### Pattern B: route before the call, a cheap model picks
144
+
145
+ Use this when there's no tool loop. A small model picks from the top 40, which is the rerank measured above. It returns JSON naming its picks and the confidence, or none.
146
+
147
+ ```ts
148
+ const complete = async (prompt: string) => (await generateText({ model: "anthropic/claude-haiku-5-5", prompt })).text;
149
+ // or any provider: (prompt) => Promise<string> returning the model's text
150
+
151
+ const res = await router.route(userMessage, { complete, k: 2 }); // candidates defaults to 40
152
+ let system = baseSystemPrompt;
153
+ for (const { skill, score } of res.matches) {
154
+ if (score < 0.5) continue; // model's confidence
155
+ const body = await loadSkillBody(skill, { cacheDir: CACHE_DIR });
156
+ if (body) system += `\n\n<skill id="${skill.id}">\n${body}\n</skill>`;
157
+ }
158
+ ```
159
+
160
+ A rerank costs one small-model call of about 6k input tokens per message. To skip it for messages that obviously need no skill, check `router.route(msg)` first without `complete`, and rerank only when `!res.none`.
161
+
162
+ ✅ Check: the three prompts from Pattern A. The flat-buttons prompt injects `make-interfaces-feel-better`, and the bash prompt injects nothing.
163
+
164
+ ## Speed: what routing costs per generation
165
+
166
+ Routing itself takes about 0.1 ms. The time goes into **model turns** and **longer, skill-guided output**. These were measured in Claude Code with Sonnet, using the same tasks with and without the router:
167
+
168
+ | Task | No skills | With router |
169
+ |---|---|---|
170
+ | "our pricing page buttons feel flat, fix it" | 12.6 s | 13.4–14.5 s (loads `make-interfaces-feel-better`) |
171
+ | "add JSON-LD for our product" | 7.6 s | 11.7 s (loads `schema`) |
172
+ | "people leave within seconds, just tell me why" | 14.5 s | 14.0–16.3 s (answers directly, no skill) |
173
+
174
+ To keep a generation fast:
175
+ - **Put the shortlist in the prompt instead of a `find_skill` turn.** Route the user's message on your server before the model call (`router.route(msg, { k: 8, relative: 0, minCoverage: 0.1 })`), and when `!res.none && res.confidence >= 0.15`, add the 8 one-line candidates (~300 tokens) to that run's system prompt: "these skills match this request (already routed, so find_skill isn't needed); pick the best fit, not necessarily the first, load it with use_skill and follow it; skip only if none is about this task." Each tool turn you avoid saves roughly 4–5 s with Sonnet. Keep `find_skill` available for later turns. Why 8 lines and a low threshold: on the blind test that lists the right skill for 89% of real tasks (5 lines at 0.25 listed 77%), and in real Claude Code sessions a list that didn't fit was ignored every time (0 wrong loads on 9 off-topic prompts).
176
+ - **Keep the skill tools loaded up front.** Claude Code and the Agent SDK can defer tools until a `ToolSearch` step, which costs a turn. Mark them always-loaded: `createSdkMcpServer({ …, alwaysLoad: true })` with the Agent SDK, or `_meta: { "anthropic/alwaysLoad": true }` on each tool of a stdio MCP server (skill-router's own MCP server does this).
177
+ - **Pre-warm the cache at startup**, in the background, so `use_skill` never waits on the network (about 0.5 s per first fetch): `for (const s of router.skills) loadSkillBody(s, { cacheDir }).catch(() => {})`.
178
+ - **Route once per task, not per chat message.** "Thanks" or "make it bigger" shouldn't re-route; the router answers "no fit" for chit-chat anyway.
179
+ - **Pattern B's rerank** adds one small-model call before the main one. Through `claude -p` it measured about 3–4 s including process start; a direct API call to a small model is usually faster. Use it when accuracy matters more than a few seconds, or run it in parallel with other setup.
180
+ - **Skills make answers more thorough**, which means more output tokens. That's the quality you're buying. If a step must be minimal, say so in that step's prompt.
181
+
182
+ ## Step 4: Handle what the skill says
183
+
184
+ - **Instructions are text, not code.** Never execute scripts a skill mentions unless your agent already has a sandboxed shell and the user approves. `loadSkillBody` only returns text.
185
+ - **Show cautions.** Skills with `warnings` (audit warnings, "moved upstream") come back tagged `caution:`. The system-prompt line plus the tag is usually enough; for stricter apps, filter `s.warnings?.length` out of `findSkill`.
186
+ - **Treat skill text as instructions from a third party.** Only route over catalogs you trust. The bundled pack lists skills that pass, or are flagged by, three security audits, pinned to reviewed commits.
187
+
188
+ ## Step 5: Bundling and deploying
189
+
190
+ The pack's data files are resolved relative to the library's own `dist/` folder:
191
+ `node_modules/@originkit/skillrouter/data/skills.json` and `…/data/keywords.json`.
192
+
193
+ - **Plain Node with `node_modules` deployed:** nothing to do.
194
+ - **Bundled server (esbuild, Rollup, webpack, `ncc`):** the relative path breaks. Copy both files next to your bundle at build time and pass the path:
195
+ ```js
196
+ // build script (example: esbuild)
197
+ await copyFile("node_modules/@originkit/skillrouter/data/skills.json", "dist/skills.json");
198
+ await copyFile("node_modules/@originkit/skillrouter/data/keywords.json", "dist/keywords.json");
199
+ ```
200
+ ```ts
201
+ // at runtime: loadPack reads keywords.json from the same folder as skills.json
202
+ import { fileURLToPath } from "node:url";
203
+ loadPack(fileURLToPath(new URL("./skills.json", import.meta.url)));
204
+ ```
205
+ If you skip `keywords.json`, routing still works but loses most of its recall on symptom-style prompts.
206
+ - **Serverless (Vercel, Lambda):** make sure the two JSON files are traced or included in the function bundle (Next.js: `outputFileTracingIncludes`). Use `os.tmpdir()` or no `cacheDir`, since the filesystem is read-only.
207
+ - **Network:** `use_skill` fetches from `raw.githubusercontent.com` the first time a skill is used. Allow it, or pre-warm the cache at build time by calling `loadSkillBody` for the skills you expect.
208
+
209
+ ✅ Check: in the built and deployed artifact, run `router.skills.length` (it should be 255 plus your own: 256 catalog entries, one renamed skill folded into its successor) and `router.skills.some(s => s.keywords?.length)` (it should be `true`).
210
+
211
+ ## Step 6: Test it
212
+
213
+ Add these as tests in your app's own framework:
214
+
215
+ | Input | Expect |
216
+ |---|---|
217
+ | `findSkill("our pricing page buttons feel flat")` | contains `make-interfaces-feel-better` |
218
+ | `findSkill("people bounce from our homepage in 3 seconds")` | contains `page-cro` (gone upstream, so tagged with a caution) or `cro-methodology` |
219
+ | `findSkill("run break-ui on the dashboard")` | first line is `emilkowalski/skills/break-ui` `[named in the task]` |
220
+ | `findSkill("fix my postgres migration")` | `No skill fits` |
221
+ | `useSkill(id, "../../etc/passwd")` | an error, never file contents |
222
+ | `useSkill("nope/nope")` | `Unknown skill id` |
223
+
224
+ ## Reference
225
+
226
+ - `router.route(task, { k, relative, minCoverage, complete, candidates })` → `{ matches: [{ skill, score, mentioned?, reason? }], none, via, confidence }`
227
+ - `confidence` is 0–1: how much of the task the top skill covers, or the model's confidence after a rerank. It's 1 when the task names a skill (`/break-ui`, "the seo skill", a full id).
228
+ - Defaults: `k` 3, `relative` 0.5, `candidates` 40.
229
+ - `router.search(task, limit)`: raw word-matching ranking, unfiltered.
230
+ - `router.get(id)`: also resolves old ids of renamed skills.
231
+ - `loadSkillBody(skill, { file?, cacheDir?, fetch? })`: reads the local `path`, or fetches `source` once and caches it.
232
+ - `createRouter(skills, { keywordBoost })`: default keyword weight 2.
233
+
234
+ A worked example in production: landers-app (`apps/server/src/app-tools.ts`, `find_skill` / `use_skill` on the Claude Agent SDK; `apps/server/scripts/build.mjs` copies the data files).