Model Router · Documentation · Previous: Glossary · Next: Performance
# Security
Python names are in `plugins/model-router/scripts/modelrouter/`, and Node tests in `tests/mod/router.test.ts`.
## Reporting a vulnerability
Report it privately through the repository's GitHub security advisory form ([Report a vulnerability](https://github.com/crisnahine/claude-code-model-router/security/advisories/new)). Put no details in a public issue.
## What it stores
Everything goes in one data folder: `CLAUDE_PLUGIN_DATA`, else `~/.claude/plugins/data/model-router-local`, with `CLAUDE_CONFIG_DIR` in place of `~/.claude` when set (`store.data_dir`). With `CLAUDE_CONFIG_DIR` unset and `CLAUDE_PLUGIN_DATA` an absolute path that ends in `plugins/data/`, the config folder, where `model-router.json`, `agents/` and the install records are read, is the one three levels above it (`store.claude_home`). On POSIX the folder is mode 0700 and each file the Python runtime writes is created 0600 (`store._private_file`).
- `ledger.jsonl`: session and agent ids, agent names, levels, efforts, reasons, model names, token counts and Claude Code's dollar estimate. A Stop ask, an early line about unchecked agent edits, a line about files an agent's shell changed, a delegation reminder, a delegation refusal and the end of the refusals each leave a row with the session id and a kind (`ledger.gate`). A `usage` row also says whether the session is on a subscription. Rows older than 30 days go, in a trim about once a day, and past 4 MiB the usage rows a later one replaces go, then the older half if the rest still fills 2 MiB (`store.append_ledger`).
- `routes.json`, `done.json`, `launched.json`, `pending.json`: where each call went and what came back. A call is known by a hash of its agent and prompt (`calls.identify`), its task by a hash of its agent and description (`calls.task`). No brief, prompt or description is stored (`SecurityClaims.test_no_brief_or_description_is_stored`).
- `switches.json`: per session, the `/model-router` switch, whether the session check ran, and the session's model family and effort (`settings.switch`, `session.check`, `session.observe`). Dropped at `/clear` (`settings.forget`), and by a write after a day unwritten. Any other session end leaves it.
- `sessions.json` (each session's model), `edits.json` (the time of the last project edit, whether an agent made the unchecked edits, the time of the last check or Stop ask, the change time and size, without paths, of the last 100 writes a file tool made, the IDs of the last 100 agents whose shell changes were noted, up to 6,000 characters of lines about those changes that the main conversation hasn't got yet, each naming up to 8 project files and removed when given, the time the line about unchecked work was last said, and the IDs of the last 20 agents a disk scan covered, each with two times), `allowlist.json` (the model settings the mod read, and the project path), `state.json` (model health, per provider), `locks.json` (lock waits and skipped writes), a `.flock` file per state file, empty marks under `mod-calls/`, and up to three `.corrupt-` copies of a `state.json` that failed to parse (`store.try_update`).
Per-session files keep their 200 most recently written sessions (`store.KEEP_ENTRIES`). `routes.json`, `done.json` and `launched.json` drop a session at the next write to the file once its entry is a day old (`calls.KEPT_FOR`), and a read does not check age. `edits.json` drops a session after 30 days. A session start deletes a temp file a killed hook left in the folder more than an hour ago, and the state files only earlier releases wrote (`store.sweep`).
Nothing is written outside that folder (`SecurityClaims.test_it_writes_only_under_its_data_directory`) except Python's own bytecode. Most Pythons write `.pyc` files into the plugin's `scripts/modelrouter/__pycache__`. One that writes none under the launcher's `-I`, as Apple's Python 3.9 does, gets a cache in `~/.cache/model-router/pycache`, used only while that folder and its parent are real folders owned by you, and set to mode 0700 (`private_cache` in `scripts/model-router.py`, `Launcher.test_the_bytecode_cache_is_a_folder_only_this_user_can_write`). Its path comes from the password database, never from `HOME`, which a repository's settings can set for a hook. Once a day a session start deletes the `.pyc` files there whose source folder no longer exists, an updated plugin's for one, and nothing else (`store.sweep`, `Store.test_a_session_start_drops_bytecode_kept_for_a_folder_that_is_gone`). Claude Code writes your settings when the mod runs a command for you (below).
A read-modify-write waits at most one second for its lock, then skips that one write and counts it in `locks.json` (`store.locked`). A shared file a newer release wrote is never written (`store.try_update`). A hand-edited state file can change routing and the reports, but can't run code or pass the cap or the floor, since every call is clamped again (`Registry.clamp`).
## Network
The plugin opens no connection. No shipped Python module imports `urllib`, `http`, `socket` or `ssl`, `hooks/router.ts` has no `$.http` or `fetch(` call, and `plugin.json` declares no `network` hosts (`SecurityClaims.test_nothing_shipped_opens_a_connection`). The agents use Claude Code's tools under your permission rules: `architect` has `WebFetch`, `verifier` has `Bash`, and `implementer` lists no `tools`, so it gets every tool the session has except `Agent`.
## What it reads, and whom it trusts
The Python runtime starts no process and runs no code from the repository. It reads hook and mod payloads, its own state, `config/models.json`, the user's and a project's `model-router.json`, agent frontmatter (`name`, `model`, `effort`, `tools` and `disallowedTools`) and Claude Code's plugin install and marketplace records (`agents.find`), the tail of the session's and a subagent's transcript (`session.transcript_tail`), the names, change times and sizes of the project's files after an agent ran a shell command, never their contents (`gates._changed_on_disk`), the first 256 KiB of the `.gitignore` at the top of the project, and only when it is a regular file (`gates._ignore_rules`), the first 256 KiB of a transcript, to find when it began (`gates._started`), the environment variable in the path of a check script a command names (`$TMPDIR`, or `$env:NAME` in PowerShell) and where its symlinks lead (`gates._project_check`), and the plugin's options and model variables from the environment, and `EVAL_MODEL_ROUTER_DELEGATION` only when its own files run from outside a plugin cache (`settings.resolve`). It opens no script.
Nothing it reads can switch routing off. A file or hook input that doesn't parse, bad bytes and nesting past the parser's limit included, says nothing (`store.loads`, `UnreadableProjectFiles.test_a_file_nested_past_the_parsers_limit_says_nothing`, `Store.test_a_bad_byte_in_the_ledger_is_one_more_line_skipped`). A user's override file over 4 MiB, a project's over 64 KiB, or one that isn't a regular file, such as a symlink to a FIFO or `/dev/zero`, reads as empty without blocking, and a long run of digits parses at once (`store.load_dict`, `UnreadableProjectFiles`). An agent folder is walked at most 10 folders deep and 20,000 entries, a symlink to `/` included, and only the first 24 KB of an agent file is read, which takes milliseconds even when it is all digits, blanks or blank lines (`agents._shallow_walk`, `agents.parse`; `AgentFoldersARepositoryControls`, `AgentFilesThatAreRead`).
It reads no settings file. The mod asks Claude Code for each settings source and passes on only `availableModels`, `deniedModels`, `availableModelsMatch`, `modelOverrides`, `maxEffortLevel`, `effortLevel` and each `modelSettings` entry's `maxEffortLevel` and `effortLevel`, never `env`, each cut to three levels deep (`KEYS`, `effortFields` and `shallow` in `hooks/router.ts`; Node tests "mod-start and mod-spawn carry the allowlist and effort keys of each settings source, and only the effort fields of modelSettings" and "a settings value nested past what the runtime reads crosses cut to three levels").
**The user's file and options.** Its `models`, `levels` and `agents` apply as written. `routing_mode` comes only from `/config`, and a `routing_mode` in either file is dropped (`config._clean`).
**A project's `.claude/model-router.json`.** The file read is the nearest one from `CLAUDE_PROJECT_DIR`, else the hook's `cwd`, up to the repository root, never the home folder, and only the start folder's when the root, its `.git` or its `.claude` belongs to another user (`config._up_to_root`, `config._mine`; `ProjectFromASubfolder.test_the_walk_stops_where_the_root_or_its_git_or_claude_folder_is_not_mine`, `ProjectFromASubfolder.test_the_walk_stops_where_the_roots_git_or_claude_folder_is_another_users`). On Windows the folder's owner SID must be the process's user or the owner its new files get, which is Administrators for an elevated admin (`Owner.test_a_folder_and_file_this_process_made_are_mine`, `Owner.test_the_windows_folder_is_not_mine`). A repository created from an elevated prompt and opened from a normal one is owned by Administrators, so there only the start folder's file is read.
- Only `models`, `levels` and `agents` are read, never `newest` or `older_aliases` (`SecurityClaims.test_a_repository_file_keeps_only_models_levels_and_agents`). A key that isn't a short plain name is dropped with a note that doesn't repeat it (`Registry.test_a_project_files_model_or_agent_key_that_is_not_a_plain_name_is_dropped_unechoed`).
- An added model whose name overlaps a shipped or user model, or a shipped twin such as Mythos, is dropped. The router never picks an added model and never counts one under a cap or a floor: it runs only when a call, an agent's own `model` or the user's rule names it (`SecurityClaims.test_a_project_model_is_never_the_routers_pick`, `test_a_project_model_cannot_take_a_trusted_name_or_count_under_a_cap`).
- Levels and agent rules only raise: a lower `needs` or `effort` is dropped, `level` is a floor, `model` applies only when it isn't weaker than what the call would run on, and `route: false` is ignored. A user rule that sets the agent's level or model holds the project's (`config._raises_only`, `config._rules`). `ProjectFileNeverRunsACallWeaker.test_no_project_file_runs_any_call_weaker` walks each kind of project file against every call shape and finds none that runs a call weaker.
- `/model-router:models` lists what was held. A rule's `model` that is not a short plain name is dropped unshown, and an agent file's `model` outside the registry is shown only when it is a plain name, so a repository can't put text of its choosing into output Claude reads (`Registry.test_a_project_rules_model_that_is_not_a_plain_name_is_dropped_unechoed`, `Registry.test_an_agent_files_model_that_is_not_a_plain_name_is_never_echoed`). The same filter, `config.plain`, holds every other name a repository's files or settings can choose on its way into a note, a reason, the ledger or a report: an agent's name, the model a run reports (`resolvedModel`, which `ANTHROPIC_DEFAULT_*_MODEL` or `modelOverrides` can make any text), a run's token rows, and a model error, kept as its type identifier alone (`TextARepositoryChooses.test_a_planted_agent_name_or_model_id_reaches_no_row_or_report`).
- A project's rules can't leave an agent below your `min_tier`, since the floor raises every model weaker than it, whatever the project file names.
- With no cap set, a raise can cost more. `max_tier` caps the model and leaves the effort alone.
**A project's `.claude/settings.json`.** Claude Code joins the non-managed `availableModels` lists, so a repository can add to the user's. It can't widen a managed list or `deniedModels`, or raise `maxEffortLevel`, since the lowest applies ([model config](https://code.claude.com/docs/en/model-config.md), [settings](https://code.claude.com/docs/en/settings-reference.md)). Its `env` block can set `CLAUDE_CODE_SUBAGENT_MODEL`, `CLAUDE_CODE_SUBAGENT_MODEL_FORCE` and `CLAUDE_CODE_WORKFLOW_SUBAGENT_MODEL` once you trust the folder, and the router doesn't lower or raise a model those set, so a cloned repository can run subagents above your `max_tier` or below your `min_tier` (`Router.test_the_users_environment_settings_win`, `RepeatGuard.test_a_refused_effort_only_rewrite_under_force_passes_through`). The notices and reports name those variables' values only as a short plain name (`Notes.test_the_session_start_notices_name_an_environment_model_only_as_a_plain_name`). The launcher runs Python with `-I`, so a `PYTHONPATH` set there loads no code (`Launcher.test_a_repositorys_python_path_cannot_load_code_into_the_launcher`), but `sh`, `ps` and `python3` are whatever `PATH` finds first, which the block can also set. Its `env` block can also set `EVAL_MODEL_ROUTER_DELEGATION`. The plugin reads that variable, ahead of the `delegation` option, only when its own files run from outside a plugin cache (a checkout, `--plugin-dir`, or `claude plugin eval `). The plugin counts itself installed when a folder named `cache` is in the resolved path of its own files, so a cache folder that is a symlink to a path with no such folder counts as outside a cache, and the variable is read there. An installed plugin ignores it, so a project's settings can't change an installed plugin's `delegation` through it, and can't turn its refusals on or off (`Options.test_an_installed_plugin_ignores_the_eval_variable`, `Options.test_an_eval_variable_beats_the_delegation_option_unless_it_is_empty`, `Options.test_an_eval_variable_changes_no_option_but_delegation`).
**Managed settings.** A managed `availableModels` applies alone, and `deniedModels` counts only there (`Allowlist.test_a_managed_list_applies_alone_else_the_other_sources_are_concatenated`). An allow list is cut to 200 entries of up to 200 characters, and a managed deny list over that leaves no model open (`Allowlist.test_a_deny_list_over_the_cap_leaves_no_model_open_while_an_allow_list_is_only_cut`). Claude Code still applies both lists to every subagent model ([sub-agents](https://code.claude.com/docs/en/sub-agents.md)).
**Prompt and brief text.** The router reads no brief. Claude names the model and effort, so text Claude reads can sway what it names, within the cap and the floor. A call that names no model gets its level from its agent definition's `tools` and `disallowedTools` alone: `lookup` when they leave out Edit, Write, NotebookEdit, Bash, PowerShell and Monitor, else `standard` (`agents.read_only`; `UnnamedCalls.test_the_pick_never_reads_the_brief`). A list it can't read with confidence, such as a block scalar, an alias or a list never closed, counts as every tool, so it never reads an agent that can write as one that only reads (`AgentTools.test_a_tool_list_that_cant_be_read_with_confidence_counts_as_every_tool`). A repository's own agent file sets that level through its tool list, as its `model` field can already set the model. A `description` starting with "Redo:" makes a call climb, inside the usable models (`router._redo`; `RepeatGuard.test_a_redo_held_under_the_cap_on_its_model_takes_more_effort_up_to_max`).
## What reaches Claude's context
All of it goes to the model provider with the conversation:
- the session-start note, which names `CLAUDE_CODE_SUBAGENT_MODEL` under FORCE only when it is a short plain name (`Notes.test_an_environment_model_reaches_claude_only_as_a_plain_name`), and, where the mod runs, the same note in the Agent tool's description and its form for a workflow script in the Workflow tool's (`tool.describe` in `hooks/router.ts`);
- a note when the user's prompt names a shipped or user model (`hooks.user_prompt`);
- where the mod runs and `delegation` is `on` or `strict`, the delegation reminder after a work call's result and, under `strict`, the refusal's message and the line that says the refusals are off (`hooks._delegate`);
- the fallback's note on each call it rewrites, and its deny reason (`fallback.route`);
- a sentence after a redo that had no step left, naming only a registry model and an effort (`spawn.redo_note`);
- the line the main conversation gets beside an agent's report, which names up to 8 project files the agent's shell changed, each in backticks, and only names made of ASCII letters, digits and `. / _ @ + - ( ) [ ]`. It names the agent by its ID only when that is letters, digits, `_` and `-`, and, where one command alone was running when a file changed, gives the number of that shell command, never the command's text (`gates._unnamed`, `SubagentChecks.test_only_a_plain_file_name_and_a_plain_agent_id_are_shown_to_the_main_conversation`);
- the fixed line that no check has run on what an agent changed (`gates.unchecked_at_return`);
- the Stop ask, which for an agent's unchecked work asks for its check or a review by `model-router:reviewer`, and the notes after a model error or a mid-run model switch (`hooks.agent_failed`, `hooks.post_agent`);
- skill output: the policy and `explain` from `/model-router:route`, model status, state file paths, held rules and a workflow pin named only as a plain name from `/model-router:models` (`Notes.test_the_models_report_names_a_workflow_pin_only_as_a_plain_name`), and agent and model names, plain ones only, tokens and dollar estimates from `/model-router:usage`.
Notices about pinned models go to `systemMessage`, shown to the user ([hooks](https://code.claude.com/docs/en/hooks.md#json-output)), and name a pinned model only as a plain name. The plugin sends Claude its text through hook output such as `additionalContext` and `permissionDecisionReason`, or through the mod's tool description and results, and uses `systemMessage` only for notices to the person. The mod's status line, toasts and session check dialog are drawn for the person, and its `/model-router` reply is marked for the person alone (`isTextDisplayOnly`).
## What it denies
It never approves a tool call (`SecurityClaims.test_it_never_approves_a_tool_call`). On the settings-hook path it denies one kind of tool call: a call it rewrote to a lower model that comes back five seconds to 30 minutes later with no result or error in between, when the model the call would run on untouched is above `max_tier`, and, under `min_tier`, a call it rewrote to a higher model that comes back the same way when the untouched model is below the floor. The denial names the model to use (`fallback._guard`; `RepeatGuard.test_the_cap_holds_even_when_a_lowering_rewrite_did_not_take`, `MinTier.test_a_refused_raise_is_denied_like_a_refused_lowering`). It keeps no agent running and refuses no hand-back: an agent whose shell changed a project file stops as it would, and the main conversation gets the line about the files (`hooks.agent_stopped`, `hooks.handing_back`; `SecurityClaims.test_no_hook_answers_with_a_block`, `SubagentChecks.test_an_agent_that_hands_its_report_back_is_noted_at_the_hand_back`). The mod denies a tool call in one case: under `delegation: strict`, the default, a Read, Grep, Glob, Edit, Write, NotebookEdit, Bash, PowerShell, WebFetch or WebSearch call of the main conversation, once it has moved 8,000 characters or more with no agent started (a fork or the web-fetch agent does not count as one), and only while the session can start an agent (the `tool.call` handler and `canStartAgent` in `hooks/router.ts`). To decide that, the mod asks Claude Code whether the `Agent` tool is allowed (`$.tool.check`), which runs nothing. The refusal says why, and the call runs again once an agent starts. With routing on, and either no Python or a spawn whose own round trip to the runtime fails twice, it holds a named model to `max_tier` and `min_tier`, lowering one above the cap and raising one below the floor (`heldTo` in `hooks/router.ts`). It also refuses a `/config` change to its own options while a main-loop turn runs or an agent whose effort it set has not ended, since the change reloads the mod (the `config.set` hook in `hooks/router.ts`; Node test "a change to this plugin's options in /config is refused while Claude works or an agent the router set the effort of runs").
## The mod
`hooks/router.ts` starts two processes: `ps`, below, and `sh /scripts/model-router.sh `, run as an argument array so no shell parses the input, with the event as JSON on stdin and an 8-second timeout (`ask`). Every hook passes the event on unchanged when anything fails (Node test "every hook falls back to next(e) when it throws"). It never changes a prompt. Its only file writes are empty marks under `mod-calls/`: one per `Agent` call it routes, and `.moved` for a spawn a later mod moved. Each is named by the call's `tool_use_id` only when that id is 1 to 128 letters, digits, `_` or `-` (`PLAIN_ID`), and the settings hooks check the same pattern before they remove one (`Mod.test_only_a_plain_tool_use_id_is_looked_up`, `MovedByAnotherMod.test_only_a_plain_tool_use_id_is_looked_up`).
## What the mod runs in an interactive session
Only in a session with a person at the prompt (`isInteractive`), never in `claude -p` or the Agent SDK (Node test "a headless run registers, draws and asks nothing, and routes as before"):
- **`/model` and `/effort`.** The session check runs Claude Code's own commands through `$.command.run` only after you pick a setup in its dialog, and only for a label it sent: a dismissal or typed text runs nothing (Node test "a dismissal or free text at either step changes nothing"). The arguments come from the runtime: a registry family alias or its newest ID, and an effort level (`session._model_choice`). Claude Code then saves the model in your user settings and the effort under `modelSettings`, as it does for a typed `/model` or `/effort`, and applies its own allowlist and organization rules. A refused `/model` stops the switch before `/effort`, and the note that the session stayed names its model only as a plain name, since a repository's settings can set it (Node test "a switch that fails says so and stops, and one Claude Code did not take says the session stayed").
- **Its own command line, once.** Before the session check, the mod runs `sh -c 'ps -o args= -p "$CLAUDE_PID"'`, a fixed script with a 2-second timeout, on the Claude Code process its hook environment names, to find a `--effort` flag, which no settings file or mod call carries. Only the level leaves that function; the rest of the line, a prompt given at launch included, is dropped unstored (`launchEffort` in `hooks/router.ts`; Node test "an effort flag at launch reaches the session check, and nothing else of the command line does").
- **One option.** The mod writes `session_check` through `$.config.set`, from `/model-router check on` or `off` or the check's "Don't ask again", and Claude Code refuses that write when managed settings own the row (Node test "/model-router check off and on write the option, unless managed settings own it"). It never writes `routing_mode`: `/model-router on` and `off` keep the switch in `switches.json` for that session only.
## Skills
Each skill's `allowed-tools` pre-approves only the launcher commands that skill runs, behind the fixed `--data-dir "${CLAUDE_PLUGIN_DATA}"` prefix, and only `models` may run `models reset`, the one skill command that writes state (`SkillGrants.test_each_skill_may_run_its_own_commands_and_nothing_that_writes_files`). `usage` and `models` pass `$ARGUMENTS` unquoted, and both set `disable-model-invocation: true`, so Claude runs them only in a turn where the user's message names them with the slash. When that message doesn't open with the name, Claude chooses the arguments. The `route` and `models` lines pass the options as `${user_config.}`, which Claude Code fills from user or managed settings, never a repository's ([plugin configs](https://code.claude.com/docs/en/settings-reference.md#pluginconfigs)).