@hasna/switcher 0.2.23 → 0.2.25

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/sdk.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 = {}) {
@@ -68,7 +68,7 @@ function canonicalPolicyJSON(value) {
68
68
  return JSON.stringify(value, (_key, item) => item && typeof item === "object" && !Array.isArray(item) ? Object.fromEntries(Object.entries(item).sort(([a], [b]) => a.localeCompare(b))) : item);
69
69
  }
70
70
  // package.json
71
- var version = "0.2.23";
71
+ var version = "0.2.25";
72
72
 
73
73
  // src/version.ts
74
74
  var VERSION = version;
@@ -922,7 +922,7 @@ var openapi_default = {
922
922
  openapi: "3.0.3",
923
923
  info: {
924
924
  title: "Switcher API",
925
- version: "0.2.23",
925
+ version: "0.2.25",
926
926
  description: "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
927
927
  },
928
928
  security: [
package/openapi.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "openapi": "3.0.3",
3
3
  "info": {
4
4
  "title": "Switcher API",
5
- "version": "0.2.23",
5
+ "version": "0.2.25",
6
6
  "description": "Authenticated provider/profile/catalog control plane. Launches run locally; the API never returns provider credentials."
7
7
  },
8
8
  "security": [
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@hasna/switcher",
3
- "version": "0.2.23",
3
+ "version": "0.2.25",
4
4
  "type": "module",
5
5
  "description": "Universal provider and model switcher for coding harnesses with an API, SDK and self-hosted storage",
6
6
  "license": "Apache-2.0",