Pick the model that serves this Claude Code session through the Edgee gateway: /edgee.

A Claude Code mod that picks the model serving the current session through the Edgee gateway. It calls the session reroute tools of the Edgee MCP server that edgee launch claude injects, with the session id from EDGEE_SESSION_ID.
/edgee show the active reroute
/edgee list [filter] models this session's API key can use
/edgee <model> [minutes] reroute the session (default 60, max 1440)
/edgee off route normally again
/edgee panel open and focus the side pane
/edgee minimize fold the pane into one line above the prompt
<model> matches an exact id (qwen/qwen3-coder-next), a bare name (qwen3-coder-next) or a unique substring (coder-next). While a reroute is active, the pane's header and the minimized band show ⇄ <model> until HH:MM.
Sessions start minimized by default. /edgee panel opens and focuses the pane: docked beside the transcript on a wide terminal, waiting unplaced on a narrow one until the window is wide enough. It shows:
● marks the model in use. Picking reroutes at once, for 24 h; a spinner shows until the gateway confirms;— means unavailable; a failed refresh marks the last known amounts as stale;↳ for subagents, and asked <model> when Claude Code asked for another model than the one that answered (a reroute at work).Each Claude Code API request (turn.step) is recorded; the served model is the one the gateway's response names. Requests made before the mod loaded are not shown, and Claude Code side calls outside the turn loop are not seen.
The pane takes the keyboard when it opens (or with ctrl+x tab, or a click). Type to search; ↑/↓ (or Tab) move the highlight from the search field down the rows, Enter picks the highlighted row (in the search field, the first match). Picking a provider fills the search with it; m (or the [–] button in the header) minimizes the pane; Esc minimizes it too and hands the keyboard back to the prompt.
Minimized, the pane closes and one line above the prompt stands in for it: where requests go (● direct, or ⇄ <model> until HH:MM), the last model served, rerouting/compression savings, and the session's requests, tokens and cache hit (as space permits). Its [+] button, or /edgee panel, brings the pane back. The choice is remembered: subsequent sessions restore the last minimized or expanded state.
edgee launch claude bundles this mod: the CLI compiles these files into its binary (src/commands/launch/claude_mods.rs), writes them to ~/.edgee/mods/edgee/ and loads them with --plugin-dir. It does so only when the Edgee MCP server is injected, on Claude Code 2.1.287 or later, and it pre-allows the three reroute tools the mod calls (listSessionModels, setSessionReroute, clearSessionReroute). EDGEE_MODS_DISABLED=1 turns it off.
The mod replaces Edgee's legacy statusline. Without mod support or Edgee MCP, there is no Edgee inline display. Gateway spend, reasoning-token totals, and fallback alerts are not shown by this mod; consult the Edgee console.
Savings come from session analytics through edgee stats --json --session <id>, using the CLI binary and profile that launched Claude. They include the whole gateway session (including background calls) and may lag behind the request timeline. Routing savings are estimates for requests with available pricing; they are not inferred from model names. The CLI needs a signed-in profile to read them. Older launchers without EDGEE_CLI_PATH show unavailable amounts.
sourceModel: every request of the session goes to the target, Claude Code's background Haiku calls included./model and status line still show the model it asks for.claude --plugin-dir ./mods/edgee # hot-reloads on save
claude plugin validate ./mods/edgee
claude plugin test ./mods/edgee
# Type-check: Claude Code writes its declarations to .claude-plugin/types/
# each time it loads the mod (any session with --plugin-dir does), which
# tsconfig.json extends.
npx -p typescript@5 tsc -p ./mods/edgeehooks/edgee.ts 832 lines1// Edgee Model: pick the model that serves this session through the Edgee
2// gateway, using the session reroute tools of the Edgee MCP server that
3// `edgee launch claude` injects.
4//
5// /edgee show the active reroute
6// /edgee list [filter] models this session's API key can use
7// /edgee <model> [minutes] reroute the session (default 60, max 1440)
8// /edgee off route normally again
9// /edgee panel open and focus the side pane: a model selector, each API request and the model that served it
10// /edgee minimize fold the pane into one line above the prompt (its [–] and Esc do too; the line's [+] unfolds it)
11
12import type { EngineInterface, On, RenderElement, TextProps, BoxProps, TurnStepInput, TurnStepResult } from "claude-code";
13import type { EdgeeModelTotals, EdgeePicker, EdgeeRequest, EdgeeReroute, EdgeeSavings } from "../types/index.d.ts";
14
15type $ = EngineInterface;
16type Elements = ReturnType<$["ui"]["resolve"]>;
17
18const SERVER = "edgee";
19const COMMAND = "edgee";
20const DEFAULT_MINUTES = 60;
21const PANE_MINUTES = 1440; // a pick in the pane lasts the longest reroute the gateway allows
22const MAX_MINUTES = 1440;
23const LIST_LIMIT = 40;
24const PANE = "edgee-requests";
25const RECENT = 30;
26const OFF = "__off"; // the selector's "no reroute" option
27const CATALOG_ATTEMPTS = 20;
28const CATALOG_RETRY_MS = 1_000;
29const ROWS = 8; // model rows under the filter; past that, typing narrows
30const SUGGESTED_PROVIDERS = 8; // provider chips shown on an empty filter
31const SPINNER = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
32const SPINNER_MS = 80;
33
34// Held by the host, so they survive a hot reload of this file.
35const reroute = { plugin: "edgee", key: "reroute" } as const;
36const requests = { plugin: "edgee", key: "requests" } as const; // the last RECENT requests
37const models = { plugin: "edgee", key: "models" } as const; // session totals per served model
38const catalog = { plugin: "edgee", key: "catalog" } as const; // models the selector offers
39const picker = { plugin: "edgee", key: "picker" } as const; // the selector's filter, duration and last notice
40const minimized = { plugin: "edgee", key: "minimized" } as const; // the pane folded into a line above the prompt
41const savings = { plugin: "edgee", key: "savings" } as const;
42let refreshingSavings = false;
43// Start minimized by default; remember an explicit choice across sessions.
44const MINIMIZED_KEY = "minimized";
45
46export function register(on: On) {
47 on("session.start", async ($, e, next) => {
48 const result = await next(e);
49 await $.command.register({
50 name: COMMAND,
51 description: "Route this session to another model through Edgee",
52 argumentHint: "[list [filter] | <model> [minutes] | off | panel | minimize]",
53 });
54 const folded = (await storedMinimized($)) !== false;
55 await $.state.set(minimized, folded);
56 // Start with the compact line unless the user last left the pane expanded.
57 // Restoring the pane does not take the keyboard.
58 if (!folded) await openPane($, { focus: false });
59 if (await $.env.get("EDGEE_CLI_PATH")) {
60 void refreshSavings($).catch(() => {}); // the host may unload during a refresh
61 // Analytics can arrive after the turn ends; keep refreshing while idle too.
62 $.clock.every(30_000, () => void refreshSavings($).catch(() => {}));
63 }
64 return result;
65 });
66
67 on("turn.complete", async ($, e, next) => {
68 const result = await next(e);
69 if (!e.agentId) {
70 await current($); // drop the reroute once expired, so the pane and band redraw
71 void refreshSavings($).catch(() => {});
72 }
73 return result;
74 });
75
76 // One step is one API request: record what Claude Code asked for and what answered.
77 on("turn.step", async function* ($, e, next) {
78 const startedAt = await $.clock.now();
79 const result = yield* next(e);
80 await record($, e, result, startedAt);
81 return result;
82 });
83
84 on("ui.render", { component: "Pane", requestId: PANE }, async ($, e) => {
85 const elements = $.ui.resolve(e);
86 return paneView(elements, {
87 sessionId: await $.env.get("EDGEE_SESSION_ID"),
88 active: await current($),
89 catalog: (await $.state.get(catalog)).value ?? [],
90 picker: (await $.state.get(picker)).value ?? {},
91 recent: (await $.state.get(requests)).value ?? [],
92 totals: (await $.state.get(models)).value ?? {},
93 savings: (await $.state.get(savings)).value,
94 columns: e.props.bodyColumns,
95 clickable: e.viewport?.isFullscreen === true,
96 isFocused: e.props.isFocused,
97 });
98 });
99
100 // The selector's elements: hooks rather than closures, so the work has `$`.
101 // Each passes first, then acts: the work redraws the pane, and the element
102 // `next` hands the event to would no longer be the one that raised it.
103 on("ui.input", { plugin: "edgee", element: "filter" }, async ($, e, next) => {
104 const result = await next(e);
105 await updatePicker($, { filter: e.value });
106 if (e.kind === "submit") {
107 // Enter picks the first match; on an empty filter it steps into the list.
108 const { value: models = [] } = await $.state.get(catalog);
109 const [first] = e.value.trim() ? matching(models, e.value.trim()) : [];
110 if (first) await pickModel($, first);
111 else if (!e.value.trim()) await $.ui.focus({ requestId: PANE, key: `pick:${OFF}` });
112 }
113 return result;
114 });
115
116 // The list's rows: plain Buttons, so ↑↓ (or Tab) walk them and Enter picks.
117 on("ui.press", { plugin: "edgee", element: /^(pick|provider):/ }, async ($, e, next) => {
118 const result = await next(e);
119 const [kind, value = ""] = splitOnce(e.element, ":");
120 if (kind === "pick") await pickModel($, value);
121 else if (kind === "provider") {
122 await updatePicker($, { filter: `${value}/` });
123 await $.ui.focus({ requestId: PANE, key: "filter" });
124 }
125 return result;
126 });
127
128 // The pane's [–] folds it into one line above the prompt; that line's [+] unfolds it.
129 on("ui.press", { plugin: "edgee", element: "minimize" }, async ($, e, next) => {
130 const result = await next(e);
131 await minimize($);
132 return result;
133 });
134
135 on("ui.press", { plugin: "edgee", element: "expand" }, async ($, e, next) => {
136 const result = await next(e);
137 await openPane($);
138 return result;
139 });
140
141 // Esc, or the pane's close mark, closes it as the person's close: fold it into the line rather than lose it.
142 on("ui.close", async ($, e, next) => {
143 const result = await next(e);
144 if (e.id === PANE && e.origin.kind === "person") await setMinimized($, true);
145 return result;
146 });
147
148 on("ui.render", { component: "AbovePrompt" }, async ($, e, next) => {
149 if (e.props.hasSurvey || !(await $.state.get(minimized)).value) return next(e);
150 // The band is shared: draw what the plugins beneath draw, then our line right above the prompt.
151 const below = await next(e);
152 const elements = $.ui.resolve(e);
153 const line = bandView(elements, {
154 active: await current($),
155 catalog: (await $.state.get(catalog)).value ?? [],
156 recent: (await $.state.get(requests)).value ?? [],
157 totals: (await $.state.get(models)).value ?? {},
158 savings: (await $.state.get(savings)).value,
159 columns: e.props.bodyColumns,
160 clickable: e.viewport?.isFullscreen === true,
161 });
162 return elements.Box({ flexDirection: "column", children: [below, line] });
163 });
164
165 on("command.run", { command: COMMAND }, async ($, e) => {
166 const [verb = "", ...rest] = e.args.trim().split(/\s+/).filter(Boolean);
167 if (verb === "panel") return { text: await openPane($) };
168 if (verb === "minimize") {
169 await minimize($);
170 return { text: `Edgee pane minimized: /${COMMAND} panel restores it.` };
171 }
172 const sessionId = await $.env.get("EDGEE_SESSION_ID");
173 if (!sessionId) {
174 return { text: "Not running under Edgee. Start Claude Code with `edgee launch claude`." };
175 }
176 try {
177 if (verb === "") return { text: await describe($) };
178 if (verb === "list") return { text: await list($, sessionId, rest.join(" ")) };
179 if (verb === "off" || verb === "clear" || verb === "reset") return { text: await clear($, sessionId) };
180 return { text: await set($, sessionId, verb, rest[0]) };
181 } catch (err) {
182 // No `edgee` server (MCP not enabled), or its reroute tools not allowed yet.
183 return { text: `Edgee MCP call failed: ${errorText(err)}` };
184 }
185 });
186}
187
188async function describe($: $): Promise<string> {
189 const active = await current($);
190 if (!active) return `No reroute: requests go to the model Claude Code asks for.\nUsage: /${COMMAND} list [filter] · /${COMMAND} <model> [minutes] · /${COMMAND} off`;
191 return `Rerouted to ${active.model} until ${clockTime(active.expiresAt)}.`;
192}
193
194async function list($: $, sessionId: string, filter: string): Promise<string> {
195 const models = await availableModels($, sessionId);
196 const needle = filter.toLowerCase();
197 const hits = models.filter((m) => m.toLowerCase().includes(needle));
198 if (hits.length === 0) return `No model matches "${filter}".`;
199 if (!needle) {
200 // 200+ models: summarise by provider instead of dumping them all.
201 const byProvider = new Map<string, number>();
202 for (const m of hits) {
203 const provider = m.split("/")[0]!;
204 byProvider.set(provider, (byProvider.get(provider) ?? 0) + 1);
205 }
206 const rows = [...byProvider].map(([p, n]) => ` ${p} (${n})`);
207 return `${hits.length} models available. Narrow with /${COMMAND} list <filter>:\n${rows.join("\n")}`;
208 }
209 const shown = hits.slice(0, LIST_LIMIT).map((m) => ` ${m}`);
210 const more = hits.length > LIST_LIMIT ? `\n … ${hits.length - LIST_LIMIT} more, narrow the filter` : "";
211 return `${shown.join("\n")}${more}`;
212}
213
214async function set($: $, sessionId: string, query: string, minutesArg: string | undefined): Promise<string> {
215 const models = await availableModels($, sessionId);
216 const match = resolveModel(models, query);
217 if (match.error !== undefined) return match.error;
218
219 const minutes = clampMinutes(minutesArg);
220 if (minutes === null) return `Invalid duration "${minutesArg}": give minutes between 1 and ${MAX_MINUTES}.`;
221 return applyReroute($, sessionId, match.model, minutes);
222}
223
224async function applyReroute($: $, sessionId: string, model: string, minutes: number): Promise<string> {
225 await callEdgee($, "setSessionReroute", { sessionId, targetModel: model, durationMinutes: minutes });
226 const expiresAt = (await $.clock.now()) + minutes * 60_000;
227 await $.state.set(reroute, { model, expiresAt });
228 const span = minutes % 60 === 0 ? `${minutes / 60} h` : `${minutes} min`;
229 return `Session rerouted to ${model} for ${span} (until ${clockTime(expiresAt)}).`;
230}
231
232async function clear($: $, sessionId: string): Promise<string> {
233 await callEdgee($, "clearSessionReroute", { sessionId });
234 await $.state.set(reroute, null);
235 return "Reroute cleared: requests go to the model Claude Code asks for.";
236}
237
238async function availableModels($: $, sessionId: string): Promise<string[]> {
239 const value = (await callEdgee($, "listSessionModels", { sessionId })) as { models?: unknown } | null;
240 return Array.isArray(value?.models) ? value.models.filter((m): m is string => typeof m === "string") : [];
241}
242
243// Exact id first, then the bare name without its provider, then a unique substring.
244function resolveModel(models: string[], query: string): { model: string; error?: undefined } | { model?: undefined; error: string } {
245 const q = query.toLowerCase();
246 const exact = models.find((m) => m.toLowerCase() === q || m.toLowerCase().split("/")[1] === q);
247 if (exact) return { model: exact };
248 const partial = models.filter((m) => m.toLowerCase().includes(q));
249 if (partial.length === 1) return { model: partial[0]! };
250 if (partial.length === 0) return { error: `Unknown model "${query}". See /${COMMAND} list <filter>.` };
251 const shown = partial.slice(0, 10).map((m) => ` ${m}`).join("\n");
252 return { error: `"${query}" matches ${partial.length} models, be more specific:\n${shown}` };
253}
254
255function clampMinutes(arg: string | undefined): number | null {
256 if (arg === undefined) return DEFAULT_MINUTES;
257 const n = Number(arg);
258 if (!Number.isInteger(n) || n < 1 || n > MAX_MINUTES) return null;
259 return n;
260}
261
262// Calls one Edgee MCP tool and returns its result parsed from JSON when it is JSON.
263async function callEdgee($: $, tool: string, args: Record<string, unknown>): Promise<unknown> {
264 const result = await $.mcp.call(SERVER, tool, args);
265 const text = (result.content ?? [])
266 .flatMap((b) => (b.type === "text" && typeof b.text === "string" ? [b.text] : []))
267 .join("\n");
268 if (result.isError) throw new Error(text || `${tool} failed`);
269 if (result.structuredContent !== undefined) return result.structuredContent;
270 try {
271 return JSON.parse(text);
272 } catch {
273 return text;
274 }
275}
276
277// The active reroute, or null once it has expired.
278async function current($: $): Promise<EdgeeReroute | null> {
279 const { value } = await $.state.get(reroute);
280 if (!value) return null;
281 if (value.expiresAt <= (await $.clock.now())) {
282 await $.state.set(reroute, null);
283 return null;
284 }
285 return value;
286}
287
288async function openPane($: $, { focus = true } = {}): Promise<string> {
289 await setMinimized($, false);
290 // Only a pane that takes the keyboard folds on Esc: a restored one leaves Esc at the prompt alone.
291 const opened = await $.ui.open({ id: PANE, title: "Edgee requests", ...(focus ? { focus: true, closeOnEscape: true } : {}) });
292 // Not awaited: the MCP server may still be connecting; the picker shows a loading state meanwhile.
293 void loadCatalog($);
294 return opened.isPlaced ? "Edgee requests pane opened." : `Edgee requests pane waits: ${opened.reason}`;
295}
296
297async function minimize($: $): Promise<void> {
298 await setMinimized($, true);
299 await $.ui.close({ id: PANE });
300}
301
302async function setMinimized($: $, value: boolean): Promise<void> {
303 if ((await $.state.get(minimized)).value === value) return;
304 await $.state.set(minimized, value);
305 try {
306 await $.store.set(MINIMIZED_KEY, value);
307 } catch {
308 // A preference: losing it means the next session starts minimized.
309 }
310}
311
312async function storedMinimized($: $): Promise<unknown> {
313 try {
314 return await $.store.get(MINIMIZED_KEY);
315 } catch {
316 return undefined;
317 }
318}
319
320// Loads the selector's models; a failure leaves the requests view working.
321// At session start the `edgee` MCP server is often still connecting, so a
322// failed load retries every second for a while before it reports.
323async function loadCatalog($: $, attemptsLeft = CATALOG_ATTEMPTS): Promise<void> {
324 const sessionId = await $.env.get("EDGEE_SESSION_ID");
325 if (!sessionId) return;
326 try {
327 await $.state.set(catalog, await availableModels($, sessionId));
328 const { value } = await $.state.get(picker);
329 if (value?.failed) await updatePicker($, { notice: undefined, failed: false });
330 } catch (err) {
331 if (attemptsLeft > 1) {
332 $.clock.after(CATALOG_RETRY_MS, () => void loadCatalog($, attemptsLeft - 1));
333 return;
334 }
335 await updatePicker($, { notice: `Edgee MCP call failed: ${errorText(err)}`, failed: true });
336 }
337}
338
339// A pick in the pane: reroute to `model`, or clear on OFF; a spinner shows
340// while the gateway applies it, then the outcome shows under the selector.
341async function pickModel($: $, model: string): Promise<void> {
342 const sessionId = await $.env.get("EDGEE_SESSION_ID");
343 let notice: string;
344 let failed = false;
345 if (!sessionId) [notice, failed] = ["Not running under Edgee.", true];
346 else {
347 await updatePicker($, { pending: model, frame: 0, notice: undefined, failed: false });
348 let frame = 0;
349 const spin = $.clock.every(SPINNER_MS, () => void updatePicker($, { frame: ++frame }));
350 try {
351 if (model === OFF) notice = await clear($, sessionId);
352 else {
353 notice = await applyReroute($, sessionId, model, PANE_MINUTES);
354 }
355 } catch (err) {
356 [notice, failed] = [`Edgee MCP call failed: ${errorText(err)}`, true];
357 } finally {
358 spin.cancel();
359 }
360 }
361 await updatePicker($, { notice, failed, pending: undefined });
362}
363
364async function updatePicker($: $, change: Partial<EdgeePicker>): Promise<void> {
365 const { value } = await $.state.get(picker);
366 await $.state.set(picker, { ...value, ...change });
367}
368
369async function record($: $, e: TurnStepInput, result: TurnStepResult | undefined, startedAt: number): Promise<void> {
370 const usage = result?.usage;
371 const entry: EdgeeRequest = {
372 at: startedAt,
373 durationMs: (await $.clock.now()) - startedAt,
374 requested: e.model,
375 served: usage?.model ?? null,
376 input: (usage?.input_tokens ?? 0) + (usage?.cache_creation_input_tokens ?? 0),
377 cached: usage?.cache_read_input_tokens ?? 0,
378 output: usage?.output_tokens ?? 0,
379 subagent: Boolean(e.agentId),
380 };
381 const { value: recent = [] } = await $.state.get(requests);
382 await $.state.set(requests, [...recent, entry].slice(-RECENT));
383
384 const key = entry.served ?? "failed";
385 const { value: totals = {} } = await $.state.get(models);
386 const t: EdgeeModelTotals = totals[key] ?? { requests: 0, input: 0, cached: 0, output: 0 };
387 await $.state.set(models, {
388 ...totals,
389 [key]: {
390 requests: t.requests + 1,
391 input: t.input + entry.input,
392 cached: t.cached + entry.cached,
393 output: t.output + entry.output,
394 },
395 });
396}
397
398// Use the CLI's profile-aware authentication; credentials never enter plugin state.
399// Replace the snapshot each time: the API totals already cover the whole session.
400async function refreshSavings($: $): Promise<void> {
401 if (refreshingSavings) return;
402 refreshingSavings = true;
403 try {
404 const binary = await $.env.get("EDGEE_CLI_PATH");
405 const sessionId = await $.env.get("EDGEE_SESSION_ID");
406 if (!binary || !sessionId) return;
407 const profile = await $.env.get("EDGEE_PROFILE");
408 const result = await $.process.run(
409 [binary, ...(profile ? ["--profile", profile] : []), "stats", "--json", "--session", sessionId],
410 { timeoutMs: 10_000, env: { EDGEE_NO_UPDATE_CHECK: "1" } },
411 );
412 if (result.exitCode !== 0 || result.isStdoutTruncated) throw new Error("Savings unavailable");
413 const value = JSON.parse(result.stdout);
414 const input = nano(value.total_token_cost_savings);
415 const output = nano(value.total_output_cost_savings);
416 await $.state.set(savings, {
417 compression: input !== null && output !== null ? input + output : null,
418 rerouting: nano(value.estimated_routing_savings),
419 remaining: nano(value.total_cost),
420 });
421 } catch {
422 const { value } = await $.state.get(savings);
423 await $.state.set(savings, { compression: null, rerouting: null, remaining: null, ...value, stale: true });
424 } finally {
425 refreshingSavings = false;
426 }
427}
428
429function nano(value: unknown): number | null {
430 return typeof value === "number" && Number.isFinite(value) && value >= 0 ? value : null;
431}
432
433function dollars(nano: number | null | undefined): string {
434 if (nano == null) return "—";
435 if (nano > 0 && nano < 10_000_000) return "<$0.01";
436 return `$${(nano / 1_000_000_000).toFixed(2)}`;
437}
438
439// The pane's palette: Edgee's accent, and one hue per provider so a model reads at a glance.
440const ACCENT = "#A78BFA";
441const PROVIDER_COLORS: Record<string, string> = {
442 anthropic: "#D97757",
443 openai: "#10A37F",
444 google: "#4285F4",
445 qwen: "#8B5CF6",
446 deepseek: "#4D6BFE",
447 mistral: "#FA520F",
448 meta: "#3B82F6",
449 xai: "#E5E7EB",
450 zai: "#22D3EE",
451 moonshotai: "#F472B6",
452 minimax: "#F43F5E",
453 nvidia: "#76B900",
454 amazon: "#FF9900",
455};
456
457type PaneData = {
458 sessionId: string | undefined;
459 active: EdgeeReroute | null;
460 catalog: string[];
461 picker: EdgeePicker;
462 recent: EdgeeRequest[];
463 totals: Record<string, EdgeeModelTotals>;
464 savings: EdgeeSavings | undefined;
465 columns: number;
466 clickable: boolean; // the surface reports mouse clicks (fullscreen only): buttons are drawn only there
467 isFocused: boolean;
468};
469
470function paneView(elements: Elements, { sessionId, active, catalog, picker, recent, totals, savings, columns, clickable, isFocused }: PaneData): RenderElement {
471 const { Box, Text, Button } = elements;
472 const inner = Math.max(24, columns - 4); // inside a card's border and padding
473 const span = (children: string, props: Omit<TextProps, "children"> = {}) => Text({ ...props, children });
474 const row = (children: RenderElement[], props: Omit<BoxProps, "children"> = {}) => Box({ flexDirection: "row", ...props, children });
475 const card = (children: RenderElement[], color: string) =>
476 Box({ flexDirection: "column", borderStyle: "round", borderColor: color, paddingX: 1, children });
477 const rule = (title: string) => row([span("── ", { color: ACCENT, dimColor: true }), span(title.toUpperCase(), { color: ACCENT, bold: true }), span(` ${"─".repeat(Math.max(0, columns - title.length - 4))}`, { color: ACCENT, dimColor: true })], { marginTop: 1 });
478
479 // ── Header: who we are and where requests go.
480 const lastAsked = [...recent].reverse().find((r) => !r.subagent)?.requested;
481 const header = card(
482 [
483 row(
484 [
485 row([span("◆ EDGEE", { color: ACCENT, bold: true }), span(` session ${sessionId ? sessionId.slice(0, 8) : "—"}`, { dimColor: true })]),
486 row([
487 picker.pending
488 ? span(` ${spinner(picker)} APPLYING `, { backgroundColor: "#92400E", color: "white", bold: true })
489 : active
490 ? span(" ⇄ REROUTED ", { backgroundColor: "#7C3AED", color: "white", bold: true })
491 : span(" ● DIRECT ", { backgroundColor: "#065F46", color: "white", bold: true }),
492 ...(clickable ? [span(" "), Button({ key: "minimize", label: "–", onPress: () => {} })] : []),
493 ]),
494 ],
495 { justifyContent: "space-between" },
496 ),
497 active
498 ? row([
499 span(fit(bare(lastAsked ?? "claude"), Math.floor(inner / 3)).trimEnd(), { dimColor: true, strikethrough: true }),
500 span(" ━━▶ ", { color: ACCENT, bold: true }),
501 span(active.model, { color: providerColor(active.model), bold: true }),
502 span(` ⏱ ${clockTime(active.expiresAt)}`, { dimColor: true }),
503 ])
504 : span(sessionId ? "No reroute: requests go to the model Claude Code asks for" : "Not under edgee launch: requests are only observed", { dimColor: true, italic: true }),
505 ],
506 active ? ACCENT : "gray",
507 );
508
509 // ── Totals as tiles, then how much of the input the prompt cache served.
510 const sum = sumTotals(totals);
511 const tile = (label: string, value: string, color: string) =>
512 Box({ flexDirection: "column", flexGrow: 1, alignItems: "center", borderStyle: "single", borderColor: color, borderDimColor: true, children: [span(value, { color, bold: true }), span(label, { dimColor: true })] });
513 const hit = cacheHit(sum);
514 const barWidth = Math.max(10, inner - 16);
515 const stats = [
516 row([tile("requests", String(sum.requests), ACCENT), tile("input", short(sum.input), "cyan"), tile("cached", short(sum.cached), "green"), tile("output", short(sum.output), "yellow")]),
517 row([span(" cache hit ", { dimColor: true }), span("█".repeat(Math.round(hit * barWidth)), { color: "green" }), span("░".repeat(barWidth - Math.round(hit * barWidth)), { dimColor: true }), span(` ${Math.round(hit * 100)}%`, { color: "green", bold: true })]),
518 savingsCard(elements, savings, inner),
519 ];
520
521 // ── Route: the selector.
522 const route: RenderElement[] = [];
523 if (catalog.length > 0) {
524 const filter = (picker.filter ?? "").trim().toLowerCase();
525 if ("Input" in elements) {
526 route.push(elements.Input({ key: "filter", label: "⌕", placeholder: "search 200+ models: qwen, opus, gpt-5…", value: picker.filter ?? "", submitLabel: "pick first", autoFocus: true, onSubmit: () => {} }));
527 route.push(span("┄".repeat(inner), { color: ACCENT, dimColor: true }));
528 }
529 route.push(...modelList(elements, { catalog, filter, active, totals, pending: picker.pending, inner }));
530 } else {
531 const waiting = sessionId ? (picker.failed ? "Models unavailable: is the Edgee MCP enabled?" : "Loading models from the Edgee MCP…") : "Launch with `edgee launch claude` to pick a model";
532 route.push(span(waiting, { dimColor: true, italic: true }));
533 }
534 if (picker.pending) {
535 const target = picker.pending === OFF ? "Claude Code's choice" : picker.pending;
536 route.push(row([span(`${spinner(picker)} `, { color: ACCENT, bold: true }), span(picker.pending === OFF ? "Clearing the reroute → " : "Rerouting to ", { dimColor: true }), span(target, { color: providerColor(target), bold: true }), span(" …", { dimColor: true })], { marginTop: 1 }));
537 } else if (picker.notice) route.push(row([span(picker.failed ? "✗ " : "✓ ", { color: picker.failed ? "red" : "green", bold: true }), span(picker.notice, { color: picker.failed ? "red" : undefined, dimColor: !picker.failed })], { marginTop: 1 }));
538
539 // ── Models served: a share bar per model, in its provider's color.
540 const entries = Object.entries(totals).sort((a, b) => b[1].requests - a[1].requests);
541 const nameWidth = Math.max(12, Math.min(34, inner - 30));
542 const shareWidth = Math.max(6, inner - nameWidth - 25);
543 const served = entries.length
544 ? entries.map(([servedAs, t]) => {
545 const model = withProvider(servedAs, catalog);
546 const filled = Math.max(1, Math.round((t.requests / sum.requests) * shareWidth));
547 const color = model === "failed" ? "red" : providerColor(model);
548 return row([
549 span("● ", { color }),
550 span(fit(model, nameWidth), { color, bold: true }),
551 span(` ${"▰".repeat(filled)}`, { color }),
552 span("▱".repeat(shareWidth - filled), { dimColor: true }),
553 span(` ${String(t.requests).padStart(3)} req `, { bold: true }),
554 span(`${short(t.input + t.cached).padStart(6)}↑ ${short(t.output).padStart(5)}↓`, { dimColor: true }),
555 ]);
556 })
557 : [span("none yet", { dimColor: true, italic: true })];
558
559 // ── Recent requests: a timeline, newest first; hovering a row lights it.
560 const reqWidth = Math.max(12, inner - 34);
561 const timeline = recent.length
562 ? [...recent].reverse().map((r, i) => {
563 const served = r.served && withProvider(r.served, catalog);
564 const color = served ? providerColor(served) : "red";
565 const secs = r.durationMs / 1000;
566 const pace = secs < 3 ? "green" : secs < 10 ? "yellow" : "red";
567 const lines = [
568 row([
569 span(clockTime(r.at, true), { dimColor: true }),
570 span(r.subagent ? " ↳ " : " ● ", { color }),
571 span(fit(served || "no response", reqWidth), { color, bold: !r.subagent }),
572 span(` ${short(r.input + r.cached).padStart(6)}`, { color: "cyan" }),
573 span("→", { dimColor: true }),
574 span(short(r.output).padEnd(5), { color: "yellow" }),
575 span(`${secs.toFixed(1).padStart(5)}s`, { color: pace }),
576 ]),
577 ];
578 if (r.served && !sameModel(r.requested, r.served)) {
579 lines.push(row([span(" ╰ ", { dimColor: true }), span(`⇄ from ${r.requested}`, { color: ACCENT, dimColor: true, italic: true })]));
580 }
581 return Box({ key: `req-${i}`, flexDirection: "column", hover: { backgroundColor: "#1F1B2E" }, children: lines });
582 })
583 : [span("none yet", { dimColor: true, italic: true })];
584
585 return Box({
586 flexDirection: "column",
587 children: [
588 header,
589 ...stats,
590 rule("Route"),
591 card(route, "cyan"),
592 rule("Models served"),
593 Box({ flexDirection: "column", paddingX: 1, children: served }),
594 rule("Recent requests"),
595 Box({ flexDirection: "column", paddingX: 1, children: timeline }),
596 row(isFocused
597 ? [span("tab", { color: ACCENT, bold: true }), span(" move ", { dimColor: true }), span("↑↓", { color: ACCENT, bold: true }), span(" choose ", { dimColor: true }), span("⏎", { color: ACCENT, bold: true }), span(" pick ", { dimColor: true }), span("/edgee minimize", { color: ACCENT, bold: true }), span(" ", { dimColor: true }), span("esc", { color: ACCENT, bold: true }), span(" fold", { dimColor: true })]
598 : [span("/edgee panel", { color: ACCENT, bold: true }), span(" focus ", { dimColor: true }), span("/edgee minimize", { color: ACCENT, bold: true }), span(" fold", { dimColor: true })], { justifyContent: "center", marginTop: 1 }),
599 ],
600 });
601}
602
603const COMPRESSION_COLOR = "#55B98A";
604const ROUTING_COLOR = "#B12ACB";
605const REMAINING_COLOR = "#60566B";
606
607function savingsCard({ Box, Text }: Elements, savings: EdgeeSavings | undefined, width: number): RenderElement {
608 const compression = savings?.compression;
609 const routing = savings?.rerouting;
610 const remaining = savings?.remaining;
611 // A session without a reroute has no routing estimate: its compression savings still count.
612 const saved = compression != null || routing != null ? (compression ?? 0) + (routing ?? 0) : null;
613 const baseline = saved != null && remaining != null ? saved + remaining : null;
614 const percent = (value: number | null | undefined) => value != null && baseline != null && baseline > 0
615 ? `${(100 * value / baseline).toFixed(1)}%` : "—";
616 const legend = [
617 ["Compression savings", compression, COMPRESSION_COLOR],
618 ["Routing savings", routing, ROUTING_COLOR],
619 ["Remaining cost", remaining, REMAINING_COLOR],
620 ] as const;
621 const details = Box({ flexDirection: "column", flexGrow: 1, children: [
622 Text({ bold: true, children: dollars(saved) }),
623 Text({ dimColor: true, children: "Estimated total saved" }),
624 Text({ children: `${percent(saved)} cost reduction` }),
625 ...legend.map(([label, value, color]) => Box({ flexDirection: "row", marginTop: 1, children: [
626 Text({ color, children: "● " }),
627 Text({ dimColor: true, children: `${label} ` }),
628 Text({ children: dollars(value) }),
629 ...(label !== "Remaining cost" ? [Text({ dimColor: true, children: ` (${percent(value)})` })] : []),
630 ] })),
631 ] });
632 return Box({ flexDirection: "column", borderStyle: "round", borderColor: ROUTING_COLOR, paddingX: 1, marginTop: 1, children: [
633 Text({ bold: true, children: "Cost savings" }),
634 Box({ flexDirection: width >= 64 ? "row" : "column", alignItems: "center", columnGap: 2, marginTop: 1, children: [
635 details,
636 savingsDonut({ Box, Text }, baseline ? [(compression ?? 0) / baseline, (routing ?? 0) / baseline] : [0, 0], percent(saved)),
637 ] }),
638 Text({ dimColor: true, children: savings?.stale ? "Refresh unavailable · last known amounts" : "Session estimates · USD · — unavailable" }),
639 ] });
640}
641
642// Braille provides 2×4 dots per terminal cell: a round ring without image support.
643// Color each cell by its angle; all numeric labels use the exact savings amounts.
644function savingsDonut({ Box, Text }: Pick<Elements, "Box" | "Text">, [compression, routing]: [number, number], label: string): RenderElement {
645 const width = 21;
646 const height = 9;
647 const dots = [[1, 8], [2, 16], [4, 32], [64, 128]];
648 const rows: RenderElement[] = [];
649 for (let y = 0; y < height; y++) {
650 const cells: RenderElement[] = [];
651 for (let x = 0; x < width; x++) {
652 if (y === 4 && x === 7) {
653 cells.push(Text({ bold: true, children: label.padStart(6).padEnd(7) }));
654 x += 6;
655 continue;
656 }
657 let mask = 0;
658 for (let dy = 0; dy < 4; dy++) for (let dx = 0; dx < 2; dx++) {
659 const px = (x * 2 + dx + 0.5 - width) / width;
660 const py = (y * 4 + dy + 0.5 - height * 2) / (height * 2);
661 const radius = px * px + py * py;
662 if (radius >= 0.52 && radius <= 1) mask |= dots[dy]![dx]!;
663 }
664 const angle = (Math.atan2((x + 0.5 - width / 2) / width, -(y + 0.5 - height / 2) / height) / (2 * Math.PI) + 1) % 1;
665 const color = angle < compression ? COMPRESSION_COLOR : angle < compression + routing ? ROUTING_COLOR : REMAINING_COLOR;
666 cells.push(Text({ color, children: mask ? String.fromCharCode(0x2800 + mask) : " " }));
667 }
668 rows.push(Box({ flexDirection: "row", children: cells }));
669 }
670 return Box({ flexDirection: "column", width, flexShrink: 0, children: rows });
671}
672
673// The models containing `filter`, those whose provider or name starts with it
674// first ("qwen" lists qwen/… before deepseek/…-qwen-14b), newest version first.
675function matching(models: string[], filter: string): string[] {
676 const f = filter.toLowerCase();
677 const rank = (m: string) => {
678 const [provider = "", name = m] = m.toLowerCase().split("/");
679 return provider.startsWith(f) ? 0 : name.startsWith(f) ? 1 : 2;
680 };
681 return models.filter((m) => m.toLowerCase().includes(f)).sort((a, b) => rank(a) - rank(b) || b.localeCompare(a, undefined, { numeric: true }));
682}
683
684function spinner(picker: EdgeePicker): string {
685 return SPINNER[(picker.frame ?? 0) % SPINNER.length]!;
686}
687
688type ListData = { catalog: string[]; filter: string; active: EdgeeReroute | null; totals: Record<string, EdgeeModelTotals>; pending: string | undefined; inner: number };
689
690// The picker's rows, each a plain Button: ↑↓ move the highlight, Enter picks.
691// Claude Code's choice is always first. An empty filter offers the active and
692// recently served models, then providers to narrow by; a filter, its matches.
693function modelList({ Box, Text, Button }: Elements, { catalog, filter, active, totals, pending, inner }: ListData): RenderElement[] {
694 const span = (children: string, props: Omit<TextProps, "children"> = {}) => Text({ ...props, children });
695 const chosen = pending ?? active?.model ?? OFF;
696 const option = (value: string, label: string, color: string, note = "") =>
697 Box({
698 flexDirection: "row",
699 children: [
700 span(value === chosen ? "● " : "○ ", { color: value === chosen ? "green" : color, bold: value === chosen }),
701 Button({ key: `pick:${value}`, label: fit(label, Math.max(12, inner - 4 - note.length)).trimEnd(), plain: true, dimColor: value !== chosen, onPress: () => {} }),
702 span(note, { dimColor: true }),
703 ],
704 });
705 const rows = [option(OFF, "Claude Code's choice", "green", " no reroute")];
706
707 if (!filter) {
708 const served = Object.keys(totals).filter((m) => m !== "failed").map((m) => withProvider(m, catalog));
709 const suggested = [...new Set([...(active ? [active.model] : []), ...served])].filter((m) => catalog.includes(m) || m === active?.model);
710 for (const m of suggested.slice(0, ROWS)) rows.push(option(m, m, providerColor(m), m === active?.model ? " active" : " used"));
711 const providers = [...countBy(catalog, (m) => m.split("/")[0] ?? m)].sort((a, b) => b[1] - a[1]).slice(0, SUGGESTED_PROVIDERS);
712 rows.push(
713 Box({
714 flexDirection: "row",
715 flexWrap: "wrap",
716 columnGap: 1,
717 marginTop: 1,
718 children: [span("browse", { dimColor: true }), ...providers.map(([p, n]) => Button({ key: `provider:${p}`, label: `${p} ${n}`, plain: true, onPress: () => {} }))],
719 }),
720 );
721 return rows;
722 }
723
724 const hits = matching(catalog, filter);
725 if (hits.length === 0) return [...rows, span(` no model matches "${filter}"`, { color: "red", italic: true })];
726 for (const m of hits.slice(0, ROWS)) rows.push(option(m, m, providerColor(m), m === active?.model ? " active" : ""));
727 if (hits.length > ROWS) rows.push(span(` +${hits.length - ROWS} more · keep typing to narrow`, { dimColor: true, italic: true }));
728 return rows;
729}
730
731function countBy<T>(items: T[], key: (item: T) => string): Map<string, number> {
732 const counts = new Map<string, number>();
733 for (const item of items) counts.set(key(item), (counts.get(key(item)) ?? 0) + 1);
734 return counts;
735}
736
737function splitOnce(text: string, sep: string): [string, string] {
738 const at = text.indexOf(sep);
739 return at < 0 ? [text, ""] : [text.slice(0, at), text.slice(at + sep.length)];
740}
741
742type BandData = Pick<PaneData, "active" | "catalog" | "recent" | "totals" | "savings" | "columns" | "clickable">;
743
744// The minimized pane: one line above the prompt, where requests go and what they cost.
745function bandView({ Box, Text, Button }: Elements, { active, catalog, recent, totals, savings, columns, clickable }: BandData): RenderElement {
746 const sum = sumTotals(totals);
747 const lastServed = [...recent].reverse().find((r) => r.served)?.served;
748 const served = lastServed ? withProvider(lastServed, catalog) : undefined;
749 const facts = [`saved ⇄ ${dollars(savings?.rerouting)} est. / compression ${dollars(savings?.compression)}${savings?.stale ? " (stale)" : ""}`, `${sum.requests} req`, `${short(sum.input + sum.cached)}↑ ${short(sum.output)}↓`, `${Math.round(cacheHit(sum) * 100)}% cache`].join(" · ");
750 return Box({
751 flexDirection: "row",
752 justifyContent: "space-between",
753 width: columns,
754 children: [
755 Box({
756 flexDirection: "row",
757 flexShrink: 1,
758 children: [
759 Text({ color: ACCENT, bold: true, children: "◆ Edgee " }),
760 active
761 ? Text({ color: ACCENT, bold: true, children: `⇄ ${bare(active.model)} until ${clockTime(active.expiresAt)}` })
762 : Text({ color: "green", children: "● direct" }),
763 ...(served ? [Text({ dimColor: true, children: " · " }), Text({ color: providerColor(served), children: bare(served) })] : []),
764 Text({ dimColor: true, wrap: "truncate-end", children: ` · ${facts}` }),
765 ],
766 }),
767 Box({
768 flexDirection: "row",
769 flexShrink: 0,
770 children: [
771 clickable
772 ? Button({ key: "expand", label: "+", hotkey: "o", onPress: () => {} })
773 : Text({ dimColor: true, children: "/edgee panel" }),
774 ],
775 }),
776 ],
777 });
778}
779
780function sumTotals(totals: Record<string, EdgeeModelTotals>): EdgeeModelTotals {
781 return Object.values(totals).reduce(
782 (s, t) => ({ requests: s.requests + t.requests, input: s.input + t.input, cached: s.cached + t.cached, output: s.output + t.output }),
783 { requests: 0, input: 0, cached: 0, output: 0 },
784 );
785}
786
787// The share of the input the prompt cache served.
788function cacheHit({ input, cached }: EdgeeModelTotals): number {
789 return input + cached > 0 ? cached / (input + cached) : 0;
790}
791
792// The gateway may name the served model without its provider (`qwen3-coder-next`):
793// find it in the catalog to label and color it like the rest.
794function withProvider(model: string, catalog: string[]): string {
795 return model.includes("/") ? model : (catalog.find((m) => m.endsWith(`/${model}`)) ?? model);
796}
797
798function providerColor(model: string): string {
799 return PROVIDER_COLORS[model.split("/")[0] ?? ""] ?? (model.startsWith("claude") ? "#D97757" : "white");
800}
801
802function bare(model: string): string {
803 return model.replace(/\[.*\]$/, "").split("/").pop() ?? model;
804}
805
806// `claude-opus-5-5[1m]` and `anthropic/claude-opus-5-5-20260101` are the same model.
807function sameModel(requested: string, served: string): boolean {
808 const a = bare(requested).toLowerCase();
809 const b = bare(served).toLowerCase();
810 return a.startsWith(b) || b.startsWith(a);
811}
812
813function errorText(err: unknown): string {
814 return err instanceof Error ? err.message : String(err);
815}
816
817function fit(text: string, width: number): string {
818 return text.length > width ? `${text.slice(0, width - 1)}…` : text.padEnd(width);
819}
820
821function short(n: number): string {
822 if (n >= 1_000_000) return `${+(n / 1_000_000).toFixed(1)}M`;
823 if (n >= 1_000) return `${+(n / 1_000).toFixed(1)}k`;
824 return String(n);
825}
826
827function clockTime(ms: number, seconds = false): string {
828 const d = new Date(ms);
829 const parts = [d.getHours(), d.getMinutes(), ...(seconds ? [d.getSeconds()] : [])];
830 return parts.map((n) => String(n).padStart(2, "0")).join(":");
831}
832types/index.d.ts 40 lines1export type EdgeeReroute = { model: string; expiresAt: number };
2
3export type EdgeeRequest = {
4 at: number;
5 durationMs: number;
6 requested: string;
7 served: string | null;
8 input: number;
9 cached: number;
10 output: number;
11 subagent: boolean;
12};
13
14export type EdgeePicker = {
15 filter?: string;
16 notice?: string;
17 failed?: boolean;
18 pending?: string; // the model a pick is applying (OFF to clear), until the gateway answers
19 frame?: number; // the pending spinner's frame
20};
21
22export type EdgeeModelTotals = { requests: number; input: number; cached: number; output: number };
23
24// Nano-USD from session analytics; null is unavailable, never an assumed zero.
25export type EdgeeSavings = { compression: number | null; rerouting: number | null; remaining: number | null; stale?: boolean };
26
27declare module "claude-code" {
28 interface PluginState {
29 "edgee": {
30 reroute: EdgeeReroute | null;
31 requests: EdgeeRequest[];
32 models: Record<string, EdgeeModelTotals>;
33 catalog: string[];
34 picker: EdgeePicker;
35 minimized: boolean;
36 savings: EdgeeSavings;
37 };
38 }
39}
40