SLOPSHOPPER

switchboard

Peer session inbox and /send, a /switchboard pane showing agents and the messages between them, a status band above the prompt, per-prompt model triage decided…

panebandcommandtoaststatusprompt
A shopper browsing a rack in a slop shop
Preview · a replayed session in a sandbox
claude · ~/work/app · switchboard
│ ┃ Inbox ✕ › fix the failing auth test and add an audit log call │ ┃ No messages yet. │ ⏺ Read(src/auth.ts) │ ⎿ Read 6 lines │ ⏺ Update(src/auth.ts) │ ⎿ Added 2 lines, removed 1 line │ ⏺ Bash(bun test) │ ⎿ 3 pass, 1 fail │ │ ● Done. refresh now rejects expired claims and logs an audit event. │ │ ✻ Worked for 42s · done 4:20 PM │ │ › /triage │ ⎿ switchboard: Triage on. Decided by Haiku: set TYPESAFE_API_KEY o │ │ triage on last turn 42s · 97.4k in (93% cached) · 1.5k out ────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── › ? for shortcuts

Draws

Band
triage on last turn 42s · 97.4k in (93% cached) · 1.5k out
Pane · Inbox
No messages yet.
Pane · Switchboard
0 agents · 0 running · 0 messages ◆ main Wire No messages yet. /send, SendMessage and peer sessions show here.
README

switchboard

A Claude Code mod (function hooks plugin). This folder in stunt-double/product-stack is its single source; other repositories install it from this repository's marketplace.

<img src="assets/switchboard-demo.gif" alt="Switchboard demo" width="100%">

Loading it

Claude Code only runs plugin code from a repo once a person has opted in, so how it loads depends on the session:

  • Interactive terminal: auto-loads from .claude/skills/switchboard once you accept the workspace trust dialog. If you trusted the folder after the session started, run /reload-plugins.
  • Cloud sessions, the Claude app, claude -p and the Agent SDK: there is no trust dialog, so it does not auto-load. Set CLAUDE_CODE_PLUGIN_DIRS to the folder's absolute path (in the cloud environment's environment variables, or the env block of ~/.claude/settings.json), e.g. CLAUDE_CODE_PLUGIN_DIRS=/home/user/product-stack/.claude/skills/switchboard, or pass --plugin-dir .claude/skills/switchboard.
  • Anywhere, installed at user scope:
/plugin install switchboard --marketplace stunt-double/product-stack

Repo settings (enabledPlugins, extraKnownMarketplaces in .claude/settings.json) can't load it: Claude Code ignores plugins enabled only by repo-authored settings.

What it does

  • Agent to agent comms: messages from other sessions, teammates and agents are kept in an inbox (last 50) with a toast. /inbox opens them in a pane; /send <to> <message> sends one by the name ListAgents shows.
  • Switchboard pane: /switchboard opens a live view of the session's orchestration: main with its route, every subagent, teammate, workflow agent and Codex handover as a tree under the agent that spawned it (status, route → model, age; press one to open its transcript), and the wire, every message between main, its agents and peer sessions, newest first. /switchboard clear empties it.
  • UI: a band above the prompt shows:
  • the current route with its effort and what decided it (deep → opus-5-5 high · jev 82%, · haiku or · pin), with pinned routes in yellow;
  • the last turn's time, tokens and prompt-cache hits (last turn 34s · 10.0k in (90% cached) · 1.2k out), so you can see the cost of switching models between turns;
  • how many subagents went to each route, which opens the switchboard pane;
  • a button for unread messages.

