@hasna/switcher 0.2.23 → 0.2.26

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/dist/cli.d.ts CHANGED
@@ -1,4 +1,15 @@
1
1
  #!/usr/bin/env bun
2
- import { type ModelPolicy } from "./domain";
2
+ import { Fault, type ModelPolicy } from "./domain";
3
+ import { type LaunchOptions } from "./launcher";
3
4
  export declare function readModelPolicy(file: string | undefined, roleValues: string[] | undefined): Promise<ModelPolicy | undefined>;
4
- export declare function main(args?: string[]): Promise<void>;
5
+ /** Launch options only `switcher resume` passes through its launch. */
6
+ type InternalLaunchOptions = Pick<LaunchOptions, "prepareOnly" | "requireDurableRoute">;
7
+ export declare function main(args?: string[], internal?: {
8
+ launchOptions?: InternalLaunchOptions;
9
+ }): Promise<void>;
10
+ /** A refusal of `switcher resume` with its documented exit code (see HELP). */
11
+ export declare class ResumeFault extends Fault {
12
+ readonly exitCode: number;
13
+ constructor(exitCode: number, status: number, code: string, message: string);
14
+ }
15
+ export {};
@@ -0,0 +1,41 @@
1
+ /**
2
+ * DeepSeek's Anthropic-compatible Messages endpoint parses a request into fixed types and refuses
3
+ * the whole request with HTTP 422 ("Failed to deserialize the JSON body into the target type:
4
+ * <path>: unknown variant `<type>`") when a tool or content block has a type it does not know.
5
+ * Measured on station08, 2026-11-05 09:05Z-09:07Z (SH-00080), against api.deepseek.com/anthropic/v1:
6
+ * - tools: untyped tools and web_search_20250305 / web_search_20260209 are accepted; every other
7
+ * type is refused, an explicit "type":"custom" included; a request whose tools are all
8
+ * defer_loading:true is refused with 400;
9
+ * - message content: text, image, document, thinking, server_tool_use, tool_use, tool_result,
10
+ * web_search_tool_result and tool_addition are accepted; redacted_thinking, compaction,
11
+ * search_result and any other type are refused; tool_result content accepts text, image,
12
+ * document and tool_reference.
13
+ * A Claude Code session that compacts sends constructs from the refused set, after which every
14
+ * turn fails. This module rewrites only the refused constructs, deterministically, and returns
15
+ * the body it was given, untouched, when nothing needs rewriting, so prompt caching keeps working.
16
+ */
17
+ type Json = Record<string, any>;
18
+ /** The DeepSeek Anthropic route (https://api.deepseek.com/anthropic/...), keyed by the provider URL every launch record keeps, as claude-context.ts and reasoning.ts key DeepSeek. */
19
+ export declare function deepSeekMessagesRoute(baseUrl: string): boolean;
20
+ /** What a rewrite changed, by construct; never content. */
21
+ export type DeepSeekRewrite = {
22
+ droppedTools: Record<string, number>;
23
+ customTypesRemoved: number;
24
+ deferLoadingRemoved: number;
25
+ convertedBlocks: Record<string, number>;
26
+ droppedBlocks: Record<string, number>;
27
+ placeholderBlocks: number;
28
+ };
29
+ /**
30
+ * Rewrite a Messages request body for DeepSeek: refused tool types are dropped (an explicit
31
+ * "custom" type is removed instead), defer_loading is removed when a tool-search tool was
32
+ * dropped or every remaining tool is deferred, and refused content blocks are converted to text
33
+ * or dropped. Returns the same body object when nothing needed rewriting.
34
+ */
35
+ export declare function rewriteDeepSeekMessages(body: Json): {
36
+ body: Json;
37
+ change?: DeepSeekRewrite;
38
+ };
39
+ /** One log line for a rewritten request: counts by construct, no content. */
40
+ export declare function deepSeekRewriteLogLine(providerId: string, change: DeepSeekRewrite): string;
41
+ export {};
@@ -1,4 +1,4 @@
1
- import { type GatewayHost, type RoutingEvent } from "./inference-gateway";
1
+ import type { GatewayHost, RoutingEvent } from "./inference-gateway";
2
2
  import { type CommandRunner } from "./gateway-supervisor";
