SLOPSHOPPER

jev-skill-suggestion

Keeps the skill listing out of the context window and lets TypeSafe's Jev, a System One decision model, pick at most one skill per prompt from the skills'…

guardstatusprompttoolmodelnetwork
★ 1v0.7.6MITupdated 2026-10-24audichuang/jev-skill-suggestion
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · jev-skill-suggestion
› fix the failing auth test and add an audit log call ● jev-skill-suggestion: [jev-skill-suggestion] find_skill not offered: it needs a TypeSafe or Gateway key and rerank on ● jev-skill-suggestion: [jev-skill-suggestion] ready on the built-in classifier, no key set; leaving the skill listing in place ⏺ Read(src/auth.ts) ⎿ Read 6 lines ⏺ Update(src/auth.ts) ⎿ Added 2 lines, removed 1 line ⏺ Bash(bun test) ⎿ 3 pass, 1 fail ● Done. refresh now rejects expired claims and logs an audit event. ✻ Worked for 42s · done 4:20 PM ● jev-skill-suggestion: [jev-skill-suggestion] no suggestion: no candidate skills ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts ⚠ jev-skill-suggestion: jev · no skill
README

jev-skill-suggestion

TypeSafe Jev, a System One decision model, picks at most one skill for each prompt you send and attaches that skill's SKILL.md to the prompt. Every other skill stays loadable: the model still sees each one by name and can load it with the Skill tool, so a skill that says "now use /other-skill" keeps working.

This is a Claude Code mod (a plugin whose behaviour lives in a hooks module). It started as a fork of jev-skill-suggestion in davila7/claude-code-templates at 55457cfcc7 (tag upstream-55457cf in this repository). See What changed from upstream.

Why the fork

Upstream's setup set every skill to user-invocable-only and turned on disableBundledSkills. That takes skills off the listing, and it also makes the Skill tool refuse every hidden skill. So the model could use only the one skill the mod injected (upstream #1013):

  • a skill that tells the model to load a second skill fails at that step;
  • a project rule such as "run /code-review before you commit" fails;
  • subagents cannot load any hidden skill;
  • when Jev picks the wrong skill, or none, the model cannot load the right one;
  • /simplify, /loop and the other bundled skills disappear, typed or not.

Claude Code has a gentler state: "name-only" in skillOverrides keeps the skill in the listing as - name, without its description, and the Skill tool still loads it. That keeps most of the context saving, because the descriptions are most of the listing. This fork's setup writes name-only, keeps the listing in place by default, and never touches the bundled skills.

Install

Requires Claude Code 2.1.287 or newer (mods load by default from there). The find_skill tool was verified on 2.1.299.

From the marketplace (any machine):

/plugin install jev-skill-suggestion --marketplace audichuang/jev-skill-suggestion

or from a shell:

claude plugin marketplace add audichuang/jev-skill-suggestion
claude plugin install jev-skill-suggestion@jev-skill-suggestion

From a clone, for every project (what you want while you edit it):

git clone https://github.com/audichuang/jev-skill-suggestion
ln -s "$PWD/jev-skill-suggestion" ~/.claude/skills/jev-skill-suggestion

A plugin folder under ~/.claude/skills/ loads in every project as jev-skill-suggestion@skills-dir. Under a project's own .claude/skills/ it loads only there, and only once you trust the project. Keep one copy: two plugins with the same name shadow each other, and /plugin reports the one it dropped.

