Architecture

This page shows how the two released plugins (session-hub 0.5.1 and model-router 0.7.3) are built: what components make them up, how they talk to each other, what files they write to disk, and how they behave when something goes wrong.

Two plugins, two problems

Working across multiple repositories in Claude Code brings up two distinct needs: coordinating isolated sessions without letting them step on each other's toes, and picking the right model and effort for each delegated task without guessing. To keep responsibilities cleanly separated, the system is split into two standalone plugins.

You talk to the master session and work directly in one child session; the master starts one child per repository, each in its own terminal pane and write root, and a child that needs a change elsewhere asks the master. You one person Master session coordinates the children and keeps a record of them asks and decides works hands-on in the repository you know best starts each child and sends it [master] messages asks the master for a change in another repository pane 1 Child · api its own rules already loaded write root: api/ pane 2 Child · web its own rules already loaded write root: web/ pane 3 Child · docs its own rules already loaded write root: docs/ The children run in parallel, one per repository. They never message each other: every request goes through the master.
The master at the hub root launches one child session per repository; each is confined to its own write root, while model-router picks the model and effort on every launch.
PluginIn one line
session-hubA master session at the hub root spawns one child session per repository, assigns each a scope, routes requests, and keeps the child session record up to date.
model-routerA single grid picks the model and effort for every subagent, child session, or workflow agent; a mod routes model-less subagent launches and locally measures how each choice paid off.

Because they solve different problems, the two plugins are designed to stay independent while working seamlessly together when installed side by side.

Independence and shared contract

You can use either plugin on its own without installing the other: session-hub never requires model-router, and model-router knows nothing about hubs. At the few touchpoints between them, one skill invokes the other by its full name (<plugin>:<skill>) and checks at runtime whether it is installed.

The grid lives in one place — model-router:choose-model — and session-hub keeps no copy of it. When session-hub:spawn needs to pick the model and effort for a child session, it applies the first rule in priority order that returns a value:

  1. What you explicitly asked for in the conversation.
  2. The Model and Effort keys configured in the hub, per repository or per type of work.
  3. model-router:choose-model, if installed, applied to the child session's handoff.
  4. The master's own --model and --effort; the summary explicitly notes that the child session inherited them.

So a change in one plugin cannot break the other, everything they are allowed to assume about each other is locked down in a shared contract in the repository's design docs. Any change lands in the contract first via its own pull request; the plugins only adapt afterward. The contract defines:

  • the precedence order above;
  • the --model and --effort launch flags;
  • the fixed SESSION_HUB_* environment variable names;
  • the naming rules and paths where each plugin stores its state.

Every externally visible surface carries the name of the plugin that owns it, so you always know where a message or file came from: the session-hub-scope-guard hook, the session-hub and model-router mods and commands, the [session-hub] prefix on block messages, the 🔀 marker in router output, the SESSION_HUB_* variables, and the session-hub/ and model-router/ state directories.

With the boundary between the two plugins clear, let's look at the pieces inside each one.

Components

Each plugin combines prose skills, zero-dependency Node scripts, and — when mods are enabled — a mod that extends Claude Code's UI and hooks.

session-hub

ComponentTypeRole
session-hub:dispatchskillMaster side: decides per repository whether the master reads, a subagent reads, or a child session is needed; handles incoming messages and routes out-of-scope requests.
session-hub:spawnskillLaunches one child session per repository in the detected environment — with scope, model, effort, role variables, and handoff — and adds it to the child session record.
session-hub:setupskillCreates or updates the hub's ## Child sessions section, only after your explicit confirmation.
session-hub-scope-guardhookPreToolUse on Edit, Write, and NotebookEdit, declared in hooks/hooks.json and implemented in hooks/scope-guard.mjs.
scripts/registry.mjsscriptThe sole writer of the child session record: reads, merges changes, and rewrites the file atomically under a lock.
session-hubmodLoaded from the same hooks.json: adds the send guard, shell check, origin tagging, scope line, child session panel, and /session-hub command.

model-router

