SLOPSHOPPER

model-router

Routes each subagent to a Claude model and effort that fits its task, judged by Jev. For each routed Agent call it sends the task text and the agent's…

guardtoolnetworktimeragents
A shopper browsing a rack in a slop shop
README

model-router

The repository README says what this mod does and how to install it. This file says what the mod can reach, what leaves the machine, the routing, the effort ladder and the troubleshooting steps.

To install, run this line in a Claude Code session:

/plugin install model-router --marketplace Akurganow/model-router

What this mod can reach

Anthropic's guide to trusting a mod asks six questions. The answers for this mod:

  • Acts on your machine as you? No. It reads no files, writes no files of its own and starts no program.
  • Reads your secrets? Only its own TypeSafe and OpenRouter keys. Claude Code hands it the plugin's sensitive api_key and openrouter_api_key options from secure storage. When an option is empty, the mod reads the key from TYPESAFE_API_KEY or OPENROUTER_API_KEY. It reads a key only for a provider the provider option allows. It reads no other environment variable and no file.
  • Sees your session? The arguments of each Agent tool call. It sends the task, the description and the description of the agent. It reads model, name and effort to decide whether to route and whether to keep the caller's effort. It also sees the name, source and description of each agent Claude Code offers, to tell a built-in from a user or plugin agent and to describe it. It asks Claude Code's permission verdict for the call through $.tool.check, which opens no dialog and runs nothing. The verdict never leaves the machine. Between calls it keeps only the latest source and description of each agent name, in memory.
  • Changes your session? Two arguments of that Agent tool call: model and effort. It sets effort only when the call names none, or, under the extended scope, replaces the one the agent's definition sets. It registers one tool the model can call, mcp__model-router__config. The tool reads the settings and opens the mod's own dialog. It writes the provider and scope options only after you pick a value there. The two commands write the same options, and only from your own prompt. The model never passes a value. Change the options has the details.
  • Acts without asking you? No. It approves nothing, and it denies only its own tool when your permission rules deny that tool. Your permission rules and prompts decide every call. Every setting change waits for your choice in the mod's dialog or your own command.
  • Spends your usage? No model calls on your plan. Up to four requests per routed call go to TypeSafe or OpenRouter, each on its own key, as What leaves the machine counts them. An OpenRouter key may also pay for your chat models, and the scoring requests spend the same credit.

claude plugin validate plugins/model-router lists the same from the code. This is the whole surface:

KindNameWhy the mod has it
hookagent.offerRecords which agents Claude Code offers, from where and with which description. It passes each offer on unchanged.
hookcommand.run{command=model-router:provider}Answers the /model-router:provider command.
hookcommand.run{command=model-router:scope}Answers the /model-router:scope command.
hooksession.startRegisters the mcp__model-router__config tool, at session start and after each plugin reload.
hooktool.call{tool=Agent}Routes the Agent call.
hooktool.call{tool=mcp__model-router__config}Answers the config tool: the settings and the dialogs.
call$.clock.afterThe TypeSafe SDK's timers run on it, for example its retry wait.
call$.clock.sleepTimes the 8 s limit.
call$.config.setWrites the provider or scope option, after you pick a value in the dialog or give a command with a value at your own prompt.
call$.env.getReads TYPESAFE_API_KEY and OPENROUTER_API_KEY, the only variables the mod reads.
call$.http.fetchSends the request to TypeSafe or OpenRouter.
call$.tool.checkAsks for the permission verdict of the call.
call$.tool.registerRegisters the config tool.
call$.ui.askOpens the mod's dialog for a setting.
call$.ui.logWrites the log line, and the request body to the debug log.

tools/surface.json in the repository lists the same names, and CI compares them with the validate output.

Routing

On each routed call the mod sets the model and, unless the call names one, the effort. One dim line per routed call shows the pick. To turn routing off, disable the plugin in /plugin.

Options

The plugin has four options. Set them in the install dialog or in /config:

  • provider: which providers may score a call, and in which order.
  • typesafe (default): TypeSafe only.
  • openrouter: OpenRouter only.
  • auto: TypeSafe, then OpenRouter when TypeSafe fails.
  • openrouter-first: OpenRouter, then TypeSafe when OpenRouter fails.
  • scope: which Agent calls the mod routes.
  • core (default): the four built-in agents, as before.
  • extended: also every other Agent call that passes no model and no name, forks excepted. Which calls are routed lists the cases. A value other than these two counts as core.
  • api_key: your TypeSafe key, a sensitive value.
  • openrouter_api_key: your OpenRouter key, a sensitive value.

With auto or openrouter-first and only one key set, that key's provider scores alone. PRIVACY.md says which company receives the task under each value.

Every request names the alias jev-latest. TypeSafe points it at the most recent official Jev release. OpenRouter routes it to its own alias for the newest Jev release. The alias moves when a release ships, so the picks can shift with no change to the plugin. TypeSafe's Models page says which version it points to, and the log line names the model that answered.

An install updated from an earlier version follows these rules:

  • The removed model option is ignored, a stored jev-preview included. The mod sends jev-latest.
  • A stored provider outside the four values counts as typesafe.
  • A missing scope counts as core, so an update changes no routing.

Claude Code ignores plugin options in project and local settings. No project can set provider or scope. PRIVACY.md says what the options can and cannot change.

Change the options

Two commands show or change an option:

  • /model-router:provider [auto|openrouter-first|typesafe|openrouter]
  • /model-router:scope [core|extended]

Run a command with no value to print the current value. The provider line also prints the order, for example provider: auto (typesafe, then openrouter). Run it with a value, for example /model-router:scope extended, to write the option and print the new value. A value outside the list prints the allowed ones. When Claude Code refuses the change, the command prints <setting> unchanged: <reason>. A command writes only when you type it at your own prompt. From any other origin the command prints the value and writes nothing. When Claude runs a command itself, the command's text tells Claude to call the tool below. /config changes the same options.

The tool mcp__model-router__config takes one optional input, setting:

  • With no setting, it returns the provider and scope lines. For each provider the provider value allows, it adds <provider> key: set or <provider> key: unset. A key counts as set when its option or its variable holds a non-empty value. The tool never returns a key, its length or any part of it.
  • With provider or scope, the mod opens its own dialog. The current value comes first, and each label says what the value does. The mod writes only the value you pick. It writes nothing for free text, for the current value or for a dismissed or interrupted dialog. It writes nothing where no dialog can open, such as claude -p. The reply equals the command's text for the same outcome.

The tool takes no key. Add a key in the plugin's settings: /plugin in the terminal, or the plugin's gear icon in VS Code. The model never passes a value. Your permission rules apply to the tool, as they do to the Agent call. Calls run one at a time. The mod reads the current value after the previous dialog closes.

To be guided through the choices, ask Claude to run the model-router-setup skill. It reads the settings and the key status through the tool, then asks about the provider, any missing key and the scope. It lists the reasons routing is off and ends with a routing check. The skill lives in skills/model-router-setup/.

Which calls are routed

Two scopes decide which Agent calls the mod routes. Both skip a call that sets a model or a name, a fork, and a call your permission rules deny.

Under core, the default, the mod routes a call to one of the built-in agents general-purpose, claude, Explore and Plan, as Claude Code ships them. A call with no subagent_type counts as general-purpose. Every other call passes through untouched:

  • A fork inherits its parent's model.
  • statusline-setup and claude-code-guide have a model of their own.
  • A user, project or plugin agent keeps its own choices. That holds for one that takes the name of a built-in too: the mod routes a name only while the latest offer for it comes from Claude Code itself.
  • A name Claude Code has not offered yet is not routed.
  • A call that sets a model or a name keeps what it set.

Under extended, the mod routes every Agent call that passes no model and no name, except a fork. That covers plugin, user and project agents, and built-ins with a model of their own, such as statusline-setup and claude-code-guide. The decision never depends on which agents Claude Code has offered.

Claude Code does not expose the model or the effort an agent definition sets. So under extended, a routed call's model and effort replace the ones the definition sets. A plugin agent that pins a strong model can therefore run on a lower tier. A caller's own effort is kept, as under core. Keep core for agents whose model or effort you chose on purpose.

Under both scopes, agents that a workflow script starts, or that another plugin starts without the Agent tool, pass through.

Precedence

The mod sets the Agent call's model, the per-invocation parameter. Claude Code ranks that parameter first, above an agent definition's model and above CLAUDE_CODE_SUBAGENT_MODEL. So a routed call's model outranks CLAUDE_CODE_SUBAGENT_MODEL.

Two settings outrank the mod:

  • CLAUDE_CODE_SUBAGENT_MODEL_FORCE makes Claude Code ignore the model a call passes, so the forced model wins.
  • CLAUDE_CODE_EFFORT_LEVEL takes precedence over the call's effort.

