router
Model and effort routing for the main conversation, advised by a prompt classifier (Jev, Clef or Clef Flash). Preserves subagent model choices.
何をするか
- プロンプトの上の帯を描く
- /model・/router を足す
- config.set・session.compact・session.end・session.start ほか 3 個にフックする
- ターンをまたいで自分の状態を持つ
- ネットワークに出る
良いところ
- プロセスを起こさない
- エラーを扱う
作り始めるためのコード
2 種類あります。上のデザインから modscode が書いた雛形と、その Mod 自身のコードのうち描いている部分です。
雛形(register.tsx)
import type { Register } from 'claude-code'
// Drawn like router by Alexei Ledenev (pane, band, toast), as modscode read it from the mod's code:
// https://modscode.com/gallery/alexei-led-router/
// Written by modscode from that reading, not copied from the mod: use it as you like.
// Each value below stands for one the mod works out at run time; put in your own.
export const register: Register = on => {
// the band above the prompt; what else goes there is drawn under it
on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
const { Box, Text, Button } = $.ui.resolve(e)
const tier = '…'
return (
<Box flexDirection="column">
<Box flexDirection="column">
<Box />
<Box />
<Box display="none">
<Text dimColor>
{"pin next turn "}
</Text>
<Button label={`${tier}`} />
<Text>
{" "}
</Text>
<Button label={`${tier}`} />
<Text>
{" "}
</Text>
<Button label={`${tier}`} />
<Text>
{" "}
</Text>
<Text>
{" "}
</Text>
<Button label="Manual" />
<Text>
{" "}
</Text>
<Button label="1 row" />
</Box>
</Box>
{await next(e)}
</Box>
)
})
}
Mod 自身のコード
Mod のライセンス(MIT)に従って載せています。全文は下にあります。写すときは著作権表示を残してください。
hooks/native-router.mjs 701〜860 行 · バンド
on('ui.render', { component: ['AbovePrompt', 'Pane'] }, async ($, e, next) => {
if (e.component === 'Pane' && e.requestId !== PANE) return next(e);
const storedView = await readView($, runtime);
const view = { ...storedView, mode: await modeOf($, runtime, storedView.mode) };
const elements = $.ui.resolve(e);
const { Box } = elements;
const usage = await $.session.usage().catch(() => null);
if (e.component === 'AbovePrompt') {
if (e.props.hasSurvey) return next(e);
return Box({
flexDirection: 'column',
children: [
await next(e),
renderBand(
elements,
config,
view,
usage,
{ columns: e.props.bodyColumns, agentId: e.props.view?.agentId },
{
open: () => openPane($, runtime),
mode: (mode) => changeMode($, runtime, mode),
pin: async (tier) => $.ui.toast(await setPin($, runtime, tier)),
unpin: () => updateView($, runtime, { pendingPin: null }),
key: () => openKeySettings($),
toggleDetail: async () => {
const bandDetail = !view.bandDetail;
await $.store.set(BAND_DETAIL, bandDetail).catch(() => {});
await updateView($, runtime, { bandDetail });
},
},
),
],
});
}
const settings = await $.settings.read().catch(() => ({}));
const modelOptions = Object.keys(config.models).filter((alias) =>
isModelAllowed(config.models[alias].id, settings.availableModels, view.nativeModel),
);
const editRoute = (tier, change) => {
const draft = routeDraftOf(config, runtime.view ?? view);
const current = effectiveRoutes(draft, config).routes[tier];
return updateView($, runtime, {
routeDraft: { ...draft, routes: { ...draft.routes, [tier]: change(current) } },
notice: null,
});
};
// Every pane save adopts the file as written, which may name another classifier than before: a hand edit
// meanwhile, or a row press. Then the new classifier starts clean and the old one's readings leave the view;
// an unavailable reason stays.
const adopt = async (loaded) => {
const switched = loaded.classifier !== config.classifier;
config = loaded;
if (!switched) return {};
clientOf(config.classifier).restore(null);
const current = runtime.view ?? view;
return {
...CLEARED_READINGS,
error: current.phase === 'unavailable' ? current.error : null,
credentials: await credentialsOf($, options, config),
health: healthOf(clientOf(config.classifier), config.classifier),
};
};
// Pending drafts re-pointed at the config a write just adopted. An edit that still differs stays; everything else
// follows the file, and the file becomes what the draft compares against, so picking a value the write replaced
// counts as a change again.
const rebased = ({ routeDraft, tuning, tuningBase }) => {
const routes = routeDraft && effectiveRoutes(routeDraft, config);
const edited = Object.entries(tuning ?? {}).filter(([key, value]) => value !== tuningBase?.[key]);
return {
routeDraft: routes ? { ...routes, base: routeDraftOf(config, {}).base } : null,
tuning: edited.length ? Object.fromEntries(edited) : null,
tuningBase: edited.length ? tuningOf(config) : null,
};
};
const save = async (change, saved) => {
const result = await saveConfig($, config.nativePath, change);
if (result.error) return updateView($, runtime, { notice: result.error });
const drafts = runtime.view ?? view;
const reset = await adopt(result.config);
return updateView($, runtime, { ...reset, ...rebased(drafts), ...saved(config) });
};
// Defaults go into the routing draft like any edit; the notice says whether Save has anything of that section left
// to write.
const loadDefaults = (patch, what) => {
const changes = routingChanges(config, { ...(runtime.view ?? view), ...patch });
const pending = what === 'route' ? changes.tiers.length + Number(changes.baseline) : changes.policy.length;
return updateView($, runtime, {
...patch,
notice: pending
? `${what === 'route' ? 'Route' : 'Policy'} defaults loaded. Save removes your ${what} overrides from router.json.`
: `${what === 'route' ? 'Routes' : 'Policy'} already at defaults.`,
});
};
// A pane write keeps the leaves it changed as router.json had them, read from the file it rewrites rather than from
// the loaded config, so Undo restores them verbatim. A later write replaces them, and Undo clears them.
const write = (label, change, patch = {}) => {
let leaves = [];
return save(
(file) => {
const written = change(file);
leaves = changedLeaves(file, written);
return written;
},
() => ({ ...patch, lastWrite: { label, leaves }, notice: `Saved: ${label}. Applies from the next turn.` }),
);
};
return renderPanel(
elements,
config,
view,
usage,
{
mode: (mode) => changeMode($, runtime, mode),
tab: (tab) => updateView($, runtime, { tab, notice: null }),
help: () => updateView($, runtime, { help: !view.help }),
pin: async (tier) => {
await updateView($, runtime, { notice: await setPin($, runtime, tier) });
},
unpin: () => updateView($, runtime, { pendingPin: null, notice: null }),
key: async () => {
openKeySettings($);
await $.ui.close({ id: PANE });
},
copyPath: async (press) => {
await $.ui.copy({ text: config.nativePath, surface: press?.surface });
await updateView($, runtime, { notice: 'Path copied.' });
},
close: () => $.ui.close({ id: PANE }),
routeModel: (tier, alias) =>
editRoute(tier, (route) => ({
model: alias,
effort: config.models[alias]?.efforts.includes(route.effort) ? route.effort : null,
})),
routeEffort: (tier, effort) => editRoute(tier, (route) => ({ model: route.model, effort })),
baseline: async (tier) => {
const draft = routeDraftOf(config, runtime.view ?? view);
await updateView($, runtime, { routeDraft: { ...draft, baselineTier: tier }, notice: null });
},
saveRouting: async () => {
const current = runtime.view ?? view;
const routeDraft = current.routeDraft;
const saved = tuningOf(config);
const base = current.tuningBase ?? saved;
const edited = Object.keys(current.tuning ?? {}).filter((key) => current.tuning[key] !== base[key]);
const changes = routingChanges(config, current).count;
if (!changes) return updateView($, runtime, { notice: 'No routing changes to save.' });
const after = Object.fromEntries(edited.map((key) => [key, current.tuning[key]]));
return write(
`${changes} routing change${changes === 1 ? '' : 's'}`,
(file) => {
const routed = routeDraft ? withRoutes(file, routeDraft) : file;
return edited.length ? withTuning(routed, { ...base, ...after }, base) : routed;
},
{ routeDraft: null, tuning: null, tuningBase: null },
);
},
discardRouting: () =>
updateView($, runtime, { routeDraft: null, tuning: null, tuningBase: null, notice: null }),
resetRoutes: () =>lib/native-band.mjs 175〜216 行 · バンド
export function renderBand({ Box, Text, Button }, config, view, usage, { columns, agentId }, actions) {
const draw = (p) => (p.button ? Button(p.button) : Text({ ...p.style, children: p.text }));
const row = (parts) => Box({ children: parts.map(draw) });
if (agentId) return row([part('○ Router · subagents keep their own model', { dimColor: true })]);
const kept = fitSegments(bandSegments(config, view, usage, actions), Math.max(0, columns - ROUTER_BUTTON));
const line = kept.flatMap((s, i) => (i ? [part(SEPARATOR, { dimColor: true }), ...s.parts] : s.parts));
line.push(part(' '), button({ key: 'details', label: 'Router', plain: true, onPress: actions.open }));
const routing = view.mode === 'auto' && view.phase !== 'unavailable';
return Box({
key: 'router-band',
flexDirection: 'column',
children: [
row(line),
view.bandDetail && routing ? row(detailRow(config, view, usage)) : null,
// Revealed while the pointer is over the band; no digit hotkeys, since a bare digit in an
// empty prompt would press them.
Box({
display: 'none',
hover: { display: 'flex' },
children: [
Text({ dimColor: true, children: routing ? 'pin next turn ' : '' }),
...(routing
? TIERS.flatMap((tier) => [
Button({ key: `band-pin-${tier}`, label: tier, onPress: () => actions.pin(tier) }),
Text({ children: ' ' }),
])
: []),
Text({ children: routing ? ' ' : '' }),
routing
? Button({ key: 'band-manual', label: 'Manual', onPress: () => actions.mode('manual') })
: Button({ key: 'band-auto-row', label: 'Auto', onPress: () => actions.mode('auto') }),
Text({ children: ' ' }),
Button({
key: 'band-detail',
label: view.bandDetail ? '1 row' : '2 rows',
onPress: actions.toggleDetail,
}),
],
}),
],
});
}ライセンスの全文(MIT)
MIT License Copyright (c) 2026 Alexei Ledenev Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
コードが呼ぶもの
通信ファイル書き込み環境変数保存
コードから読み取ったデザイン
読み取ったコミットのソースから描いたもので、動かした結果ではありません。一覧は 3 回描き、条件はデスクトップアプリで描く最初の分岐を取り、動かしたときにだけ決まる値は仮の例(点線の下線)にするか省きます。色と書体はこのサイトのものです。
コードから読めること
2026-10-06 に読んだコミット 7599fb515e29 のソースから。最初のまとまりが載せる条件で、残りは自分で判断するための材料です。後のコミットは、次に読むまで見ていません。
| 載せる条件: 確かめやすいコード | |
|---|---|
| 入口を読んだ | hooks/hooks.json が名指すモジュールをすべて読んだ。hooks/native-router.mjs |
| 解析できる | すべてのファイルが TypeScript か JavaScript として解析できる。11 ファイルを解析 |
| コードが Mod の中で完結 | import は Mod 自身のファイルかエンジンのモジュールだけ。パッケージも require もない。コードはすべて Mod の中 |
| 読める | 圧縮した行・eval・new Function・計算した道の import()・符号化した塊がない。圧縮・eval・符号化した塊なし |
| 呼び出しが見える | 通信とプログラム起動はその場で $.http.fetch・$.process.run と書き、他へ渡さない。外への呼び出しはすべてその場の $ で |
| 入れる前に自分で判断する材料 | |
| 描く場所 | コードから読んだ、描く先。ターミナル・デスクトップアプリ・両方・何も描かない(フックだけ: 見張りやプロンプトの書き換え)のどれか。出すだけで、外す理由にはしない。ターミナルとデスクトップアプリに同じように描く |
| 入れる手順 | リポジトリ自身の .claude-plugin/marketplace.json にこの Mod が載っていて、ページに書いた手順でそのマーケットプレイスから入れられるか。リポジトリの .claude-plugin/marketplace.json に載っており、そこから入れられる |
| Windows のプログラム | $.process で起動するプログラムが Windows にあるか(tail・date・open・osascript・/usr/… などは無い)。Windows にないプログラムを使わない |
| 通信 | fetch の送り先(https のホスト)がコードに書いてあるか。hooks/native-router.mjs:524 fetch(url) |
| プログラム | 起動するプログラムの名前がコードに書いてあり、シェル・インタプリタ・通信用の道具でないか。プログラムを起動しない |
| 読んで送る | ファイルや環境変数を読み、かつ通信するか。reads environment variables and files and reaches the network |
| ソースの鍵 | ソースに API キーや秘密鍵らしきものがあるか。ソースに鍵なし |
| ライセンス | オープンなライセンス(MIT・Apache-2.0・BSD・ISC・Unlicense・0BSD・CC0)で全文があれば、modscode にコードを載せる。違えばリンクだけ。MIT |
コードの文面を読んだだけで、安全の審査ではありません。動かしてはおらず、起動するプログラムの中で何が起きるかも見えません。入れる前の確認はあなたの役目です。 載せる条件
入れる
入れる前に、必ず自分で確かめてください。Mod はサンドボックスなしで、あなたの権限で動きます。modscode はこのコードの安全を保証しません。下のコードを読み(またはフォルダーで claude plugin validate .)、触るものを見て、読んだコミットを入れてください。
リポジトリがそのままマーケットプレイスです。このマーケットプレイスを足し(ターミナルでは次のコマンド、デスクトップアプリではプラグインの設定)、そこから Mod を入れます。
/plugin marketplace add alexei-led/claude-router/plugin install router@alexei-led-claude-router入るのはマーケットプレイスの最新のコミットで、ここで読んだもの(7599fb515e29)と違うことがあります。入れる前に見比べてください。
Claude に聞く
modscode のコネクタを入れると、Claude がこのデザイン・コードが触るもの・コードを読んで、それをもとに作れます。たとえば:
modscode のデザイン「alexei-led-router」をコードごと読んで、同じようなペインを作って似たデザイン
-
Claude に頼む…2h 10m · █████░░░✓ build ✓ build ✓ buildJavaKotlin3 Python■ ok 3 ■ ok 3 ■ ok 3 Razor proven 3 Razor proven 3 Razor proven 3Phases ──────── 3/3build Pythonbuild Pythonbuild Python… 3 more phasesLua ──────── 3/Kotlin■ the whole upgrade Ruby■ build build Ruby■ build build Ruby■ build build Ruby … 3 moreNext ──────── PythonRuby (by hand)Podsclick a button, or ctrl+x tab then Tab, EnterAttention ──────── 3! Scala ! Scala ! Scala … 3 moreSession ──────── okJava
-
Open a file first: /crit-tui file <path>Reopen this one in the crit browser view.Claude に頼む…
-
Claude に頼む…TodayOct 63 left · Mar overdueRemCTL: Sep✓ All done for today.● build3● Fix login ● ⚑Jul · build✓● Fix login ● ⚑Jul · build✓● Fix login ● ⚑Jul · build✓● build3● Fix login ● ⚑Jul · build✓● Fix login ● ⚑Jul · build✓● Fix login ● ⚑Jul · build✓● build3● Fix login ● ⚑Jul · build✓● Fix login ● ⚑Jul · build✓● Fix login ● ⚑Jul · build✓Updated 14:32UndoRefresh
-
Claude に頼む…TO graph› Fix login › Fix login › Fix loginScopeThis featureWhole projectHide done stepsReconnect
-
Claude に頼む…Blast Radius⚠ Blast Radius · buildCommand npm testWould CancelProceed Proceed ProceedBash1 Proceed2 CancelClaude is waiting on your answer
-
Claude に頼む…Agent Radar● Edit note · 2h 10m · 0 toolsnow: starting────────No messages yet.agent: (tool calls)agent: (tool calls)agent: (tool calls)Back bClose q