@hasna/switcher 0.1.9 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -95,6 +95,20 @@ on-request approvals. These are startup defaults; the app's own permission
95
95
  controls and managed requirements still apply. Start a new conversation after
96
96
  changing launch defaults; existing conversations can retain their own settings.
97
97
 
98
+ Browser and Computer Use are local app tools, separate from the inference
99
+ provider. Switcher preserves the app's sandbox-helper arguments so
100
+ the installed tool runtime can start. Enable the app's browser/computer plugins
101
+ and the browser extension in the desired profile; website permissions, macOS
102
+ Accessibility/Screen Recording permissions, workspace policy and model
103
+ eligibility still apply. Full access does not override those controls.
104
+
105
+ Models need function calling; screenshot workflows also need image input.
106
+ DeepSeek's Responses API supports both for `deepseek-flash`, but ignores OpenAI's
107
+ built-in `computer_use` tool. The desktop's local MCP tools are a separate path.
108
+ Successful inference does not establish browser or computer compatibility for
109
+ every provider. See the [browser extension guide](https://learn.chatgpt.com/docs/chrome-extension)
110
+ and [DeepSeek compatibility details](https://api-docs.deepseek.com/guides/responses_api/).
111
+
98
112
  Switcher starts a separate app instance with persistent provider/model state
99
113
  under `~/.hasna/switcher/state/desktop/PROFILE`. Your regular ChatGPT app and its
100
114
  signed-in state are preserved. Each profile retains its own local conversations
@@ -121,6 +135,11 @@ It verifies selected-model configuration, direct responses, delegated task
121
135
  creation, follow-up delivery, and history replay against the real provider.
122
136
  It is separate from visual desktop acceptance.
123
137
 
138
+ `test:native-chatgpt-tools` checks the installed browser/computer tool kernel
139
+ through the generated launcher without provider calls or UI actions. Set
140
+ `SWITCHER_TEST_CUA_CONFIG` to the installed unified-computer-use plugin's
141
+ `.mcp.json`; the check uses disposable state and leaves that configuration intact.
142
+
124
143
  References: [OpenAI custom provider configuration](https://learn.chatgpt.com/docs/config-file/config-advanced),
125
144
  [community desktop custom-model profiles](https://github.com/ademisler/codex-desktop-custom-models),
126
145
  [reported signed-in provider routing issue](https://github.com/openai/codex/issues/37245),
@@ -129,6 +148,12 @@ and [DeepSeek thinking controls](https://api-docs.deepseek.com/guides/thinking_m
129
148
 
130
149
  ## Claude desktop with a provider
131
150
 
151
+ Claude Code's official Chrome integration requires direct Anthropic sign-in;
152
+ API-key and third-party-provider sessions cannot use it. Routing Claude desktop
153
+ inference through Switcher does not remove that restriction. A separately
154
+ configured, provider-compatible browser MCP server is another integration path.
155
+ See [Anthropic's Chrome prerequisites](https://code.claude.com/docs/en/chrome#prerequisites).
156
+
132
157
  ```sh
133
158
  switcher launch claude-desktop --provider deepseek --model deepseek-flash
134
159
  switcher launch claude-desktop --provider my-messages-provider --model vendor/model
@@ -200,7 +225,7 @@ switcher launch codex --provider openrouter --model anthropic/claude-sonnet-4.6
200
225
 
201
226
  An interactive terminal can choose or search the catalog when `--model` is omitted. Noninteractive launches require an explicit model. `--dry-run` resolves and saves the provider/profile and fresh catalog, then prints the launch plan without starting the harness or creating a run record. Existing `switcher launch PROFILE` commands remain supported. Direct launches create or reuse records without overwriting customized providers or profiles.
202
227
 
203
- When no remote API configuration is present, each CLI invocation starts an authenticated loopback API on an allocated port, stores SQLite data in `~/.hasna/switcher`, and closes its own listener on completion. Its random operator key remains in memory. Use `HASNA_SWITCHER_HOME` to choose another owner-only home, `HASNA_SWITCHER_SQLITE_PATH` for an explicit database, or `HASNA_SWITCHER_DATABASE_URL` for PostgreSQL. API and SDK data access remains HTTP.
228
+ With no Switcher API credential configured, the CLI and `switcher-mcp` exit non-zero and name the sources they consulted (Keychain item `hasna.credentials.switcher.api-key`, `~/.hasna/switcher/config/credentials`, `HASNA_SWITCHER_API_KEY`); they never open local data by default. Set `HASNA_SWITCHER_LOCAL=1` (alias `SWITCHER_LOCAL=1`) to deliberately run on the box: each invocation then starts an authenticated loopback API on an allocated port, stores SQLite data in `~/.hasna/switcher`, prints one `switcher: LOCAL mode` line on stderr, and closes its own listener on completion. Its random operator key remains in memory. Under that opt-in, use `HASNA_SWITCHER_HOME` to choose another owner-only home, `HASNA_SWITCHER_SQLITE_PATH` for an explicit database, or `HASNA_SWITCHER_DATABASE_URL` for PostgreSQL. A configured API URL or key outranks the flag. API and SDK data access remains HTTP.
204
229
 
205
230
  Remote API configuration is resolved through Contracts, including canonical credential stores and the default gateway URL. Invalid, unavailable or unauthorized remote services fail without opening local SQLite.
206
231
 
@@ -214,7 +239,7 @@ The canonical file is `~/.hasna/switcher/config/credentials` (owner-only mode 06
214
239
 
215
240
  `HASNA_HOME` replaces `~/.hasna`; `HASNA_CONFIG_HOME` places credentials at `<root>/switcher/credentials` and `<root>/secrets/credentials`. These shared overrides must be absolute and nonblank. `HASNA_PROFILE` selects `credentials-<profile>`; API authority stays in the common credentials file. `HASNA_SWITCHER_HOME` changes Switcher's local database, bindings and launch state only, and does not relocate shared credentials. `HOME` is respected by both paths.
216
241
 
217
- Configured but missing, unsafe, conflicting or inaccessible remote credentials fail before local data is opened. Only complete absence of Switcher remote configuration retains the user-authorized automatic local API. The owned local API uses a random in-memory key. Server-side authentication remains configured separately through `HASNA_SWITCHER_API_KEY` on `switcher-serve`.
242
+ Configured but missing, unsafe, conflicting or inaccessible remote credentials fail before local data is opened, and a Keychain item that exists but cannot be read is a terminal error, never treated as absent. Complete absence of Switcher remote configuration also fails closed; the owned local API is reachable only through `HASNA_SWITCHER_LOCAL=1` and uses a random in-memory key. Server-side authentication remains configured separately through `HASNA_SWITCHER_API_KEY` on `switcher-serve`.
218
243
 
219
244
  ## Credential bindings
220
245
 
@@ -464,7 +489,7 @@ switcher providers add catalog-provider --url https://inference.example/v1 --pro
464
489
 
465
490
  For advanced provider settings, use `providers add ID --file provider.json` with `manualModels` when discovery is unavailable. Each model needs `id` and `name`; optional fields are `contextWindow`, `maxOutputTokens`, `inputModalities`, `outputModalities`, `supportedParameters`, and `available`. Use `catalogBaseUrl` and `modelsPath` for a separate discovery root/path; CLI equivalents are `--catalog-url` and `--models-path`. Use `catalogFormat: "ollama"` for `/api/tags`. Mistral presets select a capability-aware parser, including archived status. Together presets select its native bare-array parser. Fireworks requires `--catalog-account-id ID` or an explicit catalog URL and retains count evidence across its paginated account catalog. DashScope requires an explicit region/workspace `--catalog-url` with `--catalog-format dashscope`. Z.AI currently requires an explicit catalog or manual models because its documented API has no model-list contract. MiniMax defaults to its `.cn` Open Platform endpoints; use an explicit authority and credential reference for another product or region. A different authenticated catalog origin requires an explicit `catalogCredentialEnv`; a public catalog can declare `catalogAuthStyle: "none"`. Standard credential aliases are resolved only for the matching built-in provider origin. The default parser follows Anthropic-style `has_more/last_id` pagination and otherwise expects an OpenAI-style `data` array. HTTP redirects are rejected.
466
491
 
467
- Grok uses a per-launch authenticated loopback bridge because its environment overlay cannot define providers. The bridge serves model metadata and forwards the selected protocol unchanged. It holds upstream credentials only in memory; Grok receives an ephemeral local token. The same bridge handles credentialless endpoints and OpenCode auth-header mismatches. Bridged requests are limited to 4 MiB and four minutes. Grok resumes retain the selected profile model. Use `-- --resume SESSION_ID -p PROMPT` for headless continuation, or omit the prompt and type after the interactive session loads. Interactive resume with an inline positional prompt is rejected because the native client can send it before applying the selected model. Grok 1.0.13 passed source and installed development CLI resume checks against a controlled Messages fixture and live DeepSeek Flash. OpenCode's provider identity stays stable across temporary bridge ports; `-- run --session SESSION_ID PROMPT` resumes with fresh launch settings. The installed beta-19157 passed two-process Messages resume checks against a controlled local upstream and live DeepSeek Flash, including a proof-file read and preserved history. Other provider/protocol and registry-release cells remain tracked separately in COMPATIBILITY.md.
492
+ Grok uses a per-launch authenticated loopback bridge because its environment overlay cannot define providers. The bridge serves model metadata and forwards the selected protocol unchanged. It holds upstream credentials only in memory; Grok receives an ephemeral local token. The same bridge handles credentialless endpoints and OpenCode auth-header mismatches. Bridged requests are limited to 4 MiB. Inference bridges allow long responses while bytes continue arriving, including SSE keepalive comments. A four-minute inactivity watchdog bounds the wait for upstream headers and each response read; time spent waiting for a slow native client to consume buffered bytes does not count as provider inactivity. Idle failures report `provider_idle_timeout` in routing evidence and a sanitized timeout message. Caller cancellation still releases the request, and partial responses are never replayed. Grok resumes retain the selected profile model. Use `-- --resume SESSION_ID -p PROMPT` for headless continuation, or omit the prompt and type after the interactive session loads. Interactive resume with an inline positional prompt is rejected because the native client can send it before applying the selected model. Grok 1.0.13 passed source and installed development CLI resume checks against a controlled Messages fixture and live DeepSeek Flash. OpenCode's provider identity stays stable across temporary bridge ports; `-- run --session SESSION_ID PROMPT` resumes with fresh launch settings. The installed beta-19157 passed two-process Messages resume checks against a controlled local upstream and live DeepSeek Flash, including a proof-file read and preserved history. Other provider/protocol and registry-release cells remain tracked separately in COMPATIBILITY.md.
468
493
 
469
494
  Hermes uses the same loopback boundary with its documented `custom` provider. The bridge exposes only the Switcher catalog, translates the selected provider's Bearer, `x-api-key` or literal `api-key` credential, and forwards deployment prefixes unchanged. Hermes `state.db` and `sessions/` are linked to a profile-owned stable directory for resume; generated config and bridge credentials remain per-launch. Focused bridge tests cover all three native protocol routes and auth styles, including cleanup of an active stream without caller cancellation. Run `bun scripts/test-native-hermes.ts` with `SWITCHER_TEST_HERMES_EXECUTABLE` for the installed native CLI fixture proof, which performs a real `read_file` loop and deleted-file resume against a generic preset.
470
495
 
package/dist/cli/index.js CHANGED
@@ -514,7 +514,7 @@ function canonicalPolicyJSON(value) {
514
514
  }
515
515
 
516
516
  // src/domain.ts
517
- var VERSION = "0.1.9";
517
+ var VERSION = "0.2.0";
518
518
  var harnessSchema = z4.enum(["claude", "codex", "grok", "opencode", "opencode2", "pi", "omp", "dsh", "cline", "hermes", "prime-agent", "gemini", "aider", "kilo"]);
519
519
  var protocolSchema = z4.enum(["anthropic-messages", "openai-responses", "openai-chat", "gemini-generate-content"]);
520
520
  var idSchema = z4.string().regex(/^[a-zA-Z0-9][a-zA-Z0-9._-]{0,79}$/);
@@ -1566,6 +1566,7 @@ function proxyProviderStream(input) {
1566
1566
  if (ended)
1567
1567
  return;
1568
1568
  ended = true;
1569
+ input.activity?.finish();
1569
1570
  try {
1570
1571
  if (error)
1571
1572
  output.error(error);
@@ -1576,9 +1577,9 @@ function proxyProviderStream(input) {
1576
1577
  };
1577
1578
  const cancelReader = async () => {
1578
1579
  input.abort.abort();
1579
- try {
1580
- await reader.cancel();
1581
- } catch {}
1580
+ reader.cancel().catch(() => {
1581
+ return;
1582
+ });
1582
1583
  };
1583
1584
  const stream = new ReadableStream({
1584
1585
  start(controller) {
@@ -1586,7 +1587,7 @@ function proxyProviderStream(input) {
1586
1587
  },
1587
1588
  async pull(controller) {
1588
1589
  try {
1589
- const chunk = await reader.read();
1590
+ const chunk = await (input.activity ? input.activity.run(() => reader.read()) : reader.read());
1590
1591
  if (ended)
1591
1592
  return;
1592
1593
  if (chunk.done) {
@@ -1604,17 +1605,22 @@ function proxyProviderStream(input) {
1604
1605
  } catch {
1605
1606
  if (ended)
1606
1607
  return;
1607
- if (input.requestSignal.aborted || input.abort.signal.aborted || input.closing())
1608
+ if (input.activity?.timedOut()) {
1609
+ input.interrupted?.("provider_idle_timeout");
1610
+ end(new Error("Provider stream timed out waiting for activity"));
1611
+ } else if (input.requestSignal.aborted || input.abort.signal.aborted || input.closing())
1608
1612
  end();
1609
1613
  else {
1610
- input.interrupted?.();
1614
+ input.interrupted?.("stream_interrupted");
1611
1615
  end(new Error("Provider stream ended unexpectedly"));
1612
1616
  }
1617
+ await cancelReader();
1613
1618
  }
1614
1619
  },
1615
1620
  async cancel() {
1616
1621
  if (!ended) {
1617
1622
  ended = true;
1623
+ input.activity?.finish();
1618
1624
  input.release();
1619
1625
  }
1620
1626
  await cancelReader();
@@ -1626,6 +1632,58 @@ function proxyProviderStream(input) {
1626
1632
  } };
1627
1633
  }
1628
1634
 
1635
+ // src/provider-request.ts
1636
+ function createProviderRequest(requestSignal, abortSignal, timing = {}) {
1637
+ const idleTimeoutMs = timing.idleTimeoutMs ?? 240000;
1638
+ if (!Number.isFinite(idleTimeoutMs) || idleTimeoutMs <= 0)
1639
+ throw new Error("Invalid provider idle timeout.");
1640
+ const idle = new AbortController;
1641
+ const signal = AbortSignal.any([requestSignal, abortSignal, idle.signal]);
1642
+ let timer, finished = false, timedOut = false;
1643
+ const received = () => {
1644
+ clearTimeout(timer);
1645
+ timer = undefined;
1646
+ };
1647
+ const finish = () => {
1648
+ finished = true;
1649
+ received();
1650
+ signal.removeEventListener("abort", finish);
1651
+ };
1652
+ const waiting = () => {
1653
+ if (finished || signal.aborted || timer !== undefined)
1654
+ return;
1655
+ timer = setTimeout(() => {
1656
+ timedOut = true;
1657
+ idle.abort(new DOMException("Provider response idle timeout", "TimeoutError"));
1658
+ }, idleTimeoutMs);
1659
+ };
1660
+ signal.addEventListener("abort", finish, { once: true });
1661
+ waiting();
1662
+ const run = async (operation) => {
1663
+ waiting();
1664
+ let onAbort;
1665
+ try {
1666
+ if (signal.aborted)
1667
+ throw signal.reason;
1668
+ const aborted = new Promise((_, reject) => {
1669
+ onAbort = () => reject(signal.reason);
1670
+ signal.addEventListener("abort", onAbort, { once: true });
1671
+ });
1672
+ return await Promise.race([operation(), aborted]);
1673
+ } finally {
1674
+ if (onAbort)
1675
+ signal.removeEventListener("abort", onAbort);
1676
+ received();
1677
+ }
1678
+ };
1679
+ return {
1680
+ fetchOptions: { signal, timeout: false },
1681
+ run,
1682
+ finish,
1683
+ timedOut: () => timedOut
1684
+ };
1685
+ }
1686
+
1629
1687
  // src/claude-context.ts
1630
1688
  function claudeContextEnvironment(providerBaseUrl, environment = process.env) {
1631
1689
  const explicit = environment.CLAUDE_CODE_AUTO_COMPACT_WINDOW;
@@ -2316,7 +2374,7 @@ var openapi_default = {
2316
2374
  openapi: "3.0.3",
2317
2375
  info: {
2318
2376
  title: "Switcher API",
2319
- version: "0.1.9",
2377
+ version: "0.2.0",
2320
2378
  description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
2321
2379
  },
2322
2380
  security: [
@@ -6498,7 +6556,59 @@ async function startServer(options) {
6498
6556
  }
6499
6557
 
6500
6558
  // src/runtime.ts
6501
- import { resolveCredential as resolveClientCredential, clientTransportEnvKeys, appConfigDiskValue, keychainConfigValue } from "@hasna/contracts/client";
6559
+ import { resolveCredential as resolveClientCredential, clientTransportEnvKeys as clientTransportEnvKeys2, appConfigDiskValue, keychainConfigValue } from "@hasna/contracts/client";
6560
+
6561
+ // src/lib/local-opt-in.ts
6562
+ import {
6563
+ clientTransportEnvKeys,
6564
+ credentialDiskSources,
6565
+ credentialOverrideEnvKey,
6566
+ credentialPointerEnvKey,
6567
+ CREDENTIAL_PROFILE_ENV_KEY
6568
+ } from "@hasna/contracts/client";
6569
+ var SWITCHER_LOCAL_OPT_IN_ENV_KEYS = ["HASNA_SWITCHER_LOCAL", "SWITCHER_LOCAL"];
6570
+ var SWITCHER_KEYCHAIN_ITEM = "hasna.credentials.switcher.api-key";
6571
+ var SWITCHER_CREDENTIALS_FILE = "~/.hasna/switcher/config/credentials";
6572
+ function isSwitcherLocalOptIn(env = process.env) {
6573
+ return SWITCHER_LOCAL_OPT_IN_ENV_KEYS.some((key) => (env[key] ?? "").trim() !== "");
6574
+ }
6575
+ function switcherAuthorityEnvKeys() {
6576
+ const keys = clientTransportEnvKeys("switcher");
6577
+ return [
6578
+ ...keys.apiUrlKeys,
6579
+ ...keys.apiKeyKeys,
6580
+ credentialOverrideEnvKey("switcher"),
6581
+ credentialPointerEnvKey("switcher"),
6582
+ CREDENTIAL_PROFILE_ENV_KEY
6583
+ ];
6584
+ }
6585
+ function hasSwitcherEnvAuthorityIntent(env = process.env) {
6586
+ return switcherAuthorityEnvKeys().some((key) => env[key] !== undefined);
6587
+ }
6588
+ function switcherCredentialSources(env = process.env) {
6589
+ const disk = credentialDiskSources("switcher", env)[0];
6590
+ return [
6591
+ `Keychain item ${SWITCHER_KEYCHAIN_ITEM}`,
6592
+ disk ? `${SWITCHER_CREDENTIALS_FILE} (${disk})` : SWITCHER_CREDENTIALS_FILE,
6593
+ `${clientTransportEnvKeys("switcher").apiKeyKeys[0] ?? "HASNA_SWITCHER_API_KEY"} in the environment`
6594
+ ];
6595
+ }
6596
+ function remoteConfigMissingMessage(env = process.env) {
6597
+ return `No Switcher API credential is configured; consulted ${switcherCredentialSources(env).join(", ")}. ` + `Configure one of them, or set ${SWITCHER_LOCAL_OPT_IN_ENV_KEYS[0]}=1 (alias ${SWITCHER_LOCAL_OPT_IN_ENV_KEYS[1]}=1) to deliberately use the on-box local store. Nothing was read or created locally.`;
6598
+ }
6599
+ var announced = false;
6600
+ function announceSwitcherLocalMode(home, write = (line) => {
6601
+ process.stderr.write(line);
6602
+ }) {
6603
+ if (announced)
6604
+ return;
6605
+ announced = true;
6606
+ write(`switcher: LOCAL mode \u2014 using the on-box store under ${home} behind an owned per-process loopback API, not a hosted Switcher API (${SWITCHER_LOCAL_OPT_IN_ENV_KEYS[0]} is set; a configured API URL or key would outrank it).
6607
+ `);
6608
+ }
6609
+
6610
+ // src/runtime.ts
6611
+ var REMOTE_API_CONFIG_MISSING = "remote_api_config_missing";
6502
6612
  function switcherHome(env = process.env) {
6503
6613
  const override = env.HASNA_HOME?.trim();
6504
6614
  const root = override && isAbsolute4(override) ? override : join4(env.HOME?.trim() || homedir3(), ".hasna");
@@ -6514,13 +6624,18 @@ async function privateDirectory(path) {
6514
6624
  }
6515
6625
  async function openCliRuntime(env = process.env, resolveCredential) {
6516
6626
  const providerEnv = Object.fromEntries(Object.entries(env).filter(([name]) => name.startsWith("SWITCHER_PROVIDER_")));
6517
- const keys = clientTransportEnvKeys("switcher");
6518
- const credential = resolveClientCredential("switcher", env);
6519
- const configured = credential || keys.apiUrlKeys.some((name) => env[name] !== undefined) || keychainConfigValue("switcher", env) || appConfigDiskValue("switcher", env, keys.apiUrlKeys);
6520
- if (configured) {
6521
- return { client: clientFromEnv(env), mode: "remote", providerEnv, close: async () => {} };
6627
+ const remote = () => ({ client: clientFromEnv(env), mode: "remote", providerEnv, close: async () => {} });
6628
+ if (hasSwitcherEnvAuthorityIntent(env))
6629
+ return remote();
6630
+ if (!isSwitcherLocalOptIn(env)) {
6631
+ const keys = clientTransportEnvKeys2("switcher");
6632
+ const configured = resolveClientCredential("switcher", env) || keychainConfigValue("switcher", env) || appConfigDiskValue("switcher", env, keys.apiUrlKeys);
6633
+ if (configured)
6634
+ return remote();
6635
+ throw new Fault(401, REMOTE_API_CONFIG_MISSING, remoteConfigMissingMessage(env));
6522
6636
  }
6523
6637
  const home = switcherHome(env);
6638
+ announceSwitcherLocalMode(home);
6524
6639
  if (!env.HASNA_SWITCHER_DATABASE_URL && !env.HASNA_SWITCHER_SQLITE_PATH)
6525
6640
  await privateDirectory(home);
6526
6641
  const apiKey = randomBytes(32).toString("base64url");
@@ -6816,12 +6931,12 @@ async function prepareGemini(input) {
6816
6931
 
6817
6932
  // src/gemini-bridge.ts
6818
6933
  import { createHash as createHash4, timingSafeEqual as timingSafeEqual2 } from "crypto";
6819
- function geminiBridge(input) {
6934
+ function geminiBridge(input, timing = {}) {
6820
6935
  const token = crypto.randomUUID() + crypto.randomUUID(), digest = (value) => createHash4("sha256").update(value).digest(), expected = digest(token);
6821
6936
  const models = new Set(input.models.map((model) => model.id));
6822
6937
  let closing = false, stopped;
6823
6938
  const active = new Set;
6824
- const server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 4 * 1024 * 1024, idleTimeout: 255, async fetch(request) {
6939
+ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 4 * 1024 * 1024, idleTimeout: 255, async fetch(request, server2) {
6825
6940
  const fail = (status, message) => Response.json({ error: { code: status, message } }, { status });
6826
6941
  if (closing)
6827
6942
  return fail(503, "Bridge is closing");
@@ -6861,15 +6976,20 @@ function geminiBridge(input) {
6861
6976
  const record2 = { abort: new AbortController, done: new Promise((resolve5) => {
6862
6977
  complete = resolve5;
6863
6978
  }) };
6979
+ const activity = createProviderRequest(request.signal, record2.abort.signal, timing);
6864
6980
  const release = () => {
6981
+ activity.finish();
6865
6982
  active.delete(record2);
6866
6983
  complete();
6867
6984
  };
6868
6985
  active.add(record2);
6986
+ server2.timeout(request, 0);
6869
6987
  try {
6870
- const response = await fetch(endpoint(input.baseUrl) + path, { method: "POST", headers, body: JSON.stringify(body), redirect: "manual", signal: AbortSignal.any([request.signal, record2.abort.signal, AbortSignal.timeout(240000)]) });
6988
+ const response = await activity.run(() => fetch(endpoint(input.baseUrl) + path, { method: "POST", headers, body: JSON.stringify(body), redirect: "manual", ...activity.fetchOptions }));
6871
6989
  if (!response.ok) {
6872
- await response.body?.cancel();
6990
+ response.body?.cancel().catch(() => {
6991
+ return;
6992
+ });
6873
6993
  release();
6874
6994
  return fail(response.status >= 300 && response.status < 400 ? 502 : response.status, `Provider returned HTTP ${response.status}`);
6875
6995
  }
@@ -6877,12 +6997,12 @@ function geminiBridge(input) {
6877
6997
  release();
6878
6998
  return new Response(null, { status: response.status });
6879
6999
  }
6880
- const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort: record2.abort, closing: () => closing, release });
7000
+ const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort: record2.abort, closing: () => closing, release, activity });
6881
7001
  record2.cancel = cancel;
6882
7002
  return new Response(stream, { status: response.status, headers: { "content-type": response.headers.get("content-type") ?? "application/json", "cache-control": "no-store" } });
6883
7003
  } catch {
6884
7004
  release();
6885
- return fail(502, "Provider request failed");
7005
+ return fail(activity.timedOut() ? 504 : 502, activity.timedOut() ? "Provider request timed out waiting for activity" : "Provider request failed");
6886
7006
  }
6887
7007
  } });
6888
7008
  return { baseUrl: new URL("v1beta", server.url).href, token, cleanup: () => stopped ??= (async () => {
@@ -7043,7 +7163,7 @@ function normalizeCodexDelegation(body) {
7043
7163
  // src/inference-gateway.ts
7044
7164
  import { createHash as createHash5, timingSafeEqual as timingSafeEqual3 } from "crypto";
7045
7165
  var routingFields = ["models", "fallbacks", "model_list", "deployment_id", "deployment", "router", "route", "extra_body", "plugins"];
7046
- function createInferenceGateway(input) {
7166
+ function createInferenceGateway(input, timing = {}) {
7047
7167
  const token = crypto.randomUUID() + crypto.randomUUID();
7048
7168
  const digest = (value) => createHash5("sha256").update(value).digest();
7049
7169
  const expected = digest(token), policy = input.compiledPolicy;
@@ -7052,7 +7172,7 @@ function createInferenceGateway(input) {
7052
7172
  const fail = (status, code) => Response.json({ error: { type: "switcher_model_policy", code, message: code === "model_not_allowed" ? "This model is outside the launch policy. Select it with switcher launch --model or explicitly assign an allowed role model." : `Switcher inference gateway: ${code}.` } }, { status });
7053
7173
  let closing = false, stopped;
7054
7174
  const active = new Set;
7055
- const server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 4 * 1024 * 1024, idleTimeout: 255, async fetch(request) {
7175
+ const server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 4 * 1024 * 1024, idleTimeout: 255, async fetch(request, server2) {
7056
7176
  if (closing)
7057
7177
  return fail(503, "closing");
7058
7178
  const credential = request.headers.get("x-goog-api-key") ?? request.headers.get("x-api-key") ?? request.headers.get("authorization")?.replace(/^Bearer /, "") ?? "";
@@ -7125,13 +7245,16 @@ function createInferenceGateway(input) {
7125
7245
  const abort = new AbortController;
7126
7246
  let complete;
7127
7247
  const record2 = { abort, done: new Promise((r) => complete = r) };
7248
+ const activity = createProviderRequest(request.signal, abort.signal, timing);
7128
7249
  const release = () => {
7250
+ activity.finish();
7129
7251
  flush();
7130
7252
  active.delete(record2);
7131
7253
  complete();
7132
7254
  };
7133
7255
  active.add(record2);
7134
- const signal = AbortSignal.any([request.signal, abort.signal, AbortSignal.timeout(240000)]);
7256
+ const signal = activity.fetchOptions.signal;
7257
+ server2.timeout(request, 0);
7135
7258
  const headers = { "content-type": "application/json" };
7136
7259
  if (input.credential) {
7137
7260
  const [name, value] = gemini ? ["x-goog-api-key", input.credential] : authHeader(input.authStyle ?? "bearer", input.credential);
@@ -7169,16 +7292,18 @@ function createInferenceGateway(input) {
7169
7292
  const outgoing = injectModelGuidance(input.protocol, compatible2, guidance, match?.[2]);
7170
7293
  const path = gemini ? `/models/${encodeURIComponent(model)}:${match[2]}${url.search}` : suffix + (betaQuery ? "?beta=true" : "");
7171
7294
  try {
7172
- response = await fetch(endpoint(input.baseUrl) + path, { method: "POST", headers, body: JSON.stringify(outgoing), redirect: "manual", signal });
7295
+ response = await activity.run(() => fetch(endpoint(input.baseUrl) + path, { method: "POST", headers, body: JSON.stringify(outgoing), redirect: "manual", ...activity.fetchOptions }));
7173
7296
  } catch {
7174
- current.reason = signal.aborted ? "request_cancelled" : "network_error";
7297
+ current.reason = activity.timedOut() ? "provider_idle_timeout" : signal.aborted ? "request_cancelled" : "network_error";
7175
7298
  if (!signal.aborted && attempt + 1 < candidates.length)
7176
7299
  continue;
7177
7300
  throw new Error("provider_request_failed");
7178
7301
  }
7179
7302
  current.upstreamStatus = response.status;
7180
7303
  if ((response.status === 429 || response.status >= 500) && attempt + 1 < candidates.length) {
7181
- await response.body?.cancel();
7304
+ response.body?.cancel().catch(() => {
7305
+ return;
7306
+ });
7182
7307
  response = undefined;
7183
7308
  continue;
7184
7309
  }
@@ -7233,16 +7358,18 @@ function createInferenceGateway(input) {
7233
7358
  if (done && buffer)
7234
7359
  observe(buffer);
7235
7360
  };
7236
- const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort, closing: () => closing, release, inspect, interrupted: () => {
7237
- current.reason = "stream_interrupted";
7361
+ const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort, closing: () => closing, release, activity, inspect, interrupted: (reason) => {
7362
+ current.reason = reason;
7238
7363
  } });
7239
7364
  record2.cancel = cancel;
7240
7365
  return new Response(stream, { status: response.status, headers: { "content-type": response.headers.get("content-type") ?? "application/json", "cache-control": "no-store" } });
7241
7366
  } catch (error) {
7242
7367
  if (error instanceof Fault)
7243
7368
  current.reason = error.code;
7369
+ else if (activity.timedOut())
7370
+ current.reason = "provider_idle_timeout";
7244
7371
  release();
7245
- return fail(error instanceof Fault ? error.status : 502, error instanceof Fault ? error.code : "provider_request_failed");
7372
+ return fail(error instanceof Fault ? error.status : activity.timedOut() ? 504 : 502, error instanceof Fault ? error.code : activity.timedOut() ? "provider_idle_timeout" : "provider_request_failed");
7246
7373
  }
7247
7374
  } });
7248
7375
  return { baseUrl: new URL(input.protocol === "gemini-generate-content" ? "v1beta" : "v1", server.url).href, token, cleanup: () => stopped ??= (async () => {
@@ -8531,7 +8658,7 @@ var routePath = {
8531
8658
  "openai-chat": "/v1/chat/completions"
8532
8659
  };
8533
8660
  var apiMode = hermesApiMode;
8534
- function createHermesBridge(input) {
8661
+ function createHermesBridge(input, timing = {}) {
8535
8662
  const protocol = input.protocol;
8536
8663
  const token = crypto.randomUUID() + crypto.randomUUID();
8537
8664
  const modelIds = new Set(input.models.map((model3) => model3.id));
@@ -8544,7 +8671,7 @@ function createHermesBridge(input) {
8544
8671
  port: 0,
8545
8672
  maxRequestBodySize: 4 * 1024 * 1024,
8546
8673
  idleTimeout: 255,
8547
- async fetch(request) {
8674
+ async fetch(request, server2) {
8548
8675
  if (closing)
8549
8676
  return Response.json({ error: { message: "Hermes bridge is closing" } }, { status: 503 });
8550
8677
  const nativeHeader = protocol === "anthropic-messages" ? "x-api-key" : "authorization";
@@ -8589,7 +8716,9 @@ function createHermesBridge(input) {
8589
8716
  complete = resolve8;
8590
8717
  })
8591
8718
  };
8719
+ const activity = createProviderRequest(request.signal, abortController.signal, timing);
8592
8720
  const release = () => {
8721
+ activity.finish();
8593
8722
  active.delete(record3);
8594
8723
  complete();
8595
8724
  };
@@ -8609,16 +8738,19 @@ function createHermesBridge(input) {
8609
8738
  if (beta)
8610
8739
  headers["anthropic-beta"] = beta;
8611
8740
  }
8741
+ server2.timeout(request, 0);
8612
8742
  try {
8613
- const upstream = await fetch(`${input.baseUrl}${routePath[protocol].replace(/^\/v1/, "")}`, {
8743
+ const upstream = await activity.run(() => fetch(`${input.baseUrl}${routePath[protocol].replace(/^\/v1/, "")}`, {
8614
8744
  method: "POST",
8615
8745
  headers,
8616
8746
  body: JSON.stringify(body),
8617
8747
  redirect: "manual",
8618
- signal: AbortSignal.any([abortController.signal, request.signal, AbortSignal.timeout(240000)])
8619
- });
8748
+ ...activity.fetchOptions
8749
+ }));
8620
8750
  if (!upstream.ok) {
8621
- await upstream.body?.cancel();
8751
+ upstream.body?.cancel().catch(() => {
8752
+ return;
8753
+ });
8622
8754
  release();
8623
8755
  return Response.json({ error: { message: `Provider returned HTTP ${upstream.status}` } }, { status: upstream.status });
8624
8756
  }
@@ -8626,7 +8758,7 @@ function createHermesBridge(input) {
8626
8758
  release();
8627
8759
  return new Response(null, { status: upstream.status });
8628
8760
  }
8629
- const { stream, cancel } = proxyProviderStream({ response: upstream, protocol: input.protocol, requestSignal: request.signal, abort: abortController, closing: () => closing, release });
8761
+ const { stream, cancel } = proxyProviderStream({ response: upstream, protocol: input.protocol, requestSignal: request.signal, abort: abortController, closing: () => closing, release, activity });
8630
8762
  record3.cancel = cancel;
8631
8763
  return new Response(stream, {
8632
8764
  status: upstream.status,
@@ -8637,7 +8769,7 @@ function createHermesBridge(input) {
8637
8769
  });
8638
8770
  } catch {
8639
8771
  release();
8640
- return Response.json({ error: { message: "Provider request failed" } }, { status: 502 });
8772
+ return Response.json({ error: { message: activity.timedOut() ? "Provider request timed out waiting for activity" : "Provider request failed" } }, { status: activity.timedOut() ? 504 : 502 });
8641
8773
  }
8642
8774
  }
8643
8775
  });
@@ -9230,7 +9362,7 @@ function codexModel(model3, priority, baseUrl = "https://provider.invalid", sele
9230
9362
  model_messages: { instructions_template: "You are Codex, a coding assistant. Help the user with their requested work. Follow the user and developer instructions, use the available tools when appropriate, preserve unrelated changes, and report actual results and remaining limitations.", instructions_variables: null }
9231
9363
  };
9232
9364
  }
9233
- function grokBridge(input) {
9365
+ function grokBridge(input, timing = {}) {
9234
9366
  const token = crypto.randomUUID() + crypto.randomUUID();
9235
9367
  const expected = createHash8("sha256").update(`Bearer ${token}`).digest();
9236
9368
  const models = new Map(input.models.flatMap((m) => [[m.id, m.id], [grokAlias(input, m.id), m.id]]));
@@ -9240,7 +9372,7 @@ function grokBridge(input) {
9240
9372
  const active = new Set;
9241
9373
  const apiBackend = { "anthropic-messages": "messages", "openai-responses": "responses", "openai-chat": "chat_completions", "gemini-generate-content": "generate_content" }[input.protocol];
9242
9374
  const apiPath = { "anthropic-messages": "/messages", "openai-responses": "/responses", "openai-chat": "/chat/completions", "gemini-generate-content": "/generateContent" }[input.protocol];
9243
- server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 4 * 1024 * 1024, idleTimeout: 255, async fetch(request) {
9375
+ server = Bun.serve({ hostname: "127.0.0.1", port: 0, maxRequestBodySize: 4 * 1024 * 1024, idleTimeout: 255, async fetch(request, server2) {
9244
9376
  if (closing)
9245
9377
  return Response.json({ error: { message: "Bridge is closing" } }, { status: 503 });
9246
9378
  const auth = request.headers.get("authorization") ?? (request.headers.has("x-api-key") ? `Bearer ${request.headers.get("x-api-key")}` : "");
@@ -9255,7 +9387,7 @@ function grokBridge(input) {
9255
9387
  model: m.id,
9256
9388
  name: m.name,
9257
9389
  description: m.description,
9258
- base_url: new URL("v1", server.url).href,
9390
+ base_url: new URL("v1", server2.url).href,
9259
9391
  context_window: m.contextWindow,
9260
9392
  max_completion_tokens: m.maxOutputTokens,
9261
9393
  api_backend: apiBackend,
@@ -9288,15 +9420,20 @@ function grokBridge(input) {
9288
9420
  const record3 = { abort: new AbortController, done: new Promise((resolve9) => {
9289
9421
  complete = resolve9;
9290
9422
  }) };
9423
+ const activity = createProviderRequest(request.signal, record3.abort.signal, timing);
9291
9424
  const release = () => {
9425
+ activity.finish();
9292
9426
  active.delete(record3);
9293
9427
  complete();
9294
9428
  };
9295
9429
  active.add(record3);
9430
+ server2.timeout(request, 0);
9296
9431
  try {
9297
- const response = await fetch(`${input.baseUrl}${apiPath}`, { method: "POST", headers, body: JSON.stringify(body), redirect: "manual", signal: AbortSignal.any([record3.abort.signal, request.signal, AbortSignal.timeout(240000)]) });
9432
+ const response = await activity.run(() => fetch(`${input.baseUrl}${apiPath}`, { method: "POST", headers, body: JSON.stringify(body), redirect: "manual", ...activity.fetchOptions }));
9298
9433
  if (!response.ok) {
9299
- await response.body?.cancel();
9434
+ response.body?.cancel().catch(() => {
9435
+ return;
9436
+ });
9300
9437
  release();
9301
9438
  return Response.json({ error: { message: `Provider returned HTTP ${response.status}` } }, { status: response.status >= 300 && response.status < 400 ? 502 : response.status });
9302
9439
  }
@@ -9304,12 +9441,12 @@ function grokBridge(input) {
9304
9441
  release();
9305
9442
  return new Response(null, { status: response.status });
9306
9443
  }
9307
- const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort: record3.abort, closing: () => closing, release });
9444
+ const { stream, cancel } = proxyProviderStream({ response, protocol: input.protocol, requestSignal: request.signal, abort: record3.abort, closing: () => closing, release, activity });
9308
9445
  record3.cancel = cancel;
9309
9446
  return new Response(stream, { status: response.status, headers: { "content-type": response.headers.get("content-type") ?? "application/json", "cache-control": "no-store" } });
9310
9447
  } catch {
9311
9448
  release();
9312
- return Response.json({ error: { message: "Provider request failed" } }, { status: 502 });
9449
+ return Response.json({ error: { message: activity.timedOut() ? "Provider request timed out waiting for activity" : "Provider request failed" } }, { status: activity.timedOut() ? 504 : 502 });
9313
9450
  }
9314
9451
  } });
9315
9452
  return { baseUrl: new URL("v1", server.url).href, token, cleanup: () => stopped ??= (async () => {
@@ -10646,6 +10783,9 @@ async function prepareChatGPTLaunch(native, app, stateDir, sessionDir) {
10646
10783
  set -eu
10647
10784
  unset OPENAI_API_KEY CODEX_API_KEY CODEX_ACCESS_TOKEN OPENAI_BASE_URL OPENAI_ORG_ID OPENAI_ORGANIZATION OPENAI_PROJECT_ID
10648
10785
  export CODEX_HOME=${quote2(home)}
10786
+ if [ "\${1-}" = sandbox ]; then
10787
+ exec ${quote2(app.codexExecutable)} "$@"
10788
+ fi
10649
10789
  exec ${quote2(app.codexExecutable)} "$@" ${overrides.map(quote2).join(" ")}
10650
10790
  `, { mode: 448, flag: "wx" });
10651
10791
  return {
@@ -11252,7 +11392,7 @@ import { join as join16, isAbsolute as isAbsolute13, dirname as dirname8, parse
11252
11392
  import { createHash as createHash12, randomUUID as randomUUID5 } from "crypto";
11253
11393
  import { execFile as execFile5, spawn as spawn2 } from "child_process";
11254
11394
  import { promisify as promisify5 } from "util";
11255
- import { resolveCredential, resolveClientTransport, toV1BaseUrl, clientTransportEnvKeys as clientTransportEnvKeys2, keychainConfigValue as keychainConfigValue2, appConfigDiskValue as appConfigDiskValue2 } from "@hasna/contracts/client";
11395
+ import { resolveCredential, resolveClientTransport, toV1BaseUrl, clientTransportEnvKeys as clientTransportEnvKeys3, keychainConfigValue as keychainConfigValue2, appConfigDiskValue as appConfigDiskValue2 } from "@hasna/contracts/client";
11256
11396
  var execute4 = promisify5(execFile5);
11257
11397
  var reference = z7.string().regex(/^SWITCHER_PROVIDER_[A-Z0-9_]+$/).max(120);
11258
11398
  var item = z7.string().min(1).max(500).regex(/^[^\x00-\x1f\x7f]+$/);
@@ -11546,15 +11686,19 @@ function bindingTarget(selector, override, allowedOrigins) {
11546
11686
  async function readKeychain(source) {
11547
11687
  if (process.platform !== "darwin")
11548
11688
  throw new Fault(422, "keychain_unavailable", "This binding requires macOS Keychain. Use a supported vault binding or runtime environment on this station.");
11689
+ let stdout;
11549
11690
  try {
11550
- const { stdout } = await execute4("/usr/bin/security", ["find-generic-password", "-a", source.account, "-s", source.service, "-w"], { encoding: "utf8", timeout: 1e4, maxBuffer: 65536 });
11551
- const value = stdout.replace(/\r?\n$/, "");
11552
- if (!value || /[\x00-\x1f\x7f]/.test(value))
11553
- throw new Error("Invalid credential");
11554
- return value;
11555
- } catch {
11556
- throw new Fault(422, "keychain_unavailable", "The configured Keychain item is missing, locked, or inaccessible; no alternate credential was selected.");
11557
- }
11691
+ ({ stdout } = await execute4("/usr/bin/security", ["find-generic-password", "-a", source.account, "-s", source.service, "-w"], { encoding: "utf8", timeout: 1e4, maxBuffer: 65536 }));
11692
+ } catch (error) {
11693
+ const status = error.code;
11694
+ if (status === 44)
11695
+ throw new Fault(422, "keychain_item_missing", "The configured Keychain item does not exist for that service and account; no alternate credential was selected.");
11696
+ throw new Fault(422, "keychain_unavailable", `The configured Keychain item could not be read (security exited ${typeof status === "number" ? status : "without a status"}); it is locked or inaccessible. No alternate credential was selected.`);
11697
+ }
11698
+ const value = stdout.replace(/\r?\n$/, "");
11699
+ if (!value || /[\x00-\x1f\x7f]/.test(value))
11700
+ throw new Fault(422, "keychain_item_invalid", "The configured Keychain item holds an unusable value; no alternate credential was selected.");
11701
+ return value;
11558
11702
  }
11559
11703
 
11560
11704
  class CredentialResolver {
@@ -11610,7 +11754,7 @@ async function vaultEnvironment(binding, env, options = {}) {
11610
11754
  try {
11611
11755
  if (source.operator.kind === "contracts") {
11612
11756
  const pair = () => {
11613
- const keys = clientTransportEnvKeys2("secrets");
11757
+ const keys = clientTransportEnvKeys3("secrets");
11614
11758
  const configuredUrl = keys.apiUrlKeys.map((name) => env[name]).find((value) => value !== undefined) ?? keychainConfigValue2("secrets", env, options.keychain)?.value ?? appConfigDiskValue2("secrets", env, keys.apiUrlKeys)?.value;
11615
11759
  const resolution = resolveClientTransport("secrets", env, { credentials: options });
11616
11760
  const key = resolveCredential("secrets", env, options);
@@ -11815,11 +11959,14 @@ Keep Switcher running while using the app; quit that app instance to end the lau
11815
11959
  --reasoning: none, minimal, low, medium, high, xhigh, max, ultra (provider support required).
11816
11960
  --dangerously-bypass-approvals-and-sandbox: full access without prompts or command sandboxing.
11817
11961
  PROTOCOL: anthropic-messages, openai-responses, openai-chat, gemini-generate-content
11818
- Without remote API configuration, the CLI owns a local authenticated API and
11819
- stores data in ~/.hasna/switcher (override HASNA_SWITCHER_HOME).
11820
- Remote API URL/key resolve through @hasna/contracts: overrides, Keychain,
11821
- ~/.hasna/switcher/config/credentials, then environment. A key alone uses the gateway.
11822
- A configured remote API never falls back to local data.
11962
+ Data access is HTTP against the configured Switcher API. Its URL/key resolve
11963
+ through @hasna/contracts: overrides, Keychain (hasna.credentials.switcher.api-key),
11964
+ ~/.hasna/switcher/config/credentials, then environment (HASNA_SWITCHER_API_KEY).
11965
+ A key alone uses the gateway. With nothing configured the command exits 1 and
11966
+ names those sources; it never falls back to local data.
11967
+ HASNA_SWITCHER_LOCAL=1 (alias SWITCHER_LOCAL=1) deliberately selects the on-box
11968
+ store in ~/.hasna/switcher (override HASNA_SWITCHER_HOME) behind an owned
11969
+ per-command loopback API; a configured remote API outranks the flag.
11823
11970
  Provider credential references must start SWITCHER_PROVIDER_.
11824
11971
  --models-file accepts a JSON array of model metadata; --model adds one starter.
11825
11972
  Use --catalog-format none for a manual catalog; otherwise discovery stays active.