An organization's availableModels list can also replace a blocked pick with another model.

What leaves the machine

On each routed call the mod sends an HTTPS POST through Claude Code's own $.http.fetch to the first provider in the provider order:

The second provider in the order gets a request only after the first fails, as below. Each key goes only to its own provider. The body holds:

  • the task text, condensed and redacted as below
  • the agent's description as Claude Code offers it, condensed, masked and cut to 500 characters, and the caller's one-line description
  • the Jev alias jev-latest and two scoring questions with their three texts each, which ship with the plugin

Two steps run on the task text before it leaves. Fenced code blocks become a one-line size note. Token-shaped strings are masked: Bearer …, sk-… keys, and assignments to names ending in key, token, secret or password. A text over 12,000 characters keeps its start and its end, joined by a marker that says the middle is omitted. Nothing else leaves the machine.

Under the default core scope, the descriptions are those of the four built-in agents. Under extended, the descriptions and task text of your user, project and plugin agents leave too. The extended scope says what that can expose, and PRIVACY.md lists what else the mod reads, stores and passes on.

With one provider, a routed call sends one request and up to two retries. The mod uses the official TypeSafe SDK. It retries a connection error, and a 408, 429 or 5xx status, up to three attempts in all. It waits for a Retry-After header when one comes, within the limit, and otherwise backs off for a short time. Any other status is not retried.

With two providers, the first gets one attempt of 2 s and no retries. The mod moves to the second after a connection error, a timeout, or HTTP 401, 402, 403, 404, 408, 429 or 5xx. It never moves after HTTP 400 or 422, a cancel, the 8 s limit or a reply it cannot read. The second provider gets the rest of the 8 s and the retries above. One call therefore sends at most four requests.

One fixed 8 s limit covers the whole call, retries and the second provider included. A 429 with a long Retry-After can hold a task for up to 8 s. The call then runs unchanged. The mod stops waiting at the limit, but it cannot recall a request in flight. A request can reach a provider even when its answer never returns. So a retry after a network failure may be billed more than once, and an abandoned first attempt may still be billed.

The request is sent before Claude Code's permission check for the call. Before routing, the mod asks Claude Code's permission rules about the call's original arguments. If they deny the call, nothing is sent. A rule on the model the mod picks, a PreToolUse hook and the auto-mode classifier decide after the request left. A call that prompts you is sent before you answer. To read each request as it left, start Claude Code with --debug. The mod writes each request body to the debug log, in numbered pieces when it is long. The key is never written.

Any failure, from a missing key to a timeout, leaves the call unchanged. The log line then says skipped and names the cause, as Troubleshooting lists.

PRIVACY.md states the same in policy form.

Effort

Jev answers a second question: how much work the task takes once the judgment is settled, as an index from 0 to 2. The index rests on the middle and moves to an end only when Jev gives that end more than twice the middle's probability. The index then maps to an effort per model:

indexhaikusonnetopus
0, a short taskmediumlowlow
1, an ordinary taskhighmediummedium
2, a long or delicate taskxhighhighhigh

The router never sets Haiku below medium, because Anthropic measured early stops at low. max is never set. A call that names an effort gets a model and keeps its effort. A call that names a model is not routed, so it keeps both. CLAUDE_CODE_EFFORT_LEVEL outranks either, as Precedence says. Claude Code reads the per-invocation effort from v2.1.292. Under the extended scope the ladder also replaces an effort that an agent definition sets, as Which calls are routed says.

Examples

The mod needs no prompt of its own. It acts whenever Claude calls the Agent tool. Three dispatches and what the mod does with them:

  1. "Copy this function into utils.ts exactly as given and run the tests." The task holds the exact code, so Jev scores it level 0. The subagent runs on haiku.
  2. "Check this diff against the five requirements in the spec and list what is missing." Bounded judgment over given material scores level 1, sonnet.
  3. "Review the whole branch for design problems and propose a split." Open judgment scores level 2, opus.

The first runs on haiku. For it the log shows:

model-router L0 haiku · medium · p=0.91/0.62 · jev jev-1.14.0 · 812/9 tok

The second number is the probability of the chosen work index. The tail names the Jev model that answered and its input and output tokens. A part the answer lacks is left out. After a fallback the line ends with the provider that answered and why the first one failed, for example · via openrouter (typesafe HTTP 503). A kept caller effort shows as caller effort in place of the ladder label. The pick is logged as the call starts, and a call that Claude Code then refuses adds a second line, denied.

Troubleshooting

  • No log line appears: the plugin is disabled, the call passed through, or your permission rules deny the Agent call. Forks, named agents and calls that name a model pass through under both scopes. Under core, agents other than the four built-ins pass through too. Run /model-router:scope to see the scope, and Which calls are routed lists the cases. Enable the plugin in /plugin.
  • A routed call logs skipped, <cause> and runs unchanged. After two attempts the line names each provider with its cause, in attempt order, for example skipped, typesafe HTTP 503, openrouter timeout. The causes are:
  • key unset: no provider the provider option allows has a key. The TypeSafe key comes from api_key or TYPESAFE_API_KEY, the OpenRouter key from openrouter_api_key or OPENROUTER_API_KEY. Set one as Install says for your app, then run /reload-plugins. In the desktop app a saved key can read back as empty after a restart. Keys in the desktop app has the workaround.
  • bad reply: the provider answered, but the answer lacks a valid score for one of the two questions.
  • timeout: a first attempt got no answer in 2 s, or the call got no decision in the 8 s limit. Check the network and try again.
  • cancelled: Claude Code abandoned the call before the answer came, for example because you interrupted it.
  • network error: every attempt failed before an answer came. An organization fetch policy that refuses openrouter.ai shows as this too. Check the network and try again.
  • HTTP <status>: the provider answered with that status, after the retries for a status that is retried. HTTP 401 means the provider rejected the key. Check a TypeSafe key at https://console.typesafe.ai/keys and an OpenRouter key in your OpenRouter account. HTTP 429 and HTTP 503 mean the provider refused or failed on every attempt. Try again later.
  • rejected request: the SDK refused the request itself.
  • failed: any other error.
  • A subagent ran on a model you did not expect: the mod did not route the call, or CLAUDE_CODE_SUBAGENT_MODEL_FORCE forced a model. Under extended, the mod replaced the model its agent definition sets. Pass model in the Agent call to choose one, unless the force is on.
  • A subagent thinks harder or less than you expect: the effort ladder in Effort set it, or CLAUDE_CODE_EFFORT_LEVEL did. Name effort in the Agent call to keep your own. Under extended, the ladder replaces the effort an agent definition sets.
  • A subagent ran on a substituted model at the router's effort: your organization's availableModels replaced the pick. The effort stayed with the call. Name effort in the Agent call.
  • A kind of task lands on the wrong tier: add a labelled brief to calibration.jsonl at the repository root and reword a tier text in src/model.ts. Then run the calibration script.

Keys in the desktop app

The desktop app cannot set a plugin's key yet. A key saved from a shell also reads back empty after the app restarts. https://github.com/anthropics/claude-code/issues/89749

When the setup skill asks how to add a key, pick "Write it to the settings files myself" or "Same, open the files for me". Either button names the variable and the user settings file, and you add the variable to its env block. Until the bug is fixed:

  1. Open ~/.claude/settings.json.
  2. Add TYPESAFE_API_KEY, OPENROUTER_API_KEY or both to the env block, with your keys in place of YOUR_KEY and YOUR_OPENROUTER_KEY:
   {
     "env": {
       "TYPESAFE_API_KEY": "YOUR_KEY",
       "OPENROUTER_API_KEY": "YOUR_OPENROUTER_KEY"
     }
   }
  1. Start a new session.
  2. If you set OPENROUTER_API_KEY, run /model-router:provider auto in the session.
  3. Delete those lines once the bug is fixed.

The keys sit there in plaintext, and every process Claude Code starts can see them.

Support

Questions and bug reports go to https://github.com/Akurganow/model-router/issues. The privacy policy is in PRIVACY.md.

