---
title: "Architecture"
canonical: "https://mrbogomips.github.io/agent-orchestration/architecture/"
author: "MrBogomips"
published: "2026-11-28T20:45:48.000Z"
modified: "2026-11-28T20:45:48.000Z"
lang: "en"
license: "CC-BY-4.0"
code-license: "MIT"
---

This page shows how the two released plugins (session-hub 0.8.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 creates two separate problems: keeping isolated sessions from stepping on each other's toes, and picking the right model and effort for each delegated task without guessing. Rather than bundling both into one package, the system splits them into two standalone plugins.

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.

| Plugin         | In one line                                                                                                                                                                             |
| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `session-hub`  | A 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-router` | A 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. |

Each plugin works on its own, and when you install both they coordinate through a shared contract.

## Independence and shared contract

You can install and use either plugin on its own: `session-hub` never requires `model-router`, and `model-router` knows nothing about hubs. At the few points where they interact, 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 specified 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`, with a note in the summary that the child session inherited them.

To keep changes in one plugin from breaking the other, everything they are allowed to assume about each other is locked down in a shared contract in the repository's design docs. Changes land in the contract first through a dedicated pull request, and the plugins 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.

## 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`

| Component                 | Type   | Role                                                                                                                                                                      |
| ------------------------- | ------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `session-hub:dispatch`    | skill  | Master 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:spawn`       | skill  | Launches 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:setup`       | skill  | Creates or updates the hub's `## Child sessions` section, only after your explicit confirmation.                                                                          |
| `session-hub-scope-guard` | hook   | `PreToolUse` on `Edit`, `Write`, and `NotebookEdit`, declared in `hooks/hooks.json` and implemented in `hooks/scope-guard.mjs`.                                           |
| `scripts/registry.mjs`    | script | The sole writer of the child session record: reads, merges changes, and rewrites the file atomically under a lock.                                                        |
| `session-hub`             | mod    | Loaded from the same `hooks.json`: adds the send guard, shell check, origin tagging, scope line, child session panel, and `/session-hub` command.                         |

### `model-router`

| Component                                        | Type    | Role                                                                                                                                                    |
| ------------------------------------------------ | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `model-router:choose-model`                      | skill   | Defines the grid and guides the agent to pass an explicit model and effort on every launch.                                                             |
| `model-router:setup`                             | skill   | Creates or updates a project's `## Model routing` section, only after your explicit confirmation.                                                       |
| `model-router:report`                            | skill   | Runs `scripts/report.mjs` without computing anything itself.                                                                                            |
| `model-router`                                   | mod     | `hooks/model-router.tsx`: routes model-less launches, renders the `🔀` line under `Agent` calls, logs quality-loop events, and exposes `/model-router`. |
| `lib/*.mjs`                                      | modules | ES 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.mjs` | scripts | Zero-dependency Node scripts for compaction, the report page, and usage view data.                                                                      |
| `grid.json`                                      | data    | The 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.

## Roles

To enforce checks only where they belong and leave your regular sessions outside the hub untouched, the plugins cannot guess a session's role by reading the conversation. Every session is classified explicitly as a **child session**, **master**, or **neither**.

| Role    | How a session gets it                                                                                                                                                                                                                | What the plugins do                                                                                                              |
| ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------- |
| Child   | The 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 run. |
| Master  | No 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.         |
| Neither | Every 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, and any value other than an empty string, `none`, `master`, or `child` causes every guard to block.

A child session also receives `SESSION_HUB_MASTER`, `SESSION_HUB_MASTER_REF`, `SESSION_HUB_MASTER_SESSION_ID`, `SESSION_HUB_SCOPE_ROOT`, `SESSION_HUB_HANDOFF`, `SESSION_HUB_REGISTRY`, and `SESSION_HUB_GUARDS`. Name, ref, and session ID all identify the master: the name can change, but the session ID cannot.

## The spawn flow

When you ask the master to work on one or more repositories, launching a child session goes through eight 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` when installed, and otherwise 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 the handoff hook puts the handoff text into the child's context.
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.

When a child session needs something outside its scope, the request travels back in the opposite direction, always through the master.

Routing an out-of-scope request: when a decision is needed, the master asks you; it handles master-only tasks and permitted reads itself; otherwise, it sends a follow-up to the live child session that owns the repository or spawns a new one. The requesting child session always gets confirmation of what happens next.

## The scope guard

Handoff instructions tell a child session where it should work, but they do not 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 intervenes inside child sessions: it exits with code `0` to allow the call, or code `2` to block it and explain why to the model.

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, so 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 and 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 only lets the call through if 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, so the scope guard self-blocks after 7 seconds to keep anything from slipping through.

## The `session-hub` mod

The scope guard protects file-editing tools even without mods, but a child session could still write files through the shell or message a sibling session directly, and in the master you need a way to track running sessions. When mods are enabled, the `session-hub` mod covers those gaps. It is 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 that state when a session is resumed.

| Feature             | Where                 | Event                              | Behavior                                                                                                                                                                                                                                                                         |
| ------------------- | --------------------- | ---------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Send guard          | child session         | `session.send`                     | Allows sending only to the master and to the session's own subagents; recognizes the master even after a rename and delivers messages to it via its session ID; saves any message it cannot deliver to the outbox; rejects any other recipient, naming the master in the reason. |
| Shell check         | child session         | `tool.call` on `Bash`              | Best-effort: denies redirections and file-writing commands targeting paths outside the write root.                                                                                                                                                                               |
| Origin tagging      | child session         | `session.receive`, `prompt.submit` | Adds a line to every message received from another session as a reminder that it is informational only, never authorization.                                                                                                                                                     |
| Scope line          | child session, master | `prompt.compose`, `prompt.submit`  | Injects role and scope (or the record) into the system prompt and as context after startup, compaction, and `/clear`.                                                                                                                                                            |
| Child session panel | master                | `ui.render`, `command.run`         | Shows one row per child session with live status from the session list and counts pending messages in the outbox; refreshes on `/session-hub` and every 30 seconds.                                                                                                              |
| Rename warning      | master                | `command.run`, timer               | If the master has been renamed while child sessions are running, reports it once and indicates whether they can still reach it.                                                                                                                                                  |

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.

## The child session record

To track child sessions without dirtying the hub or repositories, and to avoid corruption when multiple commands access the same file, `session-hub` stores the shared record at:

```text
<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 grid and `grid.json`

On the `model-router` side, every decision stems from `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: 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.

## The router mod

The `model-router` mod handles three 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 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.

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, with its closing tags escaped.
- **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 from input to decision.

### The quality loop

To evaluate routing choices against real outcomes, 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.

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.

## 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`).

| Path                                                           | Plugin         | Contents                                                                                                                    |
| -------------------------------------------------------------- | -------------- | --------------------------------------------------------------------------------------------------------------------------- |
| `session-hub/children-<hub id>.json` and `.lock`               | `session-hub`  | The child session record and its lock                                                                                       |
| `<scratchpad or mktemp -d>/<name>-handoff.md`                  | `session-hub`  | One handoff file per child session, stored outside the hub                                                                  |
| `model-router/events.jsonl`                                    | `model-router` | Decisions, spawns, signals, reports, session ends, and outcomes (append-only)                                               |
| `model-router/archive/`                                        | `model-router` | Event log rotated by compaction past 32 MB: retains outcomes, decisions, and spawns, then keeps only outcomes after 90 days |
| `model-router/quality/user.json`, `quality/projects/<id>.json` | `model-router` | Per-user and per-project quality aggregates                                                                                 |
| `model-router/quality/state.json`, `quality/.lock`             | `model-router` | Compaction cursor and lock (stale after 2 minutes)                                                                          |
| `model-router/options.json`                                    | `model-router` | Options used by compaction and the report                                                                                   |
| `model-router/report.html`                                     | `model-router` | The local report page                                                                                                       |
| `model-router/quality/recommendations.json`                    | `model-router` | Recommendations 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.

## Failure behavior

Violating a repository's scope can damage code, whereas skipping a model optimization at worst makes a call slower or more expensive. The two plugins therefore fail in opposite directions: a guard must never let a stray write through, and a router must never block a launch.

### `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.

## Compatibility

| Requirement                                | Value                                                                                                    |
| ------------------------------------------ | -------------------------------------------------------------------------------------------------------- |
| Tested Claude Code versions                | `2.1.329` and `2.1.330`                                                                                  |
| Cross-session messaging, for `session-hub` | Claude Code `2.1.224` or later                                                                           |
| Mods                                       | Available since Claude Code `2.1.287`; both mods declare `engines["claude-code"]: ">=2.1.329"`           |
| `node`                                     | On `PATH`, for the scope guard, record script, panel, and all `model-router` scripts; zero dependencies  |
| Operating system                           | macOS 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).
