Experimental: non-Claude models (GPT, Grok, Muse) as native Claude Code subagents via a local routing gateway

Experimental. This routes all your Claude Code traffic through a local gateway; a bug here breaks your sessions until you take its wiring out of your settings (
ANTHROPIC_BASE_URL, orHTTPS_PROXYandproxyAuthHelper), which always restores direct Anthropic access.
model-router lets Claude Code delegate to GPT models as native subagents, alongside Claude models, in the same session. It runs a small loopback Anthropic-format gateway on your machine:
api.anthropic.com, with your existing claude.ai OAuth login and subscription billing untouched.gpt-6-astra) are stripped of all Anthropic credentials and forwarded to a supervised local CLIProxyAPI instance, which translates them to the Codex protocol under your separate Codex subscription OAuth. No API keys required on either side, though an OpenAI API key (billed per token) works in place of the subscription.Routed GPT models receive an honest-identity system block, so they never present themselves as Claude.
gpt-6-astra, gpt-6.1-sol, gpt-6-luna — usable from any project at any reasoning effort (Claude picks it per call; Claude Code 2.1.292+), plus dynamic per-invocation model + effort choice in Workflow orchestration./model-router:setup./model-router:setup.delegating-to-models skill that helps Claude pick the right model and effort when delegating.[web-search] in the config to opt out; Grok and Muse agents keep their vendor's search even then; only disabling the family stops it). The backend follows whichever agent asked: a GPT subagent's search uses the Codex backend even under a Claude main session, a Grok agent's search uses xAI's, a Muse agent's uses Meta's, and a Claude subagent's search stays on Anthropic even under a GPT main session.Run /model-router:setup and follow along; it also covers repair and uninstall. model-router doctor diagnoses the whole stack in one shot.
Claude Code reaches the gateway one of two ways:
api.anthropic.com, so Remote Control keeps working and sessions in the Claude desktop app route too. The gateway decrypts only Claude Code's own api.anthropic.com traffic, with a local certificate authority that is restricted to that one host (on macOS, setup adds it to your login keychain, which asks for your password); every other connection, including your tools' own Anthropic calls, passes through untouched. While the gateway is down, Claude Code and the tools it runs have no network until it restarts or you bypass it. Untested on Linux and WSL.ANTHROPIC_BASE_URL, the original wiring. Remote Control refuses to start under it, and the desktop app ignores it. Earlier installs keep working on it; setup moves them to the proxy when you ask.Both sides ride supported paths. The Claude side is a standard gateway configuration, ANTHROPIC_BASE_URL or an HTTPS proxy with your own certificate authority: requests are forwarded byte-exact and billed to your own subscription, with nothing impersonated. The GPT side spends your own Codex subscription through its own OAuth login — an arrangement OpenAI has publicly blessed regardless of the harness driving it: Codex lead Thibault Sottiaux posted the CLIProxyAPI-into-Claude-Code recipe himself ("we don't care about the harness"), and ChatGPT sign-in is a documented Codex auth method. The optional Muse family is not a supported path: Meta's terms (§3.2) restrict the subscription credential to Muse Code, and CLIProxyAPI presents itself as Muse Code. Setup shows the terms before enabling it.
Point MODEL_ROUTER_DEV at a locally built binary to bypass the release download in scripts/bootstrap.sh. docs/experiments.md records the measured Claude Code behavior this design rests on.
hooks/register.tsx 209 lines1// model-router as a mod: scripts/check.sh's rows (router down, settings to migrate, not set up,
2// wrong platform variant) in the band above the prompt, checked at startup and /clear. Buttons
3// retry the check, run setup, or have the binary edit the settings, saying what it did in a toast.
4import { atom, read, update } from 'claude-code'
5import type { EngineInterface, Register } from 'claude-code'
6
7import { noticeRows } from './notice-band'
8import type { Notice, NoticeAction } from './notice-band'
9
10const PLUGIN = 'model-router'
11const notices = atom({ plugin: 'model-router', key: 'notices' } as const, [] as Notice[])
12// Rows dismissed this session; a row with a `version` stays dismissed in the store until the next.
13const dismissed = atom({ plugin: 'model-router', key: 'dismissed' } as const, [] as string[])
14// A row whose Try again is running: its buttons give way to "restarting…" until the check settles.
15const retrying = atom({ plugin: 'model-router', key: 'retrying' } as const, null as string | null)
16
17// The directory the session started in, for the check's CLAUDE_PROJECT_DIR and project settings.
18let projectDir = ''
19
20/**
21 * Runs the plugin's check and keeps its rows; none when it fails. The check reads the wiring
22 * (ANTHROPIC_BASE_URL, or HTTPS_PROXY) from the environment Claude Code passes on, settings'
23 * `env` included, and restarts a stopped router.
24 */
25async function check($: EngineInterface): Promise<void> {
26 try {
27 const { exitCode, stdout } = await $.process.run(['bash', `${$.plugin.root}/scripts/check.sh`], {
28 env: { CLAUDE_PLUGIN_ROOT: $.plugin.root, CLAUDE_PROJECT_DIR: projectDir },
29 })
30 const found = exitCode === 0 && stdout.trim() ? (JSON.parse(stdout) as { notices: Notice[] }).notices : []
31 await update($, notices, () => found)
32 } catch {
33 // A check that fails shows nothing rather than a wrong row.
34 }
35}
36
37/** Try again on `row`: runs the check once more (one more restart attempt), the row busy meanwhile. */
38async function retry($: EngineInterface, row: string): Promise<void> {
39 await update($, retrying, () => row)
40 try {
41 await check($)
42 } finally {
43 await update($, retrying, () => null)
44 }
45}
46
47/** "gpt-6-astra, gpt-6-luna at 258K; grok-4.7 at 500K": routes grouped by compaction window. */
48function compactsAt(windows: Record<string, number>): string {
49 const byWindow = new Map<number, string[]>()
50 for (const [id, window] of Object.entries(windows)) {
51 byWindow.set(window, [...(byWindow.get(window) ?? []), id])
52 }
53 return [...byWindow].map(([window, ids]) => `${ids.join(', ')} at ${Math.round(window / 1000)}K`).join('; ')
54}
55
56/**
57 * Whether a toast shows whole on the terminal: Claude Code 2.1.299 word-wraps it at 40 columns
58 * (a 44-column box less its frame) and draws 3 lines, the third cut at its end.
59 */
60export function fitsToast(text: string): boolean {
61 const lines: string[] = []
62 for (const word of text.split(' ')) {
63 const last = lines.at(-1)
64 if (last !== undefined && last.length + 1 + word.length <= 40) lines[lines.length - 1] = `${last} ${word}`
65 else for (let at = 0; at < Math.max(word.length, 1); at += 40) lines.push(word.slice(at, at + 40))
66 }
67 return lines.length <= 3
68}
69
70/** The first of `texts` that fits in a toast, else the last. */
71const firstFitting = (...texts: string[]): string => texts.find(fitsToast) ?? texts.at(-1)!
72
73/**
74 * A settings edit by the binary (`model-router settings`, the setup skill's own), as the toast
75 * that says what it did. The edits take effect when Claude Code next starts.
76 *
77 * A toast shows 3 lines of 40 columns and cuts the rest, so what to do comes first, and the files
78 * edited only where they fit.
79 */
80async function editSettings($: EngineInterface, operation: 'models' | 'windows' | 'bypass'): Promise<string> {
81 const args = operation === 'bypass' ? ['bypass'] : [operation, '--apply']
82 const { exitCode, stdout } = await $.process.run(
83 ['bash', `${$.plugin.root}/scripts/bootstrap.sh`, 'settings', ...args, '--project-dir', projectDir],
84 { env: { CLAUDE_PLUGIN_ROOT: $.plugin.root } },
85 )
86 if (exitCode !== 0 || !stdout.trim()) return 'Could not edit your settings: run /model-router:setup'
87 const result = JSON.parse(stdout) as {
88 applied?: boolean
89 // Already as the edit would leave it: another session, or setup, made it since this one started.
90 unchanged?: boolean
91 added?: string[]
92 windows?: Record<string, number>
93 reason?: string
94 status?: 'done' | 'shared-file' | 'not-found' | 'changed'
95 files?: string[]
96 file?: string
97 }
98 // A settings file as the person knows it: relative to the project, or under ~.
99 const home = await $.env.get('HOME')
100 const shown = (file: string) => {
101 if (file.startsWith(`${projectDir}/`)) return file.slice(projectDir.length + 1)
102 return home && file.startsWith(`${home}/`) ? `~${file.slice(home.length)}` : file
103 }
104
105 if (operation === 'models') {
106 if (!result.applied) return `Not added, run /model-router:setup: ${result.reason ?? 'no reason given'}`
107 if (result.unchanged) return 'Already in /model; restart Claude Code to pick.'
108 const added = Object.fromEntries(
109 (result.added ?? []).flatMap(id => (result.windows?.[id] ? [[id, result.windows[id]]] : [])),
110 )
111 // Only retired rows dropped: nothing added to name.
112 if (!result.added?.length) return 'Updated /model. Restart Claude Code to see it.'
113 const compacts = Object.keys(added).length ? ` Compacts ${compactsAt(added)}.` : ''
114 return `Added to /model; restart Claude Code to pick.${compacts}`
115 }
116 if (operation === 'windows') {
117 if (!result.applied) return `Not changed, run /model-router:setup: ${result.reason ?? 'no reason given'}`
118 if (result.unchanged) return 'Windows already set; restart Claude Code to use them.'
119 const set = 'Windows set; restart Claude Code to use them.'
120 if (!Object.keys(result.windows ?? {}).length) return set
121 const compact = `Restart Claude Code to compact ${compactsAt(result.windows!)}`
122 // Too many routes to name (every family enabled at once): what to do still shows.
123 return firstFitting(...(result.file ? [`${compact} (in ${shown(result.file)}).`] : []), `${compact}.`, set)
124 }
125 if (result.status === 'done') {
126 return 'Bypassed the router. Restart Claude Code to get back online, then run /model-router:setup.'
127 }
128 // Another writer kept changing a file: its edit is not done, nothing of theirs was overwritten.
129 if (result.status === 'changed') {
130 const unfinished = 'Settings changed mid-edit, so Bypass router is not finished: try again.'
131 const done = result.files?.length ? [`${unfinished} Changed so far: ${result.files.map(shown).join(', ')}`] : []
132 return firstFitting(...done, unfinished)
133 }
134 if (result.status === 'shared-file') {
135 const file = shown(result.file ?? '.claude/settings.json')
136 return `In shared ${file}, remove the router's wiring (and a GPT "model"), then restart Claude Code.`
137 }
138 return 'Not wired in your settings: unset ANTHROPIC_BASE_URL or HTTPS_PROXY where you set it, then restart Claude Code.'
139}
140
141export const register: Register = on => {
142 // The SessionStart hook's lifecycle, startup and /clear, awaited: a stopped router's restart
143 // finishes before the session's first request.
144 on('classic.SessionStart', async ($, e, next) => {
145 if (e.source === 'startup' || e.source === 'clear') {
146 projectDir = e.cwd
147 await check($)
148 }
149 return next(e)
150 })
151
152 on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
153 const [below, found, hidden, running] = await Promise.all([
154 next(e),
155 read($, notices),
156 read($, dismissed),
157 read($, retrying),
158 ])
159 if (e.props.hasSurvey) return below
160
161 const candidates = (found as Notice[]).filter(notice => !hidden.includes(notice.id))
162 const stored = await Promise.all(
163 candidates.map(notice => (notice.version === undefined ? undefined : $.store.get(`dismissed:${notice.id}`))),
164 )
165 const rows = candidates
166 .filter((notice, index) => notice.version === undefined || stored[index] !== notice.version)
167 .map(notice => (running === notice.id ? { ...notice, busy: 'restarting…' } : notice))
168 if (rows.length === 0) return below
169
170 const dismiss = (notice: Notice) => update($, dismissed, list => [...list, notice.id])
171 const onAction = async (notice: Notice, action: NoticeAction) => {
172 if (action.id === 'retry') {
173 await retry($, notice.id)
174 return
175 }
176 // The settings edits take effect at the next start: the row's work is done this session.
177 if (action.id === 'add-models' || action.id === 'windows' || action.id === 'bypass') {
178 const operation = action.id === 'add-models' ? 'models' : action.id
179 const said = await editSettings($, operation).catch(
180 () => 'Could not edit your settings: run /model-router:setup',
181 )
182 await dismiss(notice)
183 $.ui.toast(said)
184 return
185 }
186 // Running setup (or Customize) dismisses the row for this session; the next session's
187 // check decides whether it comes back.
188 await dismiss(notice)
189 if (action.kind === 'command' && action.command) {
190 await $.command.run({ command: action.command.slice(1) }).catch(() => $.ui.toast(`Could not run ${action.command}`))
191 }
192 }
193 const onDismiss = async (notice: Notice) => {
194 await dismiss(notice)
195 if (notice.version !== undefined) await $.store.set(`dismissed:${notice.id}`, notice.version)
196 }
197
198 const ui = $.ui.resolve(e)
199 const drawn = noticeRows(ui, PLUGIN, rows, { onAction, onDismiss })
200
201 return (
202 <ui.Box flexDirection="column">
203 {drawn}
204 {below}
205 </ui.Box>
206 )
207 })
208}
209hooks/notice-band.tsx 92 lines1// One plugin's rows in the band above the prompt, drawn without `$`: each
2// plugin's own `ui.render` hook reads its state and stacks this over what the
3// plugins beneath drew, so third-party plugins on the band keep working.
4//
5// A plugin cannot import another's files, so each plugin that shows notices
6// carries this file; plugins/notice-band.test.ts keeps the copies identical.
7// The `notices` its check prints are this file's `Notice` as JSON.
8import type { EngineInterface, RenderElement } from 'claude-code'
9
10export type Severity = 'urgent' | 'problem' | 'action' | 'info'
11
12export type NoticeAction = {
13 id: string
14 label: string
15 // command: a slash command; copy: `command` goes on the clipboard, for a
16 // terminal command that is interactive; plugin: the plugin's own handler decides.
17 kind: 'command' | 'copy' | 'plugin'
18 command?: string
19}
20
21export type Notice = {
22 id: string
23 severity: Severity
24 // The whole message: rows wrap rather than hide what the person needs to act.
25 text: string
26 actions?: NoticeAction[]
27 // Set on "updated" notices: a dismissal holds until the plugin's next
28 // version. Without it, a dismissal holds for this session only.
29 version?: string
30 // What a pressed button is doing ("restarting…"): drawn after the text in
31 // place of the buttons, so the row never looks inert. Set by the plugin.
32 busy?: string
33}
34
35export type NoticeHandlers = {
36 onAction: (notice: Notice, action: NoticeAction) => unknown
37 onDismiss: (notice: Notice) => unknown
38}
39
40const MARK: Record<Severity, { rank: number; glyph: string; color: string }> = {
41 urgent: { rank: 0, glyph: '✖', color: 'error' },
42 problem: { rank: 1, glyph: '!', color: 'warning' },
43 action: { rank: 2, glyph: '›', color: 'suggestion' },
44 info: { rank: 3, glyph: '↑', color: 'ide' },
45}
46
47/** Draws `notices` as band rows, most severe first, each keyed and labeled by `plugin`. */
48export function noticeRows(
49 ui: ReturnType<EngineInterface['ui']['resolve']>,
50 plugin: string,
51 notices: Notice[],
52 { onAction, onDismiss }: NoticeHandlers,
53): RenderElement[] {
54 const { Box, Button, Text } = ui
55
56 return [...notices]
57 .sort((a, b) => MARK[a.severity].rank - MARK[b.severity].rank)
58 .map(notice => {
59 const mark = MARK[notice.severity]
60 const key = `${plugin}:${notice.id}`
61
62 const buttons = (notice.busy ? [] : (notice.actions ?? [])).map((action, index) => (
63 <Button
64 key={`${key}:${action.id}`}
65 label={action.label}
66 variant={index === 0 ? 'primary' : 'secondary'}
67 onPress={() => onAction(notice, action)}
68 />
69 ))
70 // An info row is a state, not a request: the band's own collapse hides it.
71 if (notice.severity !== 'info' && !notice.busy) {
72 buttons.push(<Button key={`${key}:dismiss`} label="Dismiss" dimColor onPress={() => onDismiss(notice)} />)
73 }
74
75 // The buttons wrap under the text where the row does not fit.
76 return (
77 <Box key={key} flexDirection="row" flexWrap="wrap" justifyContent="space-between" columnGap={2}>
78 <Text>
79 <Text color={mark.color} weight="semibold">
80 {mark.glyph}{' '}
81 </Text>
82 <Text weight="semibold">{plugin}</Text> {notice.busy ? `${notice.text} · ${notice.busy}` : notice.text}
83 </Text>
84 {/* Grows to fill its line, so the buttons stay right-aligned when they wrap. */}
85 <Box flexDirection="row" flexGrow={1} justifyContent="flex-end" columnGap={1}>
86 {buttons}
87 </Box>
88 </Box>
89 )
90 })
91}
92types/index.d.ts 7 lines1declare module 'claude-code' {
2 interface PluginState {
3 // `notices`: the check's rows, hooks/notice-band.tsx's Notice as parsed JSON.
4 'model-router': { notices: unknown[]; dismissed: string[]; retrying: string | null }
5 }
6}
7