Source 1 files
hooks/register.js 1554 lines
1// src/timers.ts
2var after;
3function installTimers(implementation) {
4  after = implementation;
5}
6function installed(name) {
7  if (after === void 0)
8    throw new Error(
9      `${name} was called before installTimers; call installTimers with the $.clock.after wrapper at the start of the hook`
10    );
11  return after;
12}
13function setTimeout(fn, ms) {
14  return installed("setTimeout")(ms, fn);
15}
16function clearTimeout(timer) {
17  installed("clearTimeout");
18  timer?.cancel();
19}
20
21// src/brief.ts
22var BUDGET_CHARS = 12e3;
23var ROLE_CAP = 500;
24var NO_DESCRIPTION = "An agent with no description.";
25var OMISSION_MARKER = "\n[middle of the brief omitted]\n";
26var HEAD_SHARE = 2 / 3;
27var REDACT_PATTERNS = [
28  [/Bearer\s+[A-Za-z0-9._~+/=-]+/gi, "Bearer ***"],
29  [/\bsk-[A-Za-z0-9_-]{8,}/g, "***"],
30  [
31    /\b([A-Za-z0-9_]*(?:KEY|TOKEN|SECRET|PASSWORD))(["']?\s*[=:]\s*)(?:"[^"]*"?|'[^']*'?|[^\s"']+)/gi,
32    "$1$2***"
33  ]
34];
35function prepareBrief(text, budget = BUDGET_CHARS) {
36  const condensed = condense(redact(text));
37  if (condensed.length <= budget) return condensed;
38  const kept = budget - OMISSION_MARKER.length;
39  const head = Math.floor(kept * HEAD_SHARE);
40  const tail = kept - head;
41  return `${condensed.slice(0, head)}${OMISSION_MARKER}${condensed.slice(condensed.length - tail)}`;
42}
43function condense(text) {
44  return text.replace(/```[^\n]*\n([\s\S]*?)```/g, (_, block) => {
45    const lines = block.replace(/\n$/, "").split("\n").length;
46    return `[an exact block of ${lines} lines is given verbatim]`;
47  }).replace(/\n{3,}/g, "\n\n");
48}
49function redact(text) {
50  return REDACT_PATTERNS.reduce(
51    (t, [pattern, replacement]) => t.replace(pattern, replacement),
52    text
53  );
54}
55function roleText(description) {
56  if (typeof description !== "string") return NO_DESCRIPTION;
57  const text = redact(description).replace(/\s+/g, " ").trim();
58  if (text === "") return NO_DESCRIPTION;
59  const cut = text.slice(0, ROLE_CAP);
60  return /[\uD800-\uDBFF]$/.test(cut) && text.length > ROLE_CAP ? cut.slice(0, -1) : cut;
61}
62
63// src/claude-host.ts
64function passOn(_, e, next) {
65  return next(e);
66}
67async function denied($, call) {
68  const {
69    tool,
70    tool_use_id: _id,
71    agentId: _agentId,
72    requestMeta: _meta,
73    ...input
74  } = call;
75  return (await $.tool.check({ tool, input })).decision === "deny";
76}
77
78// node_modules/@typesafe-ai/sdk/dist/index.mjs
79var requestIdFrom = (headers) => headers.get("x-typesafe-request-id") ?? void 0;
80var APIPromise = class APIPromise2 extends Promise {
81  #responsePromise;
82  #parseResponse;
83  #parsed;
84  constructor(responsePromise, parseResponse) {
85    super((resolve2) => resolve2(void 0));
86    this.#responsePromise = responsePromise;
87    this.#parseResponse = parseResponse;
88  }
89  /**
90  * Resolves to the raw `Response` without parsing the body. SDK requests buffer the full
91  * body under the request timeout before handoff; reading it afterwards is caller-owned.
92  * The caller owns the body; don't also `await` the parsed result on the same promise.
93  */
94  asResponse() {
95    return this.#responsePromise;
96  }
97  /** Return the parsed result, HTTP response, and request ID. */
98  async withResponse() {
99    const [data, response] = await Promise.all([this.#parse(), this.#responsePromise]);
100    return {
101      data,
102      response,
103      requestId: requestIdFrom(response.headers)
104    };
105  }
106  /** Transform the parsed result, sharing the HTTP response and a single body parse. */
107  map(fn) {
108    return new APIPromise2(this.#responsePromise, () => this.#parse().then(fn));
109  }
110  #parse() {
111    this.#parsed ??= this.#responsePromise.then(this.#parseResponse);
112    return this.#parsed;
113  }
114  then(onfulfilled, onrejected) {
115    return this.#parse().then(onfulfilled, onrejected);
116  }
117  catch(onrejected) {
118    return this.#parse().catch(onrejected);
119  }
120  finally(onfinally) {
121    return this.#parse().finally(onfinally);
122  }
123};
124var range = (from, to) => Array.from({ length: to - from }, (_, i) => from + i);
125var DEFAULT_RETRY_POLICY = {
126  maxRetries: 2,
127  backoffInitialMs: 500,
128  backoffMaxMs: 5e3,
129  backoffJitter: 0.25,
130  /** HTTP 408, 429, and 5xx responses. */
131  httpStatuses: /* @__PURE__ */ new Set([
132    408,
133    429,
134    ...range(500, 600)
135  ]),
136  respectRetryAfter: true,
137  /** Maximum server retry delay before falling back to backoff. */
138  maxRetryAfterMs: 6e4,
139  apiConnectionError: true,
140  apiTimeoutError: true
141};
142DEFAULT_RETRY_POLICY.maxRetries;
143var isRetryableStatus = (status, policy = DEFAULT_RETRY_POLICY) => policy.httpStatuses.has(status);
144var parseRetryAfter = (headers, now = Date.now()) => {
145  const ms = Number(headers.get("retry-after-ms"));
146  if (headers.has("retry-after-ms") && Number.isFinite(ms) && ms >= 0) return ms;
147  const raw = headers.get("retry-after");
148  if (raw === null) return void 0;
149  const seconds = Number(raw);
150  if (Number.isFinite(seconds)) return seconds >= 0 ? seconds * 1e3 : void 0;
151  const date = Date.parse(raw);
152  if (!Number.isNaN(date)) return Math.max(0, date - now);
153};
154var retryDelayMs = (attempt, headers, policy = DEFAULT_RETRY_POLICY, random = Math.random) => {
155  if (policy.respectRetryAfter && headers !== void 0) {
156    const retryAfter = parseRetryAfter(headers);
157    if (retryAfter !== void 0 && retryAfter <= policy.maxRetryAfterMs) return retryAfter;
158  }
159  const exponential = Math.min(policy.backoffInitialMs * 2 ** attempt, policy.backoffMaxMs);
160  return Math.round(exponential * (1 - random() * policy.backoffJitter));
161};
162var sleep = (ms, signal) => new Promise((resolve2, reject) => {
163  if (signal?.aborted) return reject(signal.reason);
164  const onAbort = () => {
165    clearTimeout(timer);
166    reject(signal?.reason);
167  };
168  const timer = setTimeout(() => {
169    signal?.removeEventListener("abort", onAbort);
170    resolve2();
171  }, ms);
172  signal?.addEventListener("abort", onAbort, { once: true });
173});
174var TypeSafeError = class extends Error {
175  constructor(message, options) {
176    super(message, options);
177    this.name = new.target.name;
178  }
179};
180var isRecord = (value) => typeof value === "object" && value !== null;
181var extractMessage = (body) => {
182  if (typeof body === "string") return body || void 0;
183  if (!isRecord(body)) return void 0;
184  const { error, message, detail } = body;
185  if (typeof error === "string") return error;
186  if (isRecord(error) && typeof error.message === "string") return error.message;
187  if (typeof message === "string") return message;
188  if (typeof detail === "string") return detail;
189  if (isRecord(detail) && typeof detail.message === "string") return detail.message;
190  if (Array.isArray(detail)) return describeValidationErrors(detail);
191};
192var describeValidationErrors = (errors) => {
193  const parts = errors.flatMap((e) => {
194    if (!isRecord(e) || typeof e.msg !== "string") return [];
195    const loc = Array.isArray(e.loc) ? e.loc.filter((x) => x !== "body").join(".") : "";
196    return [loc ? `${loc}: ${e.msg}` : e.msg];
197  });
198  return parts.length > 0 ? parts.join("; ") : void 0;
199};
200var MAX_RAW_BODY_IN_MESSAGE = 200;
201var APIError = class APIError2 extends TypeSafeError {
202  /** HTTP response status code. */
203  status;
204  /** HTTP response headers. */
205  headers;
206  /** Parsed JSON, response text, or `undefined` for an empty body. */
207  body;
208  /** Request ID from `x-typesafe-request-id`, or `undefined` when absent. */
209  requestId;
210  constructor(status, body, headers, message) {
211    super(message ?? APIError2.describe(status, body));
212    this.status = status;
213    this.body = body;
214    this.headers = headers;
215    this.requestId = requestIdFrom(headers);
216  }
217  static describe(status, body) {
218    const detail = extractMessage(body);
219    if (detail) return `${status} ${detail}`;
220    if (body === void 0) return `${status} status code (no body)`;
221    const raw = typeof body === "string" ? body : JSON.stringify(body);
222    return `${status} ${raw.length > MAX_RAW_BODY_IN_MESSAGE ? `${raw.slice(0, MAX_RAW_BODY_IN_MESSAGE)}\u2026` : raw}`;
223  }
224  /** Create the error subclass for an HTTP status code. */
225  static fromResponse(status, body, headers) {
226    if (status === 400) return new BadRequestError(status, body, headers);
227    if (status === 401) return new AuthenticationError(status, body, headers);
228    if (status === 403) return new PermissionDeniedError(status, body, headers);
229    if (status === 404) return new NotFoundError(status, body, headers);
230    if (status === 422) return new UnprocessableEntityError(status, body, headers);
231    if (status === 429) return new RateLimitError(status, body, headers);
232    if (status >= 500) return new InternalServerError(status, body, headers);
233    return new APIError2(status, body, headers);
234  }
235};
236var BadRequestError = class extends APIError {
237};
238var AuthenticationError = class extends APIError {
239};
240var PermissionDeniedError = class extends APIError {
241};
242var NotFoundError = class extends APIError {
243};
244var UnprocessableEntityError = class extends APIError {
245};
246var RateLimitError = class extends APIError {
247  /** Server retry delay in milliseconds, or `undefined` when absent or invalid. */
248  retryAfterMs = parseRetryAfter(this.headers);
249};
250var InternalServerError = class extends APIError {
251};
252var APIConnectionError = class extends TypeSafeError {
253  constructor(message = "Connection error.", options) {
254    super(message, options);
255  }
256};
257var APITimeoutError = class extends APIConnectionError {
258  /** Configured timeout in milliseconds. */
259  timeoutMs;
260  constructor(timeoutMs, options) {
261    super(`Request timed out after ${timeoutMs}ms.`, options);
262    this.timeoutMs = timeoutMs;
263  }
264};
265var APIUserAbortError = class extends TypeSafeError {
266  constructor(message = "Request was aborted.", options) {
267    super(message, options);
268  }
269};
270var CONTENT_TYPES = [["image/png", [
271  137,
272  80,
273  78,
274  71,
275  13,
276  10,
277  26,
278  10
279]], ["image/jpeg", [
280  255,
281  216,
282  255
283]]];
284var REFERENCE = /<image:[0-9a-f]{32}>/g;
285var IMAGE = /* @__PURE__ */ Symbol.for("@typesafe-ai/sdk/image");
286var TEXT_WITH_ASSETS = /* @__PURE__ */ Symbol.for("@typesafe-ai/sdk/text-with-assets");
287var randomHex = () => Array.from(crypto.getRandomValues(/* @__PURE__ */ new Uint8Array(16)), (byte) => byte.toString(16).padStart(2, "0")).join("");
288var isImage = (value) => IMAGE in value;
289var isTextWithAssets = (value) => TEXT_WITH_ASSETS in value;
290var typeName = (value) => {
291  if (value === null) return "null";
292  if (typeof value !== "object") return typeof value;
293  return Object.prototype.toString.call(value).slice(8, -1);
294};
295var toBytes = (data) => {
296  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)}.`);
297  return ArrayBuffer.isView(data) ? new Uint8Array(data.buffer, data.byteOffset, data.byteLength) : new Uint8Array(data);
298};
299var contentTypeOf = (bytes) => {
300  for (const [contentType, signature] of CONTENT_TYPES) if (signature.every((byte, i) => bytes[i] === byte)) return contentType;
301  return "application/octet-stream";
302};
303var Image = class Image2 {
304  type = "image";
305  /** The image file bytes, or a `Blob` read when the request is sent. */
306  data;
307  #reference = `<image:${randomHex()}>`;
308  /** @throws {TypeSafeError} `data` is empty or isn't file bytes or a `Blob`. */
309  constructor(data) {
310    this.data = data instanceof Blob ? data : toBytes(data);
311    if ((this.data instanceof Blob ? this.data.size : this.data.byteLength) === 0) throw new TypeSafeError("Image data is empty.");
312  }
313  /**
314  * Create an image from base64-encoded file bytes, decoding them now.
315  *
316  * @param text - The image file bytes, base64-encoded, without a `data:` URL prefix.
317  * @throws {TypeSafeError} `text` isn't valid base64 or decodes to no bytes.
318  *
319  * @example
320  * ```ts
321  * const photo = Image.fromBase64(upload.photoBase64);
322  * ```
323  */
324  static fromBase64(text) {
325    let binary;
326    try {
327      binary = atob(text);
328    } catch (err) {
329      throw new TypeSafeError("Image data must contain valid base64 text.", { cause: err });
330    }
331    return new Image2(Uint8Array.from(binary, (char) => char.charCodeAt(0)));
332  }
333  /** The unique reference this image is sent under, for referencing it inside text. */
334  toString() {
335    return this.#reference;
336  }
337  /** The reference, written by `JSON.stringify` wherever the image appears in a request. */
338  toJSON() {
339    return this.#reference;
340  }
341};
342Object.defineProperty(Image.prototype, IMAGE, { value: true });
343var TextWithAssets = class {
344  /** The text, with each asset replaced by its reference. */
345  text;
346  /** The assets interpolated into the text, including those in nested `withAssets` text. */
347  assets;
348  constructor(text, assets) {
349    this.text = text;
350    this.assets = assets;
351  }
352  toString() {
353    return this.text;
354  }
355  /** The text, written by `JSON.stringify` wherever this value appears in a request. */
356  toJSON() {
357    return this.text;
358  }
359};
360Object.defineProperty(TextWithAssets.prototype, TEXT_WITH_ASSETS, { value: true });
361var textWithAssets = (text, values) => {
362  const interpolated = /* @__PURE__ */ new Map();
363  collectAssets(values, interpolated, /* @__PURE__ */ new Set());
364  const assets = /* @__PURE__ */ new Map();
365  for (const [reference] of text.matchAll(REFERENCE)) {
366    const asset = interpolated.get(reference);
367    if (asset !== void 0) assets.set(reference, asset);
368  }
369  return new TextWithAssets(text, [...assets.values()]);
370};
371var 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) });
372var collectAssets = (value, found, visited) => {
373  if (typeof value !== "object" || value === null || visited.has(value)) return;
374  visited.add(value);
375  if (isImage(value)) found.set(String(value), value);
376  else if (isTextWithAssets(value)) for (const asset of value.assets) found.set(String(asset), asset);
377  else for (const item of Object.values(value)) collectAssets(item, found, visited);
378};
379var serializeRequest = (payload, assets = {}) => {
380  const names = new Map(Object.entries(assets).map(([name, asset]) => [asset, name]));
381  const known = new Map(Object.values(assets).map((asset) => [String(asset), asset]));
382  const json = JSON.stringify(payload, function(key, value) {
383    if (typeof value === "number" && !Number.isFinite(value)) return String(value);
384    const original = this[key];
385    if (typeof original !== "object" || original === null) return value;
386    if (isImage(original)) {
387      const name = names.get(original);
388      if (name !== void 0) return name;
389      known.set(String(original), original);
390    } else if (isTextWithAssets(original)) {
391      let text = original.text;
392      for (const asset of original.assets) {
393        const name = names.get(asset);
394        if (name === void 0) known.set(String(asset), asset);
395        else text = text.replaceAll(String(asset), name);
396      }
397      return text;
398    }
399    return value;
400  });
401  const unreferenced = Object.keys(assets).filter((name) => !json.includes(JSON.stringify(name).slice(1, -1)));
402  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.`);
403  const sent = new Map(Object.entries(assets));
404  const missing = /* @__PURE__ */ new Set();
405  for (const [reference] of json.matchAll(REFERENCE)) {
406    if (sent.has(reference)) continue;
407    const asset = known.get(reference);
408    if (asset === void 0) missing.add(reference);
409    else sent.set(reference, asset);
410  }
411  if (missing.size > 0) throw new TypeSafeError(`Image references without an attached image: ${[...missing].join(", ")}. Tag template literals that interpolate images with \`withAssets\`.`);
412  return {
413    json,
414    assets: sent.size === 0 ? void 0 : Object.fromEntries(sent)
415  };
416};
417var MultipartBody = class {
418  /** The JSON payload, sent as the `request` part. */
419  payload;
420  /** The `Content-Type` header value, including the boundary. */
421  contentType;
422  /** The encoded body. */
423  content;
424  constructor(payload, parts) {
425    const boundary = randomHex();
426    const chunks = [];
427    for (const { name, contentType, content, filename } of [{
428      name: "request",
429      contentType: "application/json",
430      content: JSON.stringify(payload)
431    }, ...parts]) {
432      const disposition = filename === void 0 ? `name="${name}"` : `name="${name}"; filename="${filename}"`;
433      chunks.push(`--${boundary}\r
434Content-Disposition: form-data; ${disposition}\r
435`, `Content-Type: ${contentType}\r
436\r
437`, content, "\r\n");
438    }
439    chunks.push(`--${boundary}--\r
440`);
441    this.payload = payload;
442    this.contentType = `multipart/form-data; boundary=${boundary}`;
443    this.content = new Blob(chunks);
444  }
445};
446var readImage = async (alias, { data }) => {
447  if (!(data instanceof Blob)) return data;
448  try {
449    return new Uint8Array(await data.arrayBuffer());
450  } catch (err) {
451    throw new TypeSafeError(`Asset "${alias}" could not be read: ${err.message}`, { cause: err });
452  }
453};
454var unshared = (bytes) => bytes.buffer instanceof ArrayBuffer ? bytes : bytes.slice();
455var copyAssetBytes = (assets) => Object.fromEntries(Object.entries(assets).map(([alias, asset]) => [alias, asset.data instanceof Uint8Array ? new Image(asset.data.slice()) : asset]));
456var encodeAssets = async (payload, assets) => {
457  const read2 = await Promise.all(Object.entries(assets).map(async ([alias, asset]) => [
458    alias,
459    asset,
460    await readImage(alias, asset)
461  ]));
462  const parts = [];
463  const entries = [];
464  for (const [alias, { type }, data] of read2) {
465    const name = `asset-${parts.length}`;
466    parts.push({
467      name,
468      contentType: contentTypeOf(data),
469      content: unshared(data),
470      filename: name
471    });
472    entries.push([alias, {
473      type,
474      part: name
475    }]);
476  }
477  return new MultipartBody({
478    ...payload,
479    assets: Object.fromEntries(entries)
480  }, parts);
481};
482var g$1 = globalThis;
483var zlib = () => {
484  try {
485    return g$1.process?.getBuiltinModule?.("node:zlib");
486  } catch {
487    return;
488  }
489};
490var hasZstd = () => typeof zlib()?.zstdCompress === "function";
491var resolveCompression = (compression) => {
492  if (compression === void 0) return hasZstd() ? "zstd" : false;
493  if (compression === false) return false;
494  if (compression === "zstd") {
495    if (!hasZstd()) throw new TypeSafeError("zstd compression requires Node.js 22.15 or newer. Pass `compression: false` instead.");
496    return compression;
497  }
498  throw new TypeSafeError(`\`compression\` must be "zstd" or false, got ${JSON.stringify(compression)}.`);
499};
500var zstd = async (body) => {
501  const data = new Uint8Array(await body.arrayBuffer());
502  const compressed = await new Promise((resolve2, reject) => {
503    zlib()?.zstdCompress?.(data, (err, result) => err ? reject(err) : resolve2(result));
504  });
505  return new Uint8Array(compressed);
506};
507var byteLength = (body) => typeof body === "string" ? new TextEncoder().encode(body).byteLength : body.size;
508var compressBody = (body) => zstd(typeof body === "string" ? new Blob([body]) : body);
509var ENV = {
510  /** Required API key; used when `apiKey` is omitted. */
511  apiKey: "TYPESAFE_API_KEY",
512  /** API root; defaults to `https://api.typesafe.ai`. */
513  baseURL: "TYPESAFE_BASE_URL",
514  /** Default model name; defaults to `jev-latest`. */
515  defaultModel: "TYPESAFE_DEFAULT_MODEL",
516  /** Log level; defaults to `warn`. */
517  logLevel: "TYPESAFE_LOG_LEVEL"
518};
519var readEnv = (name) => {
520  if (typeof process === "undefined" || !process.env) return void 0;
521  return process.env[name]?.trim() || void 0;
522};
523var fromCodeOrEnv = (fromCode, envVar) => fromCode ?? readEnv(envVar);
524var LOG_LEVELS = [
525  "debug",
526  "info",
527  "warn",
528  "error",
529  "off"
530];
531var DEFAULT_LOG_LEVEL = "warn";
532var isLogLevel = (value) => LOG_LEVELS.includes(value);
533var parseLogLevel = (value, source) => {
534  if (isLogLevel(value)) return value;
535  throw new TypeSafeError(`Invalid log level "${value}" from ${source}. Expected one of: ${LOG_LEVELS.join(", ")}.`);
536};
537var PREFIX = "[typesafe-sdk]";
538var consoleLogger = {
539  debug: (message, ...args) => console.debug(`${PREFIX} ${message}`, ...args),
540  info: (message, ...args) => console.info(`${PREFIX} ${message}`, ...args),
541  warn: (message, ...args) => console.warn(`${PREFIX} ${message}`, ...args),
542  error: (message, ...args) => console.error(`${PREFIX} ${message}`, ...args)
543};
544var RANK = {
545  debug: 0,
546  info: 1,
547  warn: 2,
548  error: 3,
549  off: 4
550};
551var drop = () => {
552};
553var withLevel = (sink, level) => {
554  const enabled = (at) => RANK[at] >= RANK[level];
555  return {
556    debug: enabled("debug") ? (message, ...args) => sink.debug(message, ...args) : drop,
557    info: enabled("info") ? (message, ...args) => sink.info(message, ...args) : drop,
558    warn: enabled("warn") ? (message, ...args) => sink.warn(message, ...args) : drop,
559    error: enabled("error") ? (message, ...args) => sink.error(message, ...args) : drop
560  };
561};
562var KEY_HEADERS = /* @__PURE__ */ new Set([
563  "authorization",
564  "proxy-authorization",
565  "x-api-key"
566]);
567var OPAQUE_HEADERS = /* @__PURE__ */ new Set(["cookie", "set-cookie"]);
568var redactKey = (value) => {
569  const [scheme, secret] = value.includes(" ") ? value.split(/\s+/, 2) : [void 0, value];
570  const tail = secret && secret.length > 8 ? secret.slice(-4) : "";
571  return `${scheme ? `${scheme} ` : ""}***${tail}`;
572};
573var redact2 = (name, value) => {
574  const lower = name.toLowerCase();
575  if (KEY_HEADERS.has(lower)) return redactKey(value);
576  if (OPAQUE_HEADERS.has(lower)) return "***";
577  return value;
578};
579var redactHeaders = (headers) => Object.fromEntries(Object.entries(headers).map(([name, value]) => [name, redact2(name, value)]));
580var isObject = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
581var validateChoice = (name, { criteria }) => {
582  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.`);
583  if (Object.keys(criteria).length === 0) throw new TypeSafeError(`Choice question "${name}" has no criteria; at least one choice is required.`);
584};
585var validateNoul = (name, { instructions, criteria }) => {
586  if (criteria != null && !isObject(criteria)) throw new TypeSafeError(`Noul question "${name}" criteria must be an object.`);
587  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.`);
588};
589var validateQuestions = (questions) => {
590  if (Object.keys(questions).length === 0) throw new TypeSafeError("At least one question is required.");
591  for (const [name, question] of Object.entries(questions)) {
592    if (question.type === "choice") validateChoice(name, question);
593    if (question.type === "noul") validateNoul(name, question);
594    if (question.type !== "score") continue;
595    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.`);
596    if (question.criteria.length < 2) throw new TypeSafeError(`Score question "${name}" has ${question.criteria.length} criteria; at least two scores are required.`);
597  }
598};
599var Models = class {
600  #transport;
601  constructor(transport) {
602    this.#transport = transport;
603  }
604  /** List the models available to the account. */
605  list(options = {}) {
606    return this.#transport.request("GET", "/v1/models", options).map(unwrapModels);
607  }
608};
609var unwrapModels = (wire) => {
610  if (Array.isArray(wire?.models)) return wire.models;
611  throw new TypeSafeError("Unexpected response shape from GET /v1/models; expected { models: [...] }.");
612};
613var g = globalThis;
614var isBrowser = () => typeof g.window !== "undefined" && typeof g.window.document !== "undefined" && typeof g.navigator !== "undefined";
615var describeRuntime = () => {
616  const platform = g.process?.platform && g.process?.arch ? ` (${g.process.platform}; ${g.process.arch})` : "";
617  if (g.Bun?.version) return `bun/${g.Bun.version}${platform}`;
618  if (g.Deno?.version?.deno) return `deno/${g.Deno.version.deno}${platform}`;
619  if (g.EdgeRuntime !== void 0) return "vercel-edge";
620  if (g.navigator?.userAgent === "Cloudflare-Workers") return "cloudflare-workers";
621  if (g.process?.versions?.node) return `node/${g.process.versions.node}${platform}`;
622  if (isBrowser()) return "browser";
623  return "unknown";
624};
625var VERSION = "0.7.0";
626var missingApiKey = () => {
627  throw new TypeSafeError(`No API key was provided. Pass \`apiKey\` to the TypeSafeClient constructor or set the ${ENV.apiKey} environment variable.`);
628};
629var missingFetch = () => {
630  throw new TypeSafeError("No global `fetch` is available in this runtime. Pass a `fetch` implementation to the TypeSafeClient constructor.");
631};
632var refuseBrowser = () => {
633  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.");
634};
635var defaultFetch = (input, init) => globalThis.fetch(input, init);
636var assertNonNegativeInteger = (name, value) => {
637  if (!Number.isInteger(value) || value < 0) throw new TypeSafeError(`\`${name}\` must be a non-negative integer, got ${String(value)}.`);
638  return value;
639};
640var assertPositiveMs = (name, value) => {
641  if (!Number.isFinite(value) || value <= 0) throw new TypeSafeError(`\`${name}\` must be a positive number of milliseconds, got ${String(value)}.`);
642  return value;
643};
644var assertNonNegativeMs = (name, value) => {
645  if (!Number.isFinite(value) || value < 0) throw new TypeSafeError(`\`${name}\` must be a non-negative number of milliseconds, got ${String(value)}.`);
646  return value;
647};
648var assertFraction = (name, value) => {
649  if (!Number.isFinite(value) || value < 0 || value > 1) throw new TypeSafeError(`\`${name}\` must be between 0 and 1, got ${String(value)}.`);
650  return value;
651};
652var assertStatusSet = (name, statuses) => {
653  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)}.`);
654  return statuses;
655};
656var resolveRetryPolicy = (base, overrides) => {
657  const o = overrides ?? {};
658  return {
659    maxRetries: o.maxRetries === void 0 ? base.maxRetries : assertNonNegativeInteger("retry.maxRetries", o.maxRetries),
660    backoffInitialMs: o.backoffInitialMs === void 0 ? base.backoffInitialMs : assertNonNegativeMs("retry.backoffInitialMs", o.backoffInitialMs),
661    backoffMaxMs: o.backoffMaxMs === void 0 ? base.backoffMaxMs : assertNonNegativeMs("retry.backoffMaxMs", o.backoffMaxMs),
662    backoffJitter: o.backoffJitter === void 0 ? base.backoffJitter : assertFraction("retry.backoffJitter", o.backoffJitter),
663    httpStatuses: new Set(o.httpStatuses === void 0 ? base.httpStatuses : assertStatusSet("retry.httpStatuses", o.httpStatuses)),
664    respectRetryAfter: o.respectRetryAfter ?? base.respectRetryAfter,
665    maxRetryAfterMs: o.maxRetryAfterMs === void 0 ? base.maxRetryAfterMs : assertNonNegativeMs("retry.maxRetryAfterMs", o.maxRetryAfterMs),
666    apiConnectionError: o.apiConnectionError ?? base.apiConnectionError,
667    apiTimeoutError: o.apiTimeoutError ?? base.apiTimeoutError
668  };
669};
670var isRetryableError = (err, policy) => {
671  if (err instanceof APITimeoutError) return policy.apiTimeoutError;
672  if (err instanceof APIConnectionError) return policy.apiConnectionError;
673  return false;
674};
675var resolveLogLevel = (fromCode) => {
676  if (fromCode !== void 0) return parseLogLevel(fromCode, "the `logLevel` option");
677  const fromEnv = readEnv(ENV.logLevel);
678  if (fromEnv !== void 0) return parseLogLevel(fromEnv, ENV.logLevel);
679  return DEFAULT_LOG_LEVEL;
680};
681var stripTrailingSlashes = (url) => url.replace(/\/+$/, "");
682var mergeHeaders = (...sources) => {
683  const entries = /* @__PURE__ */ new Map();
684  for (const source of sources) for (const [name, value] of Object.entries(source)) if (value === void 0) entries.delete(name.toLowerCase());
685  else entries.set(name.toLowerCase(), [name, value]);
686  return Object.fromEntries(entries.values());
687};
688var bufferResponse = async (response, signal) => {
689  const reader = response.clone().body?.getReader();
690  if (!reader) return;
691  const original = response.body?.getReader();
692  const cancel = () => {
693    reader.cancel(signal.reason).catch(() => {
694    });
695    original?.cancel(signal.reason).catch(() => {
696    });
697  };
698  signal.addEventListener("abort", cancel, { once: true });
699  try {
700    if (signal.aborted) cancel();
701    signal.throwIfAborted();
702    while (!(await reader.read()).done) signal.throwIfAborted();
703    signal.throwIfAborted();
704  } finally {
705    signal.removeEventListener("abort", cancel);
706    reader.releaseLock();
707    original?.releaseLock();
708  }
709};
710var untilAborted = (start, signal) => {
711  if (signal === void 0) return start();
712  return new Promise((resolve2, reject) => {
713    if (signal.aborted) return reject(signal.reason);
714    const onAbort = () => reject(signal.reason);
715    signal.addEventListener("abort", onAbort, { once: true });
716    start().then((value) => {
717      signal.removeEventListener("abort", onAbort);
718      resolve2(value);
719    }, (err) => {
720      signal.removeEventListener("abort", onAbort);
721      reject(err);
722    });
723  });
724};
725var RUNTIME = describeRuntime();
726var rejectedAPIPromise = (err) => {
727  const response = Promise.reject(err);
728  return new APIPromise(response, () => response);
729};
730var TypeSafeClient = class {
731  /** API key excluded from serialization and public properties. */
732  #apiKey;
733  /** API root with trailing slashes removed. */
734  baseURL;
735  /** Model used when a request omits `model`. */
736  defaultModel;
737  /** Configured log verbosity. */
738  logLevel;
739  /** The configured logger, filtered to `logLevel`. */
740  logger;
741  /** Retry settings with constructor overrides applied. */
742  retry;
743  /** Timeout per attempt in milliseconds. */
744  timeout;
745  /** Additional headers sent with each request. */
746  defaultHeaders;
747  /** Request body compression, or `false` when bodies are sent uncompressed. */
748  compression;
749  /** HTTP fetch implementation. */
750  fetch;
751  /** The models available to the account. */
752  models;
753  #requestCount = 0;
754  /**
755  * Create a client for the TypeSafe AI API.
756  *
757  * Explicit options take precedence over environment variables, then SDK defaults.
758  * Empty or whitespace-only environment values are ignored.
759  *
760  * @throws {TypeSafeError} The API key is missing, configuration is invalid, the runtime is
761  *   unsupported, or the runtime lacks the requested compression.
762  */
763  constructor(config = {}) {
764    if (isBrowser() && !config.dangerouslyAllowBrowser) refuseBrowser();
765    this.#apiKey = fromCodeOrEnv(config.apiKey, ENV.apiKey) ?? missingApiKey();
766    this.baseURL = stripTrailingSlashes(fromCodeOrEnv(config.baseURL, ENV.baseURL) ?? "https://api.typesafe.ai");
767    this.defaultModel = fromCodeOrEnv(config.defaultModel, ENV.defaultModel) ?? "jev-latest";
768    this.logLevel = resolveLogLevel(config.logLevel);
769    this.logger = withLevel(config.logger ?? consoleLogger, this.logLevel);
770    this.retry = resolveRetryPolicy(DEFAULT_RETRY_POLICY, config.retry);
771    this.timeout = assertPositiveMs("timeout", config.timeout ?? 1e4);
772    this.defaultHeaders = { ...config.defaultHeaders };
773    this.compression = resolveCompression(config.compression);
774    if (config.fetch === void 0 && typeof globalThis.fetch !== "function") missingFetch();
775    this.fetch = config.fetch ?? defaultFetch;
776    const transport = {
777      request: (method, path, options) => this.#request(method, path, options),
778      defaultModel: this.defaultModel
779    };
780    this.models = new Models(transport);
781  }
782  /**
783  * Answer named questions about text, structured state, or assets.
784  *
785  * @param request - State, questions, an optional model override, and optional assets.
786  *   Assets in `state`, question content, or `withAssets` text are sent under their references.
787  * @param options - Per-call timeout, retry, headers, and cancellation settings.
788  * @returns Answers typed by question name and criteria, with model and token usage. Every
789  *   failure below rejects the returned promise; the call itself doesn't throw.
790  * @throws {TypeSafeError} State is `null` or omitted, questions are empty, score criteria are not
791  *   a list of at least two entries, choice criteria are not a nonempty map, a noul question has
792  *   neither instructions nor a described outcome, a string holds the reference of an asset not
793  *   attached to the request, a name in `assets` doesn't appear in the request, or a `Blob`
794  *   asset can't be read.
795  * @throws {APIError} The server returns a non-2xx response after retries.
796  * @throws {APIConnectionError} The request cannot connect or times out after retries.
797  * @throws {APIUserAbortError} The caller aborts the request.
798  *
799  * @example
800  * ```ts
801  * const { answers } = await client.systemOne({
802  *   state: "I was charged twice. Please help.",
803  *   questions: { billing: noul("Is this about billing?") },
804  * });
805  * console.log(answers.billing.noul);
806  * ```
807  */
808  systemOne(request, options = {}) {
809    let body;
810    try {
811      if (request.state == null) throw new TypeSafeError("State is required.");
812      validateQuestions(request.questions);
813      const { assets, ...rest } = request;
814      const { json, assets: sent } = serializeRequest({
815        ...rest,
816        model: request.model ?? this.defaultModel
817      }, assets);
818      const payload = JSON.parse(json);
819      const copied = sent === void 0 ? void 0 : copyAssetBytes(sent);
820      body = copied === void 0 ? payload : () => encodeAssets(payload, copied);
821    } catch (err) {
822      return rejectedAPIPromise(err);
823    }
824    return this.#request("POST", "/v1/systemone", {
825      ...options,
826      body
827    });
828  }
829  /** Send a request and parse its response body. */
830  #request(method, path, options = {}) {
831    let resolved;
832    try {
833      resolved = {
834        method,
835        path,
836        body: options.body,
837        headers: mergeHeaders(this.defaultHeaders, options.headers ?? {}),
838        signal: options.signal,
839        timeout: options.timeout === void 0 ? this.timeout : assertPositiveMs("timeout", options.timeout),
840        retry: resolveRetryPolicy(this.retry, options.retry)
841      };
842    } catch (err) {
843      return rejectedAPIPromise(err);
844    }
845    const tag = `#${++this.#requestCount} ${method} ${path}`;
846    return new APIPromise(this.fetchWithRetries(tag, resolved), async (res) => {
847      const parsed = await parseBody(res);
848      this.logger.debug(`${tag} <- body`, parsed);
849      return parsed;
850    });
851  }
852  /** Retry eligible failures, logging attempt summaries at `info` and headers and bodies at `debug`. */
853  async fetchWithRetries(tag, req) {
854    const url = `${this.baseURL}${req.path}`;
855    let resolved = req.body;
856    if (typeof resolved === "function") try {
857      resolved = await untilAborted(resolved, req.signal);
858    } catch (err) {
859      if (!req.signal?.aborted) throw err;
860      this.logger.info(`${tag} aborted by caller while reading assets`);
861      throw new APIUserAbortError(void 0, { cause: err });
862    }
863    const multipart = resolved instanceof MultipartBody ? resolved : void 0;
864    const payload = multipart === void 0 ? resolved : multipart.payload;
865    const encoded = multipart?.content ?? (payload === void 0 ? void 0 : JSON.stringify(payload));
866    const encoding = encoded === void 0 || byteLength(encoded) < 1024 ? false : this.compression;
867    let body = encoded;
868    if (encoded !== void 0 && encoding !== false) try {
869      body = await untilAborted(() => compressBody(encoded), req.signal);
870    } catch (err) {
871      if (!req.signal?.aborted) throw err;
872      this.logger.info(`${tag} aborted by caller while compressing the body`);
873      throw new APIUserAbortError(void 0, { cause: err });
874    }
875    const headers = mergeHeaders(req.headers, {
876      Authorization: `Bearer ${this.#apiKey}`,
877      Accept: "application/json",
878      "User-Agent": `typesafe-sdk/${VERSION}`,
879      "X-TypeSafe-SDK": `typesafe-sdk/${VERSION}`,
880      "X-TypeSafe-Runtime": RUNTIME,
881      "Content-Type": multipart?.contentType ?? (body === void 0 ? void 0 : "application/json"),
882      "Content-Encoding": encoding === false ? void 0 : encoding,
883      "X-TypeSafe-Retry-Count": void 0
884    });
885    for (let attempt = 0; ; attempt++) {
886      const retriesLeft = req.retry.maxRetries - attempt;
887      const attemptHeaders = attempt === 0 ? headers : {
888        ...headers,
889        "X-TypeSafe-Retry-Count": String(attempt)
890      };
891      this.logger.debug(`${tag} -> ${url}`, {
892        headers: redactHeaders(attemptHeaders),
893        body: payload
894      });
895      const started = Date.now();
896      let res;
897      try {
898        res = await this.attempt(tag, url, {
899          method: req.method,
900          headers: attemptHeaders,
901          body
902        }, req);
903      } catch (err) {
904        if (err instanceof APIUserAbortError || retriesLeft <= 0) throw err;
905        if (!isRetryableError(err, req.retry)) throw err;
906        await this.backOff(tag, attempt, retriesLeft, err.message, void 0, req);
907        continue;
908      }
909      const requestId = requestIdFrom(res.headers);
910      this.logger.info(`${tag} <- ${res.status} in ${Date.now() - started}ms${requestId ? ` (request ${requestId})` : ""}`);
911      if (res.ok) return res;
912      const errorBody = await parseBody(res);
913      this.logger.debug(`${tag} <- error body`, errorBody);
914      const error = APIError.fromResponse(res.status, errorBody, res.headers);
915      if (retriesLeft <= 0 || !isRetryableStatus(res.status, req.retry)) throw error;
916      await this.backOff(tag, attempt, retriesLeft, `${res.status}`, res.headers, req);
917    }
918  }
919  /**
920  * One HTTP round trip, including body delivery, with a timeout. The caller's signal and our
921  * timer both abort the same controller; we check which fired to choose the error class.
922  */
923  async attempt(tag, url, init, { signal, timeout }) {
924    const controller = new AbortController();
925    const abortFromCaller = () => controller.abort(signal?.reason);
926    if (signal?.aborted) abortFromCaller();
927    signal?.addEventListener("abort", abortFromCaller, { once: true });
928    let timedOut = false;
929    const timer = setTimeout(() => {
930      timedOut = true;
931      controller.abort();
932    }, timeout);
933    const started = Date.now();
934    const elapsed = () => `${Date.now() - started}ms`;
935    try {
936      const response = await this.fetch(url, {
937        ...init,
938        signal: controller.signal
939      });
940      await bufferResponse(response, controller.signal);
941      return response;
942    } catch (err) {
943      if (signal?.aborted) {
944        this.logger.info(`${tag} aborted by caller after ${elapsed()}`);
945        throw new APIUserAbortError(void 0, { cause: err });
946      }
947      if (timedOut) {
948        this.logger.info(`${tag} timed out after ${elapsed()}`);
949        throw new APITimeoutError(timeout, { cause: err });
950      }
951      this.logger.info(`${tag} connection error after ${elapsed()}`, err);
952      throw new APIConnectionError(err instanceof Error ? `Connection error: ${err.message}` : void 0, { cause: err });
953    } finally {
954      clearTimeout(timer);
955      signal?.removeEventListener("abort", abortFromCaller);
956    }
957  }
958  /** Wait before retrying; caller cancellation throws `APIUserAbortError`. */
959  async backOff(tag, attempt, retriesLeft, reason, headers, { retry, signal }) {
960    const delay = retryDelayMs(attempt, headers, retry);
961    const nth = attempt + 1;
962    const total = attempt + retriesLeft;
963    this.logger.info(`${tag} retrying in ${delay}ms (retry ${nth}/${total}) after ${reason}`);
964    try {
965      await sleep(delay, signal);
966    } catch (err) {
967      this.logger.info(`${tag} aborted by caller while waiting to retry`);
968      throw new APIUserAbortError(void 0, { cause: err });
969    }
970  }
971};
972var parseBody = async (res) => {
973  const text = await res.text();
974  if (text.length === 0) return void 0;
975  if ((res.headers.get("content-type") ?? "").includes("application/json")) try {
976    return JSON.parse(text);
977  } catch {
978    return text;
979  }
980  try {
981    return JSON.parse(text);
982  } catch {
983    return text;
984  }
985};
986
987// src/provider.ts
988var PROVIDER_VALUES = [
989  "auto",
990  "openrouter-first",
991  "typesafe",
992  "openrouter"
993];
994var HOSTS = {
995  typesafe: "https://api.typesafe.ai",
996  openrouter: "https://openrouter.ai/api"
997};
998var FIRST_ATTEMPT_TIMEOUT_MS = 2e3;
999var MODEL = "jev-latest";
1000var DEFAULT_VALUE = "typesafe";
1001var FALLBACK_STATUSES = /* @__PURE__ */ new Set([
1002  401,
1003  402,
1004  403,
1005  404,
1006  408,
1007  429
1008]);
1009var SERVER_ERRORS = { min: 500, max: 599 };
1010var ORDER = {
1011  auto: ["typesafe", "openrouter"],
1012  "openrouter-first": ["openrouter", "typesafe"],
1013  typesafe: ["typesafe"],
1014  openrouter: ["openrouter"]
1015};
1016var resolve = (value) => typeof value === "string" && Object.hasOwn(ORDER, value) ? value : DEFAULT_VALUE;
1017var order = (value) => ORDER[resolve(value)];
1018function plan(value, present) {
1019  const providers = order(value).filter((p) => present[p]);
1020  return providers.map(
1021    (provider, i) => i < providers.length - 1 ? {
1022      provider,
1023      model: MODEL,
1024      timeout: FIRST_ATTEMPT_TIMEOUT_MS,
1025      retry: { maxRetries: 0 }
1026    } : { provider, model: MODEL }
1027  );
1028}
1029function fallsBack(err) {
1030  if (err instanceof APIUserAbortError) return false;
1031  if (err instanceof APIConnectionError) return true;
1032  if (!(err instanceof APIError)) return false;
1033  const { status } = err;
1034  return FALLBACK_STATUSES.has(status) || status >= SERVER_ERRORS.min && status <= SERVER_ERRORS.max;
1035}
1036
1037// src/claude-keys.ts
1038var KEY_OPTIONS = {
1039  typesafe: "api_key",
1040  openrouter: "openrouter_api_key"
1041};
1042var nonEmpty = (v) => typeof v === "string" && v !== "" ? v : void 0;
1043async function readKeys($, options, provider) {
1044  const keys = {};
1045  for (const name of order(provider)) {
1046    const key = nonEmpty(options[KEY_OPTIONS[name]]) ?? nonEmpty(await keyVariable($, name));
1047    if (key !== void 0) keys[name] = key;
1048  }
1049  return keys;
1050}
1051function keyVariable($, provider) {
1052  return provider === "typesafe" ? $.env.get("TYPESAFE_API_KEY") : $.env.get("OPENROUTER_API_KEY");
1053}
1054
1055// src/scope.ts
1056var SCOPE_VALUES = ["core", "extended"];
1057var DEFAULT_SCOPE = "core";
1058var resolveScope = (value) => SCOPE_VALUES.find((known) => known === value) ?? DEFAULT_SCOPE;
1059
1060// src/settings.ts
1061var VALUE_SETTINGS = ["provider", "scope"];
1062var KEY_SETTINGS = ["typesafe_key", "openrouter_key"];
1063var SETTING_NAMES = [...VALUE_SETTINGS, ...KEY_SETTINGS];
1064var LABEL_SEPARATOR = " - ";
1065var TEXTS = {
1066  provider: {
1067    values: PROVIDER_VALUES,
1068    resolve,
1069    about: "which providers score subagent calls",
1070    question: "Which providers should score subagent calls?",
1071    consequences: {
1072      auto: "TypeSafe, then OpenRouter if TypeSafe fails",
1073      "openrouter-first": "OpenRouter, then TypeSafe if OpenRouter fails",
1074      typesafe: "TypeSafe only",
1075      openrouter: "OpenRouter only"
1076    }
1077  },
1078  scope: {
1079    values: SCOPE_VALUES,
1080    resolve: resolveScope,
1081    about: "which agent calls the router routes",
1082    question: "Which agent calls should the router route?",
1083    consequences: {
1084      core: "today's routing: built-in general agents only",
1085      extended: "also routes other agents that pass no model"
1086    }
1087  }
1088};
1089var isValueSetting = (name) => VALUE_SETTINGS.some((known) => known === name);
1090var isValue = (setting, value) => TEXTS[setting].values.some((known) => known === value);
1091var valueLine = (setting, value) => setting === "provider" ? `provider: ${value} (${order(value).join(", then ")})` : `scope: ${resolveScope(value)}`;
1092var useOneOf = (setting) => `${setting}: use one of ${TEXTS[setting].values.join(", ")}`;
1093var unchanged = (setting, reason) => `${setting} unchanged: ${reason}`;
1094var alreadyValue = (value) => `already ${value}`;
1095var NO_ANSWER = "no answer from the dialog";
1096var NOT_OFFERED = "the answer was not one of the offered values";
1097var REFUSED = "Permission rules deny this tool, so nothing was read or changed.";
1098var keyLine = (provider, state) => `${provider} key: ${state}`;
1099var label = (setting, value) => `${value}${LABEL_SEPARATOR}${TEXTS[setting].consequences[value]}`;
1100function ask(setting, current2) {
1101  const { values, resolve: resolve2, question } = TEXTS[setting];
1102  const first = resolve2(current2);
1103  const sorted = [first, ...values.filter((value) => value !== first)];
1104  return { question, options: sorted.map((value) => label(setting, value)) };
1105}
1106function pick(setting, answer2) {
1107  return TEXTS[setting].values.find(
1108    (value) => label(setting, value) === answer2
1109  );
1110}
1111var toolDescription = (names) => `Reads the router's settings. With no input it returns the provider and scope, and whether each key the provider allows is set. With a setting name (${names.join(", ")}) the plugin asks the person in its own dialog and writes their choice. Never pass a value or a key: the person supplies them in the dialog.`;
1112var badCall = (names) => `Unknown setting. Pass no setting, or one of: ${names.join(", ")}`;
1113function describeCommand(setting) {
1114  const { about, values } = TEXTS[setting];
1115  return `Shows or changes ${about}: ${values.join(", ")}.`;
1116}
1117var COMMAND_DESCRIPTIONS = {
1118  provider: describeCommand("provider"),
1119  scope: describeCommand("scope")
1120};
1121
1122// src/claude-config.ts
1123var ROW_PREFIX = "model-router.";
1124var PERSON = "composer";
1125var TOOL_SPEC = {
1126  name: "config",
1127  description: toolDescription(VALUE_SETTINGS),
1128  inputSchema: {
1129    type: "object",
1130    properties: { setting: { type: "string", enum: VALUE_SETTINGS } }
1131  }
1132};
1133var written = {};
1134var queue = Promise.resolve();
1135function resetConfig() {
1136  for (const setting of VALUE_SETTINGS) delete written[setting];
1137  queue = Promise.resolve();
1138}
1139var current = (options, setting) => written[setting] ?? options[setting];
1140async function registerConfigTool($, e, next) {
1141  await $.tool.register(TOOL_SPEC);
1142  return next(e);
1143}
1144async function write($, setting, value) {
1145  try {
1146    const { deny } = await $.config.set({
1147      key: `${ROW_PREFIX}${setting}`,
1148      value
1149    });
1150    if (deny !== void 0) return unchanged(setting, deny);
1151    written[setting] = value;
1152    return valueLine(setting, value);
1153  } catch (err) {
1154    return unchanged(setting, err instanceof Error ? err.message : String(err));
1155  }
1156}
1157async function choose($, setting, options) {
1158  const { question, options: labels } = ask(setting, current(options, setting));
1159  let answer2;
1160  try {
1161    answer2 = await $.ui.ask(question, { options: labels, header: setting });
1162  } catch {
1163    return unchanged(setting, NO_ANSWER);
1164  }
1165  const value = pick(setting, answer2);
1166  if (value === void 0) return unchanged(setting, NOT_OFFERED);
1167  if (value === current(options, setting))
1168    return unchanged(setting, alreadyValue(value));
1169  return write($, setting, value);
1170}
1171async function read($, options) {
1172  const provider = current(options, "provider");
1173  const keys = await readKeys($, options, provider);
1174  return [
1175    valueLine("provider", provider),
1176    valueLine("scope", current(options, "scope")),
1177    ...order(provider).map(
1178      (name) => keyLine(name, keys[name] === void 0 ? "unset" : "set")
1179    )
1180  ].join("\n");
1181}
1182async function answer($, call, options) {
1183  if (await denied($, call)) return { deny: REFUSED };
1184  const { setting } = call;
1185  if (setting === void 0) return { result: await read($, options) };
1186  if (isValueSetting(setting))
1187    return { result: await choose($, setting, options) };
1188  return { result: badCall(VALUE_SETTINGS) };
1189}
1190function configCall($, call, options) {
1191  const run = queue.then(() => answer($, call, options));
1192  queue = run.catch(() => void 0);
1193  return run;
1194}
1195async function configCommand($, e, setting, options) {
1196  const args = e.args.trim();
1197  if (args !== "" && !isValue(setting, args))
1198    return { text: useOneOf(setting) };
1199  if (args === "" || e.origin.kind !== PERSON)
1200    return { text: valueLine(setting, current(options, setting)) };