Switching from npx claude-code-templates --mod: delete the project's .claude/skills/jev-skill-suggestion first. If you ran upstream's setup, change its user-invocable-only entries in ~/.claude/settings.json to name-only by hand (this fork's setup leaves existing user-invocable-only entries alone), and remove "disableBundledSkills": true if you want the bundled skills back.

Configure

The key. Set TYPESAFE_API_KEY (or AI_GATEWAY_API_KEY for the Vercel AI Gateway) in the environment Claude Code starts from, and the mod uses it. A key in the plugin options wins over the environment. Options live in user settings only (~/.claude/settings.json, or $CLAUDE_CONFIG_DIR/settings.json), under the plugin's id:

{ "pluginConfigs": { "jev-skill-suggestion@skills-dir": { "options": { "rerankTimeoutMs": 2500 } } } }

The id follows how the plugin was loaded: jev-skill-suggestion@skills-dir from a skills folder, jev-skill-suggestion@jev-skill-suggestion from the marketplace, jev-skill-suggestion with --plugin-dir. Under the wrong id every option stays at its default.

Two things to know about a key stored as an option. Claude Code reads a plaintext key from settings.json, but a value saved through /config goes to the keychain, wins over the file, and removes the plaintext copy. The environment variable avoids both: it never lands in a settings file you might commit.

With no key at all, the mod falls back to Claude Code's built-in classifier: one request, no gate, no rerank, and no time limit.

Trim the listing (optional). Run /jev-skill-suggestion:setup. It shows the user skills it will set to name-only and asks before it edits anything. It writes the old values to jev-skill-suggestion.skill-overrides.backup.json next to your settings. /jev-skill-suggestion:setup restore puts them back. Skills that are already name-only, user-invocable-only or off stay as they are. Plugin skills cannot be trimmed this way. Project skills (.claude/skills in the project) are left with their descriptions: they are the few that project needs most, and you choose how many there are. An earlier version did trim them; to give them back their descriptions, delete their entries from skillOverrides.

Restart Claude Code after either step.

Check that it works

Send a prompt in any project. The transcript should show:

[jev-skill-suggestion] ready on typesafe (https://api.typesafe.ai/v1/systemone); leaving the skill listing in place
[jev-skill-suggestion] jev: needs a skill 0.76 · top of 58: pptx-author (0.70), … · 160ms
  • ready on the built-in classifier, no key set: the key was not found. Check the environment Claude Code was started from, or the pluginConfigs id.
  • typesafe responded 401 to the ranking: the key is wrong. The prompt goes through with no suggestion.
  • No lines at all: the plugin did not load. Run claude --debug and look for hooks module jev-skill-suggestion@… loaded.

How it works

HookWhat it does
prompt.submitRuns the two requests below on the prompt you sent. It attaches the winner, if any, as a <skill_relevance> block the model reads and you never see. With inject: "content" (the default) the block holds the skill's SKILL.md; with inject: "suggest" it holds only the name, and the model loads the skill itself.
prompt.attachment on skill_listingLeaves the listing alone by default. With hideListing: true it withholds the listing, or trims it to the names in alwaysListed.
session.start, tool.describe, tool.callThe find_skill tool (see below): registered when the session starts, kept out of ToolSearch so the model sees its description from the first request, and answered with the same two requests.
skill.promptLogs whether a skill the model loaded was the suggested one, and writes the prompt of /jev-skill-suggestion:setup.

When it decides. Once per prompt you send, from that prompt's text alone. A long turn can run into sub-tasks the prompt never named, and with name-only the model sees those skills by name only. For that, the mod gives the model a find_skill tool. The model calls it with the sub-task in one sentence, and Jev answers with at most one skill: its name and the description the listing leaves out. The model then loads it with the Skill tool, or ignores it. Nothing is pushed mid-turn. A skill that hands off to another skill works as it does without the mod.

find_skill offers only skills the main conversation's listing names, because the Skill tool loads only those. It leaves out the gate questions a prompt must pass: a model that calls find_skill has already decided it wants a skill, and one sub-task sentence without its conversation scores low on them. The rerank's fits check is then the only check, so a pick the rerank never read is not answered, and the tool is offered only with a TypeSafe or Gateway key and rerank on. When a request fails or times out, it says the lookup is unavailable rather than "no skill fits". It answers a name and never a SKILL.md: a skill loaded with the Skill tool is attached again after a compaction, and one attached by the mod is not. findSkill: false turns the tool off. The tool's description and schema cost about 160 tokens in every session.

What it attaches:

<skill_relevance>
Relevant to the current request: commit. Ignore this if it does not fit what the user actually asked for.
Its instructions follow: follow them now, including any setup steps. Do not load it again with the Skill tool: it is already loaded here. Its files are in /home/me/.claude/skills/commit.
<skill name="commit" dir="/home/me/.claude/skills/commit">
…the SKILL.md body, frontmatter off, ${CLAUDE_SKILL_DIR} and ${CLAUDE_PROJECT_DIR} filled in…
</skill>
</skill_relevance>

A skill already injected is only named again on later prompts, until /clear, a resume or a compaction. When nothing is picked, nothing is attached, so the model is free to load a skill from the listing.

Candidates. Every skill $.command.list() reports, except built-ins, names in neverSuggested, and skills set to off in your user settings. A skill whose frontmatter says disable-model-invocation: true is never picked.

Known limits.

  • An injected skill skips what the Skill tool does: the skill's allowed-tools are not applied.
  • The mod cannot see which skills the model loaded itself, so a skill the model already loaded can be injected a second time later.
  • TypeSafe's choice question takes at most 255 options, so a roster larger than that gets HTTP 400 (upstream #965).

How it decides

Two requests, in the cookbook's shape. Each may come back empty-handed.

Request 1 — skim every skill. One choice (which) over every candidate, with its one-line description as the criterion; its probability distribution is the ranking. Beside it, four nouls about the request, not about any skill:

noulasks
acts_on_user_systemIs the assistant being asked to act on the user's files, accounts, devices or services, rather than only to explain or advise?
would_follow_documented_procedureWould a careful expert consult a specific documented procedure or set of commands, rather than answer from general understanding?
prose_sufficesCould a knowledgeable generalist fully satisfy this in prose, with no tools and no access to the user's files? (counts the other way round)
names_its_taskCould someone start on this message without having read the conversation before it? Mentions of the user's own files, branch, project or conventions are fine; only references to earlier messages are not.

Their mean is the gate: under gateThreshold (0.30) nothing is suggested, whatever the ranking said. Questions about subject matter would not do this job — explain what a monad is and a task that needs a skill are both software. names_its_task is this fork's: Jev reads the prompt alone, and a follow-up such as "好幫我完成優化吧" carries its task in earlier turns, so without it such replies were ranked as if they were tasks (see evals/).

Request 2 — read the top three properly. The same choice over the shortlist (shortlist, 3), now with each skill's full frontmatter description and the first excerptChars (700) of its SKILL.md as the criterion, and one noul per candidate — does this skill do the specific thing the request asks for? — answered on its own, so all of them can come back low. A shortlist whose best fits is under fitsThreshold (0.50) is dropped entirely, and when names_its_task came back under 0.3 the bar is 0.80; otherwise the choice's winner is suggested, provided its own fits clears the same bar (a winner the nouls do not back is not suggested). The two decide different things: the choice settles which, the nouls settle whether.

This is where lookalikes separate — on one line the skill that edits .pptx files reads nearly the same as the one that authors them; on 700 characters they do not.

The skill bodies come from disk, by where Claude Code keeps them: .claude/skills/<name>/SKILL.md and .claude/commands/<name>.md in the project and under ~, ~/.claude/skills/synced/<account>/<name>/SKILL.md for a skill synced from claude.ai, and for a plugin's skill its install path from ~/.claude/plugins/installed_plugins.json. A body that cannot be found leaves that candidate with its one-line description; the request still goes out. Bodies are read once per session, and the same read is what gets injected.

  • The Gateway answers a noul as a boolean with a probability; both shapes are read.
  • rerank: false skips the second request and suggests the top of the ranking, once the gate passes. A second request that was attempted and failed suggests nothing: the ranking's winner has not had its false-positive check. Nor does a pick the rerank never read, as when every shortlisted skill has disable-model-invocation and the ranking's next one would stand.
  • A skill whose frontmatter says disable-model-invocation: true is never suggested, whichever path picked it: the engine leaves it out of the listing and the Skill tool refuses it. Before the first listing has been seen the candidates come from $.command.list(), which also names such skills, so their SKILL.md is the check (read for the shortlist and for the winner).
  • The built-in classifier answers one label from the descriptions, with no gate and no second request.

Every failure — a non-2xx response, a timeout past timeoutMs (ranking) or rerankTimeoutMs (rerank), a thrown error, a malformed body — lets the prompt through with no suggestion. The mod never blocks a prompt.

Prompts that are not a task get no suggestion: notifications, peer messages, observer reports, a prompt that is itself a /name (its skill is already named), and a reply with no task of its own — no letters at all (2, 👍), or a stock go-ahead such as ok, continue, 好, 繼續. The decision model reads the prompt alone, so it could only guess at those; the model keeps whatever the task already loaded.

What you see in the transcript

With logDecisions on (the default), the mod reports every step of its own work, because nothing else in Claude Code shows it — a listing that was never sent leaves no trace:

[jev-skill-suggestion] ready on typesafe (https://api.typesafe.ai/v1/systemone); leaving the skill listing in place
[jev-skill-suggestion] jev: needs a skill 0.76 · top of 58: powerpoint (0.70), pptx-author (0.30), chroma (0.00) · 160ms
[jev-skill-suggestion] jev: rerank → pptx-author (0.81) · fits powerpoint 0.73, pptx-author 0.84, chroma 0.02 · 90ms · 3/3 bodies read
[jev-skill-suggestion] suggesting /pptx-author: rerank of 3, fits 0.84
[jev-skill-suggestion] injected /pptx-author from /home/me/.claude/skills/pptx-author/SKILL.md (4210 characters)
[jev-skill-suggestion] jev: needs a skill 0.12 · top of 58: debug (0.41), code-review (0.22), commit (0.05) · 150ms
[jev-skill-suggestion] no suggestion: needs a skill 0.12 < 0.3
  • The first line appears once per session, the first time a hook runs. It is the proof the module loaded and which backend answers it.
  • The two jev: lines are what the decision model replied to each request, before any policy is applied — the gate, the top of the ranking, then the rerank's winner and every fits, with how long each call took and how many SKILL.md bodies were found.
  • injected /name from <file> is the skill going in with the prompt; already injected this session; named again on a repeat.
  • withheld the skill listing appears only with hideListing: true: the listing hook firing, with what it cost the context and what it kept. While some listed skills still bring their whole description, the mod adds N skills are still listed with a full description; run /jev-skill-suggestion:setup … once per session.
  • find_skill "<sub-task>": suggesting /name (or no suggestion, or lookup unavailable) is the model calling find_skill mid-turn, after the same jev: lines.
  • skill /name loaded is the model calling the Skill tool on its own (inject: "suggest", or a typed /name): as suggested, or which skill was suggested instead when it reached for another.

It also keeps a one-line status on screen, replaced as it goes:

jev · skill: pptx-author
jev · no skill

Reading decisions back

The transcript lines scroll away, and a headless run writes them only to its debug log. With recordDecisions on (the default), every decision also goes to one file per session, ~/.claude/jev-skill-suggestion/decisions/<session id>.jsonl (under CLAUDE_CONFIG_DIR when set), one JSON object per line:

{"at":"2026-10-16T08:12:03.120Z","source":"prompt","text":"畫一張 web 服務的架構圖","pick":"drawio-skill","reason":"rerank of 3, fits 0.91","answered":true,"ms":1180,"model":"jev-1.13.0","gate":0.71,"gateValues":{…},"top":[{"name":"drawio-skill","probability":0.62},…],"rerank":{"winner":"drawio-skill","confidence":0.88,"fits":{…}}}
{"at":"2026-10-16T08:12:09.402Z","loaded":"drawio-skill","suggested":"drawio-skill"}

source is prompt or find_skill; a loaded line is the model calling the Skill tool, with the pick it was made under. The file holds the request text as typed: it never leaves the machine, and is there so a wrong suggestion can be read back and turned into a test case. Set recordDecisions: false to keep nothing.

To list every recorded decision, newest session files included:

cat ~/.claude/jev-skill-suggestion/decisions/*.jsonl | jq -c 'select(.source) | {source, pick, reason, text: .text[0:60]}'

No lines at all has three causes, and only the last is the module failing to load. Check them in this order:

  1. You ran claude -p (or the SDK). A headless run has no transcript and no status row: every line still goes to the debug log, ~/.claude/debug/<session-id>.txt (a .txt, not a .log; latest is a symlink to the newest), and an SDK host receives each one as ui_log.
  2. The plugin was never loaded. Claude Code adopts a plugin from a project's .claude/skills/ only once the project is trusted: it is repository content, so an untrusted folder's .claude/ is not read at all, and claude -p never asks. Open claude interactively in the folder and accept the trust prompt, or name the plugin explicitly with --plugin-dir (see Install). claude --debug settles it: a loaded module prints hooks module jev-skill-suggestion@skills-dir loaded (worker, …); events: prompt.attachment,prompt.submit,skill.prompt (@inline when loaded with --plugin-dir); Found N plugins without it means the plugin is not in the session.
  3. Claude Code is too old. Mods are on by default from 2.1.287; on an older build the debug log says installed plugins' hooks modules not loaded: rollout flag (tengu_plugin_hooks_modules) is off. Update Claude Code (this mod needs 2.1.278+, see below).

A ready on the built-in classifier, no key set line when you did set a key means the key sits under the wrong pluginConfigs entry: the key must match the plugin's id, which depends on how it was loaded (see Options).

Privacy

With a key set, the prompt text and every candidate skill's name and one-line description leave the machine on the first request, and the first excerptChars of each shortlisted skill's SKILL.md on the second, to whichever backend the key belongs to. Nothing else. With no key set, nothing leaves the machine.

Options

  typesafeApiKey:   string  TypeSafe API key; empty reads TYPESAFE_API_KEY
  gatewayApiKey:    string  Vercel AI Gateway key; empty reads AI_GATEWAY_API_KEY
  provider:         string  "auto" | "typesafe" | "gateway" | "builtin"
  typesafeBaseUrl:  string  empty uses https://api.typesafe.ai
  typesafeModel:    string  empty uses jev-1.14.0
  gatewayBaseUrl:   string  empty uses https://ai-gateway.vercel.sh/v4/ai
  gatewayModel:     string  empty uses typesafe-ai/jev
  inject:           string  "content" attaches the chosen SKILL.md (default); "suggest" names it for the Skill tool
  hideListing:      boolean withhold the engine's skill listing (default false)
  rerank:           boolean second request over the shortlist (default true)
  shortlist:        number  how many of the ranking the second request re-reads (default 3)
  gateThreshold:    number  gate mean under which nothing is suggested (default 0.3)
  fitsThreshold:    number  best `fits` under which the shortlist is dropped (default 0.5)
  excerptChars:     number  SKILL.md characters each candidate brings (default 700)
  alwaysListed:     string  comma-separated names kept when hideListing is on
  neverSuggested:   string  comma-separated names never offered to the decision model
  timeoutMs:        number  latency budget for the ranking request (default 800)
  rerankTimeoutMs:  number  latency budget for the rerank request (default 2500)
  findSkill:        boolean give the model the find_skill tool for mid-turn sub-tasks (default true; needs a key and rerank on)
  logDecisions:     boolean log each decision (default true)
  recordDecisions:  boolean keep every decision in a file per session (default true)
  sendRecentContext: boolean send the previous user message and the end of the last reply with the request (default true)

What changed from upstream

ChangeUpstream reference
Setup writes name-only, treats name-only as already done, and never sets disableBundledSkills. Restore leaves disableBundledSkills alone.#1013
hideListing defaults to false. The "run setup" hint fires only while listed skills still carry a description.#1013
Content mode attaches nothing when nothing is picked. Upstream attached "No skill in the roster appears relevant", which talked the model out of loading one itself.—
A key can come from TYPESAFE_API_KEY / AI_GATEWAY_API_KEY.#954 (closed upstream)
Gateway requests send ai-gateway-protocol-version.#1123
Setup trims user skills only: a project's own skills keep their descriptions, so the person decides how much of the listing they take. Upstream trims project skills too.#1123
The rerank request gets its own budget, rerankTimeoutMs, default 2500 ms.#962
Settings, skills, plugin records and the backup follow CLAUDE_CONFIG_DIR.#1042
Replies with no task of their own (ok, 2, 繼續) are not ranked.#1081
A prompt that opens with a path (/Users/me/app 幫我看看) is ranked; only a first word with no second / counts as a typed /name. Upstream skipped every prompt starting with /. Prompts dropped as a typed /name or a reply with no task are recorded too, with why, so a record shows what was never asked.—
A skill the Skill tool already loaded this session is named again with how to load it, not attached whole a second time. skill.prompt cannot tell a subagent's load from the main conversation's, so the model is told to load it itself if the instructions are not in its conversation; a skill missing from the main listing, which the Skill tool may refuse, still goes in whole.—
Skills set to off are never injected.—
A find_skill tool lets the model ask Jev mid-turn, so a sub-task that turns up after the prompt is not left to a guess from bare names.—
Every decision, with the request text and the ranking, is kept in a file per session (recordDecisions), so a wrong pick can be read back.—

| The turn before the request (

Source 2 files
hooks/jev-skill-suggestion.ts 863 lines
1/**
2 * jev-skill-suggestion — Claude Mod
3 *
4 * Takes the skill listing out of the context window and has TypeSafe's Jev,
5 * a System One decision model, suggest at most one skill per prompt, going
6 * by the skills' descriptions. The skills stay installed and loadable; what
7 * goes away is the listing the engine sends the model every session, one
8 * line per skill, whether the prompt has anything to do with any of them.
9 *
10 * The decision follows TypeSafe's "Skill suggestion" cookbook: two requests
11 * per prompt, one to rank every skill and ask whether the prompt needs a
12 * skill at all, one to re-read the top few with their full text and let each
13 * be rejected on its own. Either may come back empty-handed.
14 *
15 * The hooks:
16 *   prompt.attachment  — the engine's `skill_listing` attachment is answered
17 *                        with `{ text: null }` (left out) or trimmed to the
18 *                        names in `alwaysListed`. Its names are remembered:
19 *                        they are the engine's word on which skills the model
20 *                        may invoke.
21 *   prompt.submit      — the two requests run, and the winner (if any) is
22 *                        attached to the prompt as a `<skill_relevance>`
23 *                        block: with the skill's own SKILL.md inside it
24 *                        (`inject: "content"`, the default), so the skill
25 *                        loads even when `skillOverrides` hides it from the
26 *                        model, or with its name for the Skill tool
27 *                        (`inject: "suggest"`).
28 *   session.start, tool.describe, tool.call
29 *                      — the `find_skill` tool: registered when the session
30 *                        starts, kept out of ToolSearch so the model sees its
31 *                        description, and answered by the same two requests
32 *                        on the sub-task the model names. The prompt.submit
33 *                        pick covers the prompt; this covers what turns up
34 *                        mid-turn, for a model that sees most skills by name
35 *                        only. It answers a name for the Skill tool, never a
36 *                        SKILL.md.
37 *   skill.prompt       — observation: whether the model took the suggestion,
38 *                        or loaded a skill on its own. Also writes the prompt
39 *                        of the plugin's own `/jev-skill-suggestion:setup`,
40 *                        which hides every skill from the engine's listing
41 *                        (user-invocable-only) once the person has seen the
42 *                        list and said yes; the model makes the edit with its
43 *                        own tools, so it shows and asks like any other.
44 *
45 * Jev is reached one of two ways, whichever key is configured: TypeSafe's
46 * own API (`typesafeApiKey`), which reports a calibrated confidence, or the
47 * Vercel AI Gateway (`gatewayApiKey`), which does not. With neither, the
48 * engine's own `$.model.classify` stands in with a single request and no
49 * gate, so the mod is useful without any account.
50 *
51 * The candidates come from `$.command.list()`, not from the listing: the
52 * listing is only rendered at the turn's first request, after `prompt.submit`
53 * has run, so the first prompt of a session would otherwise have nothing to
54 * choose from. The listing, once seen, narrows the candidates to what the
55 * engine itself would have shown.
56 *
57 * The second request reads the opening of each shortlisted skill's SKILL.md,
58 * found on disk by how Claude Code lays skills out (project and user
59 * `.claude/skills` and `.claude/commands`, a plugin's install path from
60 * `~/.claude/plugins/installed_plugins.json`). A body that cannot be found
61 * leaves that skill with its one-line description; nothing fails over it.
62 *
63 * Only the main conversation is handled. A subagent's own listing is left as
64 * the engine renders it: its prompt is a tool call's argument, not a
65 * `prompt.submit`, so nothing here could suggest for it. `find_skill`, where a
66 * subagent is given it, is the exception (unverified: calls carry `agentId`).
67 *
68 * Every failure path is fail-open: a request that errors or runs past the
69 * latency budget lets the prompt through with no suggestion, and the listing
70 * hook always answers the same way, so the model's prompt cache holds.
71 *
72 * The API key comes from the plugin's options (userConfig "typesafeApiKey"
73 * or "gatewayApiKey"). Never hardcode it in this file.
74 *
75 * Needs Claude Code >= 2.1.278: the
76 * `prompt.attachment` event is that release's. Typed against Anthropic's
77 * declarations: https://github.com/anthropics/claude-code/tree/main/mods
78 *
79 * Privacy: with a key set, the prompt text, every candidate skill's name and
80 * description, and the opening of each shortlisted skill's SKILL.md are sent
81 * to whichever backend the key belongs to.
82 */
83import type { EngineInterface, Register } from 'claude-code'
84import {
85  DEFAULT_BASE_URL,
86  DEFAULT_EXCERPT_CHARS,
87  DEFAULT_MODEL,
88  FIND_SKILL_TOOL,
89  NONE,
90  SETUP_COMMAND,
91  builtinWide,
92  catalog,
93  classifyText,
94  commandLike,
95  configDirOf,
96  contextFree,
97  rerankCandidates,
98  routable,
99  typedCommand,
100  decide,
101  describeRerank,
102  describeSetup,
103  describeStatus,
104  describeStillListed,
105  describeWide,
106  detailOf,
107  displayIds,
108  canonical,
109  endpoint,
110  findSkillResult,
111  injectionBlock,
112  installPathsOf,
113  parseListing,
114  parseNames,
115  passesGate,
116  pluginFileCandidates,
117  readRerank,
118  readSkillSettings,
119  modelInvocable,
120  readWide,
121  recentContextOf,
122  modelOf,
123  recordLine,
124  rerankQuestions,
125  requestBody,
126  requestHeaders,
127  selectProvider,
128  setupAborted,
129  setupInstructions,
130  setupPlan,
131  shortlistOf,
132  validBackup,
133  skillFileCandidates,
134  suggestionBlock,
135  syncedFileCandidates,
136  trimListing,
137  underConfigDir,
138  wideQuestions,
139} from './policy.ts'
140import type { Candidate, PolicyConfig, Provider, RecentContext, Rerank, Skill, Trace, Wide } from './policy.ts'
141
142/** Prompt origins that are not a task of the person's: nothing to suggest for. */
143const NOT_A_TASK = new Set([
144  'task-notification',
145  'peer',
146  'peer-send-message',
147  'projects-relay',
148  'observer',
149  'observer-activity',
150])
151
152/** A SKILL.md as found on disk. */
153type SkillFile = { path: string; markdown: string }
154
155/** The backend the keys select, with where and as which model it is asked. */
156type Backend = { active: Provider | null; apiKey: string; modelId: string; url: string }
157
158/** What `choose` answers. */
159interface Choice {
160  pick: Skill | null
161  /** Why, for the log line. */
162  reason: string
163  file: SkillFile | null
164  /** False when a request failed or timed out: "no pick" is then not an answer. */
165  answered: boolean
166  /** What the requests answered, for the record file; null when none was asked. */
167  trace: Trace | null
168}
169
170/** What `choose` reads from the options, and the session state it shares with the hooks. */
171interface ChooseContext {
172  readonly backendOf: (typesafeEnv: string | undefined, gatewayEnv: string | undefined) => Backend
173  readonly forced: string
174  readonly neverSuggested: ReadonlySet<string>
175  readonly logDecisions: boolean
176  readonly recordDecisions: boolean
177  readonly sendRecentContext: boolean
178  readonly timeoutMs: number
179  readonly rerankTimeoutMs: number
180  readonly rerankEnabled: boolean
181  readonly excerptChars: number
182  readonly policy: PolicyConfig
183  // Session state, filled in as hooks run.
184  files: Map<string, SkillFile | null>
185  unusableReported: boolean
186  displayToId: Map<string, string> | null
187  /** Each session's record file as written so far, by session id. */
188  records: Map<string, string>
189}
190
191/**
192 * The turn before `current` (null mid-turn), sent beside the request; null
193 * when off or unreadable, and for a subagent, whose conversation is not the
194 * session's transcript.
195 */
196async function contextFor(
197  $: EngineInterface,
198  ctx: ChooseContext,
199  current: string | null,
200  agentId?: string,
201): Promise<RecentContext | null> {
202  if (!ctx.sendRecentContext || agentId) return null
203  try {
204    return recentContextOf(await $.session.messages(), current)
205  } catch (error) {
206    $.ui.log(`[jev-skill-suggestion] could not read the transcript: ${String(error)}`)
207    return null
208  }
209}
210
211/** A record file stops growing here, under `$.fs`'s 4 MiB per read and write. */
212const RECORD_LIMIT = 3_500_000
213
214/**
215 * Appends one line to the session's record file,
216 * `<config dir>/jev-skill-suggestion/decisions/<session id>.jsonl`. `$.fs`
217 * writes whole files, so the content so far is kept in memory, read back from
218 * disk the first time (a resumed session). Fails open, like everything else.
219 */
220async function record($: EngineInterface, ctx: ChooseContext, entry: Parameters<typeof recordLine>[1]) {
221  if (!ctx.recordDecisions) return
222  try {
223    const configDir = await configDirFor($)
224    if (!configDir) return
225    const id = await $.session.id()
226    const path = `${configDir}/jev-skill-suggestion/decisions/${id}.jsonl`
227    let content = ctx.records.get(id)
228    if (content === undefined) content = (await $.fs.exists(path)) ? await $.fs.read(path) : ''
229    const next = content + recordLine(await $.clock.now(), entry)
230    if (next.length > RECORD_LIMIT) return
231    ctx.records.set(id, next)
232    await $.fs.write(path, next)
233  } catch (error) {
234    $.ui.log(`[jev-skill-suggestion] could not record the decision: ${String(error)}`)
235  }
236}
237
238/** The user's config dir, or '' when HOME is unset and it cannot be named. */
239async function configDirFor($: EngineInterface): Promise<string> {
240  const home = (await $.env.get('HOME')) ?? ''
241  return home ? configDirOf(home, await $.env.get('CLAUDE_CONFIG_DIR')) : ''
242}
243
244/**
245 * Every command `$.command.list()` reports, under the id the engine lists,
246 * runs and overrides it by. Throws as `$.command.list()` does.
247 */
248async function listCommands($: EngineInterface, ctx: ChooseContext, configDir: string) {
249  const commands = await $.command.list()
250  if (!ctx.displayToId && commands.some((command) => !commandLike(command.name))) {
251    const found: { dir: string; markdown: string }[] = []
252    for (const dir of [`${await $.session.cwd()}/.claude/skills`, configDir && `${configDir}/skills`]) {
253      if (!dir || !(await $.fs.exists(dir))) continue
254      for (const entry of await $.fs.list(dir)) {
255        const file = `${dir}/${entry.name}/SKILL.md`
256        if (entry.kind === 'dir' && (await $.fs.exists(file))) found.push({ dir: entry.name, markdown: await $.fs.read(file) })
257      }
258    }
259    ctx.displayToId = displayIds(found)
260  }
261  return canonical(commands, ctx.displayToId ?? new Map())
262}
263
264/**
265 * Jev's pick for `text`, with the pick's SKILL.md when found, or null when
266 * the skills could not be listed. `restrictTo`, when
267 * non-empty, keeps the candidates to those names: the listing's, for a pick
268 * the model will load with the Skill tool (empty until the listing is seen).
269 * `askGate` off leaves the gate questions out, so the gate passes: a model
270 * that calls find_skill has already decided it wants a skill.
271 */
272async function choose(
273  $: EngineInterface,
274  ctx: ChooseContext,
275  text: string,
276  { restrictTo, askGate, context }: { restrictTo: ReadonlySet<string>; askGate: boolean; context: RecentContext | null },
277): Promise<Choice | null> {
278  const configDir = await configDirFor($)
279  const { active, apiKey, modelId, url } = ctx.backendOf(await $.env.get('TYPESAFE_API_KEY'), await $.env.get('AI_GATEWAY_API_KEY'))
280
281  /** One request to the active backend, or null on timeout, error or a non-2xx. */
282  const ask = async (
283    prompt: string,
284    questions: Record<string, unknown>,
285    what: string,
286    budgetMs: number,
287  ): Promise<string | null> => {
288    if (!active) return null
289    try {
290      const response = await Promise.race([
291        $.http.fetch(url, {
292          method: 'POST',
293          headers: requestHeaders(active, apiKey, modelId),
294          body: requestBody(active, prompt, questions, modelId, context),
295        }),
296        $.clock.sleep(budgetMs),
297      ])
298      if (response && response.ok) return response.text
299      if (response) $.ui.log(`[jev-skill-suggestion] ${active} responded ${response.status} to the ${what}`)
300      else $.ui.log(`[jev-skill-suggestion] ${what} passed ${budgetMs}ms; no suggestion`)
301    } catch (error) {
302      $.ui.log(`[jev-skill-suggestion] ${what} failed: ${String(error)}`)
303    }
304    return null
305  }
306
307  /** A skill's file, found on disk by Claude Code's layout, or null. */
308  const fileOf = async (
309    skill: Skill,
310    plugin: string | undefined,
311  ): Promise<SkillFile | null> => {
312    const cached = ctx.files.get(skill.name)
313    if (cached !== undefined) return cached
314    let found: SkillFile | null = null
315    try {
316      const relative = skillFileCandidates(skill.name, plugin)
317      // The engine reads the project's `.claude/` (the working directory
318      // only, not its ancestors) and the user's config dir.
319      const candidates = [...relative, ...(configDir ? relative.map((file) => underConfigDir(configDir, file)) : [])]
320      if (plugin && configDir) {
321        const installed = `${configDir}/plugins/installed_plugins.json`
322        if (await $.fs.exists(installed)) {
323          for (const path of installPathsOf(await $.fs.read(installed), plugin)) {
324            candidates.push(...pluginFileCandidates(path, skill.name, plugin))
325          }
326        }
327      }
328      // A claude.ai-synced skill sits under an account directory only
329      // `$.fs.list` can name.
330      if (configDir) {
331        const synced = `${configDir}/skills/synced`
332        if (await $.fs.exists(synced)) {
333          const accounts = (await $.fs.list(synced)).filter((entry) => entry.kind === 'dir').map((entry) => entry.name)
334          candidates.push(...syncedFileCandidates(configDir, accounts, skill.name))
335        }
336      }
337      for (const file of candidates) {
338        if (await $.fs.exists(file)) {
339          found = { path: file, markdown: await $.fs.read(file) }
340          break
341        }
342      }
343    } catch (error) {
344      $.ui.log(`[jev-skill-suggestion] could not read /${skill.name}: ${String(error)}`)
345    }
346    ctx.files.set(skill.name, found)
347    return found
348  }
349
350  if (!ctx.unusableReported && !active) {
351    ctx.unusableReported = true
352    $.ui.log(`[jev-skill-suggestion] provider "${ctx.forced}" has no key set; using the built-in classifier`)
353  }
354
355  let commands: Awaited<ReturnType<typeof $.command.list>>
356  try {
357    commands = await listCommands($, ctx, configDir)
358  } catch (error) {
359    $.ui.log(`[jev-skill-suggestion] could not list the skills: ${String(error)}`)
360    return null
361  }
362  // Loading the skill itself, the mod is not bound to what the engine would
363  // list, but a skill the person turned `off` stays off: the overrides are
364  // read from the user settings on every prompt, so an edit counts at once.
365  const off = new Set<string>()
366  try {
367    const settingsPath = `${configDir}/settings.json`
368    if (configDir && (await $.fs.exists(settingsPath))) {
369      const { skillOverrides } = readSkillSettings(await $.fs.read(settingsPath))
370      for (const [name, state] of Object.entries(skillOverrides)) if (state === 'off') off.add(name)
371    }
372  } catch (error) {
373    $.ui.log(`[jev-skill-suggestion] could not read the skill overrides: ${String(error)}`)
374  }
375  const skills = catalog(commands, restrictTo, new Set([...ctx.neverSuggested, ...off]))
376  if (skills.length === 0) {
377    return { pick: null, reason: 'no candidate skills', file: null, answered: true, trace: null }
378  }
379  const pluginOf = new Map(commands.map((command) => [command.name, command.plugin]))
380
381  // Request 1: rank everything, and ask whether the prompt wants a skill at all.
382  const startedAt = await $.clock.now()
383  let wide: Wide | null = null
384  let model: string | null = null
385  if (active) {
386    const answer = await ask(text, wideQuestions(active, skills, { askGate }), 'ranking', ctx.timeoutMs)
387    if (answer) {
388      wide = readWide(answer)
389      model = modelOf(answer)
390    }
391  } else {
392    // No backend: the engine's own small-model classifier answers the same
393    // question, with the descriptions folded into the text it reads. One
394    // label, no gate, no rerank.
395    try {
396      const label = await $.model.classify(classifyText(text, skills), [
397        NONE,
398        ...skills.map((skill) => skill.name),
399      ])
400      wide = builtinWide(label)
401    } catch (error) {
402      $.ui.log(`[jev-skill-suggestion] built-in classifier failed: ${String(error)}`)
403    }
404  }
405  // What the decision model actually answered, whatever the policy then
406  // does with it. This is the line that proves the ranking ran.
407  if (ctx.logDecisions) {
408    const ms = (await $.clock.now()) - startedAt
409    $.ui.log(`[jev-skill-suggestion] jev: ${describeWide(wide, skills.length, ms)}`)
410  }
411
412  // Request 2: re-read the shortlist with each skill's full text, and let
413  // every candidate be rejected on its own.
414  let rerank: Rerank | null = null
415  let rerankAttempted = false
416  // Before the listing has been seen, `$.command.list()` may name a skill
417  // the model is not allowed to invoke; its own frontmatter tells.
418  const barred: string[] = []
419  let offered = skills
420  if (active && ctx.rerankEnabled && wide && passesGate(wide, ctx.policy)) {
421    const bodies = new Map<string, string | null>()
422    for (const skill of shortlistOf(wide, skills, ctx.policy.shortlist)) {
423      bodies.set(skill.name, (await fileOf(skill, pluginOf.get(skill.name)))?.markdown ?? null)
424    }
425    const shortlisted = rerankCandidates(wide, skills, ctx.policy.shortlist, (name) => modelInvocable(bodies.get(name) ?? null))
426    barred.push(...shortlisted.barred)
427    offered = shortlisted.offered
428    const candidates: Candidate[] = shortlisted.candidates.map((skill) => ({
429      ...skill,
430      detail: detailOf(skill, bodies.get(skill.name) ?? null, ctx.excerptChars),
431    }))
432    if (candidates.length > 0) {
433      const rerankStartedAt = await $.clock.now()
434      rerankAttempted = true
435      const answer = await ask(text, rerankQuestions(active, candidates), 'rerank', ctx.rerankTimeoutMs)
436      if (answer) rerank = readRerank(answer)
437      if (ctx.logDecisions) {
438        const ms = (await $.clock.now()) - rerankStartedAt
439        const read = candidates.filter((candidate) => ctx.files.get(candidate.name)).length
440        $.ui.log(
441          `[jev-skill-suggestion] jev: ${describeRerank(rerank, ms)} · ${read}/${candidates.length} bodies read`,
442        )
443      }
444    }
445  }
446
447  let decision = decide(wide, rerank, offered, ctx.policy, {
448    rerankAttempted,
449    rerankOn: Boolean(active) && ctx.rerankEnabled,
450  })
451  let pick = decision.name ? (skills.find((skill) => skill.name === decision.name) ?? null) : null
452  // The winner's own frontmatter has the last word, whichever path picked it.
453  if (pick && !barred.includes(pick.name) && !modelInvocable((await fileOf(pick, pluginOf.get(pick.name)))?.markdown ?? null)) {
454    barred.push(pick.name)
455    decision = { name: null, reason: `/${pick.name} has disable-model-invocation` }
456    pick = null
457  }
458  if (ctx.logDecisions && barred.length > 0) {
459    $.ui.log(
460      `[jev-skill-suggestion] not model-invocable, left out: ${barred.map((name) => `/${name}`).join(', ')}`,
461    )
462  }
463  const file = pick ? await fileOf(pick, pluginOf.get(pick.name)) : null
464  return {
465    pick,
466    reason: decision.reason,
467    file,
468    answered: wide !== null && (!rerankAttempted || rerank !== null),
469    trace: { wide, rerank, ms: (await $.clock.now()) - startedAt, model },
470  }
471}
472
473export const register: Register = (on, options) => {
474  const text = (key: string, fallback: string) =>
475    typeof options[key] === 'string' && options[key] ? (options[key] as string) : fallback
476  const number = (key: string, fallback: number) =>
477    typeof options[key] === 'number' ? (options[key] as number) : fallback
478  const flag = (key: string, fallback: boolean) =>
479    typeof options[key] === 'boolean' ? (options[key] as boolean) : fallback
480
481  const forced = text('provider', 'auto')
482
483  // TypeSafe's own API is preferred when both keys are set: it is the only
484  // one that reports a calibrated confidence. `provider` forces one,
485  // including "builtin" to use neither. A key option wins; with none, the
486  // key's environment variable (TYPESAFE_API_KEY, AI_GATEWAY_API_KEY) is
487  // read at the first hook, since only `$` can read the environment; the
488  // first answer stands for the process.
489  let backend: Backend | null = null
490  const backendOf = (typesafeEnv: string | undefined, gatewayEnv: string | undefined): Backend => {
491    if (backend) return backend
492    const typesafeKey = text('typesafeApiKey', '') || (typesafeEnv ?? '').trim()
493    const gatewayKey = text('gatewayApiKey', '') || (gatewayEnv ?? '').trim()
494    const active = selectProvider(forced, typesafeKey, gatewayKey)
495    // Each backend keeps its own URL and model, so an override written for one
496    // can never be sent to the other when `auto` picks differently than expected.
497    backend = {
498      active,
499      apiKey: active === 'typesafe' ? typesafeKey : active === 'gateway' ? gatewayKey : '',
500      modelId: !active
501        ? ''
502        : active === 'typesafe'
503          ? text('typesafeModel', DEFAULT_MODEL.typesafe)
504          : text('gatewayModel', DEFAULT_MODEL.gateway),
505      url: !active
506        ? ''
507        : active === 'typesafe'
508          ? endpoint('typesafe', text('typesafeBaseUrl', DEFAULT_BASE_URL.typesafe))
509          : endpoint('gateway', text('gatewayBaseUrl', DEFAULT_BASE_URL.gateway)),
510    }
511    return backend
512  }
513
514  // The listing stays by default: `name-only` overrides (what the setup
515  // writes) already take the descriptions out, and a listed name is what lets
516  // the model load a skill another skill names.
517  const hideListing = flag('hideListing', false)
518  // "content": the mod reads the chosen skill's SKILL.md and attaches it, so
519  // the skill loads even when the engine lists it as user-invocable-only or
520  // off. "suggest": the cookbook's block alone, and the model loads the skill
521  // with the Skill tool, which honours the engine's skillOverrides.
522  const injectContent = text('inject', 'content') !== 'suggest'
523  const alwaysListed = parseNames(text('alwaysListed', ''))
524  const neverSuggested = parseNames(text('neverSuggested', ''))
525  const rerankEnabled = flag('rerank', true)
526  const excerptChars = number('excerptChars', DEFAULT_EXCERPT_CHARS)
527  const timeoutMs = number('timeoutMs', 800)
528  // The second request carries each shortlisted SKILL.md's opening and one
529  // question per candidate, so it gets its own, longer budget.
530  const rerankTimeoutMs = number('rerankTimeoutMs', 2500)
531  const logDecisions = flag('logDecisions', true)
532  const recordDecisions = flag('recordDecisions', true)
533  const sendRecentContext = flag('sendRecentContext', true)
534  const findSkill = flag('findSkill', true)
535  const policy: PolicyConfig = {
536    shortlist: Math.max(1, Math.round(number('shortlist', 3))),
537    gateThreshold: number('gateThreshold', 0.3),
538    fitsThreshold: number('fitsThreshold', 0.5),
539  }
540
541  // The names every skill_listing attachment carried so far. Once non-empty,
542  // only these are offered to the decision model: the listing is the engine's
543  // word on which skills the model is allowed to invoke, and `$.command.list()`
544  // also names commands the model may not.
545  const listed = new Set<string>()
546  // The skill suggested for the current prompt, so a skill.prompt that loads
547  // it can be told apart from one the model reached for on its own.
548  let suggested: string | null = null
549  // Each skill's SKILL.md as first found, with where, or null when nowhere:
550  // read once per session, since the second request wants it on every prompt
551  // it is on, and the injection wants it whole.
552  const files = new Map<string, SkillFile | null>()
553  // The skills whose instructions were already attached this session: a
554  // second time, the block only names the skill again.
555  const injected = new Set<string>()
556  // The skills the Skill tool loaded this session, in this conversation or a
557  // subagent's (`skill.prompt` does not say which): named, not attached whole.
558  const loadedByTool = new Set<string>()
559  // Said once, the first time a hook runs. A mod that loaded and one that
560  // never loaded are otherwise told apart only by the absence of later lines,
561  // and absence is not evidence: with the listing gone, silence is the norm.
562  let announced = false
563  // The setup hint, once per session.
564  let hintedSetup = false
565
566  const state: ChooseContext = {
567    backendOf,
568    forced,
569    files,
570    neverSuggested,
571    logDecisions,
572    recordDecisions,
573    sendRecentContext,
574    timeoutMs,
575    rerankTimeoutMs,
576    rerankEnabled,
577    excerptChars,
578    policy,
579    // A backend named in the options but missing its key degrades to the
580    // built-in classifier, which is silent; say so once, when a hook first runs.
581    unusableReported: forced === 'auto' || forced === 'builtin',
582    // A skill whose frontmatter `name:` has spaces ("PocketBase API Rules") is
583    // reported by `$.command.list()` under that name, but the engine lists,
584    // runs and overrides it by its directory name (`pb-api-rules`). The map
585    // from one to the other is read from disk once per session, in whichever
586    // hook first needs it.
587    displayToId: null,
588    records: new Map(),
589  }
590
591  on('prompt.attachment', { type: 'skill_listing' }, async ($, e, next) => {
592    if (!announced) {
593      announced = true
594      const { active, url } = backendOf(await $.env.get('TYPESAFE_API_KEY'), await $.env.get('AI_GATEWAY_API_KEY'))
595      if (logDecisions) {
596        $.ui.log(`[jev-skill-suggestion] ${describeSetup(active, url, hideListing, forced === 'builtin')}`)
597      }
598    }
599
600    const skills = parseListing(e.text)
601    // A subagent's listing may name skills the main conversation's does not.
602    if (!e.agentId) for (const skill of skills) listed.add(skill.name)
603
604    // A listed skill that still brings its whole description is context the
605    // setup command would trim to the name: say so once.
606    // ponytail: a `prefix:name` is taken for a plugin's skill, which
607    // skillOverrides cannot trim; read `$.command.list()` sources if a
608    // colon-named user skill ever shows up.
609    const described = skills.filter((skill) => skill.description && !skill.name.includes(':')).length
610    if (!hintedSetup && described > 0 && !e.agentId) {
611      hintedSetup = true
612      if (logDecisions) $.ui.log(`[jev-skill-suggestion] ${describeStillListed(described)}`)
613    }
614
615    // A subagent's listing is not ours: nothing here suggests for a subagent,
616    // so hiding its listing would leave it with no skills at all.
617    if (!hideListing || e.agentId) return next(e)
618
619    const kept = trimListing(e.text, alwaysListed)
620    if (logDecisions) {
621      const keptNames = kept
622        ? parseListing(kept)
623            .map((skill) => skill.name)
624            .join(', ')
625        : 'none'
626      $.ui.log(
627        `[jev-skill-suggestion] withheld the skill listing (${skills.length} skills, ${e.text.length} characters); kept listed: ${keptNames}`,
628      )
629    }
630    // Answered without `next`: the engine's text never reaches the model.
631    return { text: kept }
632  })
633
634  on('prompt.submit', async ($, e, next) => {
635    if (!announced) {
636      announced = true
637      const { active, url } = backendOf(await $.env.get('TYPESAFE_API_KEY'), await $.env.get('AI_GATEWAY_API_KEY'))
638      if (logDecisions) {
639        $.ui.log(`[jev-skill-suggestion] ${describeSetup(active, url, hideListing, forced === 'builtin')}`)
640      }
641    }
642    suggested = null
643
644    // Notifications and peer messages are not tasks; a typed `/name` already
645    // names its skill; "ok" or "繼續" carries no task the prompt alone shows.
646    // None of them gets a suggestion.
647    if (e.origin && NOT_A_TASK.has(e.origin.kind)) return next(e)
648    if (!routable(e.text)) {
649      if (logDecisions && e.text.trim() && contextFree(e.text)) {
650        $.ui.log('[jev-skill-suggestion] no suggestion: a reply with no task of its own')
651      }
652      // Recorded too: a record of routed prompts only cannot show what the
653      // pre-checks drop, and evals are built from these records.
654      if (e.text.trim()) {
655        const reason = typedCommand(e.text) ? 'not routed: a typed /name' : 'not routed: a reply with no task of its own'
656        await record($, state, { source: 'prompt', text: e.text, context: null, pick: null, reason, answered: true, trace: null })
657      }
658      return next(e)
659    }
660
661    // Content mode loads the skill itself, so it is not bound to what the
662    // engine lists; "suggest" leaves loading to the Skill tool, which is.
663    const context = await contextFor($, state, e.text)
664    const choice = await choose($, state, e.text, { restrictTo: injectContent ? new Set() : listed, askGate: true, context })
665    if (!choice) {
666      await record($, state, { source: 'prompt', text: e.text, context, pick: null, reason: 'not asked: could not list the skills', answered: false, trace: null })
667      return next(e)
668    }
669    const { pick, file } = choice
670    await record($, state, { source: 'prompt', text: e.text, context, pick: pick?.name ?? null, reason: choice.reason, answered: choice.answered, trace: choice.trace })
671    // A row in the transcript scrolls away; this line stays on screen.
672    if (logDecisions) $.ui.status(describeStatus(pick?.name ?? null))
673    if (logDecisions) {
674      $.ui.log(
675        pick
676          ? `[jev-skill-suggestion] suggesting /${pick.name}: ${choice.reason}`
677          : `[jev-skill-suggestion] no suggestion: ${choice.reason}`,
678      )
679    }
680
681    suggested = pick?.name ?? null
682    let block: string | null
683    if (injectContent && pick) {
684      const projectDir = await $.session.cwd()
685      // Named only when the Skill tool can load it here: a skill missing from the
686      // main conversation's listing (user-invocable-only, or no listing seen yet)
687      // may be refused, and a subagent's load left the body out of this conversation.
688      const already = injected.has(pick.name) ? true : loadedByTool.has(pick.name) && listed.has(pick.name) ? 'loaded' : false
689      block = injectionBlock(pick, file?.markdown ?? null, file?.path ?? null, projectDir, already)
690      if (logDecisions) {
691        $.ui.log(
692          file
693            ? already === 'loaded'
694              ? `[jev-skill-suggestion] /${pick.name} loaded by the Skill tool this session; named with how to load it`
695              : already
696              ? `[jev-skill-suggestion] /${pick.name} already injected this session; named again`
697              : `[jev-skill-suggestion] injected /${pick.name} from ${file.path} (${file.markdown.length} characters)`
698            : `[jev-skill-suggestion] no file found for /${pick.name}; suggested by name only`,
699        )
700      }
701      if (file && !already) injected.add(pick.name)
702    } else if (injectContent) {
703      // Content mode with nothing picked says nothing: "no skill is relevant"
704      // would talk the model out of loading one from the listing on its own.
705      block = null
706    } else {
707      block = suggestionBlock(pick, hideListing)
708    }
709    if (!block) return next(e)
710    // Attached on the way down: one block after the prompt as typed, read by
711    // the model and never shown to the person.
712    return next({ ...e, context: [...(e.context ?? []), block] })
713  })
714
715  // An injected skill lives in the conversation, not the process: `/clear`
716  // or a resume starts another under the same worker, and a compaction may
717  // summarize the block away. Either way the next pick goes in whole again.
718  on('session.end', async ($, e, next) => {
719    injected.clear()
720    loadedByTool.clear()
721    suggested = null
722    return next(e)
723  })
724  on('session.compact', async ($, e, next) => {
725    // The engine re-attaches what the Skill tool loaded only up to its first
726    // 5,000 tokens, so after a compaction a pick goes in whole again either way.
727    if (!e.agentId) {
728      injected.clear()
729      loadedByTool.clear()
730    }
731    return next(e)
732  })
733
734  // find_skill: the prompt's suggestion is made once, from the prompt alone;
735  // a sub-task that turns up mid-turn is the model's to look up. Registered
736  // at session.start so the tool list, and the prompt cache, stay put; the
737  // full name is the engine's (it depends on how the plugin was loaded).
738  let findSkillName = ''
739  on('session.start', async ($, e, next) => {
740    // Without a backend that reranks, nothing would check the ranking's pick,
741    // and the gate is left out: the tool is not offered.
742    const vetted = backendOf(await $.env.get('TYPESAFE_API_KEY'), await $.env.get('AI_GATEWAY_API_KEY')).active && rerankEnabled
743    if (findSkill && !vetted && logDecisions) {
744      $.ui.log('[jev-skill-suggestion] find_skill not offered: it needs a TypeSafe or Gateway key and rerank on')
745    }
746    if (findSkill && vetted) {
747      try {
748        findSkillName = (await $.tool.register(FIND_SKILL_TOOL)).tool
749      } catch (error) {
750        $.ui.log(`[jev-skill-suggestion] could not register find_skill: ${String(error)}`)
751      }
752    }
753    return next(e)
754  })
755  // Left to the engine, a plugin's tool waits behind ToolSearch, named but
756  // without its description: the model would have to guess at it, which is
757  // the very thing the tool is for.
758  on('tool.describe', async ($, e, next) => {
759    const out = await next(e)
760    return findSkillName && e.tool === findSkillName ? { ...out, isDeferred: false } : out
761  })
762  on('tool.call', async ($, e, next) => {
763    if (!findSkillName || e.tool !== findSkillName) return next(e)
764    const task = 'task' in e && typeof e.task === 'string' ? e.task.trim() : ''
765    // The model loads the answer with the Skill tool, so only what the
766    // engine lists is offered; before the listing is seen, nothing is.
767    let answer: Skill | null | 'unavailable' = 'unavailable'
768    try {
769      const context = await contextFor($, state, null, e.agentId)
770      const choice = task && listed.size > 0 ? await choose($, state, task, { restrictTo: listed, askGate: false, context }) : null
771      if (choice?.answered) answer = choice.pick
772      if (choice) {
773        const { reason, answered, trace } = choice
774        await record($, state, { source: 'find_skill', text: task, context, pick: choice.pick?.name ?? null, reason, answered, trace, agentId: e.agentId })
775      }
776    } catch (error) {
777      $.ui.log(`[jev-skill-suggestion] find_skill failed: ${String(error)}`)
778    }
779    if (logDecisions) {
780      const outcome = answer === 'unavailable' ? 'lookup unavailable' : answer ? `suggesting /${answer.name}` : 'no suggestion'
781      $.ui.log(`[jev-skill-suggestion] find_skill${e.agentId ? ` (${e.agentId})` : ''} "${task}": ${outcome}`)
782    }
783    // The latest pick, prompt's or find_skill's, is what a skill.prompt that
784    // follows is measured against: without it, a skill loaded on
785    // find_skill's word would be logged as one nothing suggested.
786    if (answer && answer !== 'unavailable') suggested = answer.name
787    return { result: findSkillResult(answer) }
788  })
789
790  on('skill.prompt', { skill: 'jev-skill-suggestion:setup' }, async ($, e, next) => {
791    // The plugin's own setup command: its markdown is a placeholder, and the
792    // prompt the model reads is written here, from the roster as the engine
793    // has it and the user settings as they are. The model does the editing
794    // with its own tools, so the change shows as a diff and asks permission.
795    const mode = /\brestore\b/i.test(e.text) ? 'restore' : 'apply'
796    // No plan from a partial roster or unreadable settings: the edit would
797    // hide too little, and the backup would save the wrong values.
798    let commands: Awaited<ReturnType<typeof $.command.list>> = []
799    try {
800      commands = await listCommands($, state, await configDirFor($))
801    } catch (error) {
802      $.ui.log(`[jev-skill-suggestion] setup: could not list the skills: ${String(error)}`)
803      return next({ ...e, text: setupAborted(`the skills could not be listed (${String(error)})`) })
804    }
805    const configDir = configDirOf((await $.env.get('HOME')) ?? '~', await $.env.get('CLAUDE_CONFIG_DIR'))
806    const settingsPath = `${configDir}/settings.json`
807    const backupPath = `${configDir}/jev-skill-suggestion.skill-overrides.backup.json`
808    let json: string | null = null
809    try {
810      if (await $.fs.exists(settingsPath)) json = await $.fs.read(settingsPath)
811    } catch (error) {
812      $.ui.log(`[jev-skill-suggestion] setup: could not read ${settingsPath}: ${String(error)}`)
813      return next({ ...e, text: setupAborted(`${settingsPath} exists but could not be read (${String(error)})`) })
814    }
815    const settings = readSkillSettings(json)
816    const plan = setupPlan(commands, settings, new Set([SETUP_COMMAND]))
817    // An earlier run's backup is reused only if it is one: a file that is
818    // not this mod's, or is corrupt, is nothing restore could apply, so no
819    // setup is built on top of it.
820    let backupExists = false
821    try {
822      backupExists = await $.fs.exists(backupPath)
823      if (backupExists && !validBackup(await $.fs.read(backupPath))) {
824        $.ui.log(`[jev-skill-suggestion] setup: ${backupPath} is not a valid backup`)
825        return next({
826          ...e,
827          text: setupAborted(
828            `${backupPath} exists but is not a backup this mod wrote (expected {"skillOverrides": {...}, "disableBundledSkills": true|false|null}); ask the user to inspect it and move it away, or fix it, before running the setup again`,
829          ),
830        })
831      }
832    } catch (error) {
833      $.ui.log(`[jev-skill-suggestion] setup: could not read ${backupPath}: ${String(error)}`)
834      return next({ ...e, text: setupAborted(`${backupPath} could not be read (${String(error)})`) })
835    }
836    if (logDecisions) {
837      $.ui.log(
838        `[jev-skill-suggestion] setup (${mode}): ${plan.hide.length} to hide, ${plan.alreadyHidden.length} already hidden, ${plan.locked.length} locked by a plugin`,
839      )
840    }
841    return next({ ...e, text: setupInstructions(mode, plan, settings, settingsPath, backupPath, backupExists) })
842  })
843
844  on('skill.prompt', async ($, e, next) => {
845    // Observation only: whether the model took the suggestion, or reached for
846    // a skill it was never told about, is the one measure of this mod's worth.
847    if (logDecisions && e.skill !== SETUP_COMMAND) {
848      const how =
849        suggested === e.skill
850          ? 'as suggested'
851          : suggested
852            ? `suggested was /${suggested}`
853            : 'nothing was suggested'
854      $.ui.log(`[jev-skill-suggestion] skill /${e.skill} loaded (${how})`)
855    }
856    if (e.skill !== SETUP_COMMAND) {
857      loadedByTool.add(e.skill)
858      await record($, state, { loaded: e.skill, suggested })
859    }
860    return next(e)
861  })
862}
863
hooks/policy.ts 1220 lines
1/**
2 * jev-skill-suggestion — pure decision logic.
3 *
4 * No `$` and no I/O here: this module reads the engine's skill listing, builds
5 * the two requests the decision API takes, reads their answers, and turns them
6 * into at most one skill name and the text that suggests it. The hooks module
7 * does every call on `$` at its own call site.
8 *
9 * The shape follows TypeSafe's "Skill suggestion" cookbook
10 * (https://docs.typesafe.ai/cookbooks/skill_suggestion):
11 *
12 *   request 1  rank every skill (`which`, a Choice with each skill's one-line
13 *              description as its criterion) and ask three Nouls about the
14 *              request itself — whether it wants an action taken rather than
15 *              an explanation given. Their mean is the gate.
16 *   request 2  re-read the top few (`which` again, now with each skill's full
17 *              description and the opening of its SKILL.md) and ask one Noul
18 *              per candidate: does this skill do the specific thing asked?
19 *              Every `fits` may come back low, and then nothing is suggested.
20 *
21 * Two backends speak to the same model with different wire shapes:
22 *
23 *   typesafe  POST https://api.typesafe.ai/v1/systemone
24 *             `{ model, state, questions }`; a yes/no question is a `noul`
25 *             and every answer carries its own `confidence`.
26 *   gateway   POST https://ai-gateway.vercel.sh/v4/ai/evaluation-model
27 *             `{ state, questions }` with the model in a header; a yes/no
28 *             question is a `boolean` answered as `probability`.
29 *
30 * The Gateway shape is not documented publicly; it was read from
31 * @ai-sdk/gateway and @ai-sdk/provider.
32 */
33
34export type Provider = 'typesafe' | 'gateway'
35
36/** One skill as the model could be told about it: its name and one line. */
37export interface Skill {
38  name: string
39  description: string
40}
41
42/** A shortlisted skill with the longer text the second request reads. */
43export interface Candidate extends Skill {
44  /** The full description and the opening of the skill's body, joined. */
45  detail: string
46}
47
48/** What the first request answered. */
49export interface Wide {
50  /** Every skill with the probability it was given, surest first. */
51  ranked: { name: string; probability: number | null }[]
52  /** The mean of the oriented gate nouls, or null when none was answered. */
53  gate: number | null
54  /** Each gate noul as answered, for the log. */
55  gateValues: Record<string, number>
56}
57
58/** What the second request answered. */
59export interface Rerank {
60  /** The candidate the Choice named. */
61  winner: string
62  /** Confidence in that choice, or null when the backend reported none. */
63  confidence: number | null
64  /** P(true) per candidate that it does the specific thing asked. */
65  fits: Record<string, number>
66}
67
68/** The label the built-in classifier answers when no skill applies. */
69export const NONE = 'none'
70
71export const DEFAULT_BASE_URL: Record<Provider, string> = {
72  typesafe: 'https://api.typesafe.ai',
73  gateway: 'https://ai-gateway.vercel.sh/v4/ai',
74}
75
76export const DEFAULT_MODEL: Record<Provider, string> = {
77  // Pinned, not `jev-latest`: an alias moves, and the thresholds are tuned
78  // against one version (evals/README.md).
79  typesafe: 'jev-1.14.0',
80  gateway: 'typesafe-ai/jev',
81}
82
83/**
84 * The Gateway's own protocol version, sent as `ai-gateway-protocol-version`:
85 * without it every request is refused with 400. Tracks the
86 * `AI_GATEWAY_PROTOCOL_VERSION` of `@ai-sdk/gateway` (4.0.87).
87 */
88const AI_GATEWAY_PROTOCOL_VERSION = '0.0.1'
89
90/**
91 * Which backend a configuration asks for, or null for the built-in
92 * classifier. `auto` prefers TypeSafe, since it is the only one that reports
93 * a calibrated confidence; a forced backend whose key is missing resolves to
94 * null rather than falling through to the other one's key.
95 */
96export function selectProvider(forced: string, typesafeKey: string, gatewayKey: string): Provider | null {
97  if (forced === 'builtin') return null
98  if (forced === 'typesafe') return typesafeKey ? 'typesafe' : null
99  if (forced === 'gateway') return gatewayKey ? 'gateway' : null
100  if (typesafeKey) return 'typesafe'
101  if (gatewayKey) return 'gateway'
102  return null
103}
104
105/** The full endpoint a backend posts to. */
106export function endpoint(provider: Provider, baseUrl: string): string {
107  const root = baseUrl.replace(/\/+$/, '')
108  return provider === 'typesafe' ? `${root}/v1/systemone` : `${root}/evaluation-model`
109}
110
111/** A comma-separated option as a set of trimmed, non-empty names. */
112export function parseNames(option: string): Set<string> {
113  return new Set(
114    option
115      .split(',')
116      .map((name) => name.trim())
117      .filter(Boolean),
118  )
119}
120
121/**
122 * Reads the engine's `skill_listing` attachment: a header line, then one
123 * `- name: description` per skill. A description may run over several lines,
124 * and an entry the engine trimmed to fit its budget has no description at
125 * all. Anything before the first entry is the header and is skipped.
126 */
127export function parseListing(text: string): Skill[] {
128  const skills: Skill[] = []
129  let current: Skill | null = null
130  for (const raw of text.split('\n')) {
131    const line = raw.trimEnd()
132    // A name has no spaces, so it runs up to the first `: `; a name that
133    // itself contains `:` (`engineering:code-review`) is kept whole.
134    const entry = /^- (\S+?)(?::\s(.*))?$/.exec(line)
135    if (entry) {
136      current = { name: entry[1] as string, description: (entry[2] ?? '').trim() }
137      skills.push(current)
138    } else if (current && line.trim()) {
139      current.description = `${current.description} ${line.trim()}`.trim()
140    }
141  }
142  return skills
143}
144
145/**
146 * The skills the decision model is offered: every command the person can run
147 * that the model may also call, less the built-ins (`/help`, `/clear`) and the
148 * names configured out. When the engine's listing has been seen, only skills
149 * it listed are offered: the listing is the engine's word on which skills the
150 * model is allowed to invoke.
151 */
152export function catalog(
153  commands: readonly { name: string; description: string; source: string }[],
154  listed: ReadonlySet<string>,
155  excluded: ReadonlySet<string>,
156): Skill[] {
157  const seen = new Set<string>()
158  const skills: Skill[] = []
159  for (const command of commands) {
160    if (command.source === 'builtin') continue
161    if (listed.size > 0 && !listed.has(command.name)) continue
162    if (excluded.has(command.name) || seen.has(command.name)) continue
163    seen.add(command.name)
164    skills.push({ name: command.name, description: command.description.trim() })
165  }
166  return skills
167}
168
169/**
170 * The listing with only `keep` left in it, or null when nothing is kept: what
171 * the model reads in place of the engine's full listing.
172 */
173export function trimListing(text: string, keep: ReadonlySet<string>): string | null {
174  if (keep.size === 0) return null
175  const kept = parseListing(text).filter((skill) => keep.has(skill.name))
176  if (kept.length === 0) return null
177  const header = text.split('\n').find((line) => line.trim() && !line.startsWith('- ')) ?? ''
178  return [header.trim(), '', ...kept.map(line)].join('\n')
179}
180
181function line(skill: Skill): string {
182  return skill.description ? `- ${skill.name}: ${skill.description}` : `- ${skill.name}`
183}
184
185/**
186 * Whether a skill or plugin name may be spliced into a path: the engine's
187 * names are directory basenames, so anything with a path separator or a
188 * `..` segment is refused rather than resolved.
189 */
190function safeName(name: string): boolean {
191  return name.length > 0 && !name.includes('/') && !name.includes('\\') && !name.split(':').includes('..')
192}
193
194/**
195 * The relative files a skill's body may live in, project or user level, by
196 * how Claude Code lays skills and commands out. A plugin's are under its
197 * install path instead, with the plugin prefix taken off the name.
198 */
199export function skillFileCandidates(name: string, plugin?: string): string[] {
200  if (!safeName(name) || (plugin !== undefined && !safeName(plugin))) return []
201  const short = plugin && name.startsWith(`${plugin}:`) ? name.slice(plugin.length + 1) : name
202  const asPath = short.replace(/:/g, '/')
203  const files = [
204    `.claude/skills/${short}/SKILL.md`,
205    `.claude/commands/${asPath}.md`,
206    `.claude/skills/${asPath}/SKILL.md`,
207  ]
208  if (plugin) {
209    // A plugin auto-loaded from a skills dir keeps its own `skills/` inside.
210    files.push(`.claude/skills/${plugin}/skills/${short}/SKILL.md`)
211    files.push(`.claude/skills/${plugin}/commands/${asPath}.md`)
212  }
213  return files
214}
215
216/** Whether a name is one the engine would run as `/name`: no whitespace. */
217export function commandLike(name: string): boolean {
218  return name.length > 0 && !/\s/.test(name)
219}
220
221/** The `name:` a SKILL.md's frontmatter declares, or null. */
222export function frontmatterName(markdown: string): string | null {
223  const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---/.exec(markdown)
224  if (!frontmatter) return null
225  const field = /^name:\s*(.*)$/m.exec(frontmatter[1] as string)
226  if (!field) return null
227  const value = (field[1] as string).trim().replace(/^["']|["']$/g, '')
228  return value || null
229}
230
231/**
232 * Display name → directory name, from the skills found on disk: only the
233 * ones whose frontmatter `name:` differs from their directory, since those
234 * are the ones `$.command.list()` reports under a name the engine will not
235 * run, list or override. First found wins.
236 */
237export function displayIds(found: readonly { dir: string; markdown: string }[]): Map<string, string> {
238  const ids = new Map<string, string>()
239  for (const { dir, markdown } of found) {
240    const declared = frontmatterName(markdown)
241    if (declared && declared !== dir && !ids.has(declared)) ids.set(declared, dir)
242  }
243  return ids
244}
245
246/** Commands with every display name replaced by the engine's id. */
247export function canonical<T extends { name: string }>(commands: readonly T[], ids: ReadonlyMap<string, string>): T[] {
248  if (ids.size === 0) return [...commands]
249  return commands.map((command) => (ids.has(command.name) ? { ...command, name: ids.get(command.name) as string } : command))
250}
251
252/**
253 * A claude.ai-synced skill's file: Claude Code keeps them under
254 * `~/.claude/skills/synced/<account>/<skill>/SKILL.md`, listed to the model
255 * with a prefix (`anthropic-skills:pptx`) that is not on disk.
256 */
257export function syncedFileCandidates(configDir: string, accounts: readonly string[], name: string): string[] {
258  if (!safeName(name)) return []
259  const short = name.includes(':') ? name.slice(name.lastIndexOf(':') + 1) : name
260  return accounts.filter(safeName).map((account) => `${configDir}/skills/synced/${account}/${short}/SKILL.md`)
261}
262
263/**
264 * Where Claude Code keeps the user's settings, skills and plugin records:
265 * `CLAUDE_CONFIG_DIR` when set, else `~/.claude`.
266 */
267export function configDirOf(home: string, override: string | undefined): string {
268  const dir = override?.trim()
269  return (dir ? dir : `${home}/.claude`).replace(/\/+$/, '')
270}
271
272/** A project-relative `.claude/...` file as it sits under the user's config dir. */
273export function underConfigDir(configDir: string, file: string): string {
274  return `${configDir}/${file.replace(/^\.claude\//, '')}`
275}
276
277/**
278 * The same files under a plugin's install path, as
279 * `~/.claude/plugins/installed_plugins.json` records it.
280 */
281export function pluginFileCandidates(installPath: string, name: string, plugin: string): string[] {
282  if (!safeName(name) || !safeName(plugin)) return []
283  const short = name.startsWith(`${plugin}:`) ? name.slice(plugin.length + 1) : name
284  const root = installPath.replace(/\/+$/, '')
285  return [`${root}/skills/${short}/SKILL.md`, `${root}/commands/${short.replace(/:/g, '/')}.md`]
286}
287
288/**
289 * The install paths `installed_plugins.json` records for a plugin name, any
290 * marketplace: the keys are `name@marketplace`.
291 */
292export function installPathsOf(installedJson: string, plugin: string): string[] {
293  let parsed: unknown
294  try {
295    parsed = JSON.parse(installedJson)
296  } catch {
297    return []
298  }
299  const plugins = (parsed as { plugins?: Record<string, { installPath?: string }[]> }).plugins
300  if (!plugins) return []
301  const paths: string[] = []
302  for (const [key, entries] of Object.entries(plugins)) {
303    if (key !== plugin && !key.startsWith(`${plugin}@`)) continue
304    for (const entry of entries ?? []) {
305      if (typeof entry?.installPath === 'string') paths.push(entry.installPath)
306    }
307  }
308  return paths
309}
310
311/**
312 * What the second request reads for one skill: its full frontmatter
313 * description, then the opening of its body with the frontmatter taken off.
314 * With no file found, the one-line description alone.
315 */
316export function detailOf(skill: Skill, markdown: string | null, excerptChars: number): string {
317  if (!markdown) return skill.description || `A skill named ${skill.name}.`
318  let body = markdown
319  let description = skill.description
320  const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(markdown)
321  if (frontmatter) {
322    body = markdown.slice(frontmatter[0].length)
323    const field = /^description:\s*(.*)$/m.exec(frontmatter[1] as string)
324    if (field) {
325      const value = (field[1] as string).trim().replace(/^["']|["']$/g, '')
326      if (value.length > description.length) description = value
327    }
328  }
329  const excerpt = body.trim().slice(0, Math.max(0, excerptChars))
330  if (!excerpt) return description || `A skill named ${skill.name}.`
331  return description ? `${description} — ${excerpt}` : excerpt
332}
333
334/**
335 * Whether a skill's own frontmatter lets the model invoke it. A skill with
336 * `disable-model-invocation: true` is left out of the engine's listing and
337 * refused by the Skill tool, so it must never be suggested; before the
338 * listing has been seen, this is the only way to tell. No file, or no such
339 * field, reads as invocable.
340 */
341/** A skill's body with its frontmatter taken off. */
342export function bodyOf(markdown: string): string {
343  const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---\r?\n?/.exec(markdown)
344  return (frontmatter ? markdown.slice(frontmatter[0].length) : markdown).trim()
345}
346
347/** The directory a skill file lives in, for `${CLAUDE_SKILL_DIR}`. */
348export function dirOf(path: string): string {
349  const cut = path.lastIndexOf('/')
350  return cut > 0 ? path.slice(0, cut) : '.'
351}
352
353/**
354 * The block attached to the prompt when the mod loads the skill itself: the
355 * cookbook's line, then the skill's instructions as the engine would have
356 * rendered them, with the paths the engine substitutes. The Skill tool is
357 * not needed, so the model is told not to load it a second time. A skill already injected earlier in
358 * the session is only named again: the engine does the same on a byte-identical
359 * re-invocation. One the Skill tool loaded (`'loaded'`) is named with the way to
360 * load it: `skill.prompt` cannot tell the main conversation from a subagent, so
361 * its body may be in this conversation or only in a subagent's.
362 */
363export function injectionBlock(
364  suggested: Skill,
365  markdown: string | null,
366  path: string | null,
367  projectDir: string,
368  alreadyLoaded: boolean | 'loaded',
369): string {
370  const lines = [
371    '<skill_relevance>',
372    `Relevant to the current request: ${suggested.name}. Ignore this if it does not fit what the user actually asked for.`,
373  ]
374  if (alreadyLoaded === 'loaded') {
375    lines.push(
376      `Skill /${suggested.name} was loaded with the Skill tool earlier in this session. If its instructions are not in this conversation (a subagent loaded it), load it with the Skill tool (skill: "${suggested.name}").`,
377    )
378  } else if (alreadyLoaded) {
379    lines.push(`Skill /${suggested.name} is already loaded above; instructions unchanged.`)
380  } else if (markdown && path) {
381    const dir = dirOf(path)
382    // Callbacks, so a path holding `$&` or `$1` goes in verbatim.
383    const body = bodyOf(markdown)
384      .replace(/\$\{CLAUDE_SKILL_DIR\}/g, () => dir)
385      .replace(/\$\{CLAUDE_PROJECT_DIR\}/g, () => projectDir)
386    lines.push(
387      `Its instructions follow: follow them now, including any setup steps. Do not load it again with the Skill tool: it is already loaded here. Its files are in ${dir}.`,
388      `<skill name="${suggested.name}" dir="${dir}">`,
389      body,
390      '</skill>',
391    )
392  } else {
393    // No file on disk (a synced or bundled skill the mod cannot read): the
394    // name and the way to load it are all there is.
395    lines.push(
396      `${line(suggested)}`,
397      `Load it with the Skill tool (skill: "${suggested.name}") before you start; if the tool refuses it, tell the user to type /${suggested.name}.`,
398    )
399  }
400  lines.push('</skill_relevance>')
401  return lines.join('\n')
402}
403
404export function modelInvocable(markdown: string | null): boolean {
405  if (!markdown) return true
406  const frontmatter = /^---\r?\n([\s\S]*?)\r?\n---/.exec(markdown)
407  if (!frontmatter) return true
408  return !/^disable-model-invocation:\s*true\s*$/m.test(frontmatter[1] as string)
409}
410
411/**
412 * The three questions about the request, each asking a different way whether
413 * it wants an action taken rather than an explanation given. Questions about
414 * subject matter would not separate "explain what a monad is" from a task
415 * that needs a skill, since both are software.
416 */
417export const GATE_QUESTIONS: Record<string, string> = {
418  acts_on_user_system:
419    "Is the assistant being asked to act on the user's files, accounts, devices, or online services, rather than only to explain or advise?",
420  would_follow_documented_procedure:
421    'Would a careful expert answering this consult a specific documented procedure or set of commands, rather than answering from general understanding?',
422  prose_suffices:
423    "Could a knowledgeable generalist fully satisfy this request in prose, with no tools, no documentation, and no access to the user's files or accounts?",
424  names_its_task:
425    'Could someone start on this message without having read the conversation before it? Mentions of the user\'s own files, branch, project or conventions are fine; only references to earlier messages are not.',
426}
427
428/** Gate questions where a yes points away from needing a skill. */
429const INVERTED = new Set(['prose_suffices'])
430
431/** The same yes/no question under two names. */
432function yesNo(provider: Provider, instructions: string | Record<string, unknown>): Record<string, unknown> {
433  return { type: provider === 'typesafe' ? 'noul' : 'boolean', instructions }
434}
435
436/** The first request's `questions`: the ranking, and the gate unless `askGate` is off. */
437export function wideQuestions(
438  provider: Provider,
439  skills: readonly Skill[],
440  { askGate = true }: { askGate?: boolean } = {},
441): Record<string, unknown> {
442  const criteria: Record<string, string> = {}
443  for (const skill of skills) criteria[skill.name] = skill.description || `A skill named ${skill.name}.`
444  const questions: Record<string, unknown> = {
445    which: {
446      type: 'choice',
447      instructions:
448        "Which of these skills, if any, is the right one to load to help with the user's latest request?",
449      criteria,
450    },
451  }
452  if (!askGate) return questions
453  for (const [key, text] of Object.entries(GATE_QUESTIONS)) {
454    questions[`gate::${key}`] = yesNo(provider, text)
455  }
456  return questions
457}
458
459/**
460 * Does this candidate do the thing asked? Structured instructions are
461 * TypeSafe's documented form; the Gateway's shape is read from its SDK, so it
462 * keeps the plain string.
463 */
464function fitsInstructions(provider: Provider, candidate: Candidate): string | Record<string, unknown> {
465  const description = candidate.description || candidate.detail
466  if (provider === 'gateway') {
467    return `Does the skill '${candidate.name}' do the specific thing the user's request asks for? It is described as: ${description}`
468  }
469  return { question: 'Does `skill` do the specific thing the request asks for?', skill: { name: candidate.name, description } }
470}
471
472/** The second request's `questions`: the shortlist re-read, one `fits` each. */
473export function rerankQuestions(
474  provider: Provider,
475  candidates: readonly Candidate[],
476): Record<string, unknown> {
477  const criteria: Record<string, string> = {}
478  for (const candidate of candidates) criteria[candidate.name] = candidate.detail
479  const questions: Record<string, unknown> = {
480    which: {
481      type: 'choice',
482      instructions:
483        "Exactly one of these skills is the right one to load for the user's latest request. Which one? Read what each actually does, not just its name.",
484      criteria,
485    },
486  }
487  for (const candidate of candidates) {
488    questions[`fits::${candidate.name}`] = yesNo(provider, fitsInstructions(provider, candidate))
489  }
490  return questions
491}
492
493/** The turn before the request, as the decision model reads it beside the request. */
494export interface RecentContext {
495  previous_user_message: string
496  assistant_reply: string
497}
498
499/**
500 * The turn before `current` in a transcript: the last user message before it
501 * and the assistant's last reply, each cut short, or null when there is none.
502 * A follow-up such as "查無資料ㄟ 為什麼??" carries its task in that turn, and
503 * the decision model otherwise reads the request alone. Mid-turn (find_skill),
504 * `current` is null: the context is the prompt being worked on and the reply
505 * so far.
506 */
507export function recentContextOf(
508  messages: readonly { role: 'user' | 'assistant'; text: string }[],
509  current: string | null,
510): RecentContext | null {
511  const said = messages.filter((message) => message.text.trim())
512  // The prompt being decided may already be in the transcript.
513  const last = said.at(-1)
514  if (current !== null && last?.role === 'user' && last.text.trim() === current.trim()) said.pop()
515  const at = said.findLastIndex((message) => message.role === 'user')
516  const user = at < 0 ? '' : (said[at] as { text: string }).text.trim()
517  const reply = said.slice(at + 1).findLast((message) => message.role === 'assistant')?.text.trim() ?? ''
518  if (!user && !reply) return null
519  return { previous_user_message: user.slice(0, 400), assistant_reply: reply.slice(-600) }
520}
521
522/** How much of a skill's body the second request reads, unless `excerptChars` says otherwise. */
523export const DEFAULT_EXCERPT_CHARS = 700
524
525/** How much of a long prompt the decision model reads: its opening, and its end. */
526export const REQUEST_HEAD_CHARS = 8_000
527export const REQUEST_TAIL_CHARS = 4_000
528
529/**
530 * The prompt as the decision model reads it. A pasted log of tens of
531 * kilobytes plus the catalog's descriptions overruns Jev's input, and the
532 * request comes back 400 `max_tokens_exceeded`, so nothing is suggested
533 * exactly when a skill is needed. The head says what was pasted and the tail
534 * holds the person's own words, which follow the paste, so the middle goes.
535 */
536export function requestText(prompt: string): string {
537  if (prompt.length <= REQUEST_HEAD_CHARS + REQUEST_TAIL_CHARS) return prompt
538  return `${prompt.slice(0, REQUEST_HEAD_CHARS)}\n…\n${prompt.slice(-REQUEST_TAIL_CHARS)}`
539}
540
541/** A request body. The Gateway carries the model in a header instead. */
542export function requestBody(
543  provider: Provider,
544  prompt: string,
545  questions: Record<string, unknown>,
546  model: string,
547  context: RecentContext | null = null,
548): string {
549  const state = { request: requestText(prompt), recent_context: context ?? '' }
550  const body = provider === 'typesafe' ? { model, state, questions } : { state, questions }
551  return JSON.stringify(body)
552}
553
554/** The request headers. */
555export function requestHeaders(provider: Provider, apiKey: string, model: string): Record<string, string> {
556  const common = { 'content-type': 'application/json', authorization: `Bearer ${apiKey}` }
557  if (provider === 'typesafe') return common
558  return {
559    ...common,
560    'ai-gateway-auth-method': 'api-key',
561    'ai-model-id': model,
562    'ai-gateway-protocol-version': AI_GATEWAY_PROTOCOL_VERSION,
563    'ai-evaluation-model-specification-version': '4',
564  }
565}
566
567type Answers = Record<string, Record<string, unknown>>
568
569function answersOf(responseText: string): Answers | null {
570  let parsed: unknown
571  try {
572    parsed = JSON.parse(responseText)
573  } catch {
574    return null
575  }
576  if (parsed === null || typeof parsed !== 'object') return null
577  const answers = (parsed as { answers?: Answers }).answers
578  return answers && typeof answers === 'object' ? answers : null
579}
580
581/** P(true) of a yes/no answer: `noul` on TypeSafe, `probability` on the Gateway. */
582function yesNoOf(answer: Record<string, unknown> | undefined): number | null {
583  if (!answer) return null
584  if (typeof answer.noul === 'number') return answer.noul
585  if (typeof answer.probability === 'number') return answer.probability
586  return null
587}
588
589/** The model version a response says answered it (`jev-latest` resolves to one), or null. */
590export function modelOf(responseText: string): string | null {
591  try {
592    const model = (JSON.parse(responseText) as { model?: unknown }).model
593    return typeof model === 'string' ? model : null
594  } catch {
595    return null
596  }
597}
598
599/**
600 * Reads the first request's answer. The ranking is the Choice's probability
601 * distribution, surest first; a backend that sends none ranks the named
602 * choice alone, at the reported confidence or none. The gate is the mean of
603 * the oriented nouls that were answered, or null when none was.
604 */
605export function readWide(responseText: string): Wide | null {
606  const answers = answersOf(responseText)
607  const which = answers?.which
608  if (!answers || !which || typeof which.choice !== 'string') return null
609
610  const probabilities = which.probabilities as Record<string, number> | undefined
611  const ranked: Wide['ranked'] = []
612  if (probabilities) {
613    for (const [name, probability] of Object.entries(probabilities)) {
614      if (typeof probability === 'number') ranked.push({ name, probability })
615    }
616    ranked.sort((a, b) => (b.probability ?? 0) - (a.probability ?? 0))
617  }
618  if (ranked.length === 0) {
619    ranked.push({
620      name: which.choice,
621      probability: typeof which.confidence === 'number' ? which.confidence : null,
622    })
623  }
624
625  const gateValues: Record<string, number> = {}
626  const oriented: number[] = []
627  for (const key of Object.keys(GATE_QUESTIONS)) {
628    const value = yesNoOf(answers[`gate::${key}`])
629    if (value === null) continue
630    gateValues[key] = value
631    oriented.push(INVERTED.has(key) ? 1 - value : value)
632  }
633  const gate = oriented.length > 0 ? oriented.reduce((a, b) => a + b, 0) / oriented.length : null
634  return { ranked, gate, gateValues }
635}
636
637/** Reads the second request's answer. */
638export function readRerank(responseText: string): Rerank | null {
639  const answers = answersOf(responseText)
640  const which = answers?.which
641  if (!answers || !which || typeof which.choice !== 'string') return null
642  const fits: Record<string, number> = {}
643  for (const [key, answer] of Object.entries(answers)) {
644    if (!key.startsWith('fits::')) continue
645    const value = yesNoOf(answer)
646    if (value !== null) fits[key.slice('fits::'.length)] = value
647  }
648  return {
649    winner: which.choice,
650    confidence: typeof which.confidence === 'number' ? which.confidence : null,
651    fits,
652  }
653}
654
655/** The first request's answer as the built-in classifier can give it: one label, no gate. */
656export function builtinWide(label: string | undefined): Wide | null {
657  if (!label) return null
658  return {
659    ranked: label === NONE ? [] : [{ name: label, probability: null }],
660    gate: null,
661    gateValues: {},
662  }
663}
664
665/**
666 * The text the built-in classifier reads: the prompt and the catalog it must
667 * choose from, since `$.model.classify` takes bare labels and the descriptions
668 * are the whole point.
669 */
670export function classifyText(prompt: string, skills: readonly Skill[]): string {
671  return [
672    'Which skill, going by its description, should be loaded before working on the prompt below? Answer "none" unless the prompt is clearly the kind of task a description names.',
673    '',
674    'Skills:',
675    ...skills.map(line),
676    `- ${NONE}: no listed skill is about this prompt`,
677    '',
678    'Prompt:',
679    prompt,
680  ].join('\n')
681}
682
683/**
684 * Replies that carry no task of their own: a greeting, an acknowledgement, a
685 * go-ahead, a bare number picking an option. The decision model reads the
686 * prompt alone, with no conversation, so ranking these only guesses; they get
687 * no suggestion, and the model keeps whatever skill the task already loaded.
688 */
689const CONTEXT_FREE = new Set([
690  'hi', 'hello', 'hey', 'thanks', 'thank you', 'thx', 'ok', 'okay', 'k', 'yes', 'y', 'no', 'n', 'sure',
691  'go', 'go ahead', 'continue', 'proceed', 'next', 'done', 'lgtm', 'sounds good', 'do it',
692  '好', '好的', '好啊', '好喔', '好哦', '可以', '是', '是的', '對', '對的', '嗯', '恩', '謝謝', '感謝',
693  '繼續', '继续', '下一步', '做吧', '好做吧', '開始', '开始', '沒問題', '没问题', '不用', '不要', 'ok啦', '可',
694])
695
696/** Whether a prompt is such a reply: no letters at all, or a stock phrase. */
697export function contextFree(text: string): boolean {
698  const trimmed = text.trim().toLowerCase()
699  if (!/\p{L}/u.test(trimmed)) return true
700  return CONTEXT_FREE.has(trimmed.replace(/[\s!.,?~。!,?~、]+$/u, '').replace(/\s+/g, ' '))
701}
702
703export interface PolicyConfig {
704  /** How many of the ranking the second request re-reads. */
705  shortlist: number
706  /** The gate mean under which nothing is suggested. */
707  gateThreshold: number
708  /** The best `fits` under which the whole shortlist is dropped. */
709  fitsThreshold: number
710  /** That bar for a prompt that does not name its task; `VAGUE_FITS` unless an eval sweeps it. */
711  vagueFits?: number
712}
713
714/** The shortlist the second request reads: the top of the ranking, by name. */
715export function shortlistOf(wide: Wide, skills: readonly Skill[], count: number): Skill[] {
716  const byName = new Map(skills.map((skill) => [skill.name, skill]))
717  const picked: Skill[] = []
718  for (const entry of wide.ranked) {
719    const skill = byName.get(entry.name)
720    if (skill) picked.push(skill)
721    if (picked.length >= count) break
722  }
723  return picked
724}
725
726/** Whether the first request's answer is worth a second look at all. */
727export function passesGate(wide: Wide, config: PolicyConfig): boolean {
728  return wide.gate === null || wide.gate >= config.gateThreshold
729}
730
731/** Under this `names_its_task`, the message leans on earlier turns for its task. */
732export const VAGUE_TASK = 0.3
733/** The `fits` such a message needs before anything is suggested. */
734export const VAGUE_FITS = 0.8
735
736/**
737 * The best `fits` a shortlist needs. A follow-up such as "都幫我修改完成"
738 * draws a skill that half fits (0.64–0.73 in `evals/`) and still passes the
739 * gate on its other questions, while a real task in few words, a bug to chase
740 * or a pasted log, comes back 0.88 or higher. With no `names_its_task` answer
741 * (no gate asked, as for `find_skill`, or the built-in classifier) the usual
742 * threshold stands.
743 */
744export function fitsBar(wide: Wide, config: PolicyConfig): number {
745  const named = wide.gateValues.names_its_task
746  if (named === undefined || named >= VAGUE_TASK) return config.fitsThreshold
747  return Math.max(config.fitsThreshold, config.vagueFits ?? VAGUE_FITS)
748}
749
750/**
751 * Whether a prompt gets a suggestion at all: not empty, not a typed `/name`
752 * (which already names its skill), and not a reply like "繼續" that carries
753 * no task of its own. A prompt that opens with a path ("/Users/me/app 幫我看看")
754 * is a task: its first word holds a second `/`, which no command name does.
755 */
756export function routable(text: string): boolean {
757  const trimmed = text.trim()
758  if (!trimmed || typedCommand(trimmed)) return false
759  return !contextFree(text)
760}
761
762/** Whether a prompt opens with a typed `/name`, as opposed to a path. */
763export function typedCommand(text: string): boolean {
764  return /^\/[^\s/]+(?:\s|$)/.test(text.trim())
765}
766
767/**
768 * The shortlist the second request reads. A shortlisted skill that may not
769 * be invoked is barred and dropped, not replaced by the next in the ranking.
770 * `offered` is `skills` without the barred ones.
771 */
772export function rerankCandidates(
773  wide: Wide,
774  skills: readonly Skill[],
775  count: number,
776  invocable: (name: string) => boolean,
777): { candidates: Skill[]; barred: string[]; offered: Skill[] } {
778  const candidates: Skill[] = []
779  const barred: string[] = []
780  for (const skill of shortlistOf(wide, skills, count)) {
781    if (invocable(skill.name)) candidates.push(skill)
782    else barred.push(skill.name)
783  }
784  return { candidates, barred, offered: skills.filter((skill) => !barred.includes(skill.name)) }
785}
786
787export interface Suggestion {
788  /** The one skill to suggest, or null for "nothing here applies". */
789  name: string | null
790  /** Why, for the log line. */
791  reason: string
792}
793
794/**
795 * At most one skill name for a request. With the second request switched
796 * off, the top of the ranking stands, which is what the first request alone
797 * can say; a second request that was attempted and failed suggests nothing.
798 */
799export function decide(
800  wide: Wide | null,
801  rerank: Rerank | null,
802  skills: readonly Skill[],
803  config: PolicyConfig,
804  {
805    rerankAttempted = false,
806    rerankOn = false,
807  }: {
808    /**
809     * Whether a second request was made: with one attempted and no answer,
810     * nothing is suggested, since the first request's winner has not had its
811     * false-positive check.
812     */
813    rerankAttempted?: boolean
814    /**
815     * Whether the second request is meant to run. On with no rerank at all
816     * (every shortlisted skill barred, so the ranking's next one would
817     * stand) the pick was never read, which is no answer. Off, the top of
818     * the ranking is the whole answer.
819     */
820    rerankOn?: boolean
821  } = {},
822): Suggestion {
823  if (!wide) return { name: null, reason: 'no answer' }
824  if (!passesGate(wide, config)) {
825    return {
826      name: null,
827      reason: `needs a skill ${(wide.gate as number).toFixed(2)} < ${config.gateThreshold}`,
828    }
829  }
830  const shortlist = shortlistOf(wide, skills, config.shortlist)
831  if (shortlist.length === 0) return { name: null, reason: 'nothing ranked' }
832
833  if (!rerank && rerankAttempted) return { name: null, reason: 'rerank gave no answer; no suggestion' }
834  if (!rerank && rerankOn) return { name: null, reason: 'no rerank read the pick' }
835
836  if (rerank) {
837    const values = Object.values(rerank.fits)
838    const best = values.length > 0 ? Math.max(...values) : null
839    const bar = fitsBar(wide, config)
840    if (best !== null && best < bar) {
841      return { name: null, reason: `nothing fits, best ${best.toFixed(2)} < ${bar}` }
842    }
843    if (!shortlist.some((skill) => skill.name === rerank.winner)) {
844      return { name: null, reason: `rerank named ${rerank.winner}, not on the shortlist` }
845    }
846    // The bar above only looks at the best fit on the list. The named choice
847    // must clear it on its own fits; one that does is taken even when another
848    // candidate fits better.
849    const fit = rerank.fits[rerank.winner]
850    if (fit === undefined || !Number.isFinite(fit)) {
851      return { name: null, reason: `winner ${rerank.winner} has no fits` }
852    }
853    if (fit < bar) {
854      return { name: null, reason: `winner ${rerank.winner} fits ${fit.toFixed(2)} < ${bar}` }
855    }
856    return { name: rerank.winner, reason: `rerank of ${shortlist.length}, fits ${fit.toFixed(2)}` }
857  }
858
859  const top = shortlist[0] as Skill
860  const probability = wide.ranked.find((entry) => entry.name === top.name)?.probability ?? null
861  return {
862    name: top.name,
863    reason: `top of ${wide.ranked.length}${probability === null ? '' : ` (${probability.toFixed(2)})`}, no rerank`,
864  }
865}
866
867/**
868 * The block attached to the prompt, in the cookbook's words. It can be
869 * ignored, because pushing harder wins compliance on wrong suggestions too.
870 * When the listing is still in place, a turn with nothing to suggest says so:
871 * sending nothing would leave "err on the side of loading" unopposed. With
872 * the listing withheld there is nothing to oppose, so nothing is sent.
873 */
874export function suggestionBlock(suggested: Skill | null, hidden: boolean): string | null {
875  if (!suggested) {
876    return hidden
877      ? null
878      : '<skill_relevance>\nNo skill in the roster appears relevant to this request.\n</skill_relevance>'
879  }
880  const lines = [
881    '<skill_relevance>',
882    `Relevant to the current request: ${suggested.name}. Ignore this if it does not fit what the user actually asked for.`,
883  ]
884  if (hidden) {
885    // The model has no listing to look the name up in, so the line it would
886    // have found there and the way to load it come along.
887    lines.push(
888      `${line(suggested)}`,
889      'Load it with the Skill tool (skill: "' +
890        suggested.name +
891        '") before you start. The full skill listing is withheld from your context; the user can invoke any skill by typing /name.',
892    )
893  }
894  lines.push('</skill_relevance>')
895  return lines.join('\n')
896}
897
898/**
899 * The tool the model calls mid-turn, when a sub-task starts that the prompt's
900 * own suggestion did not cover. Worded as facts, not orders: text that reads
901 * like a command can trip the model's prompt-injection defences.
902 */
903export const FIND_SKILL_TOOL = {
904  name: 'find_skill',
905  description:
906    'Finds which installed skill fits a sub-task. The skill listing names most skills without a description; ' +
907    'this tool reads their descriptions and SKILL.md and answers with at most one skill, to load with the Skill tool, or none. ' +
908    'Call it when a new sub-task starts partway through the work (the next step of a plan, a new kind of file, tool or service), ' +
909    'and before you hand the user something whose shape a team may have rules for: a query or command for them to run, ' +
910    'a document, a diagram, a config. Skip it when a loaded skill already covers the step. Pass the sub-task in one sentence.',
911  inputSchema: {
912    type: 'object',
913    properties: { task: { type: 'string', description: 'The sub-task, in one sentence.' } },
914    required: ['task'],
915  },
916} as const
917
918/** What the requests answered for one decision, kept for the record file. */
919export interface Trace {
920  wide: Wide | null
921  rerank: Rerank | null
922  ms: number
923  /** The model version that answered, so a shift in scores can be told from an alias moving. */
924  model: string | null
925}
926
927/** One decision as the record file keeps it. */
928export interface Decision {
929  /** Where the text came from: the person's prompt, or the model's find_skill. */
930  source: 'prompt' | 'find_skill'
931  text: string
932  /** The turn before, as sent beside the text. */
933  context: RecentContext | null
934  pick: string | null
935  reason: string
936  /** False when a request failed or timed out. */
937  answered: boolean
938  trace: Trace | null
939  /** The subagent that called find_skill, when one did. */
940  agentId?: string
941}
942
943/**
944 * One line of the session's record file (JSON Lines): a decision, with the
945 * ranking's top five, so a wrong pick can be read back and replayed later; or
946 * a skill the model loaded, with the pick it was made under.
947 */
948export function recordLine(at: number, entry: Decision | { loaded: string; suggested: string | null }): string {
949  const time = new Date(at).toISOString()
950  if ('loaded' in entry) return `${JSON.stringify({ at: time, ...entry })}\n`
951  const { trace, ...rest } = entry
952  return `${JSON.stringify({
953    at: time,
954    ...rest,
955    ms: trace?.ms ?? 0,
956    model: trace?.model ?? null,
957    gate: trace?.wide?.gate ?? null,
958    gateValues: trace?.wide?.gateValues ?? {},
959    top: trace?.wide?.ranked.slice(0, 5) ?? [],
960    rerank: trace?.rerank ? { winner: trace.rerank.winner, confidence: trace.rerank.confidence, fits: trace.rerank.fits } : null,
961  })}\n`
962}
963
964/**
965 * What `find_skill` answers: the pick with the description the listing left
966 * out, a plain "none", or that the lookup failed, which is not a "none". Never
967 * a SKILL.md: the model loads the skill with the Skill tool, which re-attaches
968 * it after a compaction.
969 */
970export function findSkillResult(pick: Skill | null | 'unavailable'): string {
971  if (pick === 'unavailable') return 'The skill lookup is unavailable right now (it failed or timed out); the skill listing still names every skill.'
972  if (!pick) return 'No installed skill fits this sub-task.'
973  return [
974    line(pick),
975    `Load it with the Skill tool (skill: "${pick.name}") if it fits the sub-task; ignore it if it does not.`,
976  ].join('\n')
977}
978
979/** A number for the log, or `n/d` when the backend reported none. */
980function reported(value: number | null): string {
981  return value === null ? 'n/d' : value.toFixed(2)
982}
983
984/**
985 * The one-time line that says the mod is alive, which backend answers it,
986 * and whether the listing is being withheld.
987 */
988export function describeSetup(
989  provider: Provider | null,
990  url: string,
991  hideListing: boolean,
992  builtinByChoice = false,
993): string {
994  const backend = provider
995    ? `${provider} (${url})`
996    : builtinByChoice
997      ? 'the built-in classifier, by choice'
998      : 'the built-in classifier, no key set'
999  const listing = hideListing ? 'withholding the skill listing' : 'leaving the skill listing in place'
1000  return `ready on ${backend}; ${listing}`
1001}
1002
1003/** What the first request answered: the gate and the top of the ranking. */
1004export function describeWide(wide: Wide | null, candidates: number, ms: number | null): string {
1005  const took = ms === null ? '' : ` · ${Math.round(ms)}ms`
1006  if (!wide) return `no answer from ${candidates} candidates${took}`
1007  const top = wide.ranked
1008    .slice(0, 3)
1009    .map((entry) => `${entry.name} (${reported(entry.probability)})`)
1010    .join(', ')
1011  return `needs a skill ${reported(wide.gate)} · top of ${candidates}: ${top || 'none'}${took}`
1012}
1013
1014/** What the second request answered: the winner and every `fits`. */
1015export function describeRerank(rerank: Rerank | null, ms: number | null): string {
1016  const took = ms === null ? '' : ` · ${Math.round(ms)}ms`
1017  if (!rerank) return `rerank: no answer${took}`
1018  const fits = Object.entries(rerank.fits)
1019    .map(([name, value]) => `${name} ${value.toFixed(2)}`)
1020    .join(', ')
1021  return `rerank → ${rerank.winner} (${reported(rerank.confidence)}) · fits ${fits || 'n/d'}${took}`
1022}
1023
1024/**
1025 * The persistent status line: the last thing the mod did, short enough to
1026 * sit on screen beside the engine's own notices.
1027 */
1028export function describeStatus(suggested: string | null): string {
1029  return suggested ? `jev · skill: ${suggested}` : 'jev · no skill'
1030}
1031
1032/** The name of the plugin's own setup command, as the engine runs it. */
1033export const SETUP_COMMAND = 'jev-skill-suggestion:setup'
1034
1035/** A user settings file's parts the setup touches. */
1036export interface SkillSettings {
1037  skillOverrides: Record<string, string>
1038  disableBundledSkills: boolean | undefined
1039}
1040
1041/** Reads the two fields from `~/.claude/settings.json`; malformed reads as empty. */
1042export function readSkillSettings(json: string | null): SkillSettings {
1043  let parsed: unknown = null
1044  try {
1045    parsed = json ? JSON.parse(json) : null
1046  } catch {
1047    parsed = null
1048  }
1049  const settings = (parsed ?? {}) as { skillOverrides?: unknown; disableBundledSkills?: unknown }
1050  const overrides: Record<string, string> = {}
1051  if (settings.skillOverrides && typeof settings.skillOverrides === 'object') {
1052    for (const [name, value] of Object.entries(settings.skillOverrides as Record<string, unknown>)) {
1053      if (typeof value === 'string') overrides[name] = value
1054    }
1055  }
1056  return {
1057    skillOverrides: overrides,
1058    disableBundledSkills: typeof settings.disableBundledSkills === 'boolean' ? settings.disableBundledSkills : undefined,
1059  }
1060}
1061
1062/**
1063 * Whether a file is this mod's backup: `skillOverrides` an object of
1064 * strings and `disableBundledSkills` a boolean or null. Anything else is
1065 * not something `restore` could apply, so a setup must not build on it.
1066 */
1067export function validBackup(json: string): boolean {
1068  let parsed: unknown
1069  try {
1070    parsed = JSON.parse(json)
1071  } catch {
1072    return false
1073  }
1074  if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) return false
1075  const { skillOverrides, disableBundledSkills } = parsed as Record<string, unknown>
1076  if (!skillOverrides || typeof skillOverrides !== 'object' || Array.isArray(skillOverrides)) return false
1077  if (!Object.values(skillOverrides as Record<string, unknown>).every((value) => typeof value === 'string')) return false
1078  return disableBundledSkills === null || typeof disableBundledSkills === 'boolean'
1079}
1080
1081/** The state the setup writes: the name stays listed, the description goes, the Skill tool still loads it. */
1082export const SETUP_STATE = 'name-only'
1083
1084/** Override states that already keep a skill's description out of the listing. */
1085const TRIMMED = new Set(['name-only', 'user-invocable-only', 'off'])
1086
1087export interface SetupPlan {
1088  /** User skills the setup lists by name only (`name-only`). */
1089  hide: string[]
1090  /** Of those, the ones already name-only, user-invocable-only or off: nothing to change. */
1091  alreadyHidden: string[]
1092  /** A plugin's skills: `skillOverrides` cannot touch them, only `/plugin` can. */
1093  locked: string[]
1094}
1095
1096/**
1097 * What the setup has to change, from the roster and the settings as they
1098 * are. Every user-level command is listed, so the person sees the whole set
1099 * before anything is written.
1100 */
1101export function setupPlan(
1102  commands: readonly { name: string; source: string }[],
1103  settings: SkillSettings,
1104  excluded: ReadonlySet<string>,
1105): SetupPlan {
1106  const hide: string[] = []
1107  const alreadyHidden: string[] = []
1108  const locked: string[] = []
1109  const seen = new Set<string>()
1110  for (const command of commands) {
1111    if (seen.has(command.name) || excluded.has(command.name)) continue
1112    seen.add(command.name)
1113    if (command.source === 'plugin') locked.push(command.name)
1114    // A project's own skills are few and the ones that project needs most:
1115    // they keep their descriptions, and the person decides how many there are.
1116    else if (command.source === 'user') {
1117      const state = settings.skillOverrides[command.name] ?? 'on'
1118      if (TRIMMED.has(state)) alreadyHidden.push(command.name)
1119      else hide.push(command.name)
1120    }
1121  }
1122  return { hide, alreadyHidden, locked }
1123}
1124
1125/**
1126 * The prompt the model reads for `/jev-skill-suggestion:setup`: the plan in
1127 * full, the exact edit, and the rule that nothing is written before the
1128 * person has seen the list and said yes. The model edits the file with its
1129 * own tools, so the change shows as a diff and asks permission like any edit.
1130 */
1131export function setupInstructions(
1132  mode: 'apply' | 'restore',
1133  plan: SetupPlan,
1134  settings: SkillSettings,
1135  settingsPath: string,
1136  backupPath: string,
1137  /**
1138   * Whether a backup from an earlier run is already there. It holds the
1139   * values from before the first run, which the current settings no longer
1140   * do, so a rerun must leave it alone.
1141   */
1142  backupExists = false,
1143): string {
1144  const lines: string[] = ['<jev_skill_suggestion_setup>']
1145  if (mode === 'restore') {
1146    lines.push(
1147      `The user asked to undo jev-skill-suggestion's setup: put their skills back the way they were before it ran.`,
1148      `1. Read ${backupPath}. It holds {"skillOverrides": {...}, "disableBundledSkills": ...} as they were before the setup.`,
1149      `   If it does not exist, say so and stop: there is nothing to restore.`,
1150      `2. Show the user what will change in ${settingsPath}: the "skillOverrides" entries that go back to their saved value (an entry not in the backup is removed). Leave "disableBundledSkills" as it is: this setup never changes it.`,
1151      `3. Ask the user to confirm. Only after a clear yes, edit ${settingsPath} with the Edit tool, changing nothing else in the file, then remove the backup by running exactly this command with the Bash tool: rm ${JSON.stringify(backupPath)}`,
1152      `4. Tell the user to restart Claude Code for /skills and /context to show the change.`,
1153      '</jev_skill_suggestion_setup>',
1154    )
1155    return lines.join('\n')
1156  }
1157  const overrides: Record<string, string> = { ...settings.skillOverrides }
1158  for (const name of plan.hide) overrides[name] = SETUP_STATE
1159  const after = JSON.stringify({ skillOverrides: overrides }, null, 2)
1160  const backup = JSON.stringify(
1161    { skillOverrides: settings.skillOverrides, disableBundledSkills: settings.disableBundledSkills ?? null },
1162    null,
1163    2,
1164  )
1165  lines.push(
1166    `The user asked jev-skill-suggestion to trim the skill listing: every skill stays listed for the model by name only (state "name-only": the description leaves the listing, the model can still load the skill with the Skill tool, and the user can still type /name), and the mod injects the one skill each prompt most needs. Nothing here is written until the user has seen the list and said yes.`,
1167    '',
1168    `Skills that will be listed by name only (${plan.hide.length}):`,
1169    ...(plan.hide.length > 0 ? plan.hide.map((name) => `- ${name}`) : ['- (none)']),
1170  )
1171  if (plan.alreadyHidden.length > 0) {
1172    lines.push('', `Already trimmed or off, left as they are (${plan.alreadyHidden.length}):`, ...plan.alreadyHidden.map((name) => `- ${name}`))
1173  }
1174  lines.push('', `Claude Code's bundled skills (simplify, loop, init, ...) are left as they are.`)
1175  if (plan.locked.length > 0) {
1176    lines.push(
1177      '',
1178      `Plugin skills cannot be hidden by skillOverrides; they stay listed unless the plugin is disabled in /plugin (${plan.locked.length}):`,
1179      ...plan.locked.map((name) => `- ${name}`),
1180    )
1181  }
1182  lines.push(
1183    '',
1184    'Steps:',
1185    `1. Show the user the lists above, in their language, and say the change goes to ${settingsPath} (their user settings) and can be undone with /${SETUP_COMMAND} restore.`,
1186    '2. Ask them to confirm. Do not edit anything before a clear yes.',
1187    ...(backupExists
1188      ? [
1189          `3. ${backupPath} already exists from an earlier run and holds the values from before the first setup: do NOT overwrite or modify it.`,
1190        ]
1191      : [`3. After the yes, first write ${backupPath} with exactly this content (it is what restore reads):`, backup]),
1192    `4. Then edit ${settingsPath} with the Edit tool (read it first; create it as {} if it does not exist) so that its top-level "skillOverrides" becomes exactly:`,
1193    after,
1194    '   Change nothing else in the file. Keep every other top-level key as it is.',
1195    '5. Tell the user to restart Claude Code: /skills will then show these skills as name-only, and the model keeps loading any of them by name, including one skill that names another.',
1196    '</jev_skill_suggestion_setup>',
1197  )
1198  return lines.join('\n')
1199}
1200