3
3
  export type GatewayStatus = {
4
4
  service: "switcher-gateway";
@@ -73,7 +73,9 @@ export type ServiceGatewayHost = GatewayHost & {
73
73
  };
74
74
  /**
75
75
  * Register each launch gateway with the persistent service. If registration fails,
76
- * the launch still runs on a per-launch gateway and says so.
76
+ * the launch still runs on a per-launch gateway, warns and records it (gateway-fallback.ts).
77
+ * requireDurableRoute: refuse instead (gateway_route_unavailable) unless the launch gets a durable
78
+ * Claude route, for a caller that starts the harness itself after this process exits.
77
79
  */
78
80
  export declare function createServiceGatewayHost(client: GatewayControlClient, context: {
79
81
  holderPid: number;
@@ -81,5 +83,6 @@ export declare function createServiceGatewayHost(client: GatewayControlClient, c
81
83
  credentialEnv?: string;
82
84
  onRoutingEvent?: (event: RoutingEvent) => void;
83
85
  warn?: (message: string) => void;
86
+ requireDurableRoute?: boolean;
84
87
  }): ServiceGatewayHost;
85
88
  export {};
@@ -0,0 +1,42 @@
1
+ import { type GatewayHost, type GatewayInput, type GatewayLease } from "./inference-gateway";
2
+ /**
3
+ * A launch that meant to use the persistent gateway but runs on its own per-launch gateway
4
+ * (the service could not start, or refused the registration). That gateway listens on a
5
+ * random loopback port and stops when `switcher launch` exits, so a session that outlives
6
+ * the launch, or is resumed later outside Switcher, finds a dead port (SH-00097). The launch
7
+ * still runs, as before, but says so loudly on stderr and leaves a record an operator can find:
8
+ * `<state>/per-launch-gateways/<launch-XXXXXX>.json`, named after the launch's state directory,
9
+ * with the port, harness, model, working directory, launcher PID and reason. It never holds the
10
+ * gateway token or a credential. `endedAt` is added when the launch ends and the port closes.
11
+ */
12
+ export declare const PER_LAUNCH_GATEWAY_DIRECTORY = "per-launch-gateways";
13
+ export type PerLaunchGatewayRecord = {
14
+ schema: 1;
15
+ launchId: string;
16
+ port: number;
17
+ harness: string;
18
+ model: string;
19
+ cwd: string;
20
+ sessionDir?: string;
21
+ launcherPid: number;
22
+ reason: string;
23
+ createdAt: string;
24
+ endedAt?: string;
25
+ };
26
+ /** Where a per-launch fallback of the launch whose state directory is `stateDir` is recorded. */
27
+ export declare function perLaunchGatewayRecordPath(stateDir: string): string;
28
+ /**
29
+ * Start a per-launch gateway in place of the persistent one, warn on stderr with the reason and
30
+ * the port, and record it under the state root (when the launch has a state directory).
31
+ */
32
+ export declare function openPerLaunchGateway(input: GatewayInput, context: {
33
+ reason: string;
34
+ stateDir?: string;
35
+ warn?: (message: string) => void;
36
+ }): Promise<GatewayLease>;
37
+ /** A gateway host that always uses a per-launch gateway, for a launch whose persistent gateway is unavailable. */
38
+ export declare function perLaunchGatewayHost(context: {
39
+ reason: string;
40
+ stateDir?: string;
41
+ warn?: (message: string) => void;
42
+ }): GatewayHost;
@@ -1,4 +1,5 @@
1
1
  import { type ProviderInput } from "./domain";
2
+ import { type RoutingEvent } from "./inference-gateway";
2
3
  import type { ProviderRequestTiming } from "./provider-request";
3
4
  import { type ConnectionPeerLookup, type EnvironmentDigestProbe, type ProcessReader } from "./process-table";
4
5
  /** Version of the control protocol between `switcher launch` and the gateway service. */
@@ -35,6 +36,11 @@ export declare function gatewaySettings(env?: NodeJS.ProcessEnv): {
35
36
  scanMs: number;
36
37
  exitIdleMs: number;
37
38
  };
39
+ /**
40
+ * The class of a request the provider or the gateway refused, or undefined for one that was served.
41
+ * Every reason the inference handler sets is a fixed code, never message or request text.
42
+ */
43
+ export declare function refusalClass(event: RoutingEvent): string | undefined;
38
44
  export type GatewayServiceOptions = {
39
45
  env?: NodeJS.ProcessEnv;
40
46
  port?: number;
package/dist/index.js CHANGED
@@ -20721,6 +20721,27 @@ class HasnaHttpError extends Error {
20721
20721
  this.credentialTier = credential?.tier ?? null;
20722
20722
  }
20723
20723
  }
20724
+ var DEFAULT_MAX_RESPONSE_BYTES = 16 * 1024 * 1024;
20725
+ var MAX_RESPONSE_BYTES_ENV_KEY = "HASNA_CONTRACTS_MAX_RESPONSE_BYTES";
20726
+
20727
+ class ContractResponseTooLargeError extends Error {
20728
+ code = "CONTRACT_RESPONSE_TOO_LARGE";
20729
+ method;
20730
+ path;
20731
+ status;
20732
+ limitBytes;
20733
+ observedBytes;
20734
+ constructor(method, path, status, limitBytes, observedBytes, refusedBy) {
20735
+ const observed = refusedBy === "content-length" ? `Content-Length declared ${observedBytes} bytes` : `received ${observedBytes} bytes`;
20736
+ super(`Hasna cloud response exceeded the transport limit: ${method} ${path} -> ${status} ` + `(${observed}; limit ${limitBytes} bytes). The response body was cancelled and not parsed.`);
20737
+ this.name = "ContractResponseTooLargeError";
20738
+ this.method = method;
20739
+ this.path = path;
20740
+ this.status = status;
20741
+ this.limitBytes = limitBytes;
20742
+ this.observedBytes = observedBytes;
20743
+ }
20744
+ }
20724
20745
  function currentCredential(name, apiKey) {
20725
20746
  if (typeof apiKey === "function") {
20726
20747
  return validateAndSealResolvedCredential(name, apiKey());
@@ -20789,12 +20810,86 @@ function appendQuery(path, query) {
20789
20810
  return `${path}${path.includes("?") ? "&" : "?"}${qs}`;
20790
20811
  }
20791
20812
  var defaultSleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
20792
- function createHasnaHttpTransportInternal(options, requestBindingProvider) {
20813
+ function invalidMaxResponseBytes(name, source) {
20814
+ return new ClientTransportConfigurationError(name, `${source} must be a positive integer number of bytes no greater than ${Number.MAX_SAFE_INTEGER}; ` + "refusing to build a client with an invalid response size cap.", source === MAX_RESPONSE_BYTES_ENV_KEY ? [MAX_RESPONSE_BYTES_ENV_KEY] : []);
20815
+ }
20816
+ function resolveMaxResponseBytes(name, explicit, env) {
20817
+ if (explicit !== undefined) {
20818
+ if (!Number.isSafeInteger(explicit) || explicit < 1) {
20819
+ throw invalidMaxResponseBytes(name, "The maxResponseBytes option");
20820
+ }
20821
+ return explicit;
20822
+ }
20823
+ const descriptor = Object.getOwnPropertyDescriptor(env, MAX_RESPONSE_BYTES_ENV_KEY);
20824
+ if (!descriptor)
20825
+ return DEFAULT_MAX_RESPONSE_BYTES;
20826
+ if (!("value" in descriptor)) {
20827
+ throw new ClientTransportConfigurationError(name, `${MAX_RESPONSE_BYTES_ENV_KEY} is accessor-backed; client configuration requires own data properties.`, [MAX_RESPONSE_BYTES_ENV_KEY]);
20828
+ }
20829
+ if (descriptor.value === undefined)
20830
+ return DEFAULT_MAX_RESPONSE_BYTES;
20831
+ if (typeof descriptor.value !== "string") {
20832
+ throw new ClientTransportConfigurationError(name, `${MAX_RESPONSE_BYTES_ENV_KEY} must be a string data property.`, [MAX_RESPONSE_BYTES_ENV_KEY]);
20833
+ }
20834
+ const raw = descriptor.value;
20835
+ if (raw.trim().length === 0) {
20836
+ throw new ClientTransportConfigurationError(name, `${MAX_RESPONSE_BYTES_ENV_KEY} is set but blank; unset it for the ${DEFAULT_MAX_RESPONSE_BYTES}-byte ` + "default or set a positive decimal byte count.", [MAX_RESPONSE_BYTES_ENV_KEY]);
20837
+ }
20838
+ const parsed = /^[1-9][0-9]*$/.test(raw) ? Number(raw) : Number.NaN;
20839
+ if (!Number.isSafeInteger(parsed)) {
20840
+ throw invalidMaxResponseBytes(name, MAX_RESPONSE_BYTES_ENV_KEY);
20841
+ }
20842
+ return parsed;
20843
+ }
20844
+ function declaredContentLength(response) {
20845
+ const raw = response.headers.get("content-length");
20846
+ if (raw === null)
20847
+ return null;
20848
+ const trimmed = raw.trim();
20849
+ if (!/^[0-9]+$/.test(trimmed))
20850
+ return null;
20851
+ const value = Number(trimmed);
20852
+ return Number.isSafeInteger(value) ? value : Number.MAX_SAFE_INTEGER;
20853
+ }
20854
+ async function cancelReader(reader) {
20855
+ try {
20856
+ await reader.cancel();
20857
+ } catch {}
20858
+ }
20859
+ async function readResponseTextWithinLimit(response, limitBytes) {
20860
+ const body = response.body;
20861
+ if (!body)
20862
+ return { ok: true, text: "" };
20863
+ const reader = body.getReader();
20864
+ const decoder = new TextDecoder;
20865
+ const parts = [];
20866
+ let received = 0;
20867
+ try {
20868
+ for (;; ) {
20869
+ const { done, value } = await reader.read();
20870
+ if (done)
20871
+ break;
20872
+ received += value.byteLength;
20873
+ if (received > limitBytes) {
20874
+ await cancelReader(reader);
20875
+ return { ok: false, observedBytes: received };
20876
+ }
20877
+ parts.push(decoder.decode(value, { stream: true }));
20878
+ }
20879
+ parts.push(decoder.decode());
20880
+ return { ok: true, text: parts.join("") };
20881
+ } catch (error62) {
20882
+ await cancelReader(reader);
20883
+ throw error62;
20884
+ }
20885
+ }
20886
+ function createHasnaHttpTransportInternal(options, requestBindingProvider, env = process.env) {
20793
20887
  const fetchImpl = options.fetchImpl ?? ((input2, init) => fetch(input2, init));
20794
20888
  const base = toV1BaseUrl(options.baseUrl);
20795
20889
  const timeoutMs = options.timeoutMs ?? 30000;
20796
20890
  const sleep = options.sleepImpl ?? defaultSleep;
20797
20891
  const defaultRetry = options.retry;
20892
+ const maxResponseBytes = resolveMaxResponseBytes(options.name, options.maxResponseBytes, env);
20798
20893
  function resolveRetry(callRetry) {
20799
20894
  const chosen = callRetry !== undefined ? callRetry : defaultRetry;
20800
20895
  if (chosen === false)
@@ -20871,12 +20966,31 @@ function createHasnaHttpTransportInternal(options, requestBindingProvider) {
20871
20966
  await response.body?.cancel();
20872
20967
  } catch {}
20873
20968
  } else {
20874
- const text = await response.text();
20875
- if (text.length > 0) {
20969
+ const streamingBody = response.body;
20970
+ const declaredBytes = streamingBody ? declaredContentLength(response) : null;
20971
+ if (declaredBytes !== null && declaredBytes > maxResponseBytes) {
20972
+ try {
20973
+ await streamingBody?.cancel();
20974
+ } catch {}
20975
+ return {
20976
+ ok: false,
20977
+ retryable: false,
20978
+ error: new ContractResponseTooLargeError(method, rel, response.status, maxResponseBytes, declaredBytes, "content-length")
20979
+ };
20980
+ }
20981
+ const bounded = await readResponseTextWithinLimit(response, maxResponseBytes);
20982
+ if (!bounded.ok) {
20983
+ return {
20984
+ ok: false,
20985
+ retryable: false,
20986
+ error: new ContractResponseTooLargeError(method, rel, response.status, maxResponseBytes, bounded.observedBytes, "stream")
20987
+ };
20988
+ }
20989
+ if (bounded.text.length > 0) {
20876
20990
  try {
20877
- parsed = JSON.parse(text);
20991
+ parsed = JSON.parse(bounded.text);
20878
20992
  } catch {
20879
- parsed = text;
20993
+ parsed = bounded.text;
20880
20994
  }
20881
20995
  }
20882
20996
  }
@@ -20949,6 +21063,7 @@ function createHasnaHttpTransportInternal(options, requestBindingProvider) {
20949
21063
  function createClientTransport(name, env = process.env, overrides) {
20950
21064
  const snapshotOptions = snapshotResolveClientTransportOptions(overrides ?? {});
20951
21065
  const resolution = resolveClientTransportSnapshot(name, env, snapshotOptions).resolution;
21066
+ const maxResponseBytes = overrides?.maxResponseBytes;
20952
21067
  const sameBinding = (left, right) => left.resolution.baseUrl === right.resolution.baseUrl && left.credential.apiKey === right.credential.apiKey && left.credential.pointerVaultKey === right.credential.pointerVaultKey && left.credential.source === right.credential.source && left.credential.tier === right.credential.tier;
20953
21068
  const unstableConfiguration = () => new ClientTransportConfigurationError(name, "The configured service authority or credential changed while a request was being prepared; no authenticated request was sent.");
20954
21069
  const assertPinnedAuthority = (snapshot) => {
@@ -20988,9 +21103,10 @@ function createClientTransport(name, env = process.env, overrides) {
20988
21103
  ...overrides?.fetchImpl ? { fetchImpl: overrides.fetchImpl } : {},
20989
21104
  ...overrides?.headers ? { headers: overrides.headers } : {},
20990
21105
  ...overrides?.timeoutMs ? { timeoutMs: overrides.timeoutMs } : {},
21106
+ ...maxResponseBytes !== undefined ? { maxResponseBytes } : {},
20991
21107
  ...overrides?.retry !== undefined ? { retry: overrides.retry } : {},
20992
21108
  ...overrides?.sleepImpl ? { sleepImpl: overrides.sleepImpl } : {}
20993
- }, requestBindingProvider),
21109
+ }, requestBindingProvider, env),
20994
21110
  resolution
20995
21111
  };
20996
21112
  }
@@ -21280,16 +21396,38 @@ function apiError(status, data, apiKey) {
21280
21396
  const message = typeof error62.message === "string" && error62.message.length <= 4096 ? redact(error62.message).replace(/[\x00-\x1f\x7f-\x9f]/g, " ").trim().slice(0, 2048) || fallback : fallback;
21281
21397
  return new SwitcherError(status, code, message, requestId);
21282
21398
  }
21399
+ var DEFAULT_RETRIES = 3;
21400
+ var DEFAULT_RETRY_BASE_MS = 200;
21401
+ var DEFAULT_RETRY_MAX_MS = 2000;
21402
+ var RETRIES_LIMIT = 5;
21403
+ var RETRY_DELAY_LIMIT_MS = 1e4;
21404
+ function retryPolicy(options) {
21405
+ if (options === false)
21406
+ return;
21407
+ const whole = (value, fallback, minimum) => value !== undefined && Number.isFinite(value) ? Math.max(minimum, Math.floor(value)) : fallback;
21408
+ return {
21409
+ retries: Math.min(whole(options?.retries, DEFAULT_RETRIES, 0), RETRIES_LIMIT),
21410
+ baseDelayMs: Math.min(whole(options?.baseDelayMs, DEFAULT_RETRY_BASE_MS, 0), RETRY_DELAY_LIMIT_MS),
21411
+ maxDelayMs: Math.min(whole(options?.maxDelayMs, DEFAULT_RETRY_MAX_MS, 0), RETRY_DELAY_LIMIT_MS),
21412
+ sleep: options?.sleep ?? ((milliseconds) => new Promise((resolve) => setTimeout(resolve, milliseconds)))
21413
+ };
21414
+ }
21415
+ function edgeFailure(error62) {
21416
+ return error62 instanceof SwitcherError && (error62.status === 503 || error62.status >= 500 && error62.code === "invalid_response");
21417
+ }
21418
+ var operationKey = (supplied) => supplied ?? crypto.randomUUID();
21283
21419
 
21284
21420
  class SwitcherClient {
21285
21421
  options;
21286
21422
  transport;
21423
+ retry;
21287
21424
  baseUrl;
21288
21425
  constructor(options) {
21289
21426
  this.baseUrl = endpoint(options.baseUrl).replace(/\/v1$/, "");
21290
21427
  if (typeof options.apiKey === "string" && (!options.apiKey || /[\r\n]/.test(options.apiKey)))
21291
21428
  throw new Error("Switcher API key is required.");
21292
21429
  this.options = { ...options };
21430
+ this.retry = retryPolicy(options.retry);
21293
21431
  }
21294
21432
  static fromEnvironment(env = process.env, options = {}) {
21295
21433
  const shared = createClientTransport("switcher", env, {
@@ -21324,15 +21462,30 @@ class SwitcherClient {
21324
21462
  throw new Error("Shared credential transport was not invoked.");
21325
21463
  } });
21326
21464
  client.transport = shared.client;
21465
+ client.retry = retryPolicy(options.retry);
21327
21466
  return client;
21328
21467
  }
21329
21468
  async request(method, path, body, options = {}) {
21330
21469
  if (!/^\/v1\/[a-zA-Z0-9/?&=._%+-]+$/.test(path) && !["/health", "/ready", "/version"].includes(path) || path.includes(".."))
21331
21470
  throw new Error("Invalid API path.");
21471
+ const key = method === "GET" ? undefined : options.idempotencyKey ?? crypto.randomUUID();
21472
+ const policy = method === "GET" || options.idempotencyKey !== undefined ? this.retry : undefined;
21473
+ for (let attempt = 0;; attempt++) {
21474
+ try {
21475
+ return await this.send(method, path, body, options.version, key);
21476
+ } catch (error62) {
21477
+ if (!policy || attempt >= policy.retries || !edgeFailure(error62))
21478
+ throw error62;
21479
+ const delay = policy.baseDelayMs * 2 ** attempt;
21480
+ await policy.sleep(Math.min(policy.maxDelayMs, delay + Math.floor(Math.random() * (delay / 2 + 1))));
21481
+ }
21482
+ }
21483
+ }
21484
+ async send(method, path, body, version3, idempotencyKey) {
21332
21485
  if (this.transport)
21333
21486
  return this.transport.request(method, path.startsWith("/v1/") ? path.slice(3) : path, body, {
21334
- idempotencyKey: method === "GET" ? undefined : options.idempotencyKey ?? crypto.randomUUID(),
21335
- headers: options.version === undefined ? undefined : { "if-match": String(options.version) },
21487
+ idempotencyKey,
21488
+ headers: version3 === undefined ? undefined : { "if-match": String(version3) },
21336
21489
  retry: false
21337
21490
  });
21338
21491
  const apiKey = typeof this.options.apiKey === "function" ? this.options.apiKey() : this.options.apiKey;
@@ -21341,10 +21494,10 @@ class SwitcherClient {
21341
21494
  const headers = { authorization: `Bearer ${apiKey}`, accept: "application/json" };
21342
21495
  if (body !== undefined)
21343
21496
  headers["content-type"] = "application/json";
21344
- if (method !== "GET")
21345
- headers["idempotency-key"] = options.idempotencyKey ?? crypto.randomUUID();
21346
- if (options.version !== undefined)
21347
- headers["if-match"] = String(options.version);
21497
+ if (idempotencyKey !== undefined)
21498
+ headers["idempotency-key"] = idempotencyKey;
21499
+ if (version3 !== undefined)
21500
+ headers["if-match"] = String(version3);
21348
21501
  let response;
21349
21502
  try {
21350
21503
  response = await (this.options.fetch ?? fetch)(`${this.baseUrl}${path}`, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), redirect: "manual", signal: AbortSignal.timeout(this.options.timeoutMs ?? 120000) });
@@ -21386,13 +21539,13 @@ class SwitcherClient {
21386
21539
  return this.request("GET", `/v1/providers/${encodeURIComponent(id)}`);
21387
21540
  }
21388
21541
  createProvider(input2, idempotencyKey) {
21389
- return this.request("POST", "/v1/providers", input2, { idempotencyKey });
21542
+ return this.request("POST", "/v1/providers", input2, { idempotencyKey: operationKey(idempotencyKey) });
21390
21543
  }
21391
21544
  updateProvider(input2, version3, idempotencyKey) {
21392
- return this.request("PUT", `/v1/providers/${encodeURIComponent(input2.id)}`, input2, { version: version3, idempotencyKey });
21545
+ return this.request("PUT", `/v1/providers/${encodeURIComponent(input2.id)}`, input2, { version: version3, idempotencyKey: operationKey(idempotencyKey) });
21393
21546
  }
21394
21547
  deleteProvider(id, version3, idempotencyKey) {
21395
- return this.request("DELETE", `/v1/providers/${encodeURIComponent(id)}`, undefined, { version: version3, idempotencyKey });
21548
+ return this.request("DELETE", `/v1/providers/${encodeURIComponent(id)}`, undefined, { version: version3, idempotencyKey: operationKey(idempotencyKey) });
21396
21549
  }
21397
21550
  async editModel(providerId, operation, value) {
21398
21551
  const model = typeof value === "string" ? undefined : parse5(modelSchema, value);
@@ -21422,10 +21575,10 @@ class SwitcherClient {
21422
21575
  return this.editModel(providerId, "remove", modelId);
21423
21576
  }
21424
21577
  refreshModels(id, idempotencyKey) {
21425
- return this.request("POST", `/v1/providers/${encodeURIComponent(id)}/refresh`, {}, { idempotencyKey });
21578
+ return this.request("POST", `/v1/providers/${encodeURIComponent(id)}/refresh`, {}, { idempotencyKey: operationKey(idempotencyKey) });
21426
21579
  }
21427
21580
  saveCatalog(id, providerVersion, catalog, idempotencyKey) {
21428
- return this.request("PUT", `/v1/providers/${encodeURIComponent(id)}/catalog`, catalog, { version: providerVersion, idempotencyKey });
21581
+ return this.request("PUT", `/v1/providers/${encodeURIComponent(id)}/catalog`, catalog, { version: providerVersion, idempotencyKey: operationKey(idempotencyKey) });
21429
21582
  }
21430
21583
  listModels(id, options = {}) {
21431
21584
  return this.request("GET", `/v1/providers/${encodeURIComponent(id)}/models?${this.query(options)}`);
@@ -21437,16 +21590,16 @@ class SwitcherClient {
21437
21590
  return this.request("GET", `/v1/profiles/${encodeURIComponent(id)}`);
21438
21591
  }
21439
21592
  createProfile(input2, idempotencyKey) {
21440
- return this.request("POST", "/v1/profiles", input2, { idempotencyKey });
21593
+ return this.request("POST", "/v1/profiles", input2, { idempotencyKey: operationKey(idempotencyKey) });
21441
21594
  }
21442
21595
  updateProfile(input2, version3, idempotencyKey) {
21443
- return this.request("PUT", `/v1/profiles/${encodeURIComponent(input2.id)}`, input2, { version: version3, idempotencyKey });
21596
+ return this.request("PUT", `/v1/profiles/${encodeURIComponent(input2.id)}`, input2, { version: version3, idempotencyKey: operationKey(idempotencyKey) });
21444
21597
  }
21445
21598
  deleteProfile(id, version3, idempotencyKey) {
21446
- return this.request("DELETE", `/v1/profiles/${encodeURIComponent(id)}`, undefined, { version: version3, idempotencyKey });
21599
+ return this.request("DELETE", `/v1/profiles/${encodeURIComponent(id)}`, undefined, { version: version3, idempotencyKey: operationKey(idempotencyKey) });
21447
21600
  }
21448
21601
  launchPlan(profileId, idempotencyKey) {
21449
- return this.request("POST", "/v1/launch-plans", { profileId }, { idempotencyKey });
21602
+ return this.request("POST", "/v1/launch-plans", { profileId }, { idempotencyKey: operationKey(idempotencyKey) });
21450
21603
  }
21451
21604
  listRuns(options = {}) {
21452
21605
  return this.request("GET", `/v1/runs?${this.query(options)}`);
@@ -21455,10 +21608,10 @@ class SwitcherClient {
21455
21608
  return this.request("GET", `/v1/runs/${encodeURIComponent(id)}`);
21456
21609
  }
21457
21610
  createRun(input2, idempotencyKey) {
21458
- return this.request("POST", "/v1/runs", { ...input2, modelPolicyVersion: 1 }, { idempotencyKey });
21611
+ return this.request("POST", "/v1/runs", { ...input2, modelPolicyVersion: 1 }, { idempotencyKey: operationKey(idempotencyKey) });
21459
21612
  }
21460
21613
  finishRun(id, version3, input2, idempotencyKey) {
21461
- return this.request("PATCH", `/v1/runs/${encodeURIComponent(id)}`, input2, { version: version3, idempotencyKey });
21614
+ return this.request("PATCH", `/v1/runs/${encodeURIComponent(id)}`, input2, { version: version3, idempotencyKey: operationKey(idempotencyKey) });
21462
21615
  }
21463
21616
  }
21464
21617
  function clientFromEnv(env = process.env, options = {}) {
@@ -41,6 +41,8 @@ export type GatewayHost = {
41
41
  export type InferenceHandlerOptions = {
42
42
  /** Resolve the provider credential when a request needs it; replaces input.credential. */
43
43
  credential?: () => Promise<string | undefined>;
44
+ /** Receives one line per refused provider request and per rewritten DeepSeek request (the persistent service writes it to its log with a timestamp). */
45
+ log?: (line: string) => void;
44
46
  };
45
47
  /** close aborts requests in flight; drain refuses new ones and lets those in flight finish. */
46
48
  export type InferenceHandler = {
@@ -54,7 +56,7 @@ export declare const MAX_REQUEST_BODY_BYTES: number;
54
56
  /** A launch's credential boundary and model policy, independent of the listener that serves it. */
55
57
  export declare function createInferenceHandler(input: GatewayInput, timing?: ProviderRequestTiming, options?: InferenceHandlerOptions): InferenceHandler;
56
58
  /** A per-launch credential boundary: the native client never receives the provider key. */
57
- export declare function createInferenceGateway(input: GatewayInput, timing?: ProviderRequestTiming): {
59
+ export declare function createInferenceGateway(input: GatewayInput, timing?: ProviderRequestTiming, options?: InferenceHandlerOptions): {
58
60
  baseUrl: string;
59
61
  token: string;
60
62
  cleanup: () => Promise<void>;
@@ -12,11 +12,23 @@ export type LaunchBackend = "direct" | "ori";
12
12
  export type GatewayMode = "local" | "service";
13
13
  /** service: register with the persistent per-user gateway so detached descendants keep working. */
14
14
  /** gatewaySupervise: false keeps a non-PATH switcher (a development checkout) from installing the login service. */
15
+ /**
16
+ * requireDurableRoute: refuse (Fault gateway_route_unavailable) instead of falling back to a
17
+ * per-launch gateway, for a launch whose harness is started later by another process.
18
+ */
15
19
  export type LaunchGatewayOptions = {
16
20
  gateway?: GatewayMode;
17
21
  gatewayCommand?: string[];
18
22
  gatewaySupervise?: boolean;
19
23
  connectGateway?: () => Promise<GatewayControlClient>;
24
+ requireDurableRoute?: boolean;
25
+ };
26
+ /** What a launch would start: the native executable, its arguments, the environment it adds (values included) and its working directory. */
27
+ export type PreparedHarness = {
28
+ executable: string;
29
+ args: string[];
30
+ env: Record<string, string>;
31
+ cwd: string;
20
32
  };
21
33
  export type LaunchOptions = LaunchGatewayOptions & {
22
34
  desktop?: ChatGPTInstallation;
@@ -35,6 +47,12 @@ export type LaunchOptions = LaunchGatewayOptions & {
35
47
  credentialEnv?: NodeJS.ProcessEnv;
36
48
  credentialPreflight?: string;
37
49
  resolveCredential?: (provider: ProviderInput) => Promise<string | undefined>;
50
+ /**
51
+ * Prepare everything a launch needs (gateway lease, route and settings files, native state)
52
+ * and hand it to this callback instead of starting the harness. The lease is then released,
53
+ * not revoked, so its durable route stays usable for the process the caller starts.
54
+ */
55
+ prepareOnly?: (prepared: PreparedHarness) => Promise<void>;
38
56
  };
39
57
  type OriPreparationOptions = Pick<LaunchOptions, "oriExecutable" | "args" | "resolveCredential" | "credentialEnv"> & {
40
58
  stateDir?: string;