The status line shows the tier and what decided it, and /triage reports all of this as text. The inbox lists the newest message first, with how long ago it arrived.

  • Model selection triage: each prompt a person sends (typed at the terminal, from the Claude app, or through claude -p and the Agent SDK) is classified, by TypeSafe's Jev when a TypeSafe API key is set and Jev is confident (Choice confidence 0.3 or more), else by Haiku, as quick, standard, deep, ultra or copywriting, and that turn's main-loop requests go to Haiku 5.5 (low effort), Opus (medium or high effort), Fable 5.1 (max for ultra, medium for copywriting). Every route has a 1M context window, so a quick turn late in a long conversation never overflows a smaller model and forces a compaction (Haiku 4.5, the old quick route, had 200K; Haiku 5.5 has 1M). /triage on|off, /triage quick|standard|deep|ultra|copywriting to pin the main loop, /triage auto to unpin.
  • Subagents and workflows: an Agent tool subagent of type general-purpose with no model given is routed by its task at spawn. Workflow agents (ultracode included) never pass agent.spawn, so their opening task is captured at session.append and they are routed on their first request. A model chosen explicitly (Agent({ model }), agent(..., { model }), a custom agent type's own model), a fork and a teammate are left alone. The band and /triage show how many subagents went to each tier.
  • Codex handover: the same spawn triage can choose codex for a large self-contained implementation, a second opinion on a risky design or a bug whose cause is still unclear; that subagent is started as codex:codex-rescue (the openai-codex plugin's forwarder) with the Agent tool's prompt, which is already self-contained. Without that plugin the spawn is routed deep instead. Workflow agents are never handed over: their type is fixed before switchboard sees them. /triage codex off turns the handover off, /triage codex on back on.

Switching models between turns drops the prompt cache, so pin a tier for long sessions where that cost matters. Routes live in ROUTES in hooks/register.tsx.

Deciding with Jev

Triage decisions go to TypeSafe's Jev (jev-latest, through the vendored JavaScript SDK in hooks/vendor/) once it has a key, from either:

  • the plugin's typesafe_api_key option, kept in secure storage: claude plugin configure switchboard, or the options screen /plugin install shows;
  • the TYPESAFE_API_KEY environment variable, read when no option is set.

With neither, or when Jev errors or is unsure, Haiku decides as before. /triage says which one is deciding.

For deliberate fan-out and Codex handoffs, see orchestrator.

Check it with claude plugin validate .claude/skills/switchboard and claude plugin test .claude/skills/switchboard.

Source 3 files
hooks/register.tsx 740 lines
1import type { AgentSpawnInput, AgentSpawnResult, EngineInterface, Register } from 'claude-code';
2import { atom, read, update } from 'claude-code';
3
4import { choice, type Fetch, TypeSafeClient } from './vendor/typesafe-sdk.mjs';
5import type {
6  SwitchboardAgent,
7  SwitchboardDecision,
8  SwitchboardMessage,
9  SwitchboardRoute,
10  SwitchboardTier,
11  SwitchboardTurn,
12  SwitchboardWire,
13} from '../types';
14
15const isTriageOn = atom({ plugin: 'switchboard', key: 'isTriageOn' } as const, true);
16const isCodexOn = atom({ plugin: 'switchboard', key: 'isCodexOn' } as const, true);
17const pinned = atom({ plugin: 'switchboard', key: 'pinned' } as const, null);
18// The main loop's route for the current turn, and who decided it.
19const decision = atom({ plugin: 'switchboard', key: 'decision' } as const, null);
20const lastTurn = atom({ plugin: 'switchboard', key: 'lastTurn' } as const, null);
21const inbox = atom({ plugin: 'switchboard', key: 'inbox' } as const, []);
22const unread = atom({ plugin: 'switchboard', key: 'unread' } as const, 0);
23const subagents = atom({ plugin: 'switchboard', key: 'subagents' } as const, {
24  quick: 0,
25  standard: 0,
26  deep: 0,
27  ultra: 0,
28  copywriting: 0,
29  codex: 0,
30});
31// ponytail: one entry per workflow agent for the session; fine at workflow scale.
32const agentTiers = atom({ plugin: 'switchboard', key: 'agentTiers' } as const, {});
33
34// The switchboard pane: every agent of the session as a tree, and every message between them.
35const agents = atom({ plugin: 'switchboard', key: 'agents' } as const, []);
36const wire = atom({ plugin: 'switchboard', key: 'wire' } as const, []);
37
38const INBOX = 'switchboard-inbox';
39const BOARD = 'switchboard-board';
40const MAIN = 'main';
41const TIERS: readonly SwitchboardTier[] = ['quick', 'standard', 'deep', 'ultra', 'copywriting'];
42
43// Cheapest model that does the job; Opus kept for hard reasoning. Every route has a 1M window:
44// a turn routed to a 200K model (Haiku 4.5) overflows a long conversation and forces compaction.
45export const ROUTES: Record<SwitchboardTier, { model: string; effort: 'low' | 'medium' | 'high' | 'max' }> = {
46  quick: { model: 'claude-haiku-5-5', effort: 'low' },
47  standard: { model: 'claude-opus-5-5', effort: 'medium' },
48  deep: { model: 'claude-opus-5-5', effort: 'high' },
49  ultra: { model: 'claude-fable-5-1', effort: 'max' },
50  copywriting: { model: 'claude-fable-5-1', effort: 'medium' },
51};
52
53const HINTS: Record<SwitchboardTier, string> = {
54  quick: 'a lookup, a one-line answer, a rename or a tiny edit',
55  standard: 'an ordinary coding task in a few files',
56  deep: 'architecture, debugging, a migration, multi-step or risky work',
57  ultra: 'full-system redesign, highest-complexity multi-step work, maximum reasoning needed',
58  copywriting: 'marketing copy, product writing, messaging, tone and voice',
59};
60
61// A generic subagent may instead be handed over to Codex (the openai-codex plugin's agent).
62export const CODEX_AGENT = 'codex:codex-rescue';
63const SPAWN_HINTS: Record<SwitchboardRoute, string> = {
64  ...HINTS,
65  codex:
66    'hand over to Codex: a large self-contained implementation, a second opinion on a risky design, or a bug whose cause is still unclear',
67};
68const ROUTE_NAMES: readonly SwitchboardRoute[] = [...TIERS, 'codex'];
69
70// TypeSafe's Jev decides first when a key is set; below this Choice confidence it is unsure.
71// ponytail: 0.3 is a starting point (a 5-way choice's peak near 0.45); tune on real prompts.
72const JEV_MODEL = 'jev-latest';
73const JEV_MIN_CONFIDENCE = 0.3;
74
75const choiceOf = <T extends string>(options: Record<T, string>, label: string | undefined): T | null =>
76  (Object.keys(options) as T[]).find((k) => label?.startsWith(k)) ?? null;
77
78export const tierOf = (label: string | undefined): SwitchboardTier | null => choiceOf(HINTS, label);
79
80// Agent types whose model nobody chose: a custom agent's own `model` is respected.
81const TRIAGED_TYPES = new Set(['general-purpose']);
82
83// An engine fork (compaction, memory) opens on the whole transcript; a workflow agent on its task.
84const MAX_OPENING_MESSAGES = 3;
85
86const INJECTED_DOORS = new Set([
87  'attachment',
88  'hook-context',
89  'note',
90  'delivery',
91  'compaction',
92  'notice',
93]);
94
95const PEER_KINDS = new Set(['peer', 'coordinator', 'peer-send-message']);
96
97// A person's own prompt: typed at the terminal, sent from the Claude app (Remote Control), or `claude -p` / the Agent SDK.
98const PERSON_KINDS = new Set(['composer', 'bridge', 'sdk']);
99
100// The key from `claude plugin configure switchboard`, else TYPESAFE_API_KEY; set by register.
101let configuredKey: string | undefined;
102
103async function typesafeKey($: EngineInterface): Promise<string | undefined> {
104  return configuredKey || (await $.env.get('TYPESAFE_API_KEY').catch(() => undefined)) || undefined;
105}
106
107// The SDK's fetch over the host's: the module has no fetch or Response of its own. The body is
108// read whole, so `body` is null and the SDK skips its streaming buffer.
109const hostFetch =
110  ($: EngineInterface): Fetch =>
111  async (url, init) => {
112    const res = await $.http.fetch(url, {
113      method: init?.method,
114      headers: init?.headers as Record<string, string> | undefined,
115      body: init?.body as string | undefined,
116    });
117    const response = {
118      ok: res.ok,
119      status: res.status,
120      headers: { get: (name: string) => res.headers[name.toLowerCase()] ?? null },
121      body: null,
122      text: async () => res.text,
123      json: async () => JSON.parse(res.text),
124      clone: () => response,
125    };
126    return response as unknown as Awaited<ReturnType<Fetch>>;
127  };
128
129// Jev first (fast, typed, calibrated); Haiku when no key is set, the call fails or Jev is unsure.
130async function jevChoice<T extends string>(
131  $: EngineInterface,
132  text: string,
133  options: Record<T, string>
134): Promise<SwitchboardDecision<T> | null> {
135  const apiKey = await typesafeKey($);
136  if (apiKey === undefined) return null;
137  try {
138    // No retries and a short timeout: a prompt waits on this, and Haiku is the fallback.
139    const client = new TypeSafeClient({
140      apiKey,
141      fetch: hostFetch($),
142      compression: false,
143      timeout: 5000,
144      retry: { maxRetries: 0 },
145    });
146    const { answers } = await client.systemOne({
147      model: JEV_MODEL,
148      state: { request: text.slice(0, 8000) },
149      questions: {
150        route: choice('Which option best describes the work the coding assistant must do for `request`?', options),
151      },
152    });
153    const { choice: picked, confidence = 0 } = answers.route;
154    const route = confidence >= JEV_MIN_CONFIDENCE ? choiceOf(options, picked) : null;
155    return route === null ? null : { route, by: 'jev', confidence };
156  } catch {
157    return null;
158  }
159}
160
161async function classify($: EngineInterface, text: string): Promise<SwitchboardDecision | null>;
162async function classify<T extends string>(
163  $: EngineInterface,
164  text: string,
165  options: Record<T, string>
166): Promise<SwitchboardDecision<T> | null>;
167async function classify(
168  $: EngineInterface,
169  text: string,
170  options: Record<string, string> = HINTS
171): Promise<SwitchboardDecision<string> | null> {
172  const labels = Object.entries(options).map(([k, hint]) => `${k}: ${hint}`);
173  return (
174    (await jevChoice($, text, options)) ??
175    $.model
176      .classify(text.slice(0, 4000), labels, { model: 'haiku' })
177      .then((label) => {
178        const route = choiceOf(options, label);
179        return route === null ? null : { route, by: 'haiku' as const };
180      })
181      .catch(() => null)
182  );
183}
184
185// Display helpers for the band, the status line and /triage.
186const shortModel = (model: string) => model.replace(/^claude-/, '');
187const tokens = (n: number) =>
188  n >= 1_000_000 ? `${(n / 1_000_000).toFixed(1)}M` : n >= 1000 ? `${(n / 1000).toFixed(1)}k` : `${n}`;
189const seconds = (ms: number) =>
190  ms >= 60_000 ? `${Math.floor(ms / 60_000)}m${Math.floor((ms % 60_000) / 1000)}s` : `${Math.round(ms / 1000)}s`;
191const ago = (ms: number) =>
192  ms < 60_000 ? 'just now' : ms < 3_600_000 ? `${Math.floor(ms / 60_000)}m ago` : `${Math.floor(ms / 3_600_000)}h ago`;
193
194export const decidedBy = (d: SwitchboardDecision<string>) =>
195  d.by === 'jev' ? `jev ${Math.round((d.confidence ?? 0) * 100)}%` : d.by;
196
197export const routeLine = (d: SwitchboardDecision) =>
198  `${d.route} → ${shortModel(ROUTES[d.route].model)} ${ROUTES[d.route].effort} · ${decidedBy(d)}`;
199
200// Cache reads show whether a model switch between turns dropped the prompt cache.
201export const turnLine = (t: SwitchboardTurn) =>
202  `last turn ${seconds(t.durationMs)} · ${tokens(t.input)} in${t.input > 0 ? ` (${Math.round((t.cached / t.input) * 100)}% cached)` : ''} · ${tokens(t.output)} out`;
203
204async function count($: EngineInterface, picked: SwitchboardRoute) {
205  // A tally kept from before a route existed lacks its key.
206  await update($, subagents, (n) => ({ ...n, [picked]: (n[picked] ?? 0) + 1 }));
207}
208
209const tallyOf = (routed: Partial<Record<SwitchboardRoute, number>>) =>
210  ROUTE_NAMES.filter((t) => (routed[t] ?? 0) > 0).map((t) => `${routed[t]} ${t}`);
211
212async function track($: EngineInterface, agent: SwitchboardAgent) {
213  await update($, agents, (all) => [...all.filter((a) => a.id !== agent.id), agent].slice(-100));
214}
215
216// A send between this session's own loops also arrives at session.receive: keep it once.
217const ECHO_MS = 10_000;
218
219async function record($: EngineInterface, message: Omit<SwitchboardWire, 'at'>, isEcho = false) {
220  const at = await $.clock.now();
221  await update($, wire, (all) =>
222    isEcho && all.some((w) => at - w.at < ECHO_MS && w.text !== '' && message.text.includes(w.text))
223      ? all
224      : [...all, { ...message, at }].slice(-200)
225  );
226}
227
228// The session's own model, read off the main loop before triage rewrites it; kept across reloads.
229const sessionModel = atom({ plugin: 'switchboard', key: 'sessionModel' } as const, null);
230// A subagent's opening task, captured at session.append until its first request.
231const openings = new Map<string, string>();
232// In-flight decisions, so concurrent steps of one agent classify once.
233const deciding = new Map<string, Promise<SwitchboardTier | null>>();
234
235type FirstStep = { agentId: string; model: string; index: number; messageCount: number };
236
237// Workflow agents never pass agent.spawn, so they are routed on their first request.
238async function decideWorkflowAgent(
239  $: EngineInterface,
240  step: FirstStep
241): Promise<SwitchboardTier | null> {
242  const known = (await read($, agentTiers))[step.agentId];
243  if (known !== undefined) return known;
244
245  const task = openings.get(step.agentId) ?? '';
246  openings.delete(step.agentId);
247  // No opening seen (a reload in between, an engine loop): leave it, and decide nothing for good.
248  if (task === '') return null;
249  const inherited = await read($, sessionModel);
250
251  const isWorkflowAgent =
252    step.index === 0 &&
253    step.messageCount <= MAX_OPENING_MESSAGES &&
254    // A model other than the session's was chosen explicitly (`agent(..., { model })`).
255    step.model === inherited &&
256    // Listed agents came through agent.spawn, which already decided.
257    !(await $.agent.list()).some((a) => a.id === step.agentId);
258
259  let picked: SwitchboardTier | null = null;
260  if (isWorkflowAgent && (await read($, isTriageOn))) {
261    picked = (await classify($, task))?.route ?? null;
262    if (picked !== null) await count($, picked);
263  }
264  await update($, agentTiers, (all) => ({ ...all, [step.agentId]: picked }));
265  if (isWorkflowAgent)
266    await track($, {
267      id: step.agentId,
268      description: (task.split('\n', 1)[0] ?? '').slice(0, 120),
269      type: 'workflow',
270      route: picked,
271      model: picked ? ROUTES[picked].model : step.model,
272      status: 'running',
273      at: await $.clock.now(),
274    });
275  return picked;
276}
277
278const STATUS: Record<SwitchboardAgent['status'], { glyph: string; color?: 'claude' | 'success' | 'error' | 'inactive' }> = {
279  running: { glyph: '●', color: 'claude' },
280  idle: { glyph: '○', color: 'inactive' },
281  completed: { glyph: '✓', color: 'success' },
282  failed: { glyph: '✗', color: 'error' },
283  killed: { glyph: '✗', color: 'error' },
284};
285
286const ROUTE_COLOR: Record<SwitchboardRoute, 'success' | 'suggestion' | 'permission' | 'claude' | 'remember' | 'warning'> = {
287  quick: 'success',
288  standard: 'suggestion',
289  deep: 'permission',
290  ultra: 'claude',
291  copywriting: 'remember',
292  codex: 'warning',
293};
294
295const clip = (text: string, width: number) => {
296  const line = text.replace(/\s+/g, ' ').trim();
297  return line.length > width ? `${line.slice(0, Math.max(1, width - 1))}…` : line;
298};
299const elapsed = (ms: number) =>
300  ms < 60_000 ? `${Math.max(0, Math.round(ms / 1000))}s` : ms < 3_600_000 ? `${Math.round(ms / 60_000)}m` : `${Math.round(ms / 3_600_000)}h`;
301
302// Depth-first under main; an agent whose parent is not tracked hangs off main.
303function treeOf(list: SwitchboardAgent[]): { agent: SwitchboardAgent; prefix: string }[] {
304  const ids = new Set(list.map((a) => a.id));
305  const children = new Map<string, SwitchboardAgent[]>();
306  for (const a of list) {
307    const parent = a.parentId !== undefined && ids.has(a.parentId) ? a.parentId : MAIN;
308    children.set(parent, [...(children.get(parent) ?? []), a]);
309  }
310  const rows: { agent: SwitchboardAgent; prefix: string }[] = [];
311  const walk = (id: string, indent: string) => {
312    const kids = children.get(id) ?? [];
313    kids.forEach((agent, i) => {
314      const isLast = i === kids.length - 1;
315      rows.push({ agent, prefix: `${indent}${isLast ? '└─' : '├─'} ` });
316      walk(agent.id, `${indent}${isLast ? '   ' : '│  '}`);
317    });
318  };
319  walk(MAIN, '');
320  return rows;
321}
322
323type Spawned = { spawned: AgentSpawnResult; route: SwitchboardRoute | null };
324
325async function routeSpawn(
326  $: EngineInterface,
327  e: AgentSpawnInput,
328  next: (e: AgentSpawnInput) => Promise<AgentSpawnResult>
329): Promise<Spawned> {
330  if (
331    e.fork ||
332    e.isTeammate ||
333    e.model !== undefined ||
334    !TRIAGED_TYPES.has(e.subagentType) ||
335    !(await read($, isTriageOn))
336  )
337    return { spawned: await next(e), route: null };
338
339  const task = `${e.description}\n\n${e.prompt}`;
340  const decided = (await read($, isCodexOn)) ? await classify($, task, SPAWN_HINTS) : await classify($, task);
341  if (decided === null) return { spawned: await next(e), route: null };
342  const picked = decided.route;
343
344  if (picked === 'codex') {
345    // Codex's agent keeps its own model; the Agent prompt is already self-contained.
346    const handed = await next({ ...e, subagentType: CODEX_AGENT });
347    if (handed.deny === undefined) {
348      await count($, 'codex');
349      return { spawned: handed, route: 'codex' };
350    }
351    // The codex plugin is not installed or refused: the work is substantial, so route it deep.
352    await count($, 'deep');
353    return { spawned: await next({ ...e, model: ROUTES.deep.model }), route: 'deep' };
354  }
355
356  await count($, picked);
357  return { spawned: await next({ ...e, model: ROUTES[picked].model }), route: picked };
358}
359
360export const register: Register = (on, options) => {
361  configuredKey = typeof options.typesafe_api_key === 'string' ? options.typesafe_api_key : undefined;
362
363  on('session.start', async ($, e, next) => {
364    await $.command.register({
365      name: 'triage',
366      description: 'Model triage: on, off, auto, pin a tier, or codex on|off for subagent handover',
367      argumentHint: '[on|off|auto|quick|standard|deep|ultra|copywriting|codex on|codex off]',
368    });
369    await $.command.register({
370      name: 'inbox',
371      description: 'Show messages from other sessions and agents',
372    });
373    await $.command.register({
374      name: 'switchboard',
375      description: 'Show the agents of this session and the messages between them',
376      argumentHint: '[clear]',
377    });
378    await $.command.register({
379      name: 'send',
380      description: 'Send a message to another session or agent',
381      argumentHint: '<to> <message>',
382    });
383
384    return next(e);
385  });
386
387  // Model selection triage: classify each typed prompt, then route the turn's requests.
388  on('prompt.submit', async ($, e, next) => {
389    if (!PERSON_KINDS.has(e.origin.kind) || e.text.startsWith('/')) return next(e);
390
391    const pin = await read($, pinned);
392    let decided: SwitchboardDecision | null = pin && { route: pin, by: 'pin' };
393    if (pin === null && (await read($, isTriageOn))) {
394      decided = await classify($, e.text);
395    }
396    await update($, decision, () => decided);
397    $.ui.status(decided ? `triage: ${decided.route} · ${decidedBy(decided)}` : undefined);
398
399    return next(e);
400  });
401
402  // Agent tool subagents: route a generic subagent nobody picked a model for, or hand it to Codex.
403  on('agent.spawn', async ($, e, next) => {
404    const { spawned, route } = await routeSpawn($, e, next);
405    // The agent has started: drawing it must not fail the spawn.
406    if (spawned.deny === undefined && spawned.agentId !== undefined)
407      await track($, {
408        id: spawned.agentId,
409        parentId: e.parentAgentId,
410        description: e.description,
411        type: route === 'codex' ? CODEX_AGENT : e.isTeammate ? 'teammate' : e.subagentType,
412        route,
413        model: spawned.model,
414        status: 'running',
415        at: await $.clock.now(),
416      }).catch(() => undefined);
417    return spawned;
418  });
419
420  // A main turn is kept as the last turn; an agent's turn ending is the end of a subagent's run, and a teammate goes idle until its next message.
421  on('turn.complete', async ($, e, next) => {
422    // The main loop's last turn: how long it took, what it cost and how much the prompt cache served.
423    if (e.agentId === undefined && e.usage !== undefined) {
424      const { model, input_tokens, cache_read_input_tokens, cache_creation_input_tokens, output_tokens } = e.usage;
425      const turn: SwitchboardTurn = {
426        model,
427        durationMs: e.durationMs,
428        input: input_tokens + cache_read_input_tokens + cache_creation_input_tokens,
429        cached: cache_read_input_tokens,
430        output: output_tokens,
431      };
432      await update($, lastTurn, () => turn);
433    }
434    const id = e.agentId;
435    if (id !== undefined && (await read($, agents)).some((a) => a.id === id)) {
436      await update($, agents, (all) =>
437        all.map((a): SwitchboardAgent =>
438          a.id !== id
439            ? a
440            : {
441                ...a,
442                status:
443                  e.reason === 'aborted'
444                    ? 'killed'
445                    : e.reason !== 'answer'
446                      ? 'failed'
447                      : a.type === 'teammate'
448                        ? 'idle'
449                        : 'completed',
450              }
451        )
452      );
453    }
454    return next(e);
455  });
456
457  // Keep the agent's own task: its first user row as typed, not what the engine or a hook injects.
458  on('session.append', ($, e, next) => {
459    const id = e.agentId;
460    if (
461      id !== undefined &&
462      e.message.role === 'user' &&
463      !e.message.isMeta &&
464      !INJECTED_DOORS.has(e.door) &&
465      !openings.has(id) &&
466      !deciding.has(id)
467    ) {
468      const text = e.message.content
469        .flatMap((block) => (block.type === 'text' ? [block.text] : []))
470        .join('\n');
471      if (text) openings.set(id, text.slice(0, 8000));
472    }
473    return next(e);
474  });
475
476  on('turn.step', async function* ($, e, next) {
477    if (e.agentId === undefined) {
478      if ((await read($, sessionModel)) !== e.model) await update($, sessionModel, () => e.model);
479      const decided = await read($, decision);
480      if (decided === null) return yield* next(e);
481
482      const { model, effort } = ROUTES[decided.route];
483      return yield* next({ ...e, model, effort });
484    }
485
486    const agentId = e.agentId;
487    let pending = deciding.get(agentId);
488    if (pending === undefined) {
489      pending = decideWorkflowAgent($, {
490        agentId,
491        model: e.model,
492        index: e.index,
493        messageCount: e.messageCount,
494      });
495      deciding.set(agentId, pending);
496    }
497    const picked = await pending;
498    if (picked === null) return yield* next(e);
499
500    // A subagent keeps the effort it was given.
501    return yield* next({ ...e, model: ROUTES[picked].model });
502  });
503
504  // Agent to agent comms: keep an inbox of peer deliveries, and send with /send.
505  on('session.send', async ($, e, next) => {
506    const sent = await next(e);
507    if (sent.isDelivered) await record($, { from: e.agentId ?? MAIN, to: e.to, text: e.text }).catch(() => undefined);
508    return sent;
509  });
510
511  on('session.receive', async ($, e, next) => {
512    if (PEER_KINDS.has(e.origin.kind)) {
513      const from = 'teammate' in e.origin ? e.origin.teammate : e.origin.kind;
514      await record($, { from, to: e.agentId ?? MAIN, text: e.text }, true).catch(() => undefined);
515      const message: SwitchboardMessage = {
516        from,
517        text: e.text,
518        at: await $.clock.now(),
519      };
520      await update($, inbox, (list) => [...list, message].slice(-50));
521      await update($, unread, (n) => n + 1);
522      $.ui.toast(`Message from ${from}`);
523    }
524
525    return next(e);
526  });
527
528  on('command.run', { command: 'send' }, async ($, e) => {
529    const [to, ...words] = e.args.trim().split(/\s+/);
530    const text = words.join(' ');
531    if (!to || !text)
532      return {
533        text: 'Usage: /send <to> <message> (names as ListAgents lists them)',
534      };
535
536    const sent = await $.session.send({ to, text });
537    return {
538      text: sent.isDelivered ? `Sent to ${to}.` : `Not sent: ${sent.reason}`,
539    };
540  });
541
542  on('command.run', { command: 'inbox' }, async ($) => {
543    await update($, unread, () => 0);
544    await $.ui.open({ id: INBOX, title: 'Inbox' });
545    return { text: 'Inbox opened.' };
546  });
547
548  on('command.run', { command: 'switchboard' }, async ($, e) => {
549    const arg = e.args.trim();
550    if (arg === 'clear') {
551      await update($, agents, () => []);
552      await update($, wire, () => []);
553    } else if (arg !== '') return { text: 'Usage: /switchboard [clear]' };
554    await $.ui.open({ id: BOARD, title: 'Switchboard' });
555    const list = await read($, agents);
556    return {
557      text: `Switchboard opened: ${list.length} agent${list.length === 1 ? '' : 's'}, ${(await read($, wire)).length} messages.`,
558    };
559  });
560
561  on('command.run', { command: 'triage' }, async ($, e) => {
562    const arg = e.args.trim().replace(/\s+/g, ' ');
563    if (arg === 'codex on' || arg === 'codex off') await update($, isCodexOn, () => arg === 'codex on');
564    else if (arg === 'on' || arg === 'off') await update($, isTriageOn, () => arg === 'on');
565    else if (arg === 'auto') await update($, pinned, () => null);
566    else if ((TIERS as readonly string[]).includes(arg))
567      await update($, pinned, () => arg as SwitchboardTier);
568    else if (arg !== '')
569      return { text: 'Usage: /triage [on|off|auto|quick|standard|deep|ultra|copywriting|codex on|codex off]' };
570
571    if (!(await read($, isTriageOn)) && (await read($, pinned)) === null) {
572      await update($, decision, () => null);
573      $.ui.status(undefined);
574    }
575    const pin = await read($, pinned);
576    const last = await read($, decision);
577    const turn = await read($, lastTurn);
578    const tally = tallyOf(await read($, subagents));
579    const codex = (await read($, isCodexOn)) ? '' : ' Codex handover off.';
580    const decider = (await typesafeKey($))
581      ? ` Decided by ${JEV_MODEL}, Haiku when unsure.`
582      : ' Decided by Haiku: set TYPESAFE_API_KEY or run `claude plugin configure switchboard` to decide with Jev.';
583    return {
584      text: `Triage ${(await read($, isTriageOn)) ? 'on' : 'off'}${pin ? `, pinned to ${pin} (${ROUTES[pin].model})` : ''}.${decider}${codex}${last ? ` Last prompt: ${routeLine(last)}.` : ''}${turn ? ` ${turnLine(turn)} on ${turn.model}.` : ''}${tally.length ? ` Subagents routed: ${tally.join(', ')}.` : ''}`,
585    };
586  });
587
588  // UI: a band above the prompt: the route and who chose it, the last turn's cost, subagents and unread messages.
589  on('ui.render', { component: 'AbovePrompt' }, async ($, e, next) => {
590    const decided = await read($, decision);
591    const turn = await read($, lastTurn);
592    const count = await read($, unread);
593    const tally = tallyOf(await read($, subagents));
594    const isOn = await read($, isTriageOn);
595    if (e.props.hasSurvey || (decided === null && turn === null && count === 0 && tally.length === 0)) return next(e);
596
597    const { Box, Button, Text } = $.ui.resolve(e);
598    const inboxButton = count > 0 && (
599      <Button
600        key="inbox"
601        label={`${count} new message${count === 1 ? '' : 's'}`}
602        onPress={async () => {
603          await update($, unread, () => 0);
604          await $.ui.open({ id: INBOX, title: 'Inbox' });
605        }}
606      />
607    );
608    const route =
609      decided !== null ? (
610        <Text>
611          <Text color={decided.by === 'pin' ? 'yellow' : 'cyan'}>{decided.route}</Text>
612          <Text dimColor>{` → ${shortModel(ROUTES[decided.route].model)} ${ROUTES[decided.route].effort} · ${decidedBy(decided)}`}</Text>
613        </Text>
614      ) : (
615        <Text dimColor>{isOn ? 'triage on' : 'triage off'}</Text>
616      );
617
618    // One row when the band is held to one, else the route over the details.
619    if (e.props.maxRows < 2)
620      return (
621        <Box gap={2}>
622          {route}
623          {inboxButton}
624        </Box>
625      );
626    return (
627      <Box flexDirection="column">
628        <Box gap={2}>
629          {route}
630          {tally.length > 0 && (
631            <Button
632              key="board"
633              label={`subagents: ${tally.join(' · ')}`}
634              onPress={async () => {
635                await $.ui.open({ id: BOARD, title: 'Switchboard' });
636              }}
637            />
638          )}
639          {inboxButton}
640        </Box>
641        {turn && <Text dimColor>{turnLine(turn)}</Text>}
642      </Box>
643    );
644  });
645
646  on('ui.render', { component: 'Pane', requestId: INBOX }, async ($, e) => {
647    const { Box, Text } = $.ui.resolve(e);
648    const list = await read($, inbox);
649    const now = await $.clock.now();
650    return (
651      <Box flexDirection="column">
652        {list.length === 0 && <Text dimColor>No messages yet.</Text>}
653        {list
654          .slice()
655          .reverse()
656          .map((m) => (
657            <Box flexDirection="column" marginBottom={1}>
658              <Text>
659                <Text bold>{m.from}</Text>
660                <Text dimColor> · {ago(now - m.at)}</Text>
661              </Text>
662              <Text>{m.text}</Text>
663            </Box>
664          ))}
665        {list.length > 0 && <Text dimColor>Reply with /send {'<to> <message>'}.</Text>}
666      </Box>
667    );
668  });
669
670  // The switchboard: main and every agent under it, then the wire between them, newest first.
671  on('ui.render', { component: 'Pane', requestId: BOARD }, async ($, e) => {
672    const { Box, Button, Text } = $.ui.resolve(e);
673    const now = await $.clock.now();
674    const width = Math.max(30, e.props.bodyColumns);
675    const live = new Map((await $.agent.list().catch(() => [])).map((a) => [a.id, a]));
676    const list = (await read($, agents)).map((a) => {
677      const status = live.get(a.id)?.status;
678      // The engine's word is fresher while the agent is listed; ours outlives the list.
679      return status === 'running' || status === 'idle' || status === 'completed' || status === 'failed' || status === 'killed'
680        ? { ...a, status }
681        : a;
682    });
683    const nameOf = (id: string) =>
684      id === MAIN ? MAIN : (live.get(id)?.name ?? list.find((a) => a.id === id)?.description ?? id);
685    const messages = (await read($, wire)).slice().reverse();
686    const picked = (await read($, decision))?.route ?? null;
687    const mainModel = picked ? ROUTES[picked].model : await read($, sessionModel);
688    const running = list.filter((a) => a.status === 'running').length;
689
690    return (
691      <Box flexDirection="column">
692        <Text bold>
693          {list.length} agent{list.length === 1 ? '' : 's'} · {running} running · {messages.length} message
694          {messages.length === 1 ? '' : 's'}
695        </Text>
696        <Box flexDirection="column" marginTop={1}>
697          <Text>
698            <Text color="claude">◆</Text> <Text bold>{MAIN}</Text>
699            {picked !== null && <Text color={ROUTE_COLOR[picked]}> {picked}</Text>}
700            {mainModel !== null && <Text dimColor> → {shortModel(mainModel)}</Text>}
701          </Text>
702          {treeOf(list).map(({ agent, prefix }) => {
703            const { glyph, color } = STATUS[agent.status];
704            const meta = `${agent.route ?? agent.type} → ${shortModel(agent.model)} · ${elapsed(now - agent.at)}`;
705            return (
706              <Button
707                key={agent.id}
708                plain
709                onPress={async () => {
710                  await $.ui.view({ agentId: agent.id }).catch(() => undefined);
711                }}
712              >
713                <Text dimColor>{prefix}</Text>
714                <Text color={color}>{glyph}</Text> {clip(agent.description || agent.id, Math.max(10, width - prefix.length - meta.length - 4))}{' '}
715                <Text dimColor {...(agent.route !== null && { color: ROUTE_COLOR[agent.route] })}>
716                  {meta}
717                </Text>
718              </Button>
719            );
720          })}
721        </Box>
722        <Box flexDirection="column" marginTop={1}>
723          <Text bold>Wire</Text>
724          {messages.length === 0 && <Text dimColor>No messages yet. /send, SendMessage and peer sessions show here.</Text>}
725          {messages.map((m) => {
726            const head = `${elapsed(now - m.at).padStart(3)}  ${nameOf(m.from)} → ${nameOf(m.to)}  `;
727            return (
728              <Text>
729                <Text dimColor>{head}</Text>
730                {clip(m.text, Math.max(10, width - head.length))}
731              </Text>
732            );
733          })}
734        </Box>
735        {list.length > 0 && <Text dimColor>Press an agent to open its transcript · /switchboard clear</Text>}
736      </Box>
737    );
738  });
739};
740
hooks/vendor/typesafe-sdk.mjs 1129 lines
1// @typesafe-ai/sdk 0.7.0 (MIT, https://github.com/typesafe-ai/typesafe-sdk-js), its dist/index.mjs vendored as is:
2// a mod imports only its own files. Update with: npm pack @typesafe-ai/sdk@<version>.
3const requestIdFrom = (headers) => headers.get("x-typesafe-request-id") ?? void 0;
4/**
5* A promise for the parsed result with access to the HTTP response.
6*
7* Non-2xx responses reject with an `APIError`, including through `asResponse()`.
8*/
9var APIPromise = class APIPromise extends Promise {
10	#responsePromise;
11	#parseResponse;
12	#parsed;
13	constructor(responsePromise, parseResponse) {
14		super((resolve) => resolve(void 0));
15		this.#responsePromise = responsePromise;
16		this.#parseResponse = parseResponse;
17	}
18	/**
19	* Resolves to the raw `Response` without parsing the body. SDK requests buffer the full
20	* body under the request timeout before handoff; reading it afterwards is caller-owned.
21	* The caller owns the body; don't also `await` the parsed result on the same promise.
22	*/
23	asResponse() {
24		return this.#responsePromise;
25	}
26	/** Return the parsed result, HTTP response, and request ID. */
27	async withResponse() {
28		const [data, response] = await Promise.all([this.#parse(), this.#responsePromise]);
29		return {
30			data,
31			response,
32			requestId: requestIdFrom(response.headers)
33		};
34	}
35	/** Transform the parsed result, sharing the HTTP response and a single body parse. */
36	map(fn) {
37		return new APIPromise(this.#responsePromise, () => this.#parse().then(fn));
38	}
39	#parse() {
40		this.#parsed ??= this.#responsePromise.then(this.#parseResponse);
41		return this.#parsed;
42	}
43	then(onfulfilled, onrejected) {
44		return this.#parse().then(onfulfilled, onrejected);
45	}
46	catch(onrejected) {
47		return this.#parse().catch(onrejected);
48	}
49	finally(onfinally) {
50		return this.#parse().finally(onfinally);
51	}
52};
53const range = (from, to) => Array.from({ length: to - from }, (_, i) => from + i);
54/** Default SDK retry policy. */
55const DEFAULT_RETRY_POLICY = {
56	maxRetries: 2,
57	backoffInitialMs: 500,
58	backoffMaxMs: 5e3,
59	backoffJitter: .25,
60	/** HTTP 408, 429, and 5xx responses. */
61	httpStatuses: /* @__PURE__ */ new Set([
62		408,
63		429,
64		...range(500, 600)
65	]),
66	respectRetryAfter: true,
67	/** Maximum server retry delay before falling back to backoff. */
68	maxRetryAfterMs: 6e4,
69	apiConnectionError: true,
70	apiTimeoutError: true
71};
72DEFAULT_RETRY_POLICY.maxRetries;
73/** Whether the policy retries an HTTP status code. */
74const isRetryableStatus = (status, policy = DEFAULT_RETRY_POLICY) => policy.httpStatuses.has(status);
75/**
76* Parse `retry-after-ms` or `Retry-After` into milliseconds, preferring `retry-after-ms`.
77*
78* Return `undefined` when neither header contains a valid delay.
79*/
80const parseRetryAfter = (headers, now = Date.now()) => {
81	const ms = Number(headers.get("retry-after-ms"));
82	if (headers.has("retry-after-ms") && Number.isFinite(ms) && ms >= 0) return ms;
83	const raw = headers.get("retry-after");
84	if (raw === null) return void 0;
85	const seconds = Number(raw);
86	if (Number.isFinite(seconds)) return seconds >= 0 ? seconds * 1e3 : void 0;
87	const date = Date.parse(raw);
88	if (!Number.isNaN(date)) return Math.max(0, date - now);
89};
90/**
91* Calculate the delay in milliseconds for a zero-based retry attempt.
92*
93* Use an allowed server delay; otherwise use capped exponential backoff with jitter.
94*/
95const retryDelayMs = (attempt, headers, policy = DEFAULT_RETRY_POLICY, random = Math.random) => {
96	if (policy.respectRetryAfter && headers !== void 0) {
97		const retryAfter = parseRetryAfter(headers);
98		if (retryAfter !== void 0 && retryAfter <= policy.maxRetryAfterMs) return retryAfter;
99	}
100	const exponential = Math.min(policy.backoffInitialMs * 2 ** attempt, policy.backoffMaxMs);
101	return Math.round(exponential * (1 - random() * policy.backoffJitter));
102};
103/** Wait `ms` milliseconds, rejecting with `signal.reason` on cancellation. */
104const sleep = (ms, signal) => new Promise((resolve, reject) => {
105	if (signal?.aborted) return reject(signal.reason);
106	const onAbort = () => {
107		clearTimeout(timer);
108		reject(signal?.reason);
109	};
110	const timer = setTimeout(() => {
111		signal?.removeEventListener("abort", onAbort);
112		resolve();
113	}, ms);
114	signal?.addEventListener("abort", onAbort, { once: true });
115});
116//#endregion
117//#region src/errors.ts
118/** Base class for SDK errors. */
119var TypeSafeError = class extends Error {
120	constructor(message, options) {
121		super(message, options);
122		this.name = new.target.name;
123	}
124};
125const isRecord = (value) => typeof value === "object" && value !== null;
126/** Extract a message from a text, error, or validation response body. */
127const extractMessage = (body) => {
128	if (typeof body === "string") return body || void 0;
129	if (!isRecord(body)) return void 0;
130	const { error, message, detail } = body;
131	if (typeof error === "string") return error;
132	if (isRecord(error) && typeof error.message === "string") return error.message;
133	if (typeof message === "string") return message;
134	if (typeof detail === "string") return detail;
135	if (isRecord(detail) && typeof detail.message === "string") return detail.message;
136	if (Array.isArray(detail)) return describeValidationErrors(detail);
137};
138/** Format validation errors as semicolon-separated `path: message` entries. */
139const describeValidationErrors = (errors) => {
140	const parts = errors.flatMap((e) => {
141		if (!isRecord(e) || typeof e.msg !== "string") return [];
142		const loc = Array.isArray(e.loc) ? e.loc.filter((x) => x !== "body").join(".") : "";
143		return [loc ? `${loc}: ${e.msg}` : e.msg];
144	});
145	return parts.length > 0 ? parts.join("; ") : void 0;
146};
147const MAX_RAW_BODY_IN_MESSAGE = 200;
148/** An unsuccessful HTTP response from the API. */
149var APIError = class APIError extends TypeSafeError {
150	/** HTTP response status code. */
151	status;
152	/** HTTP response headers. */
153	headers;
154	/** Parsed JSON, response text, or `undefined` for an empty body. */
155	body;
156	/** Request ID from `x-typesafe-request-id`, or `undefined` when absent. */
157	requestId;
158	constructor(status, body, headers, message) {
159		super(message ?? APIError.describe(status, body));
160		this.status = status;
161		this.body = body;
162		this.headers = headers;
163		this.requestId = requestIdFrom(headers);
164	}
165	static describe(status, body) {
166		const detail = extractMessage(body);
167		if (detail) return `${status} ${detail}`;
168		if (body === void 0) return `${status} status code (no body)`;
169		const raw = typeof body === "string" ? body : JSON.stringify(body);
170		return `${status} ${raw.length > MAX_RAW_BODY_IN_MESSAGE ? `${raw.slice(0, MAX_RAW_BODY_IN_MESSAGE)}…` : raw}`;
171	}
172	/** Create the error subclass for an HTTP status code. */
173	static fromResponse(status, body, headers) {
174		if (status === 400) return new BadRequestError(status, body, headers);
175		if (status === 401) return new AuthenticationError(status, body, headers);
176		if (status === 403) return new PermissionDeniedError(status, body, headers);
177		if (status === 404) return new NotFoundError(status, body, headers);
178		if (status === 422) return new UnprocessableEntityError(status, body, headers);
179		if (status === 429) return new RateLimitError(status, body, headers);
180		if (status >= 500) return new InternalServerError(status, body, headers);
181		return new APIError(status, body, headers);
182	}
183};
184/** HTTP 400: the request is invalid. */
185var BadRequestError = class extends APIError {};
186/** HTTP 401: authentication failed. */
187var AuthenticationError = class extends APIError {};
188/** HTTP 403: access is denied. */
189var PermissionDeniedError = class extends APIError {};
190/** HTTP 404: the resource was not found. */
191var NotFoundError = class extends APIError {};
192/** HTTP 422: request validation failed. */
193var UnprocessableEntityError = class extends APIError {};
194/** HTTP 429: the rate limit was exceeded. */
195var RateLimitError = class extends APIError {
196	/** Server retry delay in milliseconds, or `undefined` when absent or invalid. */
197	retryAfterMs = parseRetryAfter(this.headers);
198};
199/** HTTP 5xx: the server failed to handle the request. */
200var InternalServerError = class extends APIError {};
201/** The request or response-body delivery failed (DNS, TLS, connection closed, etc.). */
202var APIConnectionError = class extends TypeSafeError {
203	constructor(message = "Connection error.", options) {
204		super(message, options);
205	}
206};
207/** The full response did not arrive within the timeout. A kind of `APIConnectionError`. */
208var APITimeoutError = class extends APIConnectionError {
209	/** Configured timeout in milliseconds. */
210	timeoutMs;
211	constructor(timeoutMs, options) {
212		super(`Request timed out after ${timeoutMs}ms.`, options);
213		this.timeoutMs = timeoutMs;
214	}
215};
216/** The caller cancelled the request through an `AbortSignal`. */
217var APIUserAbortError = class extends TypeSafeError {
218	constructor(message = "Request was aborted.", options) {
219		super(message, options);
220	}
221};
222//#endregion
223//#region src/assets.ts
224/**
225* The file signatures that PNG (PNG spec §5.2) and JPEG (ITU T.81 SOI marker) files start
226* with, and the content type each identifies.
227*/
228const CONTENT_TYPES = [["image/png", [
229	137,
230	80,
231	78,
232	71,
233	13,
234	10,
235	26,
236	10
237]], ["image/jpeg", [
238	255,
239	216,
240	255
241]]];
242/** Matches `String(image)`: the reference an image is sent under. */
243const REFERENCE = /<image:[0-9a-f]{32}>/g;
244/** Marks `Image` objects, including those created by another copy of the SDK. */
245const IMAGE = Symbol.for("@typesafe-ai/sdk/image");
246/** Marks `TextWithAssets` objects, including those created by another copy of the SDK. */
247const TEXT_WITH_ASSETS = Symbol.for("@typesafe-ai/sdk/text-with-assets");
248/** 32 random lowercase hex digits. */
249const randomHex = () => Array.from(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, "0")).join("");
250const isImage = (value) => IMAGE in value;
251const isTextWithAssets = (value) => TEXT_WITH_ASSETS in value;
252/** `value`'s `Symbol.toStringTag`, such as `Promise`, or its `typeof` when it isn't an object. */
253const typeName = (value) => {
254	if (value === null) return "null";
255	if (typeof value !== "object") return typeof value;
256	return Object.prototype.toString.call(value).slice(8, -1);
257};
258/** A `Uint8Array` over the bytes `data` holds or views, without copying them. */
259const toBytes = (data) => {
260	if (!ArrayBuffer.isView(data) && Object.prototype.toString.call(data) !== "[object ArrayBuffer]") throw new TypeSafeError(`Image data must be file bytes or a Blob; got ${typeName(data)}.`);
261	return ArrayBuffer.isView(data) ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength) : new Uint8Array(data);
262};
263/** The content type whose signature `bytes` start with, or `application/octet-stream`. */
264const contentTypeOf = (bytes) => {
265	for (const [contentType, signature] of CONTENT_TYPES) if (signature.every((byte, i) => bytes[i] === byte)) return contentType;
266	return "application/octet-stream";
267};
268/** A PNG or JPEG image asset, created by `image` or `Image.fromBase64`. */
269var Image = class Image {
270	type = "image";
271	/** The image file bytes, or a `Blob` read when the request is sent. */
272	data;
273	#reference = `<image:${randomHex()}>`;
274	/** @throws {TypeSafeError} `data` is empty or isn't file bytes or a `Blob`. */
275	constructor(data) {
276		this.data = data instanceof Blob ? data : toBytes(data);
277		if ((this.data instanceof Blob ? this.data.size : this.data.byteLength) === 0) throw new TypeSafeError("Image data is empty.");
278	}
279	/**
280	* Create an image from base64-encoded file bytes, decoding them now.
281	*
282	* @param text - The image file bytes, base64-encoded, without a `data:` URL prefix.
283	* @throws {TypeSafeError} `text` isn't valid base64 or decodes to no bytes.
284	*
285	* @example
286	* ```ts
287	* const photo = Image.fromBase64(upload.photoBase64);
288	* ```
289	*/
290	static fromBase64(text) {
291		let binary;
292		try {
293			binary = atob(text);
294		} catch (err) {
295			throw new TypeSafeError("Image data must contain valid base64 text.", { cause: err });
296		}
297		return new Image(Uint8Array.from(binary, (char) => char.charCodeAt(0)));
298	}
299	/** The unique reference this image is sent under, for referencing it inside text. */
300	toString() {
301		return this.#reference;
302	}
303	/** The reference, written by `JSON.stringify` wherever the image appears in a request. */
304	toJSON() {
305		return this.#reference;
306	}
307};
308Object.defineProperty(Image.prototype, IMAGE, { value: true });
309/** Text from a `withAssets` tagged template, with the assets interpolated into it. */
310var TextWithAssets = class {
311	/** The text, with each asset replaced by its reference. */
312	text;
313	/** The assets interpolated into the text, including those in nested `withAssets` text. */
314	assets;
315	constructor(text, assets) {
316		this.text = text;
317		this.assets = assets;
318	}
319	toString() {
320		return this.text;
321	}
322	/** The text, written by `JSON.stringify` wherever this value appears in a request. */
323	toJSON() {
324		return this.text;
325	}
326};
327Object.defineProperty(TextWithAssets.prototype, TEXT_WITH_ASSETS, { value: true });
328/**
329* Create an image asset for `systemOne`.
330*
331* Place the image in `state` or question content, or interpolate it into a `withAssets`
332* tagged template; either way it is sent under its own reference, `String(image)`. To
333* reference it by a name of your choice, pass it in `assets` instead.
334*
335* The image must be PNG or JPEG. The API detects the format from the file bytes and rejects
336* other formats with a `BadRequestError`. `Blob` data is read when the request is sent, and its
337* `type` is ignored. For base64 text, use `Image.fromBase64`.
338*
339* @param data - Image file bytes, or a `Blob` such as a `File`.
340* @throws {TypeSafeError} `data` is empty or isn't file bytes or a `Blob`.
341*
342* @example
343* ```ts
344* // Node: `openAsBlob` reads a file as a Blob and is exported by "node:fs".
345* const { answers } = await client.systemOne({
346*   state: image(await openAsBlob("product.png")),
347*   questions: { damaged: noul("Is the product damaged?") },
348* });
349* ```
350*/
351const image = (data) => new Image(data);
352/** `text` with the assets in `values` whose references it contains, in order of appearance. */
353const textWithAssets = (text, values) => {
354	const interpolated = /* @__PURE__ */ new Map();
355	collectAssets(values, interpolated, /* @__PURE__ */ new Set());
356	const assets = /* @__PURE__ */ new Map();
357	for (const [reference] of text.matchAll(REFERENCE)) {
358		const asset = interpolated.get(reference);
359		if (asset !== void 0) assets.set(reference, asset);
360	}
361	return new TextWithAssets(text, [...assets.values()]);
362};
363/**
364* Tag a template literal so the assets interpolated into it are sent with the text.
365*
366* Each asset is replaced by its reference; other values are converted to strings, as in an
367* untagged template literal. To write a list of assets with a separator, use
368* `withAssets.join`.
369*
370* @example
371* ```ts
372* const { answers } = await client.systemOne({
373*   state: withAssets`Compare ${photo} with the listing.`,
374*   questions: { same: noul(withAssets`Is ${photo} the product in ${listing}?`) },
375* });
376* ```
377*/
378const withAssets = Object.assign((strings, ...values) => textWithAssets(strings.reduce((joined, piece, i) => joined + String(values[i - 1]) + piece), values), { join: (values, separator) => textWithAssets(values.join(separator), values) });
379/** Add the assets in `value`, including those in `withAssets` text, to `found` by reference. */
380const collectAssets = (value, found, visited) => {
381	if (typeof value !== "object" || value === null || visited.has(value)) return;
382	visited.add(value);
383	if (isImage(value)) found.set(String(value), value);
384	else if (isTextWithAssets(value)) for (const asset of value.assets) found.set(String(asset), asset);
385	else for (const item of Object.values(value)) collectAssets(item, found, visited);
386};
387/**
388* Serialize `payload` to JSON, writing each asset as its name in `assets`, or else as its
389* reference, and collect the assets the request sends.
390*
391* The assets are those in `assets`, then each asset whose reference appears in the JSON, in
392* order of appearance: assets placed in content, in `withAssets` text, or in `assets`.
393*
394* @throws {TypeSafeError} The JSON holds the reference of an asset not attached to the request,
395*   or doesn't contain the name of an asset in `assets`.
396*/
397const serializeRequest = (payload, assets = {}) => {
398	const names = new Map(Object.entries(assets).map(([name, asset]) => [asset, name]));
399	const known = new Map(Object.values(assets).map((asset) => [String(asset), asset]));
400	const json = JSON.stringify(payload, function(key, value) {
401		if (typeof value === "number" && !Number.isFinite(value)) return String(value);
402		const original = this[key];
403		if (typeof original !== "object" || original === null) return value;
404		if (isImage(original)) {
405			const name = names.get(original);
406			if (name !== void 0) return name;
407			known.set(String(original), original);
408		} else if (isTextWithAssets(original)) {
409			let text = original.text;
410			for (const asset of original.assets) {
411				const name = names.get(asset);
412				if (name === void 0) known.set(String(asset), asset);
413				else text = text.replaceAll(String(asset), name);
414			}
415			return text;
416		}
417		return value;
418	});
419	const unreferenced = Object.keys(assets).filter((name) => !json.includes(JSON.stringify(name).slice(1, -1)));
420	if (unreferenced.length > 0) throw new TypeSafeError(`Assets not referenced in the request: ${unreferenced.join(", ")}. Write each name in \`assets\` into \`state\`, question instructions, or criteria.`);
421	const sent = new Map(Object.entries(assets));
422	const missing = /* @__PURE__ */ new Set();
423	for (const [reference] of json.matchAll(REFERENCE)) {
424		if (sent.has(reference)) continue;
425		const asset = known.get(reference);
426		if (asset === void 0) missing.add(reference);
427		else sent.set(reference, asset);
428	}
429	if (missing.size > 0) throw new TypeSafeError(`Image references without an attached image: ${[...missing].join(", ")}. Tag template literals that interpolate images with \`withAssets\`.`);
430	return {
431		json,
432		assets: sent.size === 0 ? void 0 : Object.fromEntries(sent)
433	};
434};
435/** A `multipart/form-data` request body (RFC 7578) whose first part is a JSON payload. */
436var MultipartBody = class {
437	/** The JSON payload, sent as the `request` part. */
438	payload;
439	/** The `Content-Type` header value, including the boundary. */
440	contentType;
441	/** The encoded body. */
442	content;
443	constructor(payload, parts) {
444		const boundary = randomHex();
445		const chunks = [];
446		for (const { name, contentType, content, filename } of [{
447			name: "request",
448			contentType: "application/json",
449			content: JSON.stringify(payload)
450		}, ...parts]) {
451			const disposition = filename === void 0 ? `name="${name}"` : `name="${name}"; filename="${filename}"`;
452			chunks.push(`--${boundary}\r\nContent-Disposition: form-data; ${disposition}\r\n`, `Content-Type: ${contentType}\r\n\r\n`, content, "\r\n");
453		}
454		chunks.push(`--${boundary}--\r\n`);
455		this.payload = payload;
456		this.contentType = `multipart/form-data; boundary=${boundary}`;
457		this.content = new Blob(chunks);
458	}
459};
460/** The image's file bytes, reading `Blob` data. */
461const readImage = async (alias, { data }) => {
462	if (!(data instanceof Blob)) return data;
463	try {
464		return new Uint8Array(await data.arrayBuffer());
465	} catch (err) {
466		throw new TypeSafeError(`Asset "${alias}" could not be read: ${err.message}`, { cause: err });
467	}
468};
469/** `bytes`, copied when backed by a `SharedArrayBuffer`, which `Blob` doesn't accept. */
470const unshared = (bytes) => bytes.buffer instanceof ArrayBuffer ? bytes : bytes.slice();
471/**
472* `assets`, with each asset's file bytes copied, so writes to the caller's buffers after this
473* call don't change what is sent. `Blob` data can't change, and isn't copied.
474*/
475const copyAssetBytes = (assets) => Object.fromEntries(Object.entries(assets).map(([alias, asset]) => [alias, asset.data instanceof Uint8Array ? new Image(asset.data.slice()) : asset]));
476/**
477* A `multipart/form-data` body whose first part, `request`, is `payload` with `assets` added,
478* followed by each asset's file bytes in a part its entry names. `Blob` data is read
479* concurrently.
480*
481* @throws {TypeSafeError} A `Blob` can't be read.
482*/
483const encodeAssets = async (payload, assets) => {
484	const read = await Promise.all(Object.entries(assets).map(async ([alias, asset]) => [
485		alias,
486		asset,
487		await readImage(alias, asset)
488	]));
489	const parts = [];
490	const entries = [];
491	for (const [alias, { type }, data] of read) {
492		const name = `asset-${parts.length}`;
493		parts.push({
494			name,
495			contentType: contentTypeOf(data),
496			content: unshared(data),
497			filename: name
498		});
499		entries.push([alias, {
500			type,
501			part: name
502		}]);
503	}
504	return new MultipartBody({
505		...payload,
506		assets: Object.fromEntries(entries)
507	}, parts);
508};
509const g$1 = globalThis;
510/** `node:zlib`, read without an import so the SDK still loads where Node modules don't exist. */
511const zlib = () => {
512	try {
513		return g$1.process?.getBuiltinModule?.("node:zlib");
514	} catch {
515		return;
516	}
517};
518const hasZstd = () => typeof zlib()?.zstdCompress === "function";
519/**
520* Resolve the `compression` option to the `Content-Encoding` request bodies are sent with:
521* zstd when the runtime has it, otherwise `false`.
522*
523* @throws {TypeSafeError} The value isn't a supported option, or the runtime lacks it.
524*/
525const resolveCompression = (compression) => {
526	if (compression === void 0) return hasZstd() ? "zstd" : false;
527	if (compression === false) return false;
528	if (compression === "zstd") {
529		if (!hasZstd()) throw new TypeSafeError("zstd compression requires Node.js 22.15 or newer. Pass `compression: false` instead.");
530		return compression;
531	}
532	throw new TypeSafeError(`\`compression\` must be "zstd" or false, got ${JSON.stringify(compression)}.`);
533};
534const zstd = async (body) => {
535	const data = new Uint8Array(await body.arrayBuffer());
536	const compressed = await new Promise((resolve, reject) => {
537		zlib()?.zstdCompress?.(data, (err, result) => err ? reject(err) : resolve(result));
538	});
539	return new Uint8Array(compressed);
540};
541/** The size of a request body in bytes, with text measured as UTF-8. */
542const byteLength = (body) => typeof body === "string" ? new TextEncoder().encode(body).byteLength : body.size;
543/** Compress a request body with zstd. */
544const compressBody = (body) => zstd(typeof body === "string" ? new Blob([body]) : body);
545//#endregion
546//#region src/env.ts
547/** Environment variable names for client configuration. Explicit options take precedence. */
548const ENV = {
549	/** Required API key; used when `apiKey` is omitted. */
550	apiKey: "TYPESAFE_API_KEY",
551	/** API root; defaults to `https://api.typesafe.ai`. */
552	baseURL: "TYPESAFE_BASE_URL",
553	/** Default model name; defaults to `jev-latest`. */
554	defaultModel: "TYPESAFE_DEFAULT_MODEL",
555	/** Log level; defaults to `warn`. */
556	logLevel: "TYPESAFE_LOG_LEVEL"
557};
558/** Read a trimmed environment value, returning `undefined` for missing or blank values. */
559const readEnv = (name) => {
560	if (typeof process === "undefined" || !process.env) return void 0;
561	return process.env[name]?.trim() || void 0;
562};
563/** Return the explicit value, falling back to the environment. */
564const fromCodeOrEnv = (fromCode, envVar) => fromCode ?? readEnv(envVar);
565//#endregion
566//#region src/logging.ts
567/** Supported log levels, from most to least verbose. */
568const LOG_LEVELS = [
569	"debug",
570	"info",
571	"warn",
572	"error",
573	"off"
574];
575const DEFAULT_LOG_LEVEL = "warn";
576const isLogLevel = (value) => LOG_LEVELS.includes(value);
577/** Validate a configured log level, throwing `TypeSafeError` for unknown values. */
578const parseLogLevel = (value, source) => {
579	if (isLogLevel(value)) return value;
580	throw new TypeSafeError(`Invalid log level "${value}" from ${source}. Expected one of: ${LOG_LEVELS.join(", ")}.`);
581};
582const PREFIX = "[typesafe-sdk]";
583/** Default console logger with the `[typesafe-sdk]` prefix. */
584const consoleLogger = {
585	debug: (message, ...args) => console.debug(`${PREFIX} ${message}`, ...args),
586	info: (message, ...args) => console.info(`${PREFIX} ${message}`, ...args),
587	warn: (message, ...args) => console.warn(`${PREFIX} ${message}`, ...args),
588	error: (message, ...args) => console.error(`${PREFIX} ${message}`, ...args)
589};
590const RANK = {
591	debug: 0,
592	info: 1,
593	warn: 2,
594	error: 3,
595	off: 4
596};
597const drop = () => {};
598/** Filter logger calls to the configured level and above. */
599const withLevel = (sink, level) => {
600	const enabled = (at) => RANK[at] >= RANK[level];
601	return {
602		debug: enabled("debug") ? (message, ...args) => sink.debug(message, ...args) : drop,
603		info: enabled("info") ? (message, ...args) => sink.info(message, ...args) : drop,
604		warn: enabled("warn") ? (message, ...args) => sink.warn(message, ...args) : drop,
605		error: enabled("error") ? (message, ...args) => sink.error(message, ...args) : drop
606	};
607};
608/** Credential headers that retain a key suffix for identification. */
609const KEY_HEADERS = /* @__PURE__ */ new Set([
610	"authorization",
611	"proxy-authorization",
612	"x-api-key"
613]);
614/** Headers whose values are redacted in full. */
615const OPAQUE_HEADERS = /* @__PURE__ */ new Set(["cookie", "set-cookie"]);
616/** Mask a key, preserving its scheme and the last four characters of secrets longer than eight. */
617const redactKey = (value) => {
618	const [scheme, secret] = value.includes(" ") ? value.split(/\s+/, 2) : [void 0, value];
619	const tail = secret && secret.length > 8 ? secret.slice(-4) : "";
620	return `${scheme ? `${scheme} ` : ""}***${tail}`;
621};
622const redact = (name, value) => {
623	const lower = name.toLowerCase();
624	if (KEY_HEADERS.has(lower)) return redactKey(value);
625	if (OPAQUE_HEADERS.has(lower)) return "***";
626	return value;
627};
628/** Copy headers with known credential values redacted. */
629const redactHeaders = (headers) => Object.fromEntries(Object.entries(headers).map(([name, value]) => [name, redact(name, value)]));
630//#endregion
631//#region src/questions.ts
632/**
633* Create a yes/no question with optional descriptions for either outcome.
634*
635* @param instructions - The question as text, a JSON object or array; `null` or omitted
636* requires `criteria` to describe at least one outcome.
637* @param criteria - Descriptions of the yes and no outcomes.
638*/
639const noul = (instructions = null, criteria) => ({
640	type: "noul",
641	instructions,
642	criteria
643});
644/**
645* Create a score question using an ordered rubric.
646*
647* @param instructions - The question as text, a JSON object or array, or `null`.
648* @param criteria - At least two descriptions indexed by score from zero; entries may be `null`.
649*   A list built at runtime, such as a `string[]`, is accepted, and `systemOne` rejects it when
650*   it has fewer than two entries.
651*/
652const score = (instructions, criteria) => {
653	const rubric = criteria;
654	if (!Array.isArray(criteria)) throw new TypeSafeError("Score criteria must be a list of descriptions indexed by score from zero, not a map.");
655	return {
656		type: "score",
657		instructions,
658		criteria: rubric
659	};
660};
661/**
662* Create a question that selects between named alternatives.
663*
664* @param instructions - The question as text, a JSON object or array, or `null`.
665* @param criteria - Labels mapped to descriptions, or `null` for undescribed labels.
666*/
667const choice = (instructions, criteria) => {
668	if (Array.isArray(criteria)) throw new TypeSafeError("Choice criteria must be a map of labels to descriptions, not a list.");
669	return {
670		type: "choice",
671		instructions,
672		criteria
673	};
674};
675/**
676* Create a question that locates what its instructions describe in the request's image.
677* Use the `jev-preview` model for `box` questions.
678*
679* @param instructions - What to locate, as text, an asset, a JSON object or array; defaults to `null`.
680*
681* @example
682* ```ts
683* const { answers } = await client.systemOne({
684*   state: image(await openAsBlob("photo.jpg")),
685*   questions: { dog: box("The dog") },
686*   model: "jev-preview",
687* });
688* const { top, bottom, left, right } = answers.dog.box;
689* ```
690*/
691const box = (instructions = null) => ({
692	type: "box",
693	instructions
694});
695const isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
696const validateChoice = (name, { criteria }) => {
697	if (!isObject(criteria)) throw new TypeSafeError(`Choice question "${name}" has criteria that are not a map; choice criteria must be a map of labels to descriptions.`);
698	if (Object.keys(criteria).length === 0) throw new TypeSafeError(`Choice question "${name}" has no criteria; at least one choice is required.`);
699};
700const validateNoul = (name, { instructions, criteria }) => {
701	if (criteria != null && !isObject(criteria)) throw new TypeSafeError(`Noul question "${name}" criteria must be an object.`);
702	if (instructions == null && !Object.values(criteria ?? {}).some((value) => value != null)) throw new TypeSafeError(`Noul question "${name}" has neither instructions nor criteria; at least one is required.`);
703};
704/**
705* Reject empty question sets, score questions without a list of at least two criteria, choice
706* questions without a nonempty map of criteria, and noul questions with non-object criteria or
707* with neither instructions nor a described outcome.
708*/
709const validateQuestions = (questions) => {
710	if (Object.keys(questions).length === 0) throw new TypeSafeError("At least one question is required.");
711	for (const [name, question] of Object.entries(questions)) {
712		if (question.type === "choice") validateChoice(name, question);
713		if (question.type === "noul") validateNoul(name, question);
714		if (question.type !== "score") continue;
715		if (!Array.isArray(question.criteria)) throw new TypeSafeError(`Score question "${name}" has criteria that are not a list; score criteria must be a list of descriptions indexed by score from zero.`);
716		if (question.criteria.length < 2) throw new TypeSafeError(`Score question "${name}" has ${question.criteria.length} criteria; at least two scores are required.`);
717	}
718};
719//#endregion
720//#region src/resources/models.ts
721/** Access to the Models API resource. */
722var Models = class {
723	#transport;
724	constructor(transport) {
725		this.#transport = transport;
726	}
727	/** List the models available to the account. */
728	list(options = {}) {
729		return this.#transport.request("GET", "/v1/models", options).map(unwrapModels);
730	}
731};
732const unwrapModels = (wire) => {
733	if (Array.isArray(wire?.models)) return wire.models;
734	throw new TypeSafeError("Unexpected response shape from GET /v1/models; expected { models: [...] }.");
735};
736//#endregion
737//#region src/runtime.ts
738const g = globalThis;
739/** Whether browser page globals are present. */
740const isBrowser = () => typeof g.window !== "undefined" && typeof g.window.document !== "undefined" && typeof g.navigator !== "undefined";
741/** Runtime name, version, and platform for the `X-TypeSafe-Runtime` header. */
742const describeRuntime = () => {
743	const platform = g.process?.platform && g.process?.arch ? ` (${g.process.platform}; ${g.process.arch})` : "";
744	if (g.Bun?.version) return `bun/${g.Bun.version}${platform}`;
745	if (g.Deno?.version?.deno) return `deno/${g.Deno.version.deno}${platform}`;
746	if (g.EdgeRuntime !== void 0) return "vercel-edge";
747	if (g.navigator?.userAgent === "Cloudflare-Workers") return "cloudflare-workers";
748	if (g.process?.versions?.node) return `node/${g.process.versions.node}${platform}`;
749	if (isBrowser()) return "browser";
750	return "unknown";
751};
752//#endregion
753//#region src/version.ts
754const VERSION = "0.7.0";
755const missingApiKey = () => {
756	throw new TypeSafeError(`No API key was provided. Pass \`apiKey\` to the TypeSafeClient constructor or set the ${ENV.apiKey} environment variable.`);
757};
758const missingFetch = () => {
759	throw new TypeSafeError("No global `fetch` is available in this runtime. Pass a `fetch` implementation to the TypeSafeClient constructor.");
760};
761const refuseBrowser = () => {
762	throw new TypeSafeError("TypeSafeClient is running in a browser, which would expose your API key to anyone using the page. Call the API from a server instead, or pass `dangerouslyAllowBrowser: true` if you understand the risk.");
763};
764/** Call global `fetch` with its required receiver in browsers. */
765const defaultFetch = (input, init) => globalThis.fetch(input, init);
766const assertNonNegativeInteger = (name, value) => {
767	if (!Number.isInteger(value) || value < 0) throw new TypeSafeError(`\`${name}\` must be a non-negative integer, got ${String(value)}.`);
768	return value;
769};
770const assertPositiveMs = (name, value) => {
771	if (!Number.isFinite(value) || value <= 0) throw new TypeSafeError(`\`${name}\` must be a positive number of milliseconds, got ${String(value)}.`);
772	return value;
773};
774const assertNonNegativeMs = (name, value) => {
775	if (!Number.isFinite(value) || value < 0) throw new TypeSafeError(`\`${name}\` must be a non-negative number of milliseconds, got ${String(value)}.`);
776	return value;
777};
778const assertFraction = (name, value) => {
779	if (!Number.isFinite(value) || value < 0 || value > 1) throw new TypeSafeError(`\`${name}\` must be between 0 and 1, got ${String(value)}.`);
780	return value;
781};
782const assertStatusSet = (name, statuses) => {
783	for (const status of statuses) if (!Number.isInteger(status) || status < 100 || status > 999) throw new TypeSafeError(`\`${name}\` must contain HTTP status codes, got ${String(status)}.`);
784	return statuses;
785};
786/** Merge and validate retry overrides, copying the status set to isolate later mutations. */
787const resolveRetryPolicy = (base, overrides) => {
788	const o = overrides ?? {};
789	return {
790		maxRetries: o.maxRetries === void 0 ? base.maxRetries : assertNonNegativeInteger("retry.maxRetries", o.maxRetries),
791		backoffInitialMs: o.backoffInitialMs === void 0 ? base.backoffInitialMs : assertNonNegativeMs("retry.backoffInitialMs", o.backoffInitialMs),
792		backoffMaxMs: o.backoffMaxMs === void 0 ? base.backoffMaxMs : assertNonNegativeMs("retry.backoffMaxMs", o.backoffMaxMs),
793		backoffJitter: o.backoffJitter === void 0 ? base.backoffJitter : assertFraction("retry.backoffJitter", o.backoffJitter),
794		httpStatuses: new Set(o.httpStatuses === void 0 ? base.httpStatuses : assertStatusSet("retry.httpStatuses", o.httpStatuses)),
795		respectRetryAfter: o.respectRetryAfter ?? base.respectRetryAfter,
796		maxRetryAfterMs: o.maxRetryAfterMs === void 0 ? base.maxRetryAfterMs : assertNonNegativeMs("retry.maxRetryAfterMs", o.maxRetryAfterMs),
797		apiConnectionError: o.apiConnectionError ?? base.apiConnectionError,
798		apiTimeoutError: o.apiTimeoutError ?? base.apiTimeoutError
799	};
800};
801/** Whether the policy retries a connection error or timeout. */
802const isRetryableError = (err, policy) => {
803	if (err instanceof APITimeoutError) return policy.apiTimeoutError;
804	if (err instanceof APIConnectionError) return policy.apiConnectionError;
805	return false;
806};
807/** Resolve and validate the log level from configuration or the environment. */
808const resolveLogLevel = (fromCode) => {
809	if (fromCode !== void 0) return parseLogLevel(fromCode, "the `logLevel` option");
810	const fromEnv = readEnv(ENV.logLevel);
811	if (fromEnv !== void 0) return parseLogLevel(fromEnv, ENV.logLevel);
812	return DEFAULT_LOG_LEVEL;
813};
814const stripTrailingSlashes = (url) => url.replace(/\/+$/, "");
815/** Last value wins regardless of casing; undefined removes a protected header. */
816const mergeHeaders = (...sources) => {
817	const entries = /* @__PURE__ */ new Map();
818	for (const source of sources) for (const [name, value] of Object.entries(source)) if (value === void 0) entries.delete(name.toLowerCase());
819	else entries.set(name.toLowerCase(), [name, value]);
820	return Object.fromEntries(entries.values());
821};
822/** Drain a clone so the original response retains its metadata and a readable, buffered body. */
823const bufferResponse = async (response, signal) => {
824	const reader = response.clone().body?.getReader();
825	if (!reader) return;
826	const original = response.body?.getReader();
827	const cancel = () => {
828		reader.cancel(signal.reason).catch(() => {});
829		original?.cancel(signal.reason).catch(() => {});
830	};
831	signal.addEventListener("abort", cancel, { once: true });
832	try {
833		if (signal.aborted) cancel();
834		signal.throwIfAborted();
835		while (!(await reader.read()).done) signal.throwIfAborted();
836		signal.throwIfAborted();
837	} finally {
838		signal.removeEventListener("abort", cancel);
839		reader.releaseLock();
840		original?.releaseLock();
841	}
842};
843/**
844* Call `start` and settle with its result, or reject with the signal's reason when the signal
845* aborts first. `start` isn't called if the signal has already aborted.
846*/
847const untilAborted = (start, signal) => {
848	if (signal === void 0) return start();
849	return new Promise((resolve, reject) => {
850		if (signal.aborted) return reject(signal.reason);
851		const onAbort = () => reject(signal.reason);
852		signal.addEventListener("abort", onAbort, { once: true });
853		start().then((value) => {
854			signal.removeEventListener("abort", onAbort);
855			resolve(value);
856		}, (err) => {
857			signal.removeEventListener("abort", onAbort);
858			reject(err);
859		});
860	});
861};
862/** Runtime description cached for the process lifetime. */
863const RUNTIME = describeRuntime();
864/** An `APIPromise` rejected with `err`, for failures found before a request is sent. */
865const rejectedAPIPromise = (err) => {
866	const response = Promise.reject(err);
867	return new APIPromise(response, () => response);
868};
869/** Client for the TypeSafe AI API. */
870var TypeSafeClient = class {
871	/** API key excluded from serialization and public properties. */
872	#apiKey;
873	/** API root with trailing slashes removed. */
874	baseURL;
875	/** Model used when a request omits `model`. */
876	defaultModel;
877	/** Configured log verbosity. */
878	logLevel;
879	/** The configured logger, filtered to `logLevel`. */
880	logger;
881	/** Retry settings with constructor overrides applied. */
882	retry;
883	/** Timeout per attempt in milliseconds. */
884	timeout;
885	/** Additional headers sent with each request. */
886	defaultHeaders;
887	/** Request body compression, or `false` when bodies are sent uncompressed. */
888	compression;
889	/** HTTP fetch implementation. */
890	fetch;
891	/** The models available to the account. */
892	models;
893	#requestCount = 0;
894	/**
895	* Create a client for the TypeSafe AI API.
896	*
897	* Explicit options take precedence over environment variables, then SDK defaults.
898	* Empty or whitespace-only environment values are ignored.
899	*
900	* @throws {TypeSafeError} The API key is missing, configuration is invalid, the runtime is
901	*   unsupported, or the runtime lacks the requested compression.
902	*/
903	constructor(config = {}) {
904		if (isBrowser() && !config.dangerouslyAllowBrowser) refuseBrowser();
905		this.#apiKey = fromCodeOrEnv(config.apiKey, ENV.apiKey) ?? missingApiKey();
906		this.baseURL = stripTrailingSlashes(fromCodeOrEnv(config.baseURL, ENV.baseURL) ?? "https://api.typesafe.ai");
907		this.defaultModel = fromCodeOrEnv(config.defaultModel, ENV.defaultModel) ?? "jev-latest";
908		this.logLevel = resolveLogLevel(config.logLevel);
909		this.logger = withLevel(config.logger ?? consoleLogger, this.logLevel);
910		this.retry = resolveRetryPolicy(DEFAULT_RETRY_POLICY, config.retry);
911		this.timeout = assertPositiveMs("timeout", config.timeout ?? 1e4);
912		this.defaultHeaders = { ...config.defaultHeaders };
913		this.compression = resolveCompression(config.compression);
914		if (config.fetch === void 0 && typeof globalThis.fetch !== "function") missingFetch();
915		this.fetch = config.fetch ?? defaultFetch;
916		const transport = {
917			request: (method, path, options) => this.#request(method, path, options),
918			defaultModel: this.defaultModel
919		};
920		this.models = new Models(transport);
921	}
922	/**
923	* Answer named questions about text, structured state, or assets.
924	*
925	* @param request - State, questions, an optional model override, and optional assets.
926	*   Assets in `state`, question content, or `withAssets` text are sent under their references.
927	* @param options - Per-call timeout, retry, headers, and cancellation settings.
928	* @returns Answers typed by question name and criteria, with model and token usage. Every
929	*   failure below rejects the returned promise; the call itself doesn't throw.
930	* @throws {TypeSafeError} State is `null` or omitted, questions are empty, score criteria are not
931	*   a list of at least two entries, choice criteria are not a nonempty map, a noul question has
932	*   neither instructions nor a described outcome, a string holds the reference of an asset not
933	*   attached to the request, a name in `assets` doesn't appear in the request, or a `Blob`
934	*   asset can't be read.
935	* @throws {APIError} The server returns a non-2xx response after retries.
936	* @throws {APIConnectionError} The request cannot connect or times out after retries.
937	* @throws {APIUserAbortError} The caller aborts the request.
938	*
939	* @example
940	* ```ts
941	* const { answers } = await client.systemOne({
942	*   state: "I was charged twice. Please help.",
943	*   questions: { billing: noul("Is this about billing?") },
944	* });
945	* console.log(answers.billing.noul);
946	* ```
947	*/
948	systemOne(request, options = {}) {
949		let body;
950		try {
951			if (request.state == null) throw new TypeSafeError("State is required.");
952			validateQuestions(request.questions);
953			const { assets, ...rest } = request;
954			const { json, assets: sent } = serializeRequest({
955				...rest,
956				model: request.model ?? this.defaultModel
957			}, assets);
958			const payload = JSON.parse(json);
959			const copied = sent === void 0 ? void 0 : copyAssetBytes(sent);
960			body = copied === void 0 ? payload : () => encodeAssets(payload, copied);
961		} catch (err) {
962			return rejectedAPIPromise(err);
963		}
964		return this.#request("POST", "/v1/systemone", {
965			...options,
966			body
967		});
968	}
969	/** Send a request and parse its response body. */
970	#request(method, path, options = {}) {
971		let resolved;
972		try {
973			resolved = {
974				method,
975				path,
976				body: options.body,
977				headers: mergeHeaders(this.defaultHeaders, options.headers ?? {}),
978				signal: options.signal,
979				timeout: options.timeout === void 0 ? this.timeout : assertPositiveMs("timeout", options.timeout),
980				retry: resolveRetryPolicy(this.retry, options.retry)
981			};
982		} catch (err) {
983			return rejectedAPIPromise(err);
984		}
985		const tag = `#${++this.#requestCount} ${method} ${path}`;
986		return new APIPromise(this.fetchWithRetries(tag, resolved), async (res) => {
987			const parsed = await parseBody(res);
988			this.logger.debug(`${tag} <- body`, parsed);
989			return parsed;
990		});
991	}
992	/** Retry eligible failures, logging attempt summaries at `info` and headers and bodies at `debug`. */
993	async fetchWithRetries(tag, req) {
994		const url = `${this.baseURL}${req.path}`;
995		let resolved = req.body;
996		if (typeof resolved === "function") try {
997			resolved = await untilAborted(resolved, req.signal);
998		} catch (err) {
999			if (!req.signal?.aborted) throw err;
1000			this.logger.info(`${tag} aborted by caller while reading assets`);
1001			throw new APIUserAbortError(void 0, { cause: err });
1002		}
1003		const multipart = resolved instanceof MultipartBody ? resolved : void 0;
1004		const payload = multipart === void 0 ? resolved : multipart.payload;
1005		const encoded = multipart?.content ?? (payload === void 0 ? void 0 : JSON.stringify(payload));
1006		const encoding = encoded === void 0 || byteLength(encoded) < 1024 ? false : this.compression;
1007		let body = encoded;
1008		if (encoded !== void 0 && encoding !== false) try {
1009			body = await untilAborted(() => compressBody(encoded), req.signal);
1010		} catch (err) {
1011			if (!req.signal?.aborted) throw err;
1012			this.logger.info(`${tag} aborted by caller while compressing the body`);
1013			throw new APIUserAbortError(void 0, { cause: err });
1014		}
1015		const headers = mergeHeaders(req.headers, {
1016			Authorization: `Bearer ${this.#apiKey}`,
1017			Accept: "application/json",
1018			"User-Agent": `typesafe-sdk/${VERSION}`,
1019			"X-TypeSafe-SDK": `typesafe-sdk/${VERSION}`,
1020			"X-TypeSafe-Runtime": RUNTIME,
1021			"Content-Type": multipart?.contentType ?? (body === void 0 ? void 0 : "application/json"),
1022			"Content-Encoding": encoding === false ? void 0 : encoding,
1023			"X-TypeSafe-Retry-Count": void 0
1024		});
1025		for (let attempt = 0;; attempt++) {
1026			const retriesLeft = req.retry.maxRetries - attempt;
1027			const attemptHeaders = attempt === 0 ? headers : {
1028				...headers,
1029				"X-TypeSafe-Retry-Count": String(attempt)
1030			};
1031			this.logger.debug(`${tag} -> ${url}`, {
1032				headers: redactHeaders(attemptHeaders),
1033				body: payload
1034			});
1035			const started = Date.now();
1036			let res;
1037			try {
1038				res = await this.attempt(tag, url, {
1039					method: req.method,
1040					headers: attemptHeaders,
1041					body
1042				}, req);
1043			} catch (err) {
1044				if (err instanceof APIUserAbortError || retriesLeft <= 0) throw err;
1045				if (!isRetryableError(err, req.retry)) throw err;
1046				await this.backOff(tag, attempt, retriesLeft, err.message, void 0, req);
1047				continue;
1048			}
1049			const requestId = requestIdFrom(res.headers);
1050			this.logger.info(`${tag} <- ${res.status} in ${Date.now() - started}ms${requestId ? ` (request ${requestId})` : ""}`);
1051			if (res.ok) return res;
1052			const errorBody = await parseBody(res);
1053			this.logger.debug(`${tag} <- error body`, errorBody);
1054			const error = APIError.fromResponse(res.status, errorBody, res.headers);
1055			if (retriesLeft <= 0 || !isRetryableStatus(res.status, req.retry)) throw error;
1056			await this.backOff(tag, attempt, retriesLeft, `${res.status}`, res.headers, req);
1057		}
1058	}
1059	/**
1060	* One HTTP round trip, including body delivery, with a timeout. The caller's signal and our
1061	* timer both abort the same controller; we check which fired to choose the error class.
1062	*/
1063	async attempt(tag, url, init, { signal, timeout }) {
1064		const controller = new AbortController();
1065		const abortFromCaller = () => controller.abort(signal?.reason);
1066		if (signal?.aborted) abortFromCaller();
1067		signal?.addEventListener("abort", abortFromCaller, { once: true });
1068		let timedOut = false;
1069		const timer = setTimeout(() => {
1070			timedOut = true;
1071			controller.abort();
1072		}, timeout);
1073		const started = Date.now();
1074		const elapsed = () => `${Date.now() - started}ms`;
1075		try {
1076			const response = await this.fetch(url, {
1077				...init,
1078				signal: controller.signal
1079			});
1080			await bufferResponse(response, controller.signal);
1081			return response;
1082		} catch (err) {
1083			if (signal?.aborted) {
1084				this.logger.info(`${tag} aborted by caller after ${elapsed()}`);
1085				throw new APIUserAbortError(void 0, { cause: err });
1086			}
1087			if (timedOut) {
1088				this.logger.info(`${tag} timed out after ${elapsed()}`);
1089				throw new APITimeoutError(timeout, { cause: err });
1090			}
1091			this.logger.info(`${tag} connection error after ${elapsed()}`, err);
1092			throw new APIConnectionError(err instanceof Error ? `Connection error: ${err.message}` : void 0, { cause: err });
1093		} finally {
1094			clearTimeout(timer);
1095			signal?.removeEventListener("abort", abortFromCaller);
1096		}
1097	}
1098	/** Wait before retrying; caller cancellation throws `APIUserAbortError`. */
1099	async backOff(tag, attempt, retriesLeft, reason, headers, { retry, signal }) {
1100		const delay = retryDelayMs(attempt, headers, retry);
1101		const nth = attempt + 1;
1102		const total = attempt + retriesLeft;
1103		this.logger.info(`${tag} retrying in ${delay}ms (retry ${nth}/${total}) after ${reason}`);
1104		try {
1105			await sleep(delay, signal);
1106		} catch (err) {
1107			this.logger.info(`${tag} aborted by caller while waiting to retry`);
1108			throw new APIUserAbortError(void 0, { cause: err });
1109		}
1110	}
1111};
1112const parseBody = async (res) => {
1113	const text = await res.text();
1114	if (text.length === 0) return void 0;
1115	if ((res.headers.get("content-type") ?? "").includes("application/json")) try {
1116		return JSON.parse(text);
1117	} catch {
1118		return text;
1119	}
1120	try {
1121		return JSON.parse(text);
1122	} catch {
1123		return text;
1124	}
1125};
1126//#endregion
1127export { APIConnectionError, APIError, APIPromise, APITimeoutError, APIUserAbortError, AuthenticationError, BadRequestError, ENV, Image, InternalServerError, LOG_LEVELS, NotFoundError, PermissionDeniedError, RateLimitError, TypeSafeClient, TypeSafeError, UnprocessableEntityError, VERSION, box, choice, image, noul, score, withAssets };
1128
1129//# sourceMappingURL=index.mjs.map
types/index.d.ts 50 lines
1export type SwitchboardTier = 'quick' | 'standard' | 'deep' | 'ultra' | 'copywriting';
2// A subagent route: a model tier, or a handover to Codex's agent.
3export type SwitchboardRoute = SwitchboardTier | 'codex';
4export type SwitchboardMessage = { from: string; text: string; at: number };
5// One agent loop of this session as the switchboard pane draws it; `parentId` absent under main.
6export type SwitchboardAgent = {
7  id: string;
8  parentId?: string;
9  description: string;
10  type: string;
11  route: SwitchboardRoute | null;
12  model: string;
13  status: 'running' | 'idle' | 'completed' | 'failed' | 'killed';
14  at: number;
15};
16// One message on the wire: `main`, an agent's id, or a peer's name at either end.
17export type SwitchboardWire = { from: string; to: string; text: string; at: number };// Who picked a route: TypeSafe's Jev (with its Choice confidence), the Haiku classifier, or a /triage pin.
18export type SwitchboardDecision<T extends string = SwitchboardTier> = {
19  route: T;
20  by: 'jev' | 'haiku' | 'pin';
21  confidence?: number;
22};
23// The main loop's last finished turn, as its turn.complete reported it.
24export type SwitchboardTurn = {
25  model: string;
26  durationMs: number;
27  input: number;
28  cached: number;
29  output: number;
30};
31
32declare module 'claude-code' {
33  interface PluginState {
34    switchboard: {
35      isTriageOn: boolean;
36      isCodexOn: boolean;
37      pinned: SwitchboardTier | null;
38      decision: SwitchboardDecision | null;
39      lastTurn: SwitchboardTurn | null;
40      inbox: SwitchboardMessage[];
41      unread: number;
42      subagents: Record<SwitchboardRoute, number>;
43      agentTiers: Record<string, SwitchboardTier | null>;
44      sessionModel: string | null;
45      agents: SwitchboardAgent[];
46      wire: SwitchboardWire[];
47    };
48  }
49}
50