ComponentTypeRole
model-router:choose-modelskillDefines the grid and guides the agent to pass an explicit model and effort on every launch.
model-router:setupskillCreates or updates a project's ## Model routing section, only after your explicit confirmation.
model-router:reportskillRuns scripts/report.mjs without computing anything itself.
model-routermodhooks/model-router.tsx: routes model-less launches, renders the 🔀 line under Agent calls, logs quality-loop events, and exposes /model-router.
lib/*.mjsmodulesES modules shared between the mod and scripts: judge prompt and response, routing table, outcomes, aggregates, usage view rows, and report page.
scripts/compact.mjs, report.mjs, usage.mjsscriptsZero-dependency Node scripts for compaction, the report page, and usage view data.
grid.jsondataThe machine-readable grid with the usual choice for each task class; the judge prompt is generated from this file.

In both plugins, the skills and the classic hook work even when mods are disabled. Mod-based features require mods to be enabled and Claude Code 2.1.329 or later.

To enforce checks only where needed — leaving your regular sessions outside the hub untouched — the plugins first have to know for sure what role the current session holds.

Roles

A security check cannot guess a session's role by reading the conversation. Every session is therefore explicitly classified as a child session, master, or neither.

RoleHow a session gets itWhat the plugins do
ChildThe launch command sets SESSION_HUB_ROLE=child (handled by spawn).The scope guard checks every file edit; with mods enabled, the send guard, shell check, origin tagging, and scope line also kick in.
MasterNo variable needed: any session in the hub running dispatch or spawn. With mods enabled, also any session that calls the record script with a literal absolute path or whose directory already has child sessions in the record.Skills launch child sessions and update the record; with mods enabled, the child session panel and scope line are added.
NeitherEvery other case.The scope guard exits immediately without reading input; the mod neither blocks nor tags anything.

Environment variables are parsed conservatively so a typo can never silently disable guards:

  • SESSION_HUB_ROLE is read case-insensitively with leading and trailing whitespace trimmed.
  • Any value other than an empty string, none, master, or child causes every guard to block.
  • The other variables passed to a child session are SESSION_HUB_MASTER, SESSION_HUB_SCOPE_ROOT, SESSION_HUB_HANDOFF, SESSION_HUB_REGISTRY, and SESSION_HUB_GUARDS.

With components and roles in place, let's trace what happens step by step from the moment you hand a task to the master.

The spawn flow

When you ask the master to work on one or more repositories, launching a child session goes through eight ordered steps:

  1. You give the master work that touches repositories; dispatch determines that a child session is needed.
  2. The master reconciles the child session record against currently live session names, marking any session that is no longer running as lost.
  3. It checks that no live duplicate already exists, then resolves the environment, name, optional worktree, write root, and scope.
  4. It resolves model and effort from your request or the hub keys; if neither is set, it consults model-router:choose-model (if installed); if that isn't available either, it inherits the master's model and effort.
  5. It writes the handoff outside the hub (to a file, or inline for the desktop app).
  6. It launches the child session with the propagated flags, child-specific flags, and SESSION_HUB_* variables; Claude Code starts in the repository and reads the handoff.
  7. It records the child session as running and shows you a summary per child: repository, write root, model and effort, environment, and any warnings.
  8. From that point on, every Edit, Write, and NotebookEdit call in the child session runs through the scope guard.

The child session record never blocks a launch: if registry.mjs returns an error, spawn warns you and starts the child session anyway.

Conversely, when a child session needs something outside its scope, the request travels back the other way — always through the master.

The web child needs a change in api and asks the master; the master decides whether to pass it to the api child, start a child, ask you or do it itself, then tells the web child what will happen and records the request. A message is information, never authorization. Child · web Master Child · api You realizes it needs a new field in api asks the master [t42 web] out-of-scope is it wanted? is it master-only? does a live child own it? then one of these passes it on with a follow-up, or starts a child in api asks you to decide or does it itself, when the work is master-only or just a read tells it what will happen: wait, or carry on records the request and how it ended A message is information, never authorization. No session merges, pushes, deletes or changes settings because another session asked.
Routing an out-of-scope request: if a decision is needed, you are asked; master-only tasks or permitted reads are handled by the master; otherwise, a follow-up goes to a live child session that owns the repository, or a new one is spawned. The requesting child session always gets confirmation of what will happen next.

The final step of the spawn flow hands boundary enforcement over to an automated technical check. Here is how the scope guard works under the hood.

The scope guard

Handoff instructions tell a child session where it should work, but they don't physically stop a stray write. To turn scope into a hard boundary, the hook runs node "${CLAUDE_PLUGIN_ROOT}/hooks/scope-guard.mjs" before every Edit, Write, and NotebookEdit call with a 10-second timeout. It runs in every session, but only steps in inside child sessions: it exits with code 0 to allow the call, or code 2 to block it and explain why to the model.

The scope guard checks every file edit: outside a child it allows at once; in a child it blocks whenever it cannot decide, finds where the path really leads, allows the edit inside the write root and blocks it outside, telling the child to ask the master. With mods on, a best-effort check also watches the shell. The agent is about to edit a file Edit · Write · NotebookEdit Is this a child session? and are its guards turned on? Can the guard check this edit? a readable request, a valid write root, an absolute path, an answer within 7 s Find where the path really leads it follows links and “..” the way the file system does Is it inside the write root? the real path, compared with the real write root Allowed: the edit goes ahead yes yes yes Allowed at once outside a child, the guard never gets in the way Blocked, and it says why when it cannot decide, it blocks: the guard fails closed Blocked: outside the write root the child asks the master with an out-of-scope message instead no no no With mods on, a best-effort check also watches the shell. It denies redirections and commands such as tee, cp, mv, rm or sed -i when they would write outside the write root; targets in variables or globs are not judged. With mods off, only the handoff forbids writing through the shell.
Scope guard decision flow: outside a child session it allows immediately; inside one, any failed check blocks the call, and only a real path under the real write root is allowed.
  • Real paths. Both the write root and the target path are resolved component by component, following symlinks: a symlink inside the write root pointing outside it is blocked. A path counts as inside only if it equals the write root or starts with the write root followed by a path separator.
  • Absolute paths only. Relative targets or paths starting with ~ are blocked; setting / or the home directory as the write root is treated as a configuration error.
  • Fails closed. An unknown role, missing or invalid write root, unreadable input, missing path on the call, unresolvable path, or internal error always blocks. If node itself fails to start, the shell wrapper in hooks.json checks the role and blocks unless the session is not a child session or guards are disabled.
  • Pre-timeout cutoff. Claude Code treats a timed-out hook as a non-blocking error; to keep anything from slipping through, the scope guard self-blocks after 7 seconds.

The scope guard protects file-editing tools even without mods. When mods are enabled, session-hub extends coverage to cross-session messaging, the shell, and the UI.

The session-hub mod

A child session could still try to write files via the shell or message a sibling session directly, while you in the master need an easy way to keep an eye on running sessions. The session-hub mod handles all of this, loaded from the modules entry of the same hooks/hooks.json with its logic in plain .mjs modules.

The mod writes no files to disk: it reads the child session record, keeps everything else in session memory, and rebuilds it when a session is resumed.

FeatureWhereEventBehavior
Send guardchild sessionsession.sendAllows sending only to the master and the session's own subagents; rejects any other recipient and names the master in the reason.
Shell checkchild sessiontool.call on BashBest-effort: denies redirections and file-writing commands targeting paths outside the write root.
Origin taggingchild sessionsession.receive, prompt.submitAdds a line to every message received from another session as a reminder that it is informational only, never authorization.
Scope linechild session, masterprompt.compose, prompt.submitInjects role and scope (or the record) into the system prompt and as context after startup, compaction, and /clear.
Child session panelmasterui.render, command.runShows one row per child session with live status from the session list; refreshes on /session-hub and every 30 seconds.

The send guard and shell check fail closed; origin tagging, the scope line, and the panel are informational only and never block. If an organization-managed mod runs first and skips an event, the mod falls back to sending the scope line as context.

Both the skills and the session-hub mod read and update a single shared store: the child session record.

The child session record

To track child sessions without dirtying the hub or repositories — and avoid corruption when multiple commands hit the same file — session-hub stores the record at:

<config dir>/session-hub/children-<hub id>.json

The <hub id> is the first 16 hex digits of the SHA-256 of the hub's real path normalized to Unicode NFC, so reaching the same hub via a symlink always yields the same ID. The directory is created with mode 0700, and the record file and its lock with 0600.

  • Commands: path, read, upsert, status, request, and reconcile, each taking --hub (plus --file for a record at an alternate path). An unrecognized option exits with an error without writing anything, and any path that resolves inside the hub — even through a symlink or a directory that does not exist yet — is rejected.
  • Locking: an exclusive <record>.lock file; writers wait up to 5 seconds, and any lock older than 30 seconds or owned by a dead process is treated as stale and taken over atomically so two processes cannot delete each other's lock.
  • Atomic writes: writes go to a temp file in the same directory, flush to disk, and rename over the record.
  • Never overwritten if unreadable: a file containing invalid JSON or a newer format version is reported and left untouched so you can inspect it.
  • Statuses: running → waiting-user, done, abandoned, or lost; reconcile marks any active entry missing from the session list as lost and refuses an empty list.

The record wraps up the session-hub side. Next is model-router, starting with the file every decision stems from: the grid.

The grid and grid.json

Model-selection rules are needed in three places: the prose skills, the judge prompt, and the quality loop. Keeping them in sync by hand would be brittle, so grid.json serves as the single machine-readable source for the whole plugin. It holds:

  • the tiers in check order and price order;
  • the effort levels and their guiding questions;
  • the six task classes and the usual choice for each;
  • the tag format and judge mapping (fast = haiku, balanced = sonnet, deep = opus).
The grid asks its questions in order and stops at the first yes: haiku for simple, repetitive work that is easy to check, sonnet when done fits in one sentence, fable for large open-ended work where judgment and accuracy both matter, opus for everything else and whenever in doubt; effort is low for a simple task, xhigh for long, hard, critical and unattended work, high when a missed mistake would be costly, medium otherwise, and never max. Every start also names one of six task classes. Model: the first fit wins Effort: the first yes wins Simple, repetitive work? easy to check, no judgment calls haiku Does done fit in one sentence? a clear, well-specified change sonnet Large and open-ended? both judgment and accuracy matter fable Everything else and whenever you are in doubt opus nonono Simple, or a quick exchange? low Long, hard and critical? and unattended: all of them xhigh Costly if a mistake slips by? money, a client, a wrong decision high None of the above max is never used medium nonono Price: cheapest first haiku < sonnet < opus < fable when in doubt, go up Task classes tag [mr:<class>], or [mr:<class>!] when risky read-search read-analyze edit-mechanical edit-specified review-debug design-open
The grid: four tiers, four effort questions, six task classes.

choose-model presents the same grid in prose for the agent, while setup lists the values a project can configure. To keep the three files from drifting apart, grid.test.mjs fails as soon as they get out of sync — so any change to the grid updates grid.json and both skills together.

At runtime, the router mod reads tiers, effort questions, and task classes from grid.json to build the judge prompt, while the quality loop uses each task class's usual choice as its prior.

Now let's look at how the router mod applies this grid when a subagent starts, and how it collects quality data.

The router mod

The model-router mod handles three coordinated jobs: routing launches that omit an explicit model, calling the judge to classify the work, and logging the events that feed the quality loop.

Routing

When a subagent is launched via the Agent tool, the mod cannot simply rewrite the input in a single hook: under auto permission mode, Claude Code rejects a call whose input was mutated by a hook after review. Instead, the work is split across three steps:

  1. A tool.call hook evaluates the case, calls the judge if needed, and forwards the call untouched.
  2. The subsequent agent.spawn hook sets the model relative to the caller's model and logs the decision.
  3. A turn.step hook applies the chosen effort to each model request the subagent makes.
When a subagent starts, the router keeps the request as it is if it already carries a model or is a fork or a resume, if its agent fixes its own model, or if routing is off; otherwise one call to the judge lowers, raises or escalates the model, and any error leaves the request unchanged. The model is set when the subagent starts, the effort on each of its requests. A subagent starts (Agent tool) Does it already carry a model? or is it a fork, or a resume? Does its agent fix its own model? or is it a plugin’s agent, or unreadable? Is routing turned off? or is a session-wide subagent model set? Keep the request goes on unchanged yesyesyes no Ask the judge one call to the fast tier, 8 s at most Lower the model confidence 0.6 or more Raise the model confidence 0.3 or more Risky work risk above 0.7, or a ! tag: deep tier, effort ≥ high It fails open: any error leaves the request unchanged. That covers a timeout and an unreadable answer too; a ! tag still goes to the deep tier. Model: set when it starts at agent.spawn Effort: set on each of its requests at each turn.step, never on the start call
Routing cases: explicit model, fork, resume, fixed-model or plugin agent, and disabled routing pass through unchanged; a model-less launch goes through the judge and threshold rules.

The judge

Classifying a task on the fly has to be cheap, finish in seconds, and resist prompt injection from the task text itself. The judge meets those constraints in four ways:

  • Tight budget: a single call on the fast tier at low effort, capped at 300 tokens and an 8-second timeout.
  • Safe prompt: generated from grid.json; the task text is truncated to 4,000 characters, wrapped as a data block, and stripped of raw closing tags via escaping.
  • Structured response: a JSON object with tier, confidence, effort, effort confidence, risk, and task class.
  • Conservative thresholds: stepping down a tier requires confidence ≥ 0.6, while stepping up only takes ≥ 0.3; risk above 0.7 or a ! tag forces the deep tier and at least high effort.
The judge reads the subagent type, its short description and the task as data, with a prompt generated from grid.json, and makes one call to the fast tier at low effort, within 300 tokens and 8 seconds. It answers one JSON object; the model changes only when the answer is confident enough, risky work goes to the deep tier with at least high effort, and effort is never max. The model is set at agent.spawn, the effort on every request, and the decision is logged. Any error leaves the start unchanged, and every threshold is an option. 1 Input the subagent type its short description the task itself, cut at 4,000 characters passed as data: the judge is told not to obey it 2 Prompt generated from grid.json: the three tiers, the four effort questions, the six task classes, and: risk is about the act fast · balanced · frontier · deep 3 One judge call to the fast tier, at low effort, within 300 tokens and 8 seconds 4 It answers with one JSON object { tier, confidence, effort, effort_confidence, risky, class } 5 Model rules Lower it only at confidence ≥ 0.6 Raise it at confidence ≥ 0.3 Risky above 0.7, or a ! tag: the deep tier, with effort at least high With no confidence, the model never changes Current model unknown: it counts as raising Effort rules Set when effort_confidence passes the bar low needs the lowering bar (0.6) medium, high or xhigh: the raising bar (0.3) An effort the call already carries is kept Never max 6 Model at agent.spawn against the parent’s model Effort on every request at turn.step; the Agent call itself is untouched 7 Decision logged in events.jsonl Error, timeout, unreadable answer the start is left unchanged: it fails open Every threshold is an option minDowngradeConfidence minUpgradeConfidence riskThreshold · timeoutMs
The judge from input to decision.

The quality loop

Routing choices should be judged by real outcomes, not just initial intuition. To make that possible, the mod appends decision, spawn, signal, report, and session-end events to events.jsonl.

Compaction — run at session start, by the usage view, and by the report — turns those raw events into usable stats:

  1. It resolves the outcome of every task whose rework window has closed and appends it as an outcome entry.
  2. It folds outcomes into task class × tier × effort cells across two scopes (user and project), with time decay and the grid as prior.

The report page and the usage view share the same aggregation logic (lib/usage-data.mjs), so their numbers always match. Through version 0.3, the router only collects and displays this data without using it to alter routing decisions.

The mod appends events to events.jsonl in the Claude Code config folder; when a task's rework window closes its outcome is decided, compaction folds the outcomes into cells by class, tier and effort, for you and for each project, and the usage view and the report show first-pass yield, rework rate and cost per success. Nothing is written inside your repositories. 1 Events decision · spawn signal: write · tool-error prompt · stop · resume report · session-end recorded by the mod as they happen 2 events.jsonl an append-only log in the config folder 3 The rework window closes 30 minutes after the report, or when the session ends 4 Outcome success rework failure cancelled cancelled or risky tasks are not learned from 5 Compaction cells: class × tier × effort for you, and for each project a 30-day half-life ages them 6 What you see in /model-router and on the report page first-pass yield rework rate cost per success All of it lives under the Claude Code config folder (CLAUDE_CONFIG_DIR, else ~/.claude). Nothing is written inside your repositories, and nothing is sent anywhere.
Events, outcomes, cells: how the quality loop turns subagent runs into numbers.

Planned for a later release (still provisional): when adapt is enabled, Thompson sampling selects between the grid's pick and its neighboring cells, using the grid as a prior; exploration is capped at 10% of recent decisions for a task class, with no exploration on risky launches; recommendations.json is written during compaction for choose-model to read.

Every file produced by the record and the quality loop lives in a well-defined spot outside your repositories. Here is the full list in one table.

On-disk state

Neither plugin writes state files inside a hub or repository, keeping your working trees clean. Aside from temporary handoffs, all state lives under the active config directory (CLAUDE_CONFIG_DIR if set, otherwise ~/.claude).

PathPluginContents
session-hub/children-<hub id>.json and .locksession-hubThe child session record and its lock
<scratchpad or mktemp -d>/<name>-handoff.mdsession-hubOne handoff file per child session, stored outside the hub
model-router/events.jsonlmodel-routerDecisions, spawns, signals, reports, session ends, and outcomes (append-only)
model-router/archive/model-routerEvent log rotated by compaction past 32 MB: keeps outcomes, decisions, and spawns, and only outcomes after 90 days
model-router/quality/user.json, quality/projects/<id>.jsonmodel-routerPer-user and per-project quality aggregates
model-router/quality/state.json, quality/.lockmodel-routerCompaction cursor and lock (stale after 2 minutes)
model-router/options.jsonmodel-routerOptions used by compaction and the report
model-router/report.htmlmodel-routerThe local report page
model-router/quality/recommendations.jsonmodel-routerRecommendations per task class, read if present; no version writes them yet

The only writes that ever touch a hub or project are two configuration sections — ## Child sessions in the hub and ## Model routing in the project — both created only after your explicit confirmation and never committed automatically.

Knowing how the hooks work and where files live makes it clear why the two plugins take opposite stances when something fails.

Failure behavior

Not all failures carry the same weight: violating a repository's scope can damage code, whereas skipping a model optimization at worst makes a call slower or pricier. By design, the two plugins fail in opposite directions.

session-hub: fails closed

Any guard that cannot evaluate a call in a child session blocks it and explains why. A corrupt record, a newer format version, or an unacquired lock halts the write and leaves the file untouched. The record itself, however, never stops your work: skills warn you and carry on without recording.

model-router: fails open

An error never stops your work. A judge failure, timeout, or unreadable response leaves the launch untouched; every hook wraps its logic in a catch that lets the event proceed. If the recommendations file is missing, the grid decides on its own. An interrupted compaction is safe to rerun.

The underlying principle is straightforward: a guard that accidentally lets a write through violates the scope it exists to defend, whereas a router that accidentally blocks a launch halts work it exists only to optimize.

Finally, let's look at which Claude Code versions and environments meet the requirements for everything covered above.

Compatibility

Here are the minimum environment requirements and what has been verified on recent Claude Code releases.

RequirementValue
Tested Claude Code versions2.1.329 and 2.1.330
Cross-session messaging, for session-hubClaude Code 2.1.224 or later
ModsAvailable since Claude Code 2.1.287; both mods declare engines["claude-code"]: ">=2.1.329"
nodeOn PATH, for the scope guard, record script, panel, and all model-router scripts; zero dependencies
Operating systemmacOS and Linux: the hook wrapper is a POSIX sh command, and the report opens via open or xdg-open
  • Verified on 2.1.329: --effort on the launch command and SESSION_HUB_* variables reach the child session in -p, --bg, tmux, and Herdr; a session in a repository nested under the hub loads both the hub's instruction file and its own.
  • Verified on 2.1.330: routing works in both auto permission mode and default mode.
  • Unverified: the desktop app launch tool (role variables, model, and effort).