@vtxmacro/cli 2026.9.44 → 2026.9.46

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/bin/vtx.js CHANGED
@@ -77,7 +77,7 @@ var init_agent_cli_release = __esm({
77
77
  "agent-cli-release.json"() {
78
78
  agent_cli_release_default = {
79
79
  package_name: "@vtxmacro/cli",
80
- package_version: "2026.9.44",
80
+ package_version: "2026.9.46",
81
81
  codex_package_name: "@openai/codex",
82
82
  codex_version: "0.153.3",
83
83
  copilot_sdk_package_name: "@github/copilot-sdk",
@@ -18351,17 +18351,17 @@ while(($line=[Console]::In.ReadLine()) -ne $null) {
18351
18351
  clearTimeout(this.idleTimer);
18352
18352
  this.idleTimer = null;
18353
18353
  }
18354
- const pending2 = this.pending;
18354
+ const pending3 = this.pending;
18355
18355
  this.pending = null;
18356
- if (pending2) {
18357
- clearTimeout(pending2.timer);
18358
- pending2.reject(error48);
18356
+ if (pending3) {
18357
+ clearTimeout(pending3.timer);
18358
+ pending3.reject(error48);
18359
18359
  }
18360
18360
  child.kill("SIGKILL");
18361
18361
  }
18362
18362
  acceptLine(child, line) {
18363
- const pending2 = this.pending;
18364
- if (!pending2 || !line || line.length > 4096) {
18363
+ const pending3 = this.pending;
18364
+ if (!pending3 || !line || line.length > 4096) {
18365
18365
  this.failChild(child, new Error("Windows private ACL broker returned malformed output."));
18366
18366
  return;
18367
18367
  }
@@ -18370,7 +18370,7 @@ while(($line=[Console]::In.ReadLine()) -ne $null) {
18370
18370
  const parsed = JSON.parse(line);
18371
18371
  const status = String(parsed.status);
18372
18372
  const expectedKeys = status === "error" ? "error_code\0id\0status" : "id\0status";
18373
- if (Object.keys(parsed).sort().join("\0") !== expectedKeys || parsed.id !== pending2.id || !["ok", "missing", "error"].includes(status) || status === "error" && ![
18373
+ if (Object.keys(parsed).sort().join("\0") !== expectedKeys || parsed.id !== pending3.id || !["ok", "missing", "error"].includes(status) || status === "error" && ![
18374
18374
  "request_validation",
18375
18375
  "path_lookup",
18376
18376
  "principal_resolution",
@@ -18387,16 +18387,16 @@ while(($line=[Console]::In.ReadLine()) -ne $null) {
18387
18387
  return;
18388
18388
  }
18389
18389
  this.pending = null;
18390
- clearTimeout(pending2.timer);
18390
+ clearTimeout(pending3.timer);
18391
18391
  if (response.status === "ok") {
18392
- pending2.resolve();
18392
+ pending3.resolve();
18393
18393
  } else if (response.status === "missing") {
18394
18394
  const error48 = new Error("Windows private path no longer exists.");
18395
18395
  error48.code = "ENOENT";
18396
- pending2.reject(error48);
18396
+ pending3.reject(error48);
18397
18397
  } else {
18398
- pending2.reject(new Error(
18399
- `Windows private ACL ${pending2.mode} failed (${response.error_code}).`
18398
+ pending3.reject(new Error(
18399
+ `Windows private ACL ${pending3.mode} failed (${response.error_code}).`
18400
18400
  ));
18401
18401
  }
18402
18402
  this.scheduleIdleShutdown();
@@ -18707,10 +18707,10 @@ while(($line=[Console]::In.ReadLine()) -ne $null) {
18707
18707
  }
18708
18708
  return `${platform}:${identity2}`;
18709
18709
  };
18710
- const pending2 = read();
18711
- if (platform === process.platform) cachedSystemBootIdentity = pending2;
18710
+ const pending3 = read();
18711
+ if (platform === process.platform) cachedSystemBootIdentity = pending3;
18712
18712
  try {
18713
- return await pending2;
18713
+ return await pending3;
18714
18714
  } catch (error48) {
18715
18715
  if (platform === process.platform) cachedSystemBootIdentity = null;
18716
18716
  throw error48;
@@ -28801,8 +28801,8 @@ child.once('close', async (code, signal) => {
28801
28801
  }
28802
28802
  const id2 = message.id;
28803
28803
  if (typeof id2 === "number" && Number.isSafeInteger(id2) && !("method" in message)) {
28804
- const pending2 = this.pending.get(id2);
28805
- if (!pending2) {
28804
+ const pending3 = this.pending.get(id2);
28805
+ if (!pending3) {
28806
28806
  const retiredMethod = this.retiredResponseIds.get(id2);
28807
28807
  this.retiredResponseIds.delete(id2);
28808
28808
  if (retiredMethod && LATE_RESPONSE_SAFE_METHODS.has(retiredMethod)) {
@@ -28816,11 +28816,11 @@ child.once('close', async (code, signal) => {
28816
28816
  return;
28817
28817
  }
28818
28818
  this.pending.delete(id2);
28819
- if (pending2.timer) clearTimeout(pending2.timer);
28820
- pending2.abortCleanup?.();
28819
+ if (pending3.timer) clearTimeout(pending3.timer);
28820
+ pending3.abortCleanup?.();
28821
28821
  const error48 = objectOrNull(message.error);
28822
28822
  if (error48) {
28823
- pending2.reject(new CodexAppServerError({
28823
+ pending3.reject(new CodexAppServerError({
28824
28824
  message: "Codex app-server rejected a request.",
28825
28825
  category: "adapter",
28826
28826
  code: "rpc_rejected",
@@ -28830,7 +28830,7 @@ child.once('close', async (code, signal) => {
28830
28830
  }
28831
28831
  const result2 = objectOrNull(message.result);
28832
28832
  if (!result2) {
28833
- pending2.reject(new CodexAppServerError({
28833
+ pending3.reject(new CodexAppServerError({
28834
28834
  message: "Codex app-server returned an invalid result.",
28835
28835
  category: "adapter",
28836
28836
  code: "invalid_rpc_result",
@@ -28838,7 +28838,7 @@ child.once('close', async (code, signal) => {
28838
28838
  }));
28839
28839
  return;
28840
28840
  }
28841
- pending2.resolve(result2);
28841
+ pending3.resolve(result2);
28842
28842
  return;
28843
28843
  }
28844
28844
  const method = typeof message.method === "string" ? message.method : "";
@@ -28923,10 +28923,10 @@ child.once('close', async (code, signal) => {
28923
28923
  retryable: true,
28924
28924
  processExit
28925
28925
  });
28926
- for (const pending2 of this.pending.values()) {
28927
- if (pending2.timer) clearTimeout(pending2.timer);
28928
- pending2.abortCleanup?.();
28929
- pending2.reject(this.fatalError);
28926
+ for (const pending3 of this.pending.values()) {
28927
+ if (pending3.timer) clearTimeout(pending3.timer);
28928
+ pending3.abortCleanup?.();
28929
+ pending3.reject(this.fatalError);
28930
28930
  }
28931
28931
  this.pending.clear();
28932
28932
  for (const listener of this.fatalListeners) listener(this.fatalError);
@@ -28985,11 +28985,11 @@ child.once('close', async (code, signal) => {
28985
28985
  });
28986
28986
  }
28987
28987
  return await new Promise((resolve12, reject) => {
28988
- const pending2 = { resolve: resolve12, reject, timer: null, abortCleanup: null };
28989
- pending2.timer = setTimeout(() => {
28988
+ const pending3 = { resolve: resolve12, reject, timer: null, abortCleanup: null };
28989
+ pending3.timer = setTimeout(() => {
28990
28990
  this.pending.delete(id2);
28991
28991
  this.retireResponseId(id2, method);
28992
- pending2.abortCleanup?.();
28992
+ pending3.abortCleanup?.();
28993
28993
  reject(new CodexAppServerError({
28994
28994
  message: "Codex app-server request timed out.",
28995
28995
  category: "timeout",
@@ -29001,8 +29001,8 @@ child.once('close', async (code, signal) => {
29001
29001
  const onAbort = () => {
29002
29002
  this.pending.delete(id2);
29003
29003
  this.retireResponseId(id2, method);
29004
- if (pending2.timer) clearTimeout(pending2.timer);
29005
- pending2.abortCleanup?.();
29004
+ if (pending3.timer) clearTimeout(pending3.timer);
29005
+ pending3.abortCleanup?.();
29006
29006
  reject(new CodexAppServerError({
29007
29007
  message: "Codex request was cancelled.",
29008
29008
  category: "cancelled",
@@ -29011,16 +29011,16 @@ child.once('close', async (code, signal) => {
29011
29011
  }));
29012
29012
  };
29013
29013
  options.signal.addEventListener("abort", onAbort, { once: true });
29014
- pending2.abortCleanup = () => options.signal?.removeEventListener("abort", onAbort);
29014
+ pending3.abortCleanup = () => options.signal?.removeEventListener("abort", onAbort);
29015
29015
  }
29016
- this.pending.set(id2, pending2);
29016
+ this.pending.set(id2, pending3);
29017
29017
  try {
29018
29018
  this.write(params === void 0 ? { id: id2, method } : { id: id2, method, params });
29019
29019
  options.onWritten?.(id2);
29020
29020
  } catch (error48) {
29021
29021
  this.pending.delete(id2);
29022
- if (pending2.timer) clearTimeout(pending2.timer);
29023
- pending2.abortCleanup?.();
29022
+ if (pending3.timer) clearTimeout(pending3.timer);
29023
+ pending3.abortCleanup?.();
29024
29024
  reject(error48);
29025
29025
  }
29026
29026
  });
@@ -30535,15 +30535,15 @@ var init_agent_state = __esm({
30535
30535
  }
30536
30536
  }
30537
30537
  if (state.pending_decision !== null) {
30538
- const pending2 = assertPlainObject(state.pending_decision, message);
30539
- if (!hasExactKeys(pending2, [
30538
+ const pending3 = assertPlainObject(state.pending_decision, message);
30539
+ if (!hasExactKeys(pending3, [
30540
30540
  "operation_id",
30541
30541
  "candidate",
30542
30542
  "observed_at",
30543
30543
  "provenance",
30544
30544
  "first_transmit_at",
30545
30545
  "last_status_check_at"
30546
- ]) || typeof pending2.operation_id !== "string" || !pending2.operation_id || !pending2.candidate || typeof pending2.candidate !== "object" || Array.isArray(pending2.candidate) || !isIsoTimestamp(pending2.observed_at) || pending2.provenance !== null && (typeof pending2.provenance !== "object" || Array.isArray(pending2.provenance)) || pending2.first_transmit_at !== null && !isIsoTimestamp(pending2.first_transmit_at) || pending2.last_status_check_at !== null && !isIsoTimestamp(pending2.last_status_check_at)) throw new Error(message);
30546
+ ]) || typeof pending3.operation_id !== "string" || !pending3.operation_id || !pending3.candidate || typeof pending3.candidate !== "object" || Array.isArray(pending3.candidate) || !isIsoTimestamp(pending3.observed_at) || pending3.provenance !== null && (typeof pending3.provenance !== "object" || Array.isArray(pending3.provenance)) || pending3.first_transmit_at !== null && !isIsoTimestamp(pending3.first_transmit_at) || pending3.last_status_check_at !== null && !isIsoTimestamp(pending3.last_status_check_at)) throw new Error(message);
30547
30547
  }
30548
30548
  return state;
30549
30549
  };
@@ -30594,18 +30594,18 @@ var init_agent_state = __esm({
30594
30594
  ]) || state.schema_version !== "vtx_foreground_agent_control_v1" || typeof state.host_id !== "string" || !state.host_id || state.next_wake_at !== null && !isIsoTimestamp(state.next_wake_at) || !isIsoTimestamp(state.updated_at)) throw new Error(message);
30595
30595
  if (state.assignment !== null) assertRuntimeAssignment(state.assignment, message);
30596
30596
  if (state.pending_next !== null) {
30597
- const pending2 = assertPlainObject(state.pending_next, message);
30598
- if (!hasExactKeys(pending2, ["operation_id", "requested_at"]) || typeof pending2.operation_id !== "string" || !pending2.operation_id || !isIsoTimestamp(pending2.requested_at)) throw new Error(message);
30597
+ const pending3 = assertPlainObject(state.pending_next, message);
30598
+ if (!hasExactKeys(pending3, ["operation_id", "requested_at"]) || typeof pending3.operation_id !== "string" || !pending3.operation_id || !isIsoTimestamp(pending3.requested_at)) throw new Error(message);
30599
30599
  }
30600
30600
  if (state.pending_decision !== null) {
30601
30601
  if (state.assignment === null) throw new Error(message);
30602
- const pending2 = assertPlainObject(state.pending_decision, message);
30603
- if (!hasExactKeys(pending2, [
30602
+ const pending3 = assertPlainObject(state.pending_decision, message);
30603
+ if (!hasExactKeys(pending3, [
30604
30604
  "request",
30605
30605
  "first_transmit_at",
30606
30606
  "last_status_check_at"
30607
30607
  ])) throw new Error(message);
30608
- const request = assertPlainObject(pending2.request, message);
30608
+ const request = assertPlainObject(pending3.request, message);
30609
30609
  if (!hasExactKeys(request, [
30610
30610
  "assignment_id",
30611
30611
  "assignment_generation",
@@ -30613,7 +30613,7 @@ var init_agent_state = __esm({
30613
30613
  "candidate",
30614
30614
  "observed_at",
30615
30615
  "provenance"
30616
- ]) || request.assignment_id !== state.assignment.assignment_id || request.assignment_generation !== state.assignment.assignment_generation || typeof request.operation_id !== "string" || !request.operation_id || !request.candidate || typeof request.candidate !== "object" || Array.isArray(request.candidate) || !isIsoTimestamp(request.observed_at) || !request.provenance || typeof request.provenance !== "object" || Array.isArray(request.provenance) || pending2.first_transmit_at !== null && !isIsoTimestamp(pending2.first_transmit_at) || pending2.last_status_check_at !== null && !isIsoTimestamp(pending2.last_status_check_at)) throw new Error(message);
30616
+ ]) || request.assignment_id !== state.assignment.assignment_id || request.assignment_generation !== state.assignment.assignment_generation || typeof request.operation_id !== "string" || !request.operation_id || !request.candidate || typeof request.candidate !== "object" || Array.isArray(request.candidate) || !isIsoTimestamp(request.observed_at) || !request.provenance || typeof request.provenance !== "object" || Array.isArray(request.provenance) || pending3.first_transmit_at !== null && !isIsoTimestamp(pending3.first_transmit_at) || pending3.last_status_check_at !== null && !isIsoTimestamp(pending3.last_status_check_at)) throw new Error(message);
30617
30617
  }
30618
30618
  return state;
30619
30619
  };
@@ -30663,12 +30663,12 @@ var init_agent_state = __esm({
30663
30663
  if (Object.keys(record5).sort().join("\0") !== exactKeys.slice().sort().join("\0") || record5.schema_version !== "vtx_inference_agent_attempt_v1" || typeof record5.host_id !== "string" || !record5.host_id || typeof record5.job_id !== "string" || !record5.job_id || typeof record5.attempt_id !== "string" || !record5.attempt_id || typeof record5.claim_handle !== "string" || !record5.claim_handle || typeof record5.completion_operation_id !== "string" || !record5.completion_operation_id || typeof record5.failure_operation_id !== "string" || !record5.failure_operation_id || typeof record5.requested_model !== "string" || !record5.requested_model || typeof record5.requested_reasoning_effort !== "string" || !record5.requested_reasoning_effort || !["provider_response", "decision_candidate"].includes(String(record5.response_mode)) || typeof record5.deadline_at !== "string" || !Number.isFinite(Date.parse(record5.deadline_at)) || typeof record5.received_at !== "string" || !Number.isFinite(Date.parse(record5.received_at))) {
30664
30664
  throw new Error("Agent-driven inference attempt state is invalid.");
30665
30665
  }
30666
- const pending2 = record5.pending_terminal;
30667
- if (pending2 !== null) {
30668
- if (!pending2 || typeof pending2 !== "object" || Array.isArray(pending2)) {
30666
+ const pending3 = record5.pending_terminal;
30667
+ if (pending3 !== null) {
30668
+ if (!pending3 || typeof pending3 !== "object" || Array.isArray(pending3)) {
30669
30669
  throw new Error("Agent-driven inference terminal recovery state is invalid.");
30670
30670
  }
30671
- const terminal = pending2;
30671
+ const terminal = pending3;
30672
30672
  if (Object.keys(terminal).sort().join("\0") !== ["kind", "request"].sort().join("\0")) {
30673
30673
  throw new Error("Agent-driven inference terminal recovery state is invalid.");
30674
30674
  }
@@ -34473,7 +34473,7 @@ var init_runner = __esm({
34473
34473
  if (state.pending_decision) {
34474
34474
  return { success: false, value: { error: "decision_outcome_unresolved" } };
34475
34475
  }
34476
- const pending2 = {
34476
+ const pending3 = {
34477
34477
  operation_id: randomUUID(),
34478
34478
  candidate,
34479
34479
  observed_at: nowIso(),
@@ -34492,17 +34492,17 @@ var init_runner = __esm({
34492
34492
  if (state.pending_turn.decision_operation_ids.length >= 128) {
34493
34493
  return { success: false, value: { error: "agent_turn_decision_limit" } };
34494
34494
  }
34495
- state = { ...state, pending_decision: pending2, pending_turn: {
34495
+ state = { ...state, pending_decision: pending3, pending_turn: {
34496
34496
  ...state.pending_turn,
34497
34497
  decision_operation_ids: [
34498
34498
  ...state.pending_turn.decision_operation_ids,
34499
- pending2.operation_id
34499
+ pending3.operation_id
34500
34500
  ]
34501
34501
  }, updated_at: nowIso() };
34502
34502
  await writeInferenceAgentRuntimeState(this.options.statePath, state);
34503
34503
  state = {
34504
34504
  ...state,
34505
- pending_decision: { ...pending2, first_transmit_at: nowIso() },
34505
+ pending_decision: { ...pending3, first_transmit_at: nowIso() },
34506
34506
  updated_at: nowIso()
34507
34507
  };
34508
34508
  await writeInferenceAgentRuntimeState(this.options.statePath, state);
@@ -34511,10 +34511,10 @@ var init_runner = __esm({
34511
34511
  submitStatus = await this.options.controlClient.submitDecision({
34512
34512
  assignment_id: assignment.assignment_id,
34513
34513
  assignment_generation: assignment.assignment_generation,
34514
- operation_id: pending2.operation_id,
34515
- candidate: pending2.candidate,
34516
- observed_at: pending2.observed_at,
34517
- provenance: pending2.provenance
34514
+ operation_id: pending3.operation_id,
34515
+ candidate: pending3.candidate,
34516
+ observed_at: pending3.observed_at,
34517
+ provenance: pending3.provenance
34518
34518
  }, { signal: turnAbort.signal });
34519
34519
  } catch {
34520
34520
  const recovery = {};
@@ -34716,12 +34716,12 @@ var init_runner = __esm({
34716
34716
  return null;
34717
34717
  }
34718
34718
  async resolveLegacyPendingDecision(state, signal) {
34719
- const pending2 = state.pending_decision;
34720
- if (!pending2) return state;
34719
+ const pending3 = state.pending_decision;
34720
+ if (!pending3) return state;
34721
34721
  const checkedAt = new Date(this.now()).toISOString();
34722
34722
  const checking = {
34723
34723
  ...state,
34724
- pending_decision: { ...pending2, last_status_check_at: checkedAt },
34724
+ pending_decision: { ...pending3, last_status_check_at: checkedAt },
34725
34725
  updated_at: checkedAt
34726
34726
  };
34727
34727
  await writeInferenceAgentRuntimeState(this.options.statePath, checking);
@@ -34729,7 +34729,7 @@ var init_runner = __esm({
34729
34729
  host_id: this.options.hostId,
34730
34730
  assignment_id: state.assignment.assignment_id,
34731
34731
  assignment_generation: state.assignment.assignment_generation,
34732
- operation_id: pending2.operation_id
34732
+ operation_id: pending3.operation_id
34733
34733
  }, { signal });
34734
34734
  if (status.status !== "applied" && status.status !== "not_applied") return checking;
34735
34735
  const resolved = {
@@ -34741,12 +34741,12 @@ var init_runner = __esm({
34741
34741
  return resolved;
34742
34742
  }
34743
34743
  async resolvePendingDecision(state, signal, onStatus) {
34744
- const pending2 = state.pending_decision;
34745
- if (!pending2) return state;
34744
+ const pending3 = state.pending_decision;
34745
+ if (!pending3) return state;
34746
34746
  const checkedAt = new Date(this.now()).toISOString();
34747
34747
  const checking = {
34748
34748
  ...state,
34749
- pending_decision: { ...pending2, last_status_check_at: checkedAt },
34749
+ pending_decision: { ...pending3, last_status_check_at: checkedAt },
34750
34750
  updated_at: checkedAt
34751
34751
  };
34752
34752
  await writeInferenceAgentRuntimeState(this.options.statePath, checking);
@@ -34754,7 +34754,7 @@ var init_runner = __esm({
34754
34754
  host_id: this.options.hostId,
34755
34755
  assignment_id: state.assignment.assignment_id,
34756
34756
  assignment_generation: state.assignment.assignment_generation,
34757
- operation_id: pending2.operation_id
34757
+ operation_id: pending3.operation_id
34758
34758
  }, { signal });
34759
34759
  onStatus?.(status);
34760
34760
  if (status.status !== "applied" && status.status !== "not_applied") return checking;
@@ -34968,18 +34968,18 @@ async function reauthorizeInferenceHost(options) {
34968
34968
  return options.state;
34969
34969
  }
34970
34970
  const pair = generateExternalInferenceEnvelopeKeyPair();
34971
- const pending2 = await (options.beginLogin ?? beginInferenceOAuthLogin)({
34971
+ const pending3 = await (options.beginLogin ?? beginInferenceOAuthLogin)({
34972
34972
  apiUrl: config2.apiUrl,
34973
34973
  hostId: previous.host_id,
34974
34974
  keyGeneration: previous.key_generation + 1,
34975
34975
  x25519PrivateKey: pair.private_key,
34976
34976
  store: stagedStore
34977
34977
  });
34978
- options.emitAuthorization(pending2.authorizationUrl);
34978
+ options.emitAuthorization(pending3.authorizationUrl);
34979
34979
  try {
34980
- access5 = await pending2.completion;
34980
+ access5 = await pending3.completion;
34981
34981
  } catch (error48) {
34982
- await pending2.cancel().catch(() => void 0);
34982
+ await pending3.cancel().catch(() => void 0);
34983
34983
  throw error48;
34984
34984
  }
34985
34985
  candidate = await store.readRecovery();
@@ -35510,9 +35510,9 @@ var init_codex_adapter = __esm({
35510
35510
  return document2.attempts;
35511
35511
  }
35512
35512
  enqueue(operation) {
35513
- const pending2 = this.queue.then(operation, operation);
35514
- this.queue = pending2.then(() => void 0, () => void 0);
35515
- return pending2;
35513
+ const pending3 = this.queue.then(operation, operation);
35514
+ this.queue = pending3.then(() => void 0, () => void 0);
35515
+ return pending3;
35516
35516
  }
35517
35517
  async load(attemptId) {
35518
35518
  await this.queue;
@@ -37810,7 +37810,7 @@ var init_deepseek_transport_proxy = __esm({
37810
37810
  }
37811
37811
  const reader = upstream.body.getReader();
37812
37812
  const decoder2 = new TextDecoder();
37813
- let pending2 = "";
37813
+ let pending3 = "";
37814
37814
  let observedId = "";
37815
37815
  let observedModel = "";
37816
37816
  let terminalObserved = false;
@@ -37845,13 +37845,13 @@ var init_deepseek_transport_proxy = __esm({
37845
37845
  while (true) {
37846
37846
  const part = await reader.read();
37847
37847
  if (part.done) break;
37848
- pending2 += decoder2.decode(part.value, { stream: true });
37849
- const lines = pending2.split(/\r?\n/u);
37850
- pending2 = lines.pop() ?? "";
37848
+ pending3 += decoder2.decode(part.value, { stream: true });
37849
+ const lines = pending3.split(/\r?\n/u);
37850
+ pending3 = lines.pop() ?? "";
37851
37851
  for (const line of lines) forwardLine(line);
37852
37852
  }
37853
- pending2 += decoder2.decode();
37854
- if (pending2) forwardLine(pending2);
37853
+ pending3 += decoder2.decode();
37854
+ if (pending3) forwardLine(pending3);
37855
37855
  if (!terminalObserved) {
37856
37856
  throw new Error("deepseek_provider_receipt_missing_or_mismatched");
37857
37857
  }
@@ -38643,7 +38643,7 @@ var init_pi_transport = __esm({
38643
38643
  reasoningEffortChanged: false
38644
38644
  };
38645
38645
  this.receipts.push(receipt);
38646
- let pending2 = "";
38646
+ let pending3 = "";
38647
38647
  const decoder2 = new TextDecoder();
38648
38648
  const inspect3 = (data4) => {
38649
38649
  if (!data4.trim() || data4.trim() === "[DONE]") return;
@@ -38704,9 +38704,9 @@ var init_pi_transport = __esm({
38704
38704
  }
38705
38705
  };
38706
38706
  const consume = (flush = false) => {
38707
- if (pending2.length > 2e6) throw new Error("pi_receipt_event_too_large");
38708
- const events = pending2.split(/\r?\n\r?\n/u);
38709
- pending2 = flush ? "" : events.pop();
38707
+ if (pending3.length > 2e6) throw new Error("pi_receipt_event_too_large");
38708
+ const events = pending3.split(/\r?\n\r?\n/u);
38709
+ pending3 = flush ? "" : events.pop();
38710
38710
  for (const event of events) {
38711
38711
  const data4 = event.split(/\r?\n/u).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n");
38712
38712
  if (data4) inspect3(data4);
@@ -38714,12 +38714,12 @@ var init_pi_transport = __esm({
38714
38714
  };
38715
38715
  const stream = response.body.pipeThrough(new TransformStream({
38716
38716
  transform: (chunk, controller) => {
38717
- pending2 += decoder2.decode(chunk, { stream: true });
38717
+ pending3 += decoder2.decode(chunk, { stream: true });
38718
38718
  consume();
38719
38719
  controller.enqueue(chunk);
38720
38720
  },
38721
38721
  flush: () => {
38722
- pending2 += decoder2.decode();
38722
+ pending3 += decoder2.decode();
38723
38723
  consume(true);
38724
38724
  }
38725
38725
  }));
@@ -39401,18 +39401,18 @@ var init_grok_policy = __esm({
39401
39401
  init_dist();
39402
39402
  validateGrokPolicy = (value) => {
39403
39403
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Grok runtime policy is missing.");
39404
- const policy = value;
39405
- const url2 = new URL(String(policy.subscription_proxy_base_url));
39404
+ const policy2 = value;
39405
+ const url2 = new URL(String(policy2.subscription_proxy_base_url));
39406
39406
  if (url2.protocol !== "https:" || url2.hostname !== "cli-chat-proxy.grok.com" || url2.pathname !== "/v1" || url2.port || url2.search || url2.hash || url2.username || url2.password) throw new Error("Grok subscription endpoint is invalid.");
39407
39407
  for (const key of ["maximum_transport_request_bytes", "maximum_transport_response_bytes"]) {
39408
- if (!Number.isSafeInteger(policy[key]) || Number(policy[key]) < 1 || Number(policy[key]) > 64 * 1024 * 1024) {
39408
+ if (!Number.isSafeInteger(policy2[key]) || Number(policy2[key]) < 1 || Number(policy2[key]) > 64 * 1024 * 1024) {
39409
39409
  throw new Error("Grok transport bounds are missing or invalid.");
39410
39410
  }
39411
39411
  }
39412
39412
  return Object.freeze({
39413
39413
  subscription_proxy_base_url: url2.href,
39414
- maximum_transport_request_bytes: Number(policy.maximum_transport_request_bytes),
39415
- maximum_transport_response_bytes: Number(policy.maximum_transport_response_bytes)
39414
+ maximum_transport_request_bytes: Number(policy2.maximum_transport_request_bytes),
39415
+ maximum_transport_response_bytes: Number(policy2.maximum_transport_response_bytes)
39416
39416
  });
39417
39417
  };
39418
39418
  loadGrokPolicy = async () => {
@@ -39790,7 +39790,7 @@ var init_grok_transport_proxy = __esm({
39790
39790
  const reader = upstream.body.getReader();
39791
39791
  const decoder2 = new TextDecoder();
39792
39792
  let bytes3 = 0;
39793
- let pending2 = "";
39793
+ let pending3 = "";
39794
39794
  let eventData = [];
39795
39795
  let id2 = "";
39796
39796
  let model = "";
@@ -39902,9 +39902,9 @@ var init_grok_transport_proxy = __esm({
39902
39902
  bytes3 += part.value.byteLength;
39903
39903
  if (bytes3 > this.options.maxResponseBytes) throw new Error("grok_response_too_large");
39904
39904
  if (route) {
39905
- pending2 += decoder2.decode(part.value, { stream: true });
39906
- const lines = pending2.split(/\r?\n/u);
39907
- pending2 = lines.pop() ?? "";
39905
+ pending3 += decoder2.decode(part.value, { stream: true });
39906
+ const lines = pending3.split(/\r?\n/u);
39907
+ pending3 = lines.pop() ?? "";
39908
39908
  for (const line of lines) {
39909
39909
  if (!line) inspect3();
39910
39910
  else if (line.startsWith("data:")) eventData.push(line.slice(5));
@@ -39913,8 +39913,8 @@ var init_grok_transport_proxy = __esm({
39913
39913
  if (!response.write(part.value)) await once(response, "drain", { signal });
39914
39914
  }
39915
39915
  if (route) {
39916
- pending2 += decoder2.decode();
39917
- if (pending2.startsWith("data:")) eventData.push(pending2.slice(5));
39916
+ pending3 += decoder2.decode();
39917
+ if (pending3.startsWith("data:")) eventData.push(pending3.slice(5));
39918
39918
  inspect3();
39919
39919
  if (!terminal || !id2 || !model) throw new Error("grok_provider_terminal_missing");
39920
39920
  }
@@ -40614,11 +40614,11 @@ var init_grok_adapter = __esm({
40614
40614
  try {
40615
40615
  signal.throwIfAborted();
40616
40616
  const deadline = Date.now() + 3e4;
40617
- const policy = this.options.policy ?? await loadGrokPolicy();
40617
+ const policy2 = this.options.policy ?? await loadGrokPolicy();
40618
40618
  proxy = await createGrokTransportProxy({
40619
- upstreamBaseUrl: policy.subscription_proxy_base_url,
40620
- maxRequestBytes: policy.maximum_transport_request_bytes,
40621
- maxResponseBytes: policy.maximum_transport_response_bytes,
40619
+ upstreamBaseUrl: policy2.subscription_proxy_base_url,
40620
+ maxRequestBytes: policy2.maximum_transport_request_bytes,
40621
+ maxResponseBytes: policy2.maximum_transport_response_bytes,
40622
40622
  metadataOnly: true,
40623
40623
  requestedModel: "",
40624
40624
  requestedReasoningEffort: "none",
@@ -40693,7 +40693,7 @@ var init_grok_adapter = __esm({
40693
40693
  input.signal.throwIfAborted();
40694
40694
  const startedAt = Date.now();
40695
40695
  const binary = await this.binary();
40696
- const policy = this.options.policy ?? await loadGrokPolicy();
40696
+ const policy2 = this.options.policy ?? await loadGrokPolicy();
40697
40697
  input.signal.throwIfAborted();
40698
40698
  const workspace = agent?.durableThread ? await validateGrokOwnedThread(this.stateOptions, agent.durableThread) : await createGrokOwnedWorkspace(this.stateOptions, agent ? "agent" : "attempt");
40699
40699
  let mcp = null;
@@ -40743,9 +40743,9 @@ var init_grok_adapter = __esm({
40743
40743
  return result3;
40744
40744
  } }) : null;
40745
40745
  proxy = await createGrokTransportProxy({
40746
- upstreamBaseUrl: policy.subscription_proxy_base_url,
40747
- maxRequestBytes: policy.maximum_transport_request_bytes,
40748
- maxResponseBytes: policy.maximum_transport_response_bytes,
40746
+ upstreamBaseUrl: policy2.subscription_proxy_base_url,
40747
+ maxRequestBytes: policy2.maximum_transport_request_bytes,
40748
+ maxResponseBytes: policy2.maximum_transport_response_bytes,
40749
40749
  expectedSystemPrompt: input.systemPrompt,
40750
40750
  requestedModel: input.requestedModel,
40751
40751
  requestedReasoningEffort: input.requestedReasoningEffort,
@@ -40956,7 +40956,7 @@ var init_grok_auth = __esm({
40956
40956
  stdio: ["ignore", "pipe", "pipe"],
40957
40957
  windowsHide: true
40958
40958
  });
40959
- let pending2 = "";
40959
+ let pending3 = "";
40960
40960
  let bytes3 = 0;
40961
40961
  let verificationUrl = "";
40962
40962
  let userCode = "";
@@ -40974,9 +40974,9 @@ var init_grok_auth = __esm({
40974
40974
  stop();
40975
40975
  return;
40976
40976
  }
40977
- pending2 += chunk.toString("utf8");
40978
- const lines = pending2.split(/\r?\n/u);
40979
- pending2 = lines.pop() ?? "";
40977
+ pending3 += chunk.toString("utf8");
40978
+ const lines = pending3.split(/\r?\n/u);
40979
+ pending3 = lines.pop() ?? "";
40980
40980
  for (const line of lines) {
40981
40981
  const clean = line.replace(/\x1b\[[0-9;]*[A-Za-z]/gu, "").trim();
40982
40982
  if (/^https:\/\//u.test(clean)) {
@@ -41444,16 +41444,16 @@ var init_exo_policy = __esm({
41444
41444
  init_define_VTX_PI_MODEL_POLICY();
41445
41445
  init_dist();
41446
41446
  validateExoPolicy = (value) => {
41447
- const policy = value;
41448
- if (!policy || typeof policy !== "object" || Array.isArray(policy) || Object.keys(policy).sort().join(",") !== "endpoints,maximum_tool_rounds,models,upstream_commit" || typeof policy.upstream_commit !== "string" || !/^[a-f0-9]{40}$/u.test(policy.upstream_commit) || !Number.isSafeInteger(policy.maximum_tool_rounds) || policy.maximum_tool_rounds < 1 || policy.maximum_tool_rounds > 64 || !Array.isArray(policy.models) || !policy.models.length || policy.models.length > 64) {
41447
+ const policy2 = value;
41448
+ if (!policy2 || typeof policy2 !== "object" || Array.isArray(policy2) || Object.keys(policy2).sort().join(",") !== "endpoints,maximum_tool_rounds,models,upstream_commit" || typeof policy2.upstream_commit !== "string" || !/^[a-f0-9]{40}$/u.test(policy2.upstream_commit) || !Number.isSafeInteger(policy2.maximum_tool_rounds) || policy2.maximum_tool_rounds < 1 || policy2.maximum_tool_rounds > 64 || !Array.isArray(policy2.models) || !policy2.models.length || policy2.models.length > 64) {
41449
41449
  throw new Error("Exo runtime policy is missing or invalid.");
41450
41450
  }
41451
- if (!policy.endpoints || Object.keys(policy.endpoints).sort().join(",") !== "openai,venice") throw new Error("Exo provider endpoints are invalid.");
41452
- for (const [provider, endpoint] of Object.entries(policy.endpoints)) {
41451
+ if (!policy2.endpoints || Object.keys(policy2.endpoints).sort().join(",") !== "openai,venice") throw new Error("Exo provider endpoints are invalid.");
41452
+ for (const [provider, endpoint] of Object.entries(policy2.endpoints)) {
41453
41453
  const url2 = new URL(endpoint);
41454
41454
  if (url2.protocol !== "https:" || url2.username || url2.password || url2.search || url2.hash || url2.hostname !== (provider === "openai" ? "api.openai.com" : "api.venice.ai") || url2.port || url2.pathname !== (provider === "openai" ? "/v1" : "/api/v1")) throw new Error("Exo provider endpoint is not qualified.");
41455
41455
  }
41456
- const models = policy.models.map((model) => {
41456
+ const models = policy2.models.map((model) => {
41457
41457
  if (!model || typeof model !== "object" || Array.isArray(model) || Object.keys(model).sort().join(",") !== "default_effort,efforts,model,name,reasoning" || typeof model.model !== "string" || !/^(?:openai|venice)\/[A-Za-z0-9][A-Za-z0-9._-]{0,110}$/u.test(model.model) || typeof model.name !== "string" || !model.name.trim() || model.name.length > 128 || typeof model.reasoning !== "boolean" || !Array.isArray(model.efforts) || !model.efforts.length || model.efforts.some((effort2) => typeof effort2 !== "string" || !["none", "minimal", "low", "medium", "high", "xhigh", "max"].includes(effort2)) || new Set(model.efforts).size !== model.efforts.length || !model.efforts.includes(model.default_effort) || !model.reasoning && (model.efforts.length !== 1 || model.efforts[0] !== "none") || model.model.startsWith("venice/") && (model.model !== "venice/google-gemma-4-31b-it" || !model.reasoning || model.efforts.length !== 1 || model.efforts[0] !== "none")) {
41458
41458
  throw new Error("Exo model qualification policy is invalid.");
41459
41459
  }
@@ -41462,7 +41462,7 @@ var init_exo_policy = __esm({
41462
41462
  if (new Set(models.map((model) => model.model)).size !== models.length) {
41463
41463
  throw new Error("Exo policy contains duplicate model identities.");
41464
41464
  }
41465
- return Object.freeze({ ...policy, endpoints: Object.freeze({ ...policy.endpoints }), models: Object.freeze(models) });
41465
+ return Object.freeze({ ...policy2, endpoints: Object.freeze({ ...policy2.endpoints }), models: Object.freeze(models) });
41466
41466
  };
41467
41467
  loadExoPolicy = async () => {
41468
41468
  if (typeof define_VTX_EXO_POLICY_default !== "undefined") return validateExoPolicy(define_VTX_EXO_POLICY_default);
@@ -42028,6 +42028,11 @@ var init_runtime_policy_generated = __esm({
42028
42028
  performance_defaults: {
42029
42029
  default_timeframe: "30d"
42030
42030
  },
42031
+ execution_metadata_retry: {
42032
+ max_attempts: 3,
42033
+ base_delay_milliseconds: 2e3,
42034
+ max_delay_milliseconds: 3e4
42035
+ },
42031
42036
  auth_bootstrap_retry: {
42032
42037
  max_attempts: 3,
42033
42038
  jitter_milliseconds: 750,
@@ -42137,6 +42142,54 @@ var init_runtime_policy_generated = __esm({
42137
42142
  max_inflight: 16,
42138
42143
  max_queue: 64
42139
42144
  }
42145
+ },
42146
+ exchange: {
42147
+ hyperliquid: {
42148
+ client_public_read_budget: {
42149
+ max_weight: 900,
42150
+ window_seconds: 60,
42151
+ cooldown_seconds: 60,
42152
+ metadata_ttl_seconds: 300,
42153
+ user_fees_ttl_seconds: 300,
42154
+ account_mode_ttl_seconds: 30,
42155
+ default_request_weight: 20,
42156
+ cache_max_entries: 512
42157
+ },
42158
+ read_budget: {
42159
+ weights: {
42160
+ exchangeStatus: 2,
42161
+ clearinghouseState: 2,
42162
+ spotClearinghouseState: 2,
42163
+ l2Book: 2,
42164
+ allMids: 2,
42165
+ userFills: 120,
42166
+ userFillsByTime: 120,
42167
+ historicalOrders: 120,
42168
+ twapHistory: 120,
42169
+ userTwapSliceFills: 120,
42170
+ userFunding: 45,
42171
+ userNonFundingLedgerUpdates: 45,
42172
+ candleSnapshot: 104,
42173
+ userRole: 60,
42174
+ userAbstraction: 20,
42175
+ userDexAbstraction: 20,
42176
+ userActiveAssetData: 20,
42177
+ activeAssetData: 20,
42178
+ openOrders: 20,
42179
+ orderStatus: 2,
42180
+ portfolio: 20,
42181
+ userFees: 20,
42182
+ metaAndAssetCtxs: 20,
42183
+ meta: 20,
42184
+ perpDexs: 20,
42185
+ spotMeta: 20,
42186
+ approvedAgents: 20,
42187
+ authorizedAgents: 20,
42188
+ agents: 20,
42189
+ apiWallets: 20
42190
+ }
42191
+ }
42192
+ }
42140
42193
  }
42141
42194
  };
42142
42195
  }
@@ -43308,11 +43361,11 @@ ${result2.stderr}`)) {
43308
43361
  let stdout = "";
43309
43362
  let cooperativeStopTimedOut = false;
43310
43363
  let cooperativeStopTimer = null;
43311
- const pending2 = { stdout: "", stderr: "" };
43364
+ const pending3 = { stdout: "", stderr: "" };
43312
43365
  const writeTaggedOutput = (stream, text, flush = false) => {
43313
- const lines = `${pending2[stream]}${text}`.split(/\r?\n/u);
43366
+ const lines = `${pending3[stream]}${text}`.split(/\r?\n/u);
43314
43367
  const remainder = lines.pop() ?? "";
43315
- pending2[stream] = flush ? "" : remainder;
43368
+ pending3[stream] = flush ? "" : remainder;
43316
43369
  if (flush && remainder) lines.push(remainder);
43317
43370
  if (flush && lines.at(-1) === "") lines.pop();
43318
43371
  for (const line of lines) {
@@ -44617,7 +44670,7 @@ Waiting for approval...
44617
44670
  }
44618
44671
  }
44619
44672
  };
44620
- const pending2 = await beginLogin({
44673
+ const pending3 = await beginLogin({
44621
44674
  apiUrl: config2.apiUrl,
44622
44675
  hostId,
44623
44676
  x25519PrivateKey: keyPair.private_key,
@@ -44627,23 +44680,23 @@ Waiting for approval...
44627
44680
  const emitStdout = dependencies.emitStdout ?? ((text) => {
44628
44681
  process.stdout.write(text);
44629
44682
  });
44630
- emitStdout(parsed.json ? `${JSON.stringify({ authorizationUrl: pending2.authorizationUrl })}
44683
+ emitStdout(parsed.json ? `${JSON.stringify({ authorizationUrl: pending3.authorizationUrl })}
44631
44684
  ` : `Open this URL to authorize the VTX inference host:
44632
- ${pending2.authorizationUrl}
44685
+ ${pending3.authorizationUrl}
44633
44686
 
44634
44687
  Waiting for approval...
44635
44688
  `);
44636
44689
  if (!parsed.json && Boolean(process.stdout.isTTY) && Boolean(process.stdin.isTTY)) {
44637
44690
  try {
44638
- (dependencies.openBrowser ?? defaultOpenBrowser)(pending2.authorizationUrl);
44691
+ (dependencies.openBrowser ?? defaultOpenBrowser)(pending3.authorizationUrl);
44639
44692
  } catch {
44640
44693
  }
44641
44694
  }
44642
44695
  let access5;
44643
44696
  try {
44644
- access5 = await pending2.completion;
44697
+ access5 = await pending3.completion;
44645
44698
  } catch (error48) {
44646
- await pending2.cancel().catch(() => void 0);
44699
+ await pending3.cancel().catch(() => void 0);
44647
44700
  throw error48;
44648
44701
  }
44649
44702
  const state = {
@@ -45603,13 +45656,13 @@ Waiting for approval...
45603
45656
  };
45604
45657
  await writeInferenceForegroundAgentControlState(config2.statePath, state);
45605
45658
  }
45606
- const pending2 = state.pending_next;
45659
+ const pending3 = state.pending_next;
45607
45660
  let result2;
45608
45661
  try {
45609
45662
  result2 = await session.client.callTool("inference.agent.assignment.next", {
45610
- operation_id: pending2.operation_id,
45663
+ operation_id: pending3.operation_id,
45611
45664
  host_id: session.localState.host_id,
45612
- requested_at: pending2.requested_at,
45665
+ requested_at: pending3.requested_at,
45613
45666
  contract_version: "agent_assignment_v2",
45614
45667
  ...state.assignment ? {
45615
45668
  assignment_id: state.assignment.assignment_id,
@@ -46150,23 +46203,23 @@ Waiting for approval...
46150
46203
  });
46151
46204
  const stopAt = now().getTime() + parsed.waitSeconds * 1e3;
46152
46205
  while (true) {
46153
- let pending2 = await readInferenceAgentNextState(config2.statePath);
46154
- if (!pending2) {
46155
- pending2 = {
46206
+ let pending3 = await readInferenceAgentNextState(config2.statePath);
46207
+ if (!pending3) {
46208
+ pending3 = {
46156
46209
  schema_version: "vtx_inference_agent_next_v1",
46157
46210
  operation_id: agentOperationId("agent-next"),
46158
46211
  requested_at: now().toISOString()
46159
46212
  };
46160
- await writeInferenceAgentNextState(config2.statePath, pending2);
46213
+ await writeInferenceAgentNextState(config2.statePath, pending3);
46161
46214
  }
46162
46215
  let result2;
46163
46216
  const callStartedAtMs = now().getTime();
46164
46217
  const callStartedMonotonicMs = performance.now();
46165
46218
  try {
46166
46219
  result2 = await session.client.callTool("inference.agent.next", {
46167
- operation_id: pending2.operation_id,
46220
+ operation_id: pending3.operation_id,
46168
46221
  host_id: session.localState.host_id,
46169
- requested_at: pending2.requested_at,
46222
+ requested_at: pending3.requested_at,
46170
46223
  provider_dispatch_freshness_contract: "foreground_v1"
46171
46224
  });
46172
46225
  } catch (error48) {
@@ -46188,7 +46241,7 @@ Waiting for approval...
46188
46241
  const conservativeDeadline = Math.min(
46189
46242
  Date.parse(result2.provider_dispatch_not_after),
46190
46243
  receivedAtMs + Number(result2.provider_dispatch_freshness_remaining_ms) - roundTripMs,
46191
- Date.parse(pending2.requested_at) + Number(result2.provider_dispatch_freshness_remaining_ms),
46244
+ Date.parse(pending3.requested_at) + Number(result2.provider_dispatch_freshness_remaining_ms),
46192
46245
  active?.provider_dispatch_local_not_after ? Date.parse(active.provider_dispatch_local_not_after) : Number.POSITIVE_INFINITY
46193
46246
  );
46194
46247
  localDispatchDeadline = new Date(conservativeDeadline).toISOString();
@@ -47154,6 +47207,7 @@ var init_client = __esm({
47154
47207
  init_define_VTX_PI_MODEL_POLICY();
47155
47208
  init_types();
47156
47209
  SECRET_RESPONSE_FIELDS = /* @__PURE__ */ new Set([
47210
+ "provider_key_slots",
47157
47211
  "hyperliquid_signing_key",
47158
47212
  "local_ai_api_key",
47159
47213
  "openai_compatible_api_key",
@@ -47168,6 +47222,7 @@ var init_client = __esm({
47168
47222
  "mistral_api_key",
47169
47223
  "together_api_key",
47170
47224
  "fireworks_api_key",
47225
+ "byteplus_api_key",
47171
47226
  "cerebras_api_key",
47172
47227
  "moonshot_api_key",
47173
47228
  "alibaba_cloud_model_studio_api_key",
@@ -47890,6 +47945,491 @@ var init_hyperliquid_market_symbol = __esm({
47890
47945
  }
47891
47946
  });
47892
47947
 
47948
+ // lib/runtime/abort.ts
47949
+ var ABORT_MESSAGE_TOKENS, readAbortLikeMessage, isAbortLikeError;
47950
+ var init_abort = __esm({
47951
+ "lib/runtime/abort.ts"() {
47952
+ "use strict";
47953
+ init_define_VTX_EXO_POLICY();
47954
+ init_define_VTX_GROK_POLICY();
47955
+ init_define_VTX_PI_MODEL_POLICY();
47956
+ ABORT_MESSAGE_TOKENS = [
47957
+ "the operation was aborted",
47958
+ "the user aborted a request",
47959
+ "request was aborted",
47960
+ "request aborted",
47961
+ "signal is aborted",
47962
+ "client runtime stop requested"
47963
+ ];
47964
+ readAbortLikeMessage = (error48) => {
47965
+ if (error48 instanceof Error) {
47966
+ return error48.message;
47967
+ }
47968
+ if (typeof error48 === "string") {
47969
+ return error48;
47970
+ }
47971
+ if (error48 && typeof error48 === "object" && typeof error48.message === "string") {
47972
+ return String(error48.message);
47973
+ }
47974
+ return "";
47975
+ };
47976
+ isAbortLikeError = (error48) => {
47977
+ if (typeof DOMException !== "undefined" && error48 instanceof DOMException) {
47978
+ return error48.name === "AbortError";
47979
+ }
47980
+ if (error48 instanceof Error && error48.name === "AbortError") {
47981
+ return true;
47982
+ }
47983
+ if (error48 && typeof error48 === "object" && error48.name === "AbortError") {
47984
+ return true;
47985
+ }
47986
+ const normalized = readAbortLikeMessage(error48).trim().toLowerCase();
47987
+ if (!normalized) {
47988
+ return false;
47989
+ }
47990
+ return ABORT_MESSAGE_TOKENS.some((token) => normalized.includes(token));
47991
+ };
47992
+ }
47993
+ });
47994
+
47995
+ // lib/runtime/runtime-redaction.ts
47996
+ var REDACTED_VALUE, SECRET_QUERY_PARAM_PATTERN, BEARER_TOKEN_PATTERN, SECRET_ASSIGNMENT_PATTERN, SECRET_KEYWORD_VALUE_PATTERN, OPENAI_STYLE_KEY_PATTERN, VERTEX_EXPRESS_KEY_PATTERN, sanitizeRuntimeDiagnosticValue, sanitizeRuntimeNetworkPath, getSanitizedRuntimeErrorMessage, toSanitizedRuntimeError;
47997
+ var init_runtime_redaction = __esm({
47998
+ "lib/runtime/runtime-redaction.ts"() {
47999
+ "use strict";
48000
+ init_define_VTX_EXO_POLICY();
48001
+ init_define_VTX_GROK_POLICY();
48002
+ init_define_VTX_PI_MODEL_POLICY();
48003
+ init_abort();
48004
+ REDACTED_VALUE = "[REDACTED]";
48005
+ SECRET_QUERY_PARAM_PATTERN = /([?&](?:access_token|api(?:_|-)?key|auth|authorization|key|private_key|secret|sig|signature|token)=)[^&#\s]*/gi;
48006
+ BEARER_TOKEN_PATTERN = /\b(Bearer)\s+[A-Za-z0-9._:-]+\b/gi;
48007
+ SECRET_ASSIGNMENT_PATTERN = /((?:authorization\s*[:=]\s*['"]?Bearer\s+|x-api-key\s*[:=]\s*['"]?|api(?:_|-)?key\s*[:=]\s*['"]?|\bkey\s*[:=]\s*['"]?|token\s*[:=]\s*['"]?|secret\s*[:=]\s*['"]?))[^'"\s,}]+/gi;
48008
+ SECRET_KEYWORD_VALUE_PATTERN = /((?:private(?:_|-|\s)?key|signing(?:_|-|\s)?key)\s*[:=]\s*['"]?)(0x[a-fA-F0-9]{64}|[^'"\s,}]+)/gi;
48009
+ OPENAI_STYLE_KEY_PATTERN = /\bsk-[A-Za-z0-9._-]+\b/g;
48010
+ VERTEX_EXPRESS_KEY_PATTERN = /\bAQ\.[A-Za-z0-9._-]+\b/g;
48011
+ sanitizeRuntimeDiagnosticValue = (value) => {
48012
+ const normalized = String(value || "");
48013
+ if (!normalized) {
48014
+ return normalized;
48015
+ }
48016
+ return normalized.replace(SECRET_QUERY_PARAM_PATTERN, `$1${REDACTED_VALUE}`).replace(BEARER_TOKEN_PATTERN, `$1 ${REDACTED_VALUE}`).replace(SECRET_ASSIGNMENT_PATTERN, `$1${REDACTED_VALUE}`).replace(SECRET_KEYWORD_VALUE_PATTERN, `$1${REDACTED_VALUE}`).replace(OPENAI_STYLE_KEY_PATTERN, REDACTED_VALUE).replace(VERTEX_EXPRESS_KEY_PATTERN, REDACTED_VALUE);
48017
+ };
48018
+ sanitizeRuntimeNetworkPath = (value) => {
48019
+ const normalized = String(value || "").trim();
48020
+ if (!normalized) {
48021
+ return "/";
48022
+ }
48023
+ const withoutFragment = normalized.split("#", 1)[0] || normalized;
48024
+ const withoutQuery = withoutFragment.split("?", 1)[0] || withoutFragment;
48025
+ const sanitized = sanitizeRuntimeDiagnosticValue(withoutQuery.trim());
48026
+ return sanitized || "/";
48027
+ };
48028
+ getSanitizedRuntimeErrorMessage = (error48) => {
48029
+ const message = error48 instanceof Error ? error48.message : typeof error48 === "string" ? error48 : error48 == null ? null : String(error48);
48030
+ if (message == null) {
48031
+ return null;
48032
+ }
48033
+ return sanitizeRuntimeDiagnosticValue(message);
48034
+ };
48035
+ toSanitizedRuntimeError = (error48) => {
48036
+ const message = getSanitizedRuntimeErrorMessage(error48) || "Unknown runtime error.";
48037
+ if (error48 instanceof Error && error48.message === message) {
48038
+ if (isAbortLikeError(error48) && error48.name !== "AbortError") {
48039
+ error48.name = "AbortError";
48040
+ }
48041
+ return error48;
48042
+ }
48043
+ const sanitized = new Error(message);
48044
+ if (isAbortLikeError(error48)) {
48045
+ sanitized.name = "AbortError";
48046
+ } else if (error48 instanceof Error && error48.name) {
48047
+ sanitized.name = error48.name;
48048
+ }
48049
+ return sanitized;
48050
+ };
48051
+ }
48052
+ });
48053
+
48054
+ // lib/runtime-policy.generated.json
48055
+ var runtime_policy_generated_default2;
48056
+ var init_runtime_policy_generated2 = __esm({
48057
+ "lib/runtime-policy.generated.json"() {
48058
+ runtime_policy_generated_default2 = {
48059
+ ui: {
48060
+ performance_defaults: {
48061
+ default_timeframe: "30d"
48062
+ },
48063
+ execution_metadata_retry: {
48064
+ max_attempts: 3,
48065
+ base_delay_milliseconds: 2e3,
48066
+ max_delay_milliseconds: 3e4
48067
+ },
48068
+ auth_bootstrap_retry: {
48069
+ max_attempts: 3,
48070
+ jitter_milliseconds: 750,
48071
+ base_delay_milliseconds: 500,
48072
+ min_delay_milliseconds: 250,
48073
+ max_delay_milliseconds: 1e4
48074
+ }
48075
+ },
48076
+ ai_dashboard: {
48077
+ market_news_bounds: {
48078
+ max_items_min: 1,
48079
+ max_items_max: 100,
48080
+ lookback_hours_min: 1,
48081
+ lookback_hours_max: 168,
48082
+ max_items_steps: [
48083
+ 1,
48084
+ 2,
48085
+ 3,
48086
+ 4,
48087
+ 5,
48088
+ 6,
48089
+ 7,
48090
+ 8,
48091
+ 9,
48092
+ 10,
48093
+ 15,
48094
+ 20,
48095
+ 25,
48096
+ 30,
48097
+ 40,
48098
+ 50,
48099
+ 60,
48100
+ 75,
48101
+ 90,
48102
+ 100
48103
+ ],
48104
+ lookback_hours_steps: [
48105
+ 1,
48106
+ 2,
48107
+ 4,
48108
+ 8,
48109
+ 12,
48110
+ 24,
48111
+ 48,
48112
+ 72,
48113
+ 168
48114
+ ]
48115
+ }
48116
+ },
48117
+ trading: {
48118
+ engine: {
48119
+ client_runtime: {
48120
+ recovery: {
48121
+ resume_retry_base_delay_ms: 1e3,
48122
+ resume_retry_max_delay_ms: 3e4,
48123
+ transient_load_min_delay_ms: 3e4,
48124
+ transient_load_max_delay_ms: 12e4,
48125
+ rate_limit_buffer_ms: 1e3,
48126
+ rate_limit_max_delay_ms: 3e5,
48127
+ engine_stop_settle_retry_delay_ms: 250,
48128
+ recoverable_reset_settle_retry_delay_ms: 1500,
48129
+ local_ai_preflight_timeout_ms: 3e3,
48130
+ surge_stagger_max_ms: 6e4,
48131
+ surge_stagger_min_ms: 2e3,
48132
+ surge_stagger_min_candidates: 4,
48133
+ stagger_deadline_ttl_ms: 3e5,
48134
+ server_active_reprobe_delay_ms: 6e4,
48135
+ transient_load_jitter_ms: 1e4,
48136
+ cross_host_completed_ttl_ms: 15e3,
48137
+ telemetry_dedupe_ttl_ms: 5e3,
48138
+ browser_presence_heartbeat_interval_ms: 3e4,
48139
+ host_liveness_heartbeat_interval_ms: 3e4,
48140
+ host_liveness_recovery_nudge_ttl_ms: 1e4
48141
+ }
48142
+ }
48143
+ }
48144
+ },
48145
+ external_inference: {
48146
+ service: {
48147
+ update_check_interval_ms: 3e5,
48148
+ update_registry_timeout_ms: 15e3,
48149
+ startup_max_attempts: 40,
48150
+ startup_poll_interval_ms: 250,
48151
+ restart_stable_uptime_ms: 6e4,
48152
+ restart_backoff_base_ms: 1e3,
48153
+ restart_backoff_max_ms: 3e4,
48154
+ restart_exponent_max: 5
48155
+ }
48156
+ },
48157
+ desktop: {
48158
+ runtime_watchdog: {
48159
+ ping_interval_milliseconds: 15e3,
48160
+ telemetry_interval_milliseconds: 3e5
48161
+ }
48162
+ },
48163
+ screener: {
48164
+ resource_scheduler: {
48165
+ client_lock_ttl_milliseconds: 12e4,
48166
+ client_poll_interval_milliseconds: 250
48167
+ }
48168
+ },
48169
+ deployment: {
48170
+ cutover_buffer: {
48171
+ target_timeout_ms: 3e3,
48172
+ retired_timeout_ms: 45e3,
48173
+ max_body_bytes: 33554432,
48174
+ max_inflight: 16,
48175
+ max_queue: 64
48176
+ }
48177
+ },
48178
+ exchange: {
48179
+ hyperliquid: {
48180
+ client_public_read_budget: {
48181
+ max_weight: 900,
48182
+ window_seconds: 60,
48183
+ cooldown_seconds: 60,
48184
+ metadata_ttl_seconds: 300,
48185
+ user_fees_ttl_seconds: 300,
48186
+ account_mode_ttl_seconds: 30,
48187
+ default_request_weight: 20,
48188
+ cache_max_entries: 512
48189
+ },
48190
+ read_budget: {
48191
+ weights: {
48192
+ exchangeStatus: 2,
48193
+ clearinghouseState: 2,
48194
+ spotClearinghouseState: 2,
48195
+ l2Book: 2,
48196
+ allMids: 2,
48197
+ userFills: 120,
48198
+ userFillsByTime: 120,
48199
+ historicalOrders: 120,
48200
+ twapHistory: 120,
48201
+ userTwapSliceFills: 120,
48202
+ userFunding: 45,
48203
+ userNonFundingLedgerUpdates: 45,
48204
+ candleSnapshot: 104,
48205
+ userRole: 60,
48206
+ userAbstraction: 20,
48207
+ userDexAbstraction: 20,
48208
+ userActiveAssetData: 20,
48209
+ activeAssetData: 20,
48210
+ openOrders: 20,
48211
+ orderStatus: 2,
48212
+ portfolio: 20,
48213
+ userFees: 20,
48214
+ metaAndAssetCtxs: 20,
48215
+ meta: 20,
48216
+ perpDexs: 20,
48217
+ spotMeta: 20,
48218
+ approvedAgents: 20,
48219
+ authorizedAgents: 20,
48220
+ agents: 20,
48221
+ apiWallets: 20
48222
+ }
48223
+ }
48224
+ }
48225
+ }
48226
+ };
48227
+ }
48228
+ });
48229
+
48230
+ // lib/runtime/hyperliquid-public-read.ts
48231
+ var policy, weights, budgets, unpersistedBudgets, cache, pending2, PREFIX, abortError2, checkAbort, wait, storage, loadBudget, saveBudget, withBudgetLock, admit, cooldown, reserveHyperliquidPublicReads, readHyperliquidPublicInfo;
48232
+ var init_hyperliquid_public_read = __esm({
48233
+ "lib/runtime/hyperliquid-public-read.ts"() {
48234
+ "use strict";
48235
+ init_define_VTX_EXO_POLICY();
48236
+ init_define_VTX_GROK_POLICY();
48237
+ init_define_VTX_PI_MODEL_POLICY();
48238
+ init_runtime_redaction();
48239
+ init_runtime_policy_generated2();
48240
+ policy = runtime_policy_generated_default2.exchange.hyperliquid.client_public_read_budget;
48241
+ weights = runtime_policy_generated_default2.exchange.hyperliquid.read_budget.weights;
48242
+ budgets = /* @__PURE__ */ new Map();
48243
+ unpersistedBudgets = /* @__PURE__ */ new Set();
48244
+ cache = /* @__PURE__ */ new Map();
48245
+ pending2 = /* @__PURE__ */ new Map();
48246
+ PREFIX = "vtx:hl-public-read-budget:v1:";
48247
+ abortError2 = (signal) => signal?.reason instanceof Error ? signal.reason : new DOMException("Aborted", "AbortError");
48248
+ checkAbort = (signal) => {
48249
+ if (signal?.aborted) throw abortError2(signal);
48250
+ };
48251
+ wait = (ms, signal) => new Promise((resolve12, reject) => {
48252
+ checkAbort(signal);
48253
+ const aborted2 = () => {
48254
+ clearTimeout(timer);
48255
+ reject(abortError2(signal));
48256
+ };
48257
+ const timer = setTimeout(() => {
48258
+ signal?.removeEventListener("abort", aborted2);
48259
+ resolve12();
48260
+ }, Math.min(ms, 2147483647));
48261
+ signal?.addEventListener("abort", aborted2, { once: true });
48262
+ });
48263
+ storage = () => {
48264
+ try {
48265
+ return typeof localStorage === "undefined" ? null : localStorage;
48266
+ } catch {
48267
+ return null;
48268
+ }
48269
+ };
48270
+ loadBudget = (key) => {
48271
+ const memory = budgets.get(key) ?? { reservations: [], cooldownUntil: 0 };
48272
+ if (unpersistedBudgets.has(key)) return memory;
48273
+ try {
48274
+ const target = storage();
48275
+ if (target && target.getItem(key) == null) return { reservations: [], cooldownUntil: 0 };
48276
+ const stored = JSON.parse(target?.getItem(key) ?? "null");
48277
+ if (stored && Array.isArray(stored.reservations) && Number.isFinite(stored.cooldownUntil) && stored.reservations.every((r) => Number.isFinite(r.at) && Number.isFinite(r.weight) && r.weight > 0)) return stored;
48278
+ } catch {
48279
+ }
48280
+ return memory;
48281
+ };
48282
+ saveBudget = (key, budget) => {
48283
+ budgets.set(key, budget);
48284
+ try {
48285
+ const target = storage();
48286
+ if (!target) {
48287
+ unpersistedBudgets.add(key);
48288
+ return;
48289
+ }
48290
+ target.setItem(key, JSON.stringify(budget));
48291
+ unpersistedBudgets.delete(key);
48292
+ } catch {
48293
+ unpersistedBudgets.add(key);
48294
+ }
48295
+ };
48296
+ withBudgetLock = async (key, signal, work) => {
48297
+ checkAbort(signal);
48298
+ if (typeof navigator !== "undefined" && navigator.locks?.request) {
48299
+ return navigator.locks.request(key, { ...signal ? { signal } : {} }, work);
48300
+ }
48301
+ return work();
48302
+ };
48303
+ admit = async (apiUrl, requestType, signal, bundleWeight, bundleId) => {
48304
+ const key = `${PREFIX}${apiUrl}`;
48305
+ const weight = bundleWeight ?? weights[requestType] ?? policy.default_request_weight;
48306
+ if (!(weight > 0 && weight <= policy.max_weight)) throw new Error("Invalid Hyperliquid public read weight.");
48307
+ for (; ; ) {
48308
+ checkAbort(signal);
48309
+ const delay2 = await withBudgetLock(key, signal, () => {
48310
+ const now = Date.now();
48311
+ const budget = loadBudget(key);
48312
+ budget.reservations = budget.reservations.filter((r) => r.at > now - policy.window_seconds * 1e3);
48313
+ if (budget.cooldownUntil > now) throw Object.assign(new Error("Hyperliquid public read rate-limit cooldown."), { status: 429, requestType });
48314
+ let used = budget.reservations.reduce((sum, r) => sum + r.weight, 0);
48315
+ if (used + weight <= policy.max_weight) {
48316
+ budget.reservations.push({ at: now, weight, ...bundleId ? { id: bundleId } : {} });
48317
+ saveBudget(key, budget);
48318
+ return 0;
48319
+ }
48320
+ for (const reservation of budget.reservations) {
48321
+ used -= reservation.weight;
48322
+ if (used + weight <= policy.max_weight) return Math.max(1, reservation.at + policy.window_seconds * 1e3 - now);
48323
+ }
48324
+ throw new Error("Invalid Hyperliquid public read budget.");
48325
+ });
48326
+ if (!delay2) return;
48327
+ if (bundleWeight != null) throw Object.assign(new Error("Hyperliquid public read bundle budget exhausted."), { code: "public_budget_exhausted" });
48328
+ await wait(delay2, signal);
48329
+ }
48330
+ };
48331
+ cooldown = async (apiUrl, retryAfter) => {
48332
+ const key = `${PREFIX}${apiUrl}`;
48333
+ await withBudgetLock(key, void 0, () => {
48334
+ const now = Date.now();
48335
+ const seconds = retryAfter == null ? NaN : Number(retryAfter);
48336
+ const providerUntil = Number.isFinite(seconds) ? now + seconds * 1e3 : Date.parse(retryAfter ?? "");
48337
+ const budget = loadBudget(key);
48338
+ budget.cooldownUntil = Math.max(budget.cooldownUntil, now + policy.cooldown_seconds * 1e3, Number.isFinite(providerUntil) ? providerUntil : 0);
48339
+ saveBudget(key, budget);
48340
+ });
48341
+ };
48342
+ reserveHyperliquidPublicReads = async (endpoint, bodies, signal) => {
48343
+ const apiUrl = endpoint.replace(/\/$/, "");
48344
+ const weight = bodies.reduce((sum, body) => sum + (weights[String(body.type)] ?? policy.default_request_weight), 0);
48345
+ const id2 = crypto.randomUUID();
48346
+ const admittedAtMs = Date.now();
48347
+ await admit(apiUrl, "bundle", signal, weight, id2);
48348
+ const remaining = /* @__PURE__ */ new Map();
48349
+ for (const body of bodies) {
48350
+ const key = JSON.stringify(body);
48351
+ remaining.set(key, (remaining.get(key) ?? 0) + 1);
48352
+ }
48353
+ return { id: id2, endpoint: apiUrl, expiresAtMs: admittedAtMs + policy.window_seconds * 1e3, remaining };
48354
+ };
48355
+ readHyperliquidPublicInfo = async (endpoint, body, options = {}) => {
48356
+ const apiUrl = endpoint.replace(/\/$/, "");
48357
+ const requestType = String(body.type ?? "info");
48358
+ const ttlSeconds = ["meta", "spotMeta", "perpDexs"].includes(requestType) ? policy.metadata_ttl_seconds : requestType === "userFees" ? policy.user_fees_ttl_seconds : options.cacheAccountMode && ["userAbstraction", "userDexAbstraction"].includes(requestType) ? policy.account_mode_ttl_seconds : 0;
48359
+ const key = `${apiUrl}:${JSON.stringify(body)}`;
48360
+ checkAbort(options.signal);
48361
+ if (ttlSeconds) {
48362
+ for (; ; ) {
48363
+ const existing = cache.get(key);
48364
+ if (existing && Date.now() - existing.fetchedAtMs >= 0 && Date.now() - existing.fetchedAtMs < ttlSeconds * 500) return existing;
48365
+ const running = pending2.get(key);
48366
+ if (!running) break;
48367
+ await new Promise((resolve12, reject) => {
48368
+ const aborted2 = () => {
48369
+ options.signal?.removeEventListener("abort", aborted2);
48370
+ reject(abortError2(options.signal));
48371
+ };
48372
+ options.signal?.addEventListener("abort", aborted2, { once: true });
48373
+ running.then(() => {
48374
+ options.signal?.removeEventListener("abort", aborted2);
48375
+ resolve12();
48376
+ });
48377
+ });
48378
+ checkAbort(options.signal);
48379
+ }
48380
+ }
48381
+ let settled;
48382
+ if (ttlSeconds) pending2.set(key, new Promise((resolve12) => {
48383
+ settled = resolve12;
48384
+ }));
48385
+ try {
48386
+ const reservedKey = JSON.stringify(body);
48387
+ const remaining = options.reservation?.remaining.get(reservedKey) ?? 0;
48388
+ if (options.reservation?.endpoint === apiUrl && remaining > 0) {
48389
+ if (Date.now() >= options.reservation.expiresAtMs) throw Object.assign(new Error("Hyperliquid public read reservation expired."), { code: "public_budget_exhausted" });
48390
+ await withBudgetLock(`${PREFIX}${apiUrl}`, options.signal, () => {
48391
+ const budget = loadBudget(`${PREFIX}${apiUrl}`);
48392
+ const row = budget.reservations.find((entry) => entry.id === options.reservation.id);
48393
+ if (!row || Date.now() >= options.reservation.expiresAtMs) throw Object.assign(new Error("Hyperliquid public read reservation expired."), { code: "public_budget_exhausted" });
48394
+ row.at = Date.now();
48395
+ budget.reservations.sort((a, b2) => a.at - b2.at);
48396
+ saveBudget(`${PREFIX}${apiUrl}`, budget);
48397
+ });
48398
+ options.reservation.remaining.set(reservedKey, remaining - 1);
48399
+ } else await admit(apiUrl, requestType, options.signal);
48400
+ checkAbort(options.signal);
48401
+ if (loadBudget(`${PREFIX}${apiUrl}`).cooldownUntil > Date.now()) throw Object.assign(new Error("Hyperliquid public read rate-limit cooldown."), { status: 429, requestType });
48402
+ const response = await fetch(`${apiUrl}/info`, {
48403
+ method: "POST",
48404
+ headers: { "Content-Type": "application/json" },
48405
+ body: JSON.stringify(body),
48406
+ signal: options.signal
48407
+ });
48408
+ if (response.status === 429) await cooldown(apiUrl, response.headers.get("Retry-After"));
48409
+ const payload = await response.json().catch(() => ({}));
48410
+ if (!response.ok) {
48411
+ const detail = sanitizeRuntimeDiagnosticValue(typeof payload?.response === "string" ? payload.response : typeof payload?.detail === "string" ? payload.detail : "");
48412
+ throw Object.assign(new Error(`Hyperliquid info request failed (${response.status}) request_type=${requestType}.${detail ? ` ${detail}` : ""}`), {
48413
+ status: response.status,
48414
+ requestType
48415
+ });
48416
+ }
48417
+ const result2 = { payload, fetchedAtMs: Date.now() };
48418
+ if (ttlSeconds) {
48419
+ cache.set(key, result2);
48420
+ while (cache.size > policy.cache_max_entries) cache.delete(cache.keys().next().value);
48421
+ }
48422
+ return result2;
48423
+ } finally {
48424
+ if (ttlSeconds) {
48425
+ pending2.delete(key);
48426
+ settled?.();
48427
+ }
48428
+ }
48429
+ };
48430
+ }
48431
+ });
48432
+
47893
48433
  // lib/sort-utils.ts
47894
48434
  function compareCaseInsensitive(left, right) {
47895
48435
  return String(left ?? "").localeCompare(String(right ?? ""), void 0, { sensitivity: "base" });
@@ -48514,112 +49054,6 @@ var init_hyperliquid_fee_contract = __esm({
48514
49054
  }
48515
49055
  });
48516
49056
 
48517
- // lib/runtime/abort.ts
48518
- var ABORT_MESSAGE_TOKENS, readAbortLikeMessage, isAbortLikeError;
48519
- var init_abort = __esm({
48520
- "lib/runtime/abort.ts"() {
48521
- "use strict";
48522
- init_define_VTX_EXO_POLICY();
48523
- init_define_VTX_GROK_POLICY();
48524
- init_define_VTX_PI_MODEL_POLICY();
48525
- ABORT_MESSAGE_TOKENS = [
48526
- "the operation was aborted",
48527
- "the user aborted a request",
48528
- "request was aborted",
48529
- "request aborted",
48530
- "signal is aborted",
48531
- "client runtime stop requested"
48532
- ];
48533
- readAbortLikeMessage = (error48) => {
48534
- if (error48 instanceof Error) {
48535
- return error48.message;
48536
- }
48537
- if (typeof error48 === "string") {
48538
- return error48;
48539
- }
48540
- if (error48 && typeof error48 === "object" && typeof error48.message === "string") {
48541
- return String(error48.message);
48542
- }
48543
- return "";
48544
- };
48545
- isAbortLikeError = (error48) => {
48546
- if (typeof DOMException !== "undefined" && error48 instanceof DOMException) {
48547
- return error48.name === "AbortError";
48548
- }
48549
- if (error48 instanceof Error && error48.name === "AbortError") {
48550
- return true;
48551
- }
48552
- if (error48 && typeof error48 === "object" && error48.name === "AbortError") {
48553
- return true;
48554
- }
48555
- const normalized = readAbortLikeMessage(error48).trim().toLowerCase();
48556
- if (!normalized) {
48557
- return false;
48558
- }
48559
- return ABORT_MESSAGE_TOKENS.some((token) => normalized.includes(token));
48560
- };
48561
- }
48562
- });
48563
-
48564
- // lib/runtime/runtime-redaction.ts
48565
- var REDACTED_VALUE, SECRET_QUERY_PARAM_PATTERN, BEARER_TOKEN_PATTERN, SECRET_ASSIGNMENT_PATTERN, SECRET_KEYWORD_VALUE_PATTERN, OPENAI_STYLE_KEY_PATTERN, VERTEX_EXPRESS_KEY_PATTERN, sanitizeRuntimeDiagnosticValue, sanitizeRuntimeNetworkPath, getSanitizedRuntimeErrorMessage, toSanitizedRuntimeError;
48566
- var init_runtime_redaction = __esm({
48567
- "lib/runtime/runtime-redaction.ts"() {
48568
- "use strict";
48569
- init_define_VTX_EXO_POLICY();
48570
- init_define_VTX_GROK_POLICY();
48571
- init_define_VTX_PI_MODEL_POLICY();
48572
- init_abort();
48573
- REDACTED_VALUE = "[REDACTED]";
48574
- SECRET_QUERY_PARAM_PATTERN = /([?&](?:access_token|api(?:_|-)?key|auth|authorization|key|private_key|secret|sig|signature|token)=)[^&#\s]*/gi;
48575
- BEARER_TOKEN_PATTERN = /\b(Bearer)\s+[A-Za-z0-9._:-]+\b/gi;
48576
- SECRET_ASSIGNMENT_PATTERN = /((?:authorization\s*[:=]\s*['"]?Bearer\s+|x-api-key\s*[:=]\s*['"]?|api(?:_|-)?key\s*[:=]\s*['"]?|\bkey\s*[:=]\s*['"]?|token\s*[:=]\s*['"]?|secret\s*[:=]\s*['"]?))[^'"\s,}]+/gi;
48577
- SECRET_KEYWORD_VALUE_PATTERN = /((?:private(?:_|-|\s)?key|signing(?:_|-|\s)?key)\s*[:=]\s*['"]?)(0x[a-fA-F0-9]{64}|[^'"\s,}]+)/gi;
48578
- OPENAI_STYLE_KEY_PATTERN = /\bsk-[A-Za-z0-9._-]+\b/g;
48579
- VERTEX_EXPRESS_KEY_PATTERN = /\bAQ\.[A-Za-z0-9._-]+\b/g;
48580
- sanitizeRuntimeDiagnosticValue = (value) => {
48581
- const normalized = String(value || "");
48582
- if (!normalized) {
48583
- return normalized;
48584
- }
48585
- return normalized.replace(SECRET_QUERY_PARAM_PATTERN, `$1${REDACTED_VALUE}`).replace(BEARER_TOKEN_PATTERN, `$1 ${REDACTED_VALUE}`).replace(SECRET_ASSIGNMENT_PATTERN, `$1${REDACTED_VALUE}`).replace(SECRET_KEYWORD_VALUE_PATTERN, `$1${REDACTED_VALUE}`).replace(OPENAI_STYLE_KEY_PATTERN, REDACTED_VALUE).replace(VERTEX_EXPRESS_KEY_PATTERN, REDACTED_VALUE);
48586
- };
48587
- sanitizeRuntimeNetworkPath = (value) => {
48588
- const normalized = String(value || "").trim();
48589
- if (!normalized) {
48590
- return "/";
48591
- }
48592
- const withoutFragment = normalized.split("#", 1)[0] || normalized;
48593
- const withoutQuery = withoutFragment.split("?", 1)[0] || withoutFragment;
48594
- const sanitized = sanitizeRuntimeDiagnosticValue(withoutQuery.trim());
48595
- return sanitized || "/";
48596
- };
48597
- getSanitizedRuntimeErrorMessage = (error48) => {
48598
- const message = error48 instanceof Error ? error48.message : typeof error48 === "string" ? error48 : error48 == null ? null : String(error48);
48599
- if (message == null) {
48600
- return null;
48601
- }
48602
- return sanitizeRuntimeDiagnosticValue(message);
48603
- };
48604
- toSanitizedRuntimeError = (error48) => {
48605
- const message = getSanitizedRuntimeErrorMessage(error48) || "Unknown runtime error.";
48606
- if (error48 instanceof Error && error48.message === message) {
48607
- if (isAbortLikeError(error48) && error48.name !== "AbortError") {
48608
- error48.name = "AbortError";
48609
- }
48610
- return error48;
48611
- }
48612
- const sanitized = new Error(message);
48613
- if (isAbortLikeError(error48)) {
48614
- sanitized.name = "AbortError";
48615
- } else if (error48 instanceof Error && error48.name) {
48616
- sanitized.name = error48.name;
48617
- }
48618
- return sanitized;
48619
- };
48620
- }
48621
- });
48622
-
48623
49057
  // lib/runtime/channel-sender.ts
48624
49058
  var RUNTIME_TAB_ID_STORAGE_KEY, createRuntimeUuid, getOrCreateRuntimeTabSenderId;
48625
49059
  var init_channel_sender = __esm({
@@ -49092,6 +49526,7 @@ var init_hyperliquid_account_state_adapter = __esm({
49092
49526
  init_define_VTX_EXO_POLICY();
49093
49527
  init_define_VTX_GROK_POLICY();
49094
49528
  init_define_VTX_PI_MODEL_POLICY();
49529
+ init_hyperliquid_public_read();
49095
49530
  init_sort_utils();
49096
49531
  init_hyperliquid_account_contract();
49097
49532
  init_hyperliquid_active_asset_contract();
@@ -49841,40 +50276,14 @@ var init_hyperliquid_account_state_adapter = __esm({
49841
50276
  }
49842
50277
  return true;
49843
50278
  };
49844
- fetchHyperliquidInfoPayload = async (apiUrl, body, signal) => {
49845
- const requestUrl = `${apiUrl.replace(/\/$/, "")}/info`;
49846
- const requestType = String(body?.type || "info").trim() || "info";
49847
- const trace = startRuntimeNetworkDebugTrace({
49848
- kind: "exchange",
49849
- label: `hyperliquid_info:${requestType}`,
49850
- method: "POST",
49851
- url: requestUrl,
49852
- note: `type=${requestType}`
49853
- });
49854
- let response = null;
50279
+ fetchHyperliquidInfoPayload = async (apiUrl, body, signal, reservation) => {
50280
+ const trace = startRuntimeNetworkDebugTrace({ kind: "exchange", label: `hyperliquid_info:${String(body.type)}`, method: "POST", url: `${apiUrl.replace(/\/$/, "")}/info` });
49855
50281
  try {
49856
- response = await fetch(requestUrl, {
49857
- method: "POST",
49858
- headers: {
49859
- "Content-Type": "application/json"
49860
- },
49861
- body: JSON.stringify(body),
49862
- signal
49863
- });
49864
- const payload = await response.json().catch(() => ({}));
49865
- if (!response.ok) {
49866
- const responseDetail = typeof payload?.response === "string" ? payload.response : typeof payload?.detail === "string" ? payload.detail : "";
49867
- const detail = response.status === 429 ? `Hyperliquid info request failed (${response.status}) request_type=${requestType}.${responseDetail ? ` ${responseDetail}` : ""}` : responseDetail || `Hyperliquid info request failed (${response.status}) request_type=${requestType}.`;
49868
- const requestError = new Error(detail);
49869
- requestError.status = response.status;
49870
- requestError.detail = detail;
49871
- requestError.requestType = requestType;
49872
- throw requestError;
49873
- }
49874
- trace.completeSuccess(response.status);
49875
- return payload;
50282
+ const result2 = await readHyperliquidPublicInfo(apiUrl, body, { signal, reservation });
50283
+ trace.completeSuccess(200);
50284
+ return result2.payload;
49876
50285
  } catch (error48) {
49877
- trace.completeError(error48, response?.status ?? null);
50286
+ trace.completeError(error48, error48?.status ?? null);
49878
50287
  throw error48;
49879
50288
  }
49880
50289
  };
@@ -50009,11 +50418,58 @@ var init_hyperliquid_account_state_adapter = __esm({
50009
50418
  dexNames,
50010
50419
  staleIf429MaxAgeMs
50011
50420
  }) => {
50421
+ const userFeesPromise = input.includeEffectiveTakerRate === true ? (async () => ({
50422
+ ...await readHyperliquidPublicInfo(apiUrl, { type: "userFees", user: walletAddress }, { signal: input.signal }).catch((error48) => {
50423
+ if (input.signal?.aborted) throw error48;
50424
+ return { payload: null, fetchedAtMs: Date.now() };
50425
+ }).then((result2) => ({ payload: result2.payload, capturedAt: new Date(result2.fetchedAtMs).toISOString() }))
50426
+ }))() : Promise.resolve(null);
50427
+ const exactAccountModePromise = input.includeExactAccountMode === true ? (async () => {
50428
+ const abstractionRead = await readHyperliquidPublicInfo(apiUrl, { type: "userAbstraction", user: walletAddress }, { signal: input.signal, cacheAccountMode: true });
50429
+ const userAbstraction = abstractionRead.payload;
50430
+ let capturedAtMs = abstractionRead.fetchedAtMs;
50431
+ const preliminaryMode = extractCanonicalHyperliquidAccountMode(userAbstraction);
50432
+ if (!preliminaryMode) {
50433
+ throw new Error("Exact Hyperliquid userAbstraction response is invalid.");
50434
+ }
50435
+ let userDexAbstraction;
50436
+ if (preliminaryMode === "default" || preliminaryMode === "disabled") {
50437
+ const dexRead = await readHyperliquidPublicInfo(apiUrl, { type: "userDexAbstraction", user: walletAddress }, { signal: input.signal, cacheAccountMode: true });
50438
+ userDexAbstraction = dexRead.payload;
50439
+ capturedAtMs = Math.min(capturedAtMs, dexRead.fetchedAtMs);
50440
+ }
50441
+ return {
50442
+ accountMode: resolveExactHyperliquidAccountMode(
50443
+ userAbstraction,
50444
+ userDexAbstraction
50445
+ ),
50446
+ capturedAt: new Date(capturedAtMs).toISOString()
50447
+ };
50448
+ })() : Promise.resolve(null);
50449
+ await Promise.all([userFeesPromise, exactAccountModePromise]);
50450
+ const metadataByDex = /* @__PURE__ */ new Map();
50451
+ if (input.includeEffectiveTakerRate === true) {
50452
+ await Promise.all(["", ...dexNames].map(async (dex) => {
50453
+ try {
50454
+ metadataByDex.set(dex, await fetchHyperliquidInfoPayload(apiUrl, { type: "meta", ...dex ? { dex } : {} }, input.signal));
50455
+ } catch (error48) {
50456
+ if (input.signal?.aborted) throw error48;
50457
+ metadataByDex.set(dex, null);
50458
+ }
50459
+ }));
50460
+ }
50461
+ const reservation = await reserveHyperliquidPublicReads(apiUrl, [
50462
+ { type: "clearinghouseState", user: walletAddress },
50463
+ ...dexNames.map((dex) => ({ type: "clearinghouseState", user: walletAddress, dex })),
50464
+ { type: "spotClearinghouseState", user: walletAddress },
50465
+ ...input.includeActiveAssetData === false ? [] : activeAssetRequestTypes.map((type) => ({ type, user: walletAddress, coin: symbol2 }))
50466
+ ], input.signal);
50012
50467
  const perpsPromise = (async () => {
50013
50468
  const defaultResponse = await fetchHyperliquidInfoPayload(
50014
50469
  apiUrl,
50015
50470
  { type: "clearinghouseState", user: walletAddress },
50016
- input.signal
50471
+ input.signal,
50472
+ reservation
50017
50473
  );
50018
50474
  if (input.includeEffectiveTakerRate === true) {
50019
50475
  requirePromptClearinghouseState(defaultResponse, "default");
@@ -50023,7 +50479,8 @@ var init_hyperliquid_account_state_adapter = __esm({
50023
50479
  const response = await fetchHyperliquidInfoPayload(
50024
50480
  apiUrl,
50025
50481
  { type: "clearinghouseState", user: walletAddress, dex: dexName },
50026
- input.signal
50482
+ input.signal,
50483
+ reservation
50027
50484
  );
50028
50485
  if (input.includeEffectiveTakerRate === true) {
50029
50486
  requirePromptClearinghouseState(response, dexName);
@@ -50058,7 +50515,8 @@ var init_hyperliquid_account_state_adapter = __esm({
50058
50515
  payload = await fetchHyperliquidInfoPayload(
50059
50516
  apiUrl,
50060
50517
  { type: "spotClearinghouseState", user: walletAddress },
50061
- input.signal
50518
+ input.signal,
50519
+ reservation
50062
50520
  );
50063
50521
  } catch (error48) {
50064
50522
  recordInfoRateLimitCooldownFromError(apiUrl, error48, staleIf429MaxAgeMs);
@@ -50076,12 +50534,14 @@ var init_hyperliquid_account_state_adapter = __esm({
50076
50534
  const payload = await fetchHyperliquidInfoPayload(
50077
50535
  apiUrl,
50078
50536
  { type: typeName, user: walletAddress, coin: symbol2 },
50079
- input.signal
50537
+ input.signal,
50538
+ reservation
50080
50539
  );
50081
50540
  return { payload, type: typeName };
50082
50541
  } catch (error48) {
50083
50542
  lastError = error48;
50084
50543
  recordInfoRateLimitCooldownFromError(apiUrl, error48, staleIf429MaxAgeMs);
50544
+ if (isRateLimitError(error48)) throw error48;
50085
50545
  if (typeName === "userActiveAssetData" && isUnsupportedUserActiveAssetError(error48)) {
50086
50546
  rememberUnsupportedUserActiveAssetKey(activeAssetCacheKey);
50087
50547
  }
@@ -50089,43 +50549,6 @@ var init_hyperliquid_account_state_adapter = __esm({
50089
50549
  }
50090
50550
  throw lastError instanceof Error ? lastError : new Error("Failed to fetch browser active asset data.");
50091
50551
  })();
50092
- const userFeesPromise = input.includeEffectiveTakerRate === true ? (async () => ({
50093
- payload: await fetchHyperliquidInfoPayload(
50094
- apiUrl,
50095
- { type: "userFees", user: walletAddress },
50096
- input.signal
50097
- ).catch((error48) => {
50098
- if (input.signal?.aborted) throw error48;
50099
- return null;
50100
- }),
50101
- capturedAt: (/* @__PURE__ */ new Date()).toISOString()
50102
- }))() : Promise.resolve(null);
50103
- const exactAccountModePromise = input.includeExactAccountMode === true ? (async () => {
50104
- const userAbstraction = await fetchHyperliquidInfoPayload(
50105
- apiUrl,
50106
- { type: "userAbstraction", user: walletAddress },
50107
- input.signal
50108
- );
50109
- const preliminaryMode = extractCanonicalHyperliquidAccountMode(userAbstraction);
50110
- if (!preliminaryMode) {
50111
- throw new Error("Exact Hyperliquid userAbstraction response is invalid.");
50112
- }
50113
- let userDexAbstraction;
50114
- if (preliminaryMode === "default" || preliminaryMode === "disabled") {
50115
- userDexAbstraction = await fetchHyperliquidInfoPayload(
50116
- apiUrl,
50117
- { type: "userDexAbstraction", user: walletAddress },
50118
- input.signal
50119
- );
50120
- }
50121
- return {
50122
- accountMode: resolveExactHyperliquidAccountMode(
50123
- userAbstraction,
50124
- userDexAbstraction
50125
- ),
50126
- capturedAt: (/* @__PURE__ */ new Date()).toISOString()
50127
- };
50128
- })() : Promise.resolve(null);
50129
50552
  const [perpsResult, spotResult, activeAssetResult, userFeesResult, exactAccountMode] = await Promise.all([
50130
50553
  perpsPromise,
50131
50554
  spotPromise,
@@ -50154,11 +50577,7 @@ var init_hyperliquid_account_state_adapter = __esm({
50154
50577
  const feeDexes = [...new Set(feeSymbols.map(getHyperliquidMarketDex))];
50155
50578
  const metadata = await Promise.all(feeDexes.map(async (dex) => {
50156
50579
  try {
50157
- const payload = await fetchHyperliquidInfoPayload(
50158
- apiUrl,
50159
- { type: "meta", ...dex ? { dex } : {} },
50160
- input.signal
50161
- );
50580
+ const payload = metadataByDex.get(dex) ?? null;
50162
50581
  return [dex, payload];
50163
50582
  } catch (error48) {
50164
50583
  if (input.signal?.aborted) throw error48;
@@ -50415,19 +50834,20 @@ var init_byokProviderRegistry = __esm({
50415
50834
  { key: "alibaba_cloud_model_studio", runtimeProvider: "alibaba_cloud_model_studio", displayName: "Alibaba Cloud Model Studio", apiKeyField: "alibaba_cloud_model_studio_api_key", envKey: "ALIBABA_CLOUD_MODEL_STUDIO_API_KEY", baseUrl: "https://dashscope-us.aliyuncs.com/compatible-mode/v1", modelsUrl: "https://dashscope-us.aliyuncs.com/compatible-mode/v1/models", requestContractStrategy: "extra_body_enable_thinking", clientRuntimeSupported: true, uiGroup: BYOK_UI_GROUP, providerKind: "direct", displayOrder: 10, aliases: ["alibaba", "alibaba cloud", "dashscope", "model studio"] },
50416
50835
  { key: "amazon_bedrock", runtimeProvider: "amazon_bedrock", displayName: "Amazon Bedrock", apiKeyField: "amazon_bedrock_api_key", envKey: "AMAZON_API_KEY", baseUrl: "https://bedrock-mantle.us-east-1.api.aws/v1", modelsUrl: "https://bedrock-mantle.us-east-1.api.aws/v1/models", requestContractStrategy: "top_level_reasoning_effort", clientRuntimeSupported: true, uiGroup: BYOK_UI_GROUP, providerKind: "hosted", displayOrder: 20, aliases: ["amazon", "aws", "aws bedrock", "bedrock"] },
50417
50836
  { key: "anthropic", runtimeProvider: "anthropic", displayName: "Anthropic", apiKeyField: "anthropic_api_key", envKey: "ANTHROPIC_API_KEY", baseUrl: null, modelsUrl: null, requestContractStrategy: "native", clientRuntimeSupported: true, uiGroup: BYOK_UI_GROUP, providerKind: "direct", displayOrder: 30, aliases: ["claude"] },
50418
- { key: "cerebras", runtimeProvider: "cerebras", displayName: "Cerebras", apiKeyField: "cerebras_api_key", envKey: "CEREBRAS_API_KEY", baseUrl: "https://api.cerebras.ai/v1", modelsUrl: "https://api.cerebras.ai/v1/models", requestContractStrategy: "top_level_reasoning_effort_and_extra_body_disable_reasoning", clientRuntimeSupported: true, uiGroup: BYOK_UI_GROUP, providerKind: "hosted", displayOrder: 40, aliases: [] },
50419
- { key: "deepseek", runtimeProvider: "deepseek", displayName: "DeepSeek", apiKeyField: "deepseek_api_key", envKey: "DEEPSEEK_API_KEY", baseUrl: "https://api.deepseek.com", modelsUrl: "https://api.deepseek.com/models", requestContractStrategy: "deepseek_extra_body", clientRuntimeSupported: true, uiGroup: BYOK_UI_GROUP, providerKind: "direct", displayOrder: 50, aliases: ["deep seek", "deepseek ai", "deepseek.ai"] },
50420
- { key: "fireworks", runtimeProvider: "fireworks", displayName: "Fireworks AI", apiKeyField: "fireworks_api_key", envKey: "FIREWORKS_API_KEY", baseUrl: "https://api.fireworks.ai/inference/v1", modelsUrl: "https://api.fireworks.ai/inference/v1/models", requestContractStrategy: "top_level_reasoning_effort_and_extra_body_thinking_type", clientRuntimeSupported: true, uiGroup: BYOK_UI_GROUP, providerKind: "hosted", displayOrder: 60, aliases: ["fireworks ai"] },
50421
- { key: "google", runtimeProvider: "gemini", displayName: "Google Gemini", apiKeyField: "gemini_api_key", envKey: "GOOGLE_AI_PLATFORM_API_KEY", baseUrl: null, modelsUrl: null, requestContractStrategy: "native", clientRuntimeSupported: true, uiGroup: BYOK_UI_GROUP, providerKind: "direct", displayOrder: 70, aliases: ["gemini"] },
50422
- { key: "groq", runtimeProvider: "groq", displayName: "Groq", apiKeyField: "groq_api_key", envKey: "GROQ_API_KEY", baseUrl: "https://api.groq.com/openai/v1", modelsUrl: "https://api.groq.com/openai/v1/models", requestContractStrategy: "native", clientRuntimeSupported: true, uiGroup: BYOK_UI_GROUP, providerKind: "hosted", displayOrder: 80, aliases: ["groqcloud", "groq cloud"] },
50423
- { key: "lightning", runtimeProvider: "lightning", displayName: "Lightning AI", apiKeyField: "lightning_api_key", envKey: "LIGHTNING_API_KEY", baseUrl: "https://lightning.ai/api/v1", modelsUrl: "https://lightning.ai/api/v1/models", requestContractStrategy: "none", clientRuntimeSupported: true, uiGroup: BYOK_UI_GROUP, providerKind: "hosted", displayOrder: 90, aliases: ["litai", "lightning ai"] },
50424
- { key: "mistral", runtimeProvider: "mistral", displayName: "Mistral", apiKeyField: "mistral_api_key", envKey: "MISTRAL_API_KEY", baseUrl: "https://api.mistral.ai/v1", modelsUrl: "https://api.mistral.ai/v1/models", requestContractStrategy: "top_level_reasoning_effort", clientRuntimeSupported: true, uiGroup: BYOK_UI_GROUP, providerKind: "direct", displayOrder: 100, aliases: ["mistral ai"] },
50425
- { key: "moonshot", runtimeProvider: "moonshot", displayName: "Moonshot/Kimi", apiKeyField: "moonshot_api_key", envKey: "MOONSHOT_API_KEY", baseUrl: "https://api.moonshot.ai/v1", modelsUrl: "https://api.moonshot.ai/v1/models", requestContractStrategy: "extra_body_thinking_type", clientRuntimeSupported: true, uiGroup: BYOK_UI_GROUP, providerKind: "direct", displayOrder: 110, aliases: ["kimi", "moonshot ai"] },
50426
- { key: "openai", runtimeProvider: "openai", displayName: "OpenAI", apiKeyField: "openai_api_key", envKey: "OPENAI_API_KEY", baseUrl: "https://api.openai.com/v1", modelsUrl: "https://api.openai.com/v1/models", requestContractStrategy: "native", clientRuntimeSupported: true, uiGroup: BYOK_UI_GROUP, providerKind: "direct", displayOrder: 120, aliases: [] },
50427
- { key: "openrouter", runtimeProvider: "openrouter", displayName: "OpenRouter", apiKeyField: "openrouter_api_key", envKey: "OPENROUTER_API_KEY", baseUrl: "https://openrouter.ai/api/v1", modelsUrl: "https://openrouter.ai/api/v1/models", requestContractStrategy: "openrouter", clientRuntimeSupported: true, uiGroup: BYOK_UI_GROUP, providerKind: "hosted", displayOrder: 130, aliases: ["open-router", "open router", "openrouter ai"] },
50428
- { key: "together", runtimeProvider: "together", displayName: "Together AI", apiKeyField: "together_api_key", envKey: "TOGETHER_API_KEY", baseUrl: "https://api.together.xyz/v1", modelsUrl: "https://api.together.xyz/v1/models", requestContractStrategy: "top_level_reasoning_effort_and_extra_body_reasoning_enabled", clientRuntimeSupported: true, uiGroup: BYOK_UI_GROUP, providerKind: "hosted", displayOrder: 140, aliases: ["together ai"] },
50429
- { key: "venice", runtimeProvider: "venice", displayName: "Venice AI", apiKeyField: "venice_api_key", envKey: "VENICE_API_KEY", baseUrl: "https://api.venice.ai/api/v1", modelsUrl: "https://api.venice.ai/api/v1/models", requestContractStrategy: "venice", clientRuntimeSupported: true, uiGroup: BYOK_UI_GROUP, providerKind: "hosted", displayOrder: 150, aliases: ["venice.ai"] },
50430
- { key: "xai", runtimeProvider: "grok", displayName: "xAI", apiKeyField: "grok_api_key", envKey: "XAI_API_KEY", baseUrl: "https://api.x.ai/v1", modelsUrl: "https://api.x.ai/v1/models", requestContractStrategy: "native", clientRuntimeSupported: true, uiGroup: BYOK_UI_GROUP, providerKind: "direct", displayOrder: 160, aliases: ["x", "x.ai", "grok"] }
50837
+ { key: "byteplus", runtimeProvider: "byteplus", displayName: "BytePlus Coding Plan", apiKeyField: "byteplus_api_key", envKey: "BYTEPLUS_API_KEY", baseUrl: "https://ark.ap-southeast.bytepluses.com/api/coding/v3", modelsUrl: "https://ark.ap-southeast.bytepluses.com/api/coding/v3/models", requestContractStrategy: "extra_body_thinking_type", clientRuntimeSupported: true, uiGroup: BYOK_UI_GROUP, providerKind: "hosted", displayOrder: 40, aliases: ["bytedance", "byteplus coding plan", "ark"] },
50838
+ { key: "cerebras", runtimeProvider: "cerebras", displayName: "Cerebras", apiKeyField: "cerebras_api_key", envKey: "CEREBRAS_API_KEY", baseUrl: "https://api.cerebras.ai/v1", modelsUrl: "https://api.cerebras.ai/v1/models", requestContractStrategy: "top_level_reasoning_effort_and_extra_body_disable_reasoning", clientRuntimeSupported: true, uiGroup: BYOK_UI_GROUP, providerKind: "hosted", displayOrder: 50, aliases: [] },
50839
+ { key: "deepseek", runtimeProvider: "deepseek", displayName: "DeepSeek", apiKeyField: "deepseek_api_key", envKey: "DEEPSEEK_API_KEY", baseUrl: "https://api.deepseek.com", modelsUrl: "https://api.deepseek.com/models", requestContractStrategy: "deepseek_extra_body", clientRuntimeSupported: true, uiGroup: BYOK_UI_GROUP, providerKind: "direct", displayOrder: 60, aliases: ["deep seek", "deepseek ai", "deepseek.ai"] },
50840
+ { key: "fireworks", runtimeProvider: "fireworks", displayName: "Fireworks AI", apiKeyField: "fireworks_api_key", envKey: "FIREWORKS_API_KEY", baseUrl: "https://api.fireworks.ai/inference/v1", modelsUrl: "https://api.fireworks.ai/inference/v1/models", requestContractStrategy: "top_level_reasoning_effort_and_extra_body_thinking_type", clientRuntimeSupported: true, uiGroup: BYOK_UI_GROUP, providerKind: "hosted", displayOrder: 70, aliases: ["fireworks ai"] },
50841
+ { key: "google", runtimeProvider: "gemini", displayName: "Google Gemini", apiKeyField: "gemini_api_key", envKey: "GOOGLE_AI_PLATFORM_API_KEY", baseUrl: null, modelsUrl: null, requestContractStrategy: "native", clientRuntimeSupported: true, uiGroup: BYOK_UI_GROUP, providerKind: "direct", displayOrder: 80, aliases: ["gemini"] },
50842
+ { key: "groq", runtimeProvider: "groq", displayName: "Groq", apiKeyField: "groq_api_key", envKey: "GROQ_API_KEY", baseUrl: "https://api.groq.com/openai/v1", modelsUrl: "https://api.groq.com/openai/v1/models", requestContractStrategy: "native", clientRuntimeSupported: true, uiGroup: BYOK_UI_GROUP, providerKind: "hosted", displayOrder: 90, aliases: ["groqcloud", "groq cloud"] },
50843
+ { key: "lightning", runtimeProvider: "lightning", displayName: "Lightning AI", apiKeyField: "lightning_api_key", envKey: "LIGHTNING_API_KEY", baseUrl: "https://lightning.ai/api/v1", modelsUrl: "https://lightning.ai/api/v1/models", requestContractStrategy: "none", clientRuntimeSupported: true, uiGroup: BYOK_UI_GROUP, providerKind: "hosted", displayOrder: 100, aliases: ["litai", "lightning ai"] },
50844
+ { key: "mistral", runtimeProvider: "mistral", displayName: "Mistral", apiKeyField: "mistral_api_key", envKey: "MISTRAL_API_KEY", baseUrl: "https://api.mistral.ai/v1", modelsUrl: "https://api.mistral.ai/v1/models", requestContractStrategy: "top_level_reasoning_effort", clientRuntimeSupported: true, uiGroup: BYOK_UI_GROUP, providerKind: "direct", displayOrder: 110, aliases: ["mistral ai"] },
50845
+ { key: "moonshot", runtimeProvider: "moonshot", displayName: "Moonshot/Kimi", apiKeyField: "moonshot_api_key", envKey: "MOONSHOT_API_KEY", baseUrl: "https://api.moonshot.ai/v1", modelsUrl: "https://api.moonshot.ai/v1/models", requestContractStrategy: "extra_body_thinking_type", clientRuntimeSupported: true, uiGroup: BYOK_UI_GROUP, providerKind: "direct", displayOrder: 120, aliases: ["kimi", "moonshot ai"] },
50846
+ { key: "openai", runtimeProvider: "openai", displayName: "OpenAI", apiKeyField: "openai_api_key", envKey: "OPENAI_API_KEY", baseUrl: "https://api.openai.com/v1", modelsUrl: "https://api.openai.com/v1/models", requestContractStrategy: "native", clientRuntimeSupported: true, uiGroup: BYOK_UI_GROUP, providerKind: "direct", displayOrder: 130, aliases: [] },
50847
+ { key: "openrouter", runtimeProvider: "openrouter", displayName: "OpenRouter", apiKeyField: "openrouter_api_key", envKey: "OPENROUTER_API_KEY", baseUrl: "https://openrouter.ai/api/v1", modelsUrl: "https://openrouter.ai/api/v1/models", requestContractStrategy: "openrouter", clientRuntimeSupported: true, uiGroup: BYOK_UI_GROUP, providerKind: "hosted", displayOrder: 140, aliases: ["open-router", "open router", "openrouter ai"] },
50848
+ { key: "together", runtimeProvider: "together", displayName: "Together AI", apiKeyField: "together_api_key", envKey: "TOGETHER_API_KEY", baseUrl: "https://api.together.xyz/v1", modelsUrl: "https://api.together.xyz/v1/models", requestContractStrategy: "top_level_reasoning_effort_and_extra_body_reasoning_enabled", clientRuntimeSupported: true, uiGroup: BYOK_UI_GROUP, providerKind: "hosted", displayOrder: 150, aliases: ["together ai"] },
50849
+ { key: "venice", runtimeProvider: "venice", displayName: "Venice AI", apiKeyField: "venice_api_key", envKey: "VENICE_API_KEY", baseUrl: "https://api.venice.ai/api/v1", modelsUrl: "https://api.venice.ai/api/v1/models", requestContractStrategy: "venice", clientRuntimeSupported: true, uiGroup: BYOK_UI_GROUP, providerKind: "hosted", displayOrder: 160, aliases: ["venice.ai"] },
50850
+ { key: "xai", runtimeProvider: "grok", displayName: "xAI", apiKeyField: "grok_api_key", envKey: "XAI_API_KEY", baseUrl: "https://api.x.ai/v1", modelsUrl: "https://api.x.ai/v1/models", requestContractStrategy: "native", clientRuntimeSupported: true, uiGroup: BYOK_UI_GROUP, providerKind: "direct", displayOrder: 170, aliases: ["x", "x.ai", "grok"] }
50431
50851
  ];
50432
50852
  BYOK_PROVIDER_KEY_BY_ALIAS = /* @__PURE__ */ new Map();
50433
50853
  for (const provider of BYOK_PROVIDERS) {
@@ -50467,6 +50887,7 @@ var init_client_runtime_provider_visibility_contract = __esm({
50467
50887
  "alibaba_cloud_model_studio",
50468
50888
  "amazon_bedrock",
50469
50889
  "anthropic",
50890
+ "byteplus",
50470
50891
  "cerebras",
50471
50892
  "deepseek",
50472
50893
  "fireworks",
@@ -50845,129 +51266,6 @@ var init_local_breadcrumbs = __esm({
50845
51266
  }
50846
51267
  });
50847
51268
 
50848
- // lib/runtime-policy.generated.json
50849
- var runtime_policy_generated_default2;
50850
- var init_runtime_policy_generated2 = __esm({
50851
- "lib/runtime-policy.generated.json"() {
50852
- runtime_policy_generated_default2 = {
50853
- ui: {
50854
- performance_defaults: {
50855
- default_timeframe: "30d"
50856
- },
50857
- auth_bootstrap_retry: {
50858
- max_attempts: 3,
50859
- jitter_milliseconds: 750,
50860
- base_delay_milliseconds: 500,
50861
- min_delay_milliseconds: 250,
50862
- max_delay_milliseconds: 1e4
50863
- }
50864
- },
50865
- ai_dashboard: {
50866
- market_news_bounds: {
50867
- max_items_min: 1,
50868
- max_items_max: 100,
50869
- lookback_hours_min: 1,
50870
- lookback_hours_max: 168,
50871
- max_items_steps: [
50872
- 1,
50873
- 2,
50874
- 3,
50875
- 4,
50876
- 5,
50877
- 6,
50878
- 7,
50879
- 8,
50880
- 9,
50881
- 10,
50882
- 15,
50883
- 20,
50884
- 25,
50885
- 30,
50886
- 40,
50887
- 50,
50888
- 60,
50889
- 75,
50890
- 90,
50891
- 100
50892
- ],
50893
- lookback_hours_steps: [
50894
- 1,
50895
- 2,
50896
- 4,
50897
- 8,
50898
- 12,
50899
- 24,
50900
- 48,
50901
- 72,
50902
- 168
50903
- ]
50904
- }
50905
- },
50906
- trading: {
50907
- engine: {
50908
- client_runtime: {
50909
- recovery: {
50910
- resume_retry_base_delay_ms: 1e3,
50911
- resume_retry_max_delay_ms: 3e4,
50912
- transient_load_min_delay_ms: 3e4,
50913
- transient_load_max_delay_ms: 12e4,
50914
- rate_limit_buffer_ms: 1e3,
50915
- rate_limit_max_delay_ms: 3e5,
50916
- engine_stop_settle_retry_delay_ms: 250,
50917
- recoverable_reset_settle_retry_delay_ms: 1500,
50918
- local_ai_preflight_timeout_ms: 3e3,
50919
- surge_stagger_max_ms: 6e4,
50920
- surge_stagger_min_ms: 2e3,
50921
- surge_stagger_min_candidates: 4,
50922
- stagger_deadline_ttl_ms: 3e5,
50923
- server_active_reprobe_delay_ms: 6e4,
50924
- transient_load_jitter_ms: 1e4,
50925
- cross_host_completed_ttl_ms: 15e3,
50926
- telemetry_dedupe_ttl_ms: 5e3,
50927
- browser_presence_heartbeat_interval_ms: 3e4,
50928
- host_liveness_heartbeat_interval_ms: 3e4,
50929
- host_liveness_recovery_nudge_ttl_ms: 1e4
50930
- }
50931
- }
50932
- }
50933
- },
50934
- external_inference: {
50935
- service: {
50936
- update_check_interval_ms: 3e5,
50937
- update_registry_timeout_ms: 15e3,
50938
- startup_max_attempts: 40,
50939
- startup_poll_interval_ms: 250,
50940
- restart_stable_uptime_ms: 6e4,
50941
- restart_backoff_base_ms: 1e3,
50942
- restart_backoff_max_ms: 3e4,
50943
- restart_exponent_max: 5
50944
- }
50945
- },
50946
- desktop: {
50947
- runtime_watchdog: {
50948
- ping_interval_milliseconds: 15e3,
50949
- telemetry_interval_milliseconds: 3e5
50950
- }
50951
- },
50952
- screener: {
50953
- resource_scheduler: {
50954
- client_lock_ttl_milliseconds: 12e4,
50955
- client_poll_interval_milliseconds: 250
50956
- }
50957
- },
50958
- deployment: {
50959
- cutover_buffer: {
50960
- target_timeout_ms: 3e3,
50961
- retired_timeout_ms: 45e3,
50962
- max_body_bytes: 33554432,
50963
- max_inflight: 16,
50964
- max_queue: 64
50965
- }
50966
- }
50967
- };
50968
- }
50969
- });
50970
-
50971
51269
  // lib/api/shared.ts
50972
51270
  function getProfileHeaders(baseHeaders = {}, explicitProfileId) {
50973
51271
  const headers = { ...baseHeaders };
@@ -50975,7 +51273,7 @@ function getProfileHeaders(baseHeaders = {}, explicitProfileId) {
50975
51273
  if (profileId) headers["x-profile-id"] = profileId.toString();
50976
51274
  return headers;
50977
51275
  }
50978
- var getApiUrl, API_URL, sleep2, AUTH_BOOTSTRAP_GET_MAX_ATTEMPTS, AUTH_BOOTSTRAP_RETRY_JITTER_MS, isTransientNetworkFetchError, createIdempotencyKey, getErrorMessage, getErrorPayloadOrEmpty, getErrorPayloadOrFallbackDetail, getErrorMessageFromResponse, activeProfileId, PROFILE_STORAGE_KEY;
51276
+ var getApiUrl, API_URL, sleep2, AUTH_BOOTSTRAP_GET_MAX_ATTEMPTS, AUTH_BOOTSTRAP_RETRY_JITTER_MS, parseRetryAfterMs2, isTransientNetworkFetchError, createIdempotencyKey, getErrorMessage, getErrorPayloadOrEmpty, getErrorPayloadOrFallbackDetail, getErrorMessageFromResponse, activeProfileId, PROFILE_STORAGE_KEY;
50979
51277
  var init_shared = __esm({
50980
51278
  "lib/api/shared.ts"() {
50981
51279
  "use strict";
@@ -51015,6 +51313,14 @@ var init_shared = __esm({
51015
51313
  sleep2 = (ms) => new Promise((resolve12) => setTimeout(resolve12, ms));
51016
51314
  AUTH_BOOTSTRAP_GET_MAX_ATTEMPTS = runtime_policy_generated_default2.ui.auth_bootstrap_retry.max_attempts;
51017
51315
  AUTH_BOOTSTRAP_RETRY_JITTER_MS = runtime_policy_generated_default2.ui.auth_bootstrap_retry.jitter_milliseconds;
51316
+ parseRetryAfterMs2 = (value) => {
51317
+ if (!value) return null;
51318
+ const seconds = Number(value);
51319
+ if (Number.isFinite(seconds) && seconds >= 0) return Math.round(seconds * 1e3);
51320
+ const retryAtMs = Date.parse(value);
51321
+ if (Number.isFinite(retryAtMs)) return Math.max(0, retryAtMs - Date.now());
51322
+ return null;
51323
+ };
51018
51324
  isTransientNetworkFetchError = (error48) => {
51019
51325
  const message = error48 instanceof Error ? error48.message : String(error48 || "");
51020
51326
  const normalized = message.toLowerCase();
@@ -51087,13 +51393,21 @@ async function getExecutionAssetMetadata(exchange, symbol2, options) {
51087
51393
  const response = await fetch(url2, {
51088
51394
  headers: getProfileHeaders({}, options?.profileId),
51089
51395
  credentials: "include",
51090
- cache: "no-store"
51396
+ cache: "no-store",
51397
+ signal: options?.signal
51091
51398
  });
51092
51399
  if (!response.ok) {
51093
- throw new Error(`Failed to fetch execution asset metadata: ${response.status} ${response.statusText}`);
51400
+ const summary = `Failed to fetch execution asset metadata: ${response.status} ${response.statusText}`;
51401
+ const detail = await getErrorMessageFromResponse(response, summary);
51402
+ throw new ExecutionAssetMetadataRequestError(
51403
+ detail === summary ? summary : `${summary}: ${detail}`,
51404
+ response.status,
51405
+ parseRetryAfterMs2(response.headers.get("Retry-After"))
51406
+ );
51094
51407
  }
51095
51408
  return response.json();
51096
51409
  }
51410
+ var ExecutionAssetMetadataRequestError;
51097
51411
  var init_market_data = __esm({
51098
51412
  "lib/api/market-data.ts"() {
51099
51413
  "use strict";
@@ -51103,6 +51417,14 @@ var init_market_data = __esm({
51103
51417
  init_abort();
51104
51418
  init_network_debug();
51105
51419
  init_shared();
51420
+ ExecutionAssetMetadataRequestError = class extends Error {
51421
+ constructor(message, status, retryAfterMs) {
51422
+ super(message);
51423
+ this.status = status;
51424
+ this.retryAfterMs = retryAfterMs;
51425
+ this.name = "ExecutionAssetMetadataRequestError";
51426
+ }
51427
+ };
51106
51428
  }
51107
51429
  });
51108
51430
 
@@ -52196,8 +52518,8 @@ var init_api2 = __esm({
52196
52518
  };
52197
52519
  CLIENT_EXCHANGE_AUTHORITY_DEVICE_KEY = "vtx_client_exchange_authority_device_v1";
52198
52520
  CLIENT_EXCHANGE_AUTHORITY_SESSION_KEY = "vtx_client_exchange_authority_session_v1";
52199
- getOrCreateClientExchangeAuthorityIdentity = (storage, key, label) => {
52200
- const existing = String(storage.getItem(key) || "").trim().toLowerCase();
52521
+ getOrCreateClientExchangeAuthorityIdentity = (storage2, key, label) => {
52522
+ const existing = String(storage2.getItem(key) || "").trim().toLowerCase();
52201
52523
  if (/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(existing)) {
52202
52524
  return existing;
52203
52525
  }
@@ -52205,7 +52527,7 @@ var init_api2 = __esm({
52205
52527
  if (!generated || !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(generated)) {
52206
52528
  throw new Error(`Secure ${label} generation is unavailable.`);
52207
52529
  }
52208
- storage.setItem(key, generated);
52530
+ storage2.setItem(key, generated);
52209
52531
  return generated;
52210
52532
  };
52211
52533
  resolveClientExchangeMutationAuthority = (profileId, requiredRuntimeSessionId, explicitRuntimeLeaseToken, explicitRuntimeDeviceId, explicitSchedulerInstanceId) => {
@@ -53500,7 +53822,7 @@ function unpercent(value) {
53500
53822
  return String.fromCharCode(parseInt(code, 16));
53501
53823
  }));
53502
53824
  }
53503
- function wait(delay2) {
53825
+ function wait2(delay2) {
53504
53826
  return new Promise((resolve12) => setTimeout(resolve12, delay2));
53505
53827
  }
53506
53828
  var MAX_ATTEMPTS, SLOT_INTERVAL, defaultGetUrlFunc, reData, reIpfs, locked, Gateways, fetchSignals, FetchCancelSignal, FetchRequest, FetchResponse;
@@ -53863,7 +54185,7 @@ var init_fetch = __esm({
53863
54185
  request: _request
53864
54186
  });
53865
54187
  if (delay2 > 0) {
53866
- await wait(delay2);
54188
+ await wait2(delay2);
53867
54189
  }
53868
54190
  let req = this.clone();
53869
54191
  const scheme = (req.url.split(":")[0] || "").toLowerCase();
@@ -77478,9 +77800,9 @@ var init_provider_socket = __esm({
77478
77800
  */
77479
77801
  _register(filterId, subscriber) {
77480
77802
  this.#subs.set(filterId, subscriber);
77481
- const pending2 = this.#pending.get(filterId);
77482
- if (pending2) {
77483
- for (const message of pending2) {
77803
+ const pending3 = this.#pending.get(filterId);
77804
+ if (pending3) {
77805
+ for (const message of pending3) {
77484
77806
  subscriber._handleMessage(message);
77485
77807
  }
77486
77808
  this.#pending.delete(filterId);
@@ -77532,12 +77854,12 @@ var init_provider_socket = __esm({
77532
77854
  if (subscriber) {
77533
77855
  subscriber._handleMessage(result2.params.result);
77534
77856
  } else {
77535
- let pending2 = this.#pending.get(filterId);
77536
- if (pending2 == null) {
77537
- pending2 = [];
77538
- this.#pending.set(filterId, pending2);
77857
+ let pending3 = this.#pending.get(filterId);
77858
+ if (pending3 == null) {
77859
+ pending3 = [];
77860
+ this.#pending.set(filterId, pending3);
77539
77861
  }
77540
- pending2.push(result2.params.result);
77862
+ pending3.push(result2.params.result);
77541
77863
  }
77542
77864
  } else {
77543
77865
  this.emit("error", makeError("received unexpected message", "UNKNOWN_ERROR", {
@@ -83044,6 +83366,7 @@ var init_hyperliquid_client = __esm({
83044
83366
  init_define_VTX_EXO_POLICY();
83045
83367
  init_define_VTX_GROK_POLICY();
83046
83368
  init_define_VTX_PI_MODEL_POLICY();
83369
+ init_hyperliquid_public_read();
83047
83370
  init_api2();
83048
83371
  init_abort();
83049
83372
  init_hyperliquid_market_symbol();
@@ -83128,11 +83451,11 @@ var init_hyperliquid_client = __esm({
83128
83451
  return 0;
83129
83452
  }
83130
83453
  try {
83131
- const storage = window.localStorage;
83132
- if (!storage) {
83454
+ const storage2 = window.localStorage;
83455
+ if (!storage2) {
83133
83456
  return 0;
83134
83457
  }
83135
- const parsed = Number.parseInt(storage.getItem(HYPERLIQUID_NONCE_STORAGE_KEY) || "0", 10);
83458
+ const parsed = Number.parseInt(storage2.getItem(HYPERLIQUID_NONCE_STORAGE_KEY) || "0", 10);
83136
83459
  return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
83137
83460
  } catch {
83138
83461
  return 0;
@@ -83143,11 +83466,11 @@ var init_hyperliquid_client = __esm({
83143
83466
  return;
83144
83467
  }
83145
83468
  try {
83146
- const storage = window.localStorage;
83147
- if (!storage) {
83469
+ const storage2 = window.localStorage;
83470
+ if (!storage2) {
83148
83471
  return;
83149
83472
  }
83150
- storage.setItem(HYPERLIQUID_NONCE_STORAGE_KEY, String(nonce));
83473
+ storage2.setItem(HYPERLIQUID_NONCE_STORAGE_KEY, String(nonce));
83151
83474
  } catch {
83152
83475
  }
83153
83476
  };
@@ -83310,27 +83633,13 @@ var init_hyperliquid_client = __esm({
83310
83633
  method: "POST",
83311
83634
  url: requestUrl
83312
83635
  });
83313
- let response = null;
83314
83636
  try {
83315
- response = await fetch(requestUrl, {
83316
- method: "POST",
83317
- headers: {
83318
- "Content-Type": "application/json"
83319
- },
83320
- body: JSON.stringify(body),
83321
- signal: input.signal
83322
- });
83323
- const payload = await response.json().catch(() => ({}));
83324
- if (!response.ok) {
83325
- throw new Error(sanitizeRuntimeDiagnosticValue(
83326
- typeof payload?.response === "string" ? String(payload.response) : typeof payload?.detail === "string" ? String(payload.detail) : `Hyperliquid ${label} request failed.`
83327
- ));
83328
- }
83329
- trace.completeSuccess(response.status);
83637
+ const { payload } = await readHyperliquidPublicInfo(apiUrl, body, { signal: input.signal });
83638
+ trace.completeSuccess(200);
83330
83639
  return payload;
83331
83640
  } catch (error48) {
83332
83641
  const sanitizedError = toSanitizedRuntimeError(error48);
83333
- trace.completeError(sanitizedError, response?.status ?? null);
83642
+ trace.completeError(sanitizedError, error48?.status ?? null);
83334
83643
  throw sanitizedError;
83335
83644
  }
83336
83645
  };
@@ -83764,11 +84073,11 @@ var init_hyperliquid_client = __esm({
83764
84073
  ancestors: /* @__PURE__ */ new Set()
83765
84074
  }));
83766
84075
  while (pendingOrders.length > 0) {
83767
- const pending2 = pendingOrders.shift();
83768
- if (pending2 == null) {
84076
+ const pending3 = pendingOrders.shift();
84077
+ if (pending3 == null) {
83769
84078
  break;
83770
84079
  }
83771
- const { raw, inheritedCoin, depth, ancestors } = pending2;
84080
+ const { raw, inheritedCoin, depth, ancestors } = pending3;
83772
84081
  if (raw == null || typeof raw !== "object" || Array.isArray(raw)) {
83773
84082
  throw new Error("Malformed Hyperliquid frontendOpenOrders member.");
83774
84083
  }
@@ -84548,12 +84857,12 @@ var init_hyperliquid_client = __esm({
84548
84857
  };
84549
84858
  };
84550
84859
  loadClientExecutionReferenceEvidence = async (input, executionObservabilityDeadlineMs) => {
84551
- const policy = input.config?.client_runtime_execution_observability;
84552
- if (policy?.enabled !== true || policy.fresh_l2_fallback_enabled !== true || !input.durableMutation) {
84860
+ const policy2 = input.config?.client_runtime_execution_observability;
84861
+ if (policy2?.enabled !== true || policy2.fresh_l2_fallback_enabled !== true || !input.durableMutation) {
84553
84862
  return null;
84554
84863
  }
84555
- const timeoutMs = Number(policy.snapshot_timeout_ms);
84556
- const acceptableAgeMs = Number(policy.acceptable_snapshot_age_ms);
84864
+ const timeoutMs = Number(policy2.snapshot_timeout_ms);
84865
+ const acceptableAgeMs = Number(policy2.acceptable_snapshot_age_ms);
84557
84866
  if (!Number.isInteger(timeoutMs) || timeoutMs <= 0 || !Number.isInteger(acceptableAgeMs) || acceptableAgeMs < 0) {
84558
84867
  return { referenceSourceKind: "policy_unavailable" };
84559
84868
  }
@@ -85243,7 +85552,7 @@ function validateDeviceSecrets(value, options) {
85243
85552
  return [provider, slots];
85244
85553
  }).filter(([, slots]) => slots.some(Boolean))
85245
85554
  );
85246
- const storage = normalizeDeviceSecretStorage(record5.storage);
85555
+ const storage2 = normalizeDeviceSecretStorage(record5.storage);
85247
85556
  const hyperliquidSigningKey = typeof record5.hyperliquidSigningKey === "string" ? record5.hyperliquidSigningKey.trim() || void 0 : void 0;
85248
85557
  const rawLocalAi = record5.localAi && typeof record5.localAi === "object" ? record5.localAi : {};
85249
85558
  const localAi = normalizeLocalAiSecrets({
@@ -85295,7 +85604,7 @@ function validateDeviceSecrets(value, options) {
85295
85604
  ...Object.keys(providerBaseUrlSlots).length > 0 ? { providerBaseUrlSlots } : {},
85296
85605
  ...localAi ? { localAi } : {},
85297
85606
  ...openaiCompatible ? { openaiCompatible } : {},
85298
- storage
85607
+ storage: storage2
85299
85608
  },
85300
85609
  activeProvider,
85301
85610
  hasHyperliquidSigningKey,
@@ -85545,8 +85854,8 @@ var init_vault = __esm({
85545
85854
  mergeHydratedSecrets = (existingLocalSecrets, remoteSecrets, options) => {
85546
85855
  const localNormalized = validateDeviceSecrets(existingLocalSecrets, options).normalized;
85547
85856
  const remoteNormalized = validateDeviceSecrets(remoteSecrets, options).normalized;
85548
- const storage = normalizeDeviceSecretStorage(localNormalized?.storage ?? remoteNormalized?.storage);
85549
- const mergedLocalAi = storage.byok === "device" ? normalizeLocalAiSecrets({
85857
+ const storage2 = normalizeDeviceSecretStorage(localNormalized?.storage ?? remoteNormalized?.storage);
85858
+ const mergedLocalAi = storage2.byok === "device" ? normalizeLocalAiSecrets({
85550
85859
  baseUrl: localNormalized?.localAi?.baseUrl,
85551
85860
  apiKey: localNormalized?.localAi?.apiKey,
85552
85861
  serverType: localNormalized?.localAi?.serverType
@@ -85555,7 +85864,7 @@ var init_vault = __esm({
85555
85864
  apiKey: remoteNormalized?.localAi?.apiKey ?? localNormalized?.localAi?.apiKey,
85556
85865
  serverType: localNormalized?.localAi?.serverType
85557
85866
  });
85558
- const mergedOpenAiCompatible = storage.byok === "device" ? normalizeOpenAiCompatibleSecrets({
85867
+ const mergedOpenAiCompatible = storage2.byok === "device" ? normalizeOpenAiCompatibleSecrets({
85559
85868
  baseUrl: localNormalized?.openaiCompatible?.baseUrl,
85560
85869
  apiKey: localNormalized?.openaiCompatible?.apiKey
85561
85870
  }) : normalizeOpenAiCompatibleSecrets({
@@ -85563,14 +85872,14 @@ var init_vault = __esm({
85563
85872
  apiKey: remoteNormalized?.openaiCompatible?.apiKey ?? localNormalized?.openaiCompatible?.apiKey
85564
85873
  });
85565
85874
  return validateDeviceSecrets({
85566
- hyperliquidSigningKey: storage.hyperliquid === "device" ? localNormalized?.hyperliquidSigningKey : remoteNormalized?.hyperliquidSigningKey,
85567
- providerKeys: storage.byok === "device" ? { ...localNormalized?.providerKeys ?? {} } : { ...remoteNormalized?.providerKeys ?? {} },
85568
- providerKeySlots: storage.byok === "device" ? { ...localNormalized?.providerKeySlots ?? {} } : { ...remoteNormalized?.providerKeySlots ?? {} },
85569
- providerBaseUrls: storage.byok === "device" ? { ...localNormalized?.providerBaseUrls ?? {} } : { ...remoteNormalized?.providerBaseUrls ?? {} },
85570
- providerBaseUrlSlots: storage.byok === "device" ? { ...localNormalized?.providerBaseUrlSlots ?? {} } : { ...remoteNormalized?.providerBaseUrlSlots ?? {} },
85875
+ hyperliquidSigningKey: storage2.hyperliquid === "device" ? localNormalized?.hyperliquidSigningKey : remoteNormalized?.hyperliquidSigningKey,
85876
+ providerKeys: storage2.byok === "device" ? { ...localNormalized?.providerKeys ?? {} } : { ...remoteNormalized?.providerKeys ?? {} },
85877
+ providerKeySlots: storage2.byok === "device" ? { ...localNormalized?.providerKeySlots ?? {} } : { ...remoteNormalized?.providerKeySlots ?? {} },
85878
+ providerBaseUrls: storage2.byok === "device" ? { ...localNormalized?.providerBaseUrls ?? {} } : { ...remoteNormalized?.providerBaseUrls ?? {} },
85879
+ providerBaseUrlSlots: storage2.byok === "device" ? { ...localNormalized?.providerBaseUrlSlots ?? {} } : { ...remoteNormalized?.providerBaseUrlSlots ?? {} },
85571
85880
  ...mergedLocalAi ? { localAi: mergedLocalAi } : {},
85572
85881
  ...mergedOpenAiCompatible ? { openaiCompatible: mergedOpenAiCompatible } : {},
85573
- storage
85882
+ storage: storage2
85574
85883
  }, options).normalized;
85575
85884
  };
85576
85885
  preserveDeviceOnlySecrets = (value, options) => {
@@ -85578,18 +85887,18 @@ var init_vault = __esm({
85578
85887
  if (!normalized) {
85579
85888
  return null;
85580
85889
  }
85581
- const storage = normalizeDeviceSecretStorage(normalized.storage);
85582
- const localAi = storage.byok === "device" ? normalizeLocalAiSecrets(normalized.localAi) : normalizeLocalAiSecrets({ apiKey: normalized.localAi?.apiKey, serverType: normalized.localAi?.serverType });
85583
- const openaiCompatible = storage.byok === "device" ? normalizeOpenAiCompatibleSecrets(normalized.openaiCompatible) : normalizeOpenAiCompatibleSecrets({ apiKey: normalized.openaiCompatible?.apiKey });
85890
+ const storage2 = normalizeDeviceSecretStorage(normalized.storage);
85891
+ const localAi = storage2.byok === "device" ? normalizeLocalAiSecrets(normalized.localAi) : normalizeLocalAiSecrets({ apiKey: normalized.localAi?.apiKey, serverType: normalized.localAi?.serverType });
85892
+ const openaiCompatible = storage2.byok === "device" ? normalizeOpenAiCompatibleSecrets(normalized.openaiCompatible) : normalizeOpenAiCompatibleSecrets({ apiKey: normalized.openaiCompatible?.apiKey });
85584
85893
  return validateDeviceSecrets({
85585
- hyperliquidSigningKey: storage.hyperliquid === "device" ? normalized.hyperliquidSigningKey : void 0,
85586
- providerKeys: storage.byok === "device" ? { ...normalized.providerKeys } : {},
85587
- providerKeySlots: storage.byok === "device" ? { ...normalized.providerKeySlots ?? {} } : {},
85588
- providerBaseUrls: storage.byok === "device" ? { ...normalized.providerBaseUrls ?? {} } : {},
85589
- providerBaseUrlSlots: storage.byok === "device" ? { ...normalized.providerBaseUrlSlots ?? {} } : {},
85894
+ hyperliquidSigningKey: storage2.hyperliquid === "device" ? normalized.hyperliquidSigningKey : void 0,
85895
+ providerKeys: storage2.byok === "device" ? { ...normalized.providerKeys } : {},
85896
+ providerKeySlots: storage2.byok === "device" ? { ...normalized.providerKeySlots ?? {} } : {},
85897
+ providerBaseUrls: storage2.byok === "device" ? { ...normalized.providerBaseUrls ?? {} } : {},
85898
+ providerBaseUrlSlots: storage2.byok === "device" ? { ...normalized.providerBaseUrlSlots ?? {} } : {},
85590
85899
  ...localAi ? { localAi } : {},
85591
85900
  ...openaiCompatible ? { openaiCompatible } : {},
85592
- storage
85901
+ storage: storage2
85593
85902
  }, options).normalized;
85594
85903
  };
85595
85904
  normalizeClientRuntimeSecretProvider = (value) => {
@@ -86562,9 +86871,9 @@ var init_runtime_execution = __esm({
86562
86871
  return null;
86563
86872
  }
86564
86873
  };
86565
- setClientRuntimeProtectionStorage = (storage) => {
86566
- if (clientRuntimeProtectionStorage === storage) return;
86567
- clientRuntimeProtectionStorage = storage;
86874
+ setClientRuntimeProtectionStorage = (storage2) => {
86875
+ if (clientRuntimeProtectionStorage === storage2) return;
86876
+ clientRuntimeProtectionStorage = storage2;
86568
86877
  trailingStopMemory.clear();
86569
86878
  protectiveGroupMemory.clear();
86570
86879
  protectiveGroupReadFailures.clear();
@@ -86575,10 +86884,10 @@ var init_runtime_execution = __esm({
86575
86884
  const key = trailingStopStorageKey(profileId, symbol2);
86576
86885
  const inMemory = trailingStopMemory.get(key);
86577
86886
  let raw = inMemory ?? [];
86578
- const storage = resolveClientRuntimeProtectionStorage();
86579
- if (inMemory === void 0 && storage) {
86887
+ const storage2 = resolveClientRuntimeProtectionStorage();
86888
+ if (inMemory === void 0 && storage2) {
86580
86889
  try {
86581
- const persisted = storage.getItem(key);
86890
+ const persisted = storage2.getItem(key);
86582
86891
  if (persisted !== null) {
86583
86892
  raw = JSON.parse(persisted);
86584
86893
  }
@@ -86612,20 +86921,20 @@ var init_runtime_execution = __esm({
86612
86921
  const key = trailingStopStorageKey(profileId, symbol2);
86613
86922
  if (records.length === 0) {
86614
86923
  trailingStopMemory.set(key, []);
86615
- const storage2 = resolveClientRuntimeProtectionStorage();
86616
- if (storage2) {
86924
+ const storage3 = resolveClientRuntimeProtectionStorage();
86925
+ if (storage3) {
86617
86926
  try {
86618
- storage2.removeItem(key);
86927
+ storage3.removeItem(key);
86619
86928
  } catch {
86620
86929
  }
86621
86930
  }
86622
86931
  return;
86623
86932
  }
86624
86933
  trailingStopMemory.set(key, records);
86625
- const storage = resolveClientRuntimeProtectionStorage();
86626
- if (storage) {
86934
+ const storage2 = resolveClientRuntimeProtectionStorage();
86935
+ if (storage2) {
86627
86936
  try {
86628
- storage.setItem(key, JSON.stringify(records));
86937
+ storage2.setItem(key, JSON.stringify(records));
86629
86938
  } catch {
86630
86939
  }
86631
86940
  }
@@ -86642,10 +86951,10 @@ var init_runtime_execution = __esm({
86642
86951
  const key = protectiveGroupStorageKey(profileId, symbol2);
86643
86952
  const inMemory = protectiveGroupMemory.get(key);
86644
86953
  let raw = inMemory ?? [];
86645
- const storage = resolveClientRuntimeProtectionStorage();
86646
- if (inMemory === void 0 && storage) {
86954
+ const storage2 = resolveClientRuntimeProtectionStorage();
86955
+ if (inMemory === void 0 && storage2) {
86647
86956
  try {
86648
- const persisted = storage.getItem(key);
86957
+ const persisted = storage2.getItem(key);
86649
86958
  if (persisted !== null) {
86650
86959
  raw = JSON.parse(persisted);
86651
86960
  }
@@ -86693,12 +87002,12 @@ var init_runtime_execution = __esm({
86693
87002
  protectiveGroupReadFailures.add(key);
86694
87003
  return [];
86695
87004
  }
86696
- const pending2 = replacementRecord;
86697
- const mutationId = String(pending2.mutationId ?? "").trim().toLowerCase();
86698
- const clientOrderId = String(pending2.clientOrderId ?? "").trim().toLowerCase();
86699
- const previousOrderId = Number(pending2.previousOrderId);
86700
- const replacementTriggerPrice = Number(pending2.triggerPrice);
86701
- const replacementSize = Number(pending2.size);
87005
+ const pending3 = replacementRecord;
87006
+ const mutationId = String(pending3.mutationId ?? "").trim().toLowerCase();
87007
+ const clientOrderId = String(pending3.clientOrderId ?? "").trim().toLowerCase();
87008
+ const previousOrderId = Number(pending3.previousOrderId);
87009
+ const replacementTriggerPrice = Number(pending3.triggerPrice);
87010
+ const replacementSize = Number(pending3.size);
86702
87011
  if (!/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(mutationId) || clientOrderId !== `0x${mutationId.replaceAll("-", "")}` || !Number.isSafeInteger(previousOrderId) || previousOrderId <= 0 || previousOrderId !== orderId || !Number.isFinite(replacementTriggerPrice) || replacementTriggerPrice <= 0 || !Number.isFinite(replacementSize) || replacementSize <= 0) {
86703
87012
  protectiveGroupReadFailures.add(key);
86704
87013
  return [];
@@ -86728,10 +87037,10 @@ var init_runtime_execution = __esm({
86728
87037
  protectiveGroupReadFailures.add(key);
86729
87038
  return [];
86730
87039
  }
86731
- const pending2 = pendingRecord;
86732
- const stopLoss = pending2.stopLoss;
86733
- const takeProfit = pending2.takeProfit;
86734
- if (typeof pending2.entryMutationId !== "string" || !/^[0-9a-f-]{36}$/.test(pending2.entryMutationId) || typeof pending2.entryClientOrderId !== "string" || !/^0x[0-9a-f]{32}$/.test(pending2.entryClientOrderId) || pending2.entrySide !== "buy" && pending2.entrySide !== "sell" || !Number.isFinite(Number(pending2.requestedSize)) || Number(pending2.requestedSize) <= 0 || stopLoss == null || typeof stopLoss !== "object" || Array.isArray(stopLoss) || takeProfit == null || typeof takeProfit !== "object" || Array.isArray(takeProfit)) {
87040
+ const pending3 = pendingRecord;
87041
+ const stopLoss = pending3.stopLoss;
87042
+ const takeProfit = pending3.takeProfit;
87043
+ if (typeof pending3.entryMutationId !== "string" || !/^[0-9a-f-]{36}$/.test(pending3.entryMutationId) || typeof pending3.entryClientOrderId !== "string" || !/^0x[0-9a-f]{32}$/.test(pending3.entryClientOrderId) || pending3.entrySide !== "buy" && pending3.entrySide !== "sell" || !Number.isFinite(Number(pending3.requestedSize)) || Number(pending3.requestedSize) <= 0 || stopLoss == null || typeof stopLoss !== "object" || Array.isArray(stopLoss) || takeProfit == null || typeof takeProfit !== "object" || Array.isArray(takeProfit)) {
86735
87044
  protectiveGroupReadFailures.add(key);
86736
87045
  return [];
86737
87046
  }
@@ -86742,10 +87051,10 @@ var init_runtime_execution = __esm({
86742
87051
  return [];
86743
87052
  }
86744
87053
  pendingEntry = {
86745
- entryMutationId: pending2.entryMutationId,
86746
- entryClientOrderId: pending2.entryClientOrderId,
86747
- entrySide: pending2.entrySide,
86748
- requestedSize: Number(pending2.requestedSize),
87054
+ entryMutationId: pending3.entryMutationId,
87055
+ entryClientOrderId: pending3.entryClientOrderId,
87056
+ entrySide: pending3.entrySide,
87057
+ requestedSize: Number(pending3.requestedSize),
86749
87058
  stopLoss: {
86750
87059
  enabled: sl.enabled,
86751
87060
  mode: sl.mode,
@@ -86832,16 +87141,16 @@ var init_runtime_execution = __esm({
86832
87141
  };
86833
87142
  writeClientProtectiveGroups = (profileId, symbol2, groups) => {
86834
87143
  const key = protectiveGroupStorageKey(profileId, symbol2);
86835
- const storage = resolveClientRuntimeProtectionStorage();
86836
- if (!storage) {
87144
+ const storage2 = resolveClientRuntimeProtectionStorage();
87145
+ if (!storage2) {
86837
87146
  protectiveGroupMemory.delete(key);
86838
87147
  protectiveGroupReadFailures.add(key);
86839
87148
  return false;
86840
87149
  }
86841
87150
  try {
86842
87151
  if (groups.length === 0) {
86843
- storage.removeItem(key);
86844
- const removed = storage.getItem(key) === null;
87152
+ storage2.removeItem(key);
87153
+ const removed = storage2.getItem(key) === null;
86845
87154
  if (removed) {
86846
87155
  protectiveGroupMemory.set(key, []);
86847
87156
  protectiveGroupReadFailures.delete(key);
@@ -86849,8 +87158,8 @@ var init_runtime_execution = __esm({
86849
87158
  return removed;
86850
87159
  } else {
86851
87160
  const serialized = JSON.stringify(groups);
86852
- storage.setItem(key, serialized);
86853
- const persisted = storage.getItem(key) === serialized;
87161
+ storage2.setItem(key, serialized);
87162
+ const persisted = storage2.getItem(key) === serialized;
86854
87163
  if (persisted) {
86855
87164
  protectiveGroupMemory.set(key, groups);
86856
87165
  protectiveGroupReadFailures.delete(key);
@@ -87078,18 +87387,18 @@ var init_runtime_execution = __esm({
87078
87387
  throw createClientRuntimeWindowHandoffBeforePlanDispatchError(cleanup);
87079
87388
  };
87080
87389
  canPersistClientProtectiveGroups = (profileId, symbol2) => {
87081
- const storage = resolveClientRuntimeProtectionStorage();
87082
- if (!storage) return false;
87390
+ const storage2 = resolveClientRuntimeProtectionStorage();
87391
+ if (!storage2) return false;
87083
87392
  const probeKey = `${protectiveGroupStorageKey(profileId, symbol2)}:probe`;
87084
87393
  const probeValue = `${Date.now()}:${Math.random()}`;
87085
87394
  try {
87086
- storage.setItem(probeKey, probeValue);
87087
- const durable = storage.getItem(probeKey) === probeValue;
87088
- storage.removeItem(probeKey);
87395
+ storage2.setItem(probeKey, probeValue);
87396
+ const durable = storage2.getItem(probeKey) === probeValue;
87397
+ storage2.removeItem(probeKey);
87089
87398
  return durable;
87090
87399
  } catch {
87091
87400
  try {
87092
- storage.removeItem(probeKey);
87401
+ storage2.removeItem(probeKey);
87093
87402
  } catch {
87094
87403
  }
87095
87404
  return false;
@@ -92638,8 +92947,19 @@ function resolveProviderInvocation(input) {
92638
92947
  }
92639
92948
  const endpoints = objectOrNull3(input.llmConfig.client_runtime_provider_endpoints) ?? {};
92640
92949
  const secretField = OPENAI_COMPATIBLE_SECRET_FIELD[sourceKey] ?? `${sourceKey}_api_key`;
92950
+ const endpointSlots = objectOrNull3(input.secrets.provider_base_url_slots);
92951
+ const sourceEndpointSlots = endpointSlots?.[sourceKey];
92952
+ const slotBaseUrl = Array.isArray(sourceEndpointSlots) ? optionalText(sourceEndpointSlots[0]) : null;
92953
+ const baseUrl = requireText(slotBaseUrl ?? endpoints[`${sourceKey}_base_url`], `${sourceKey} base URL`);
92954
+ const model = requireText(input.prompt.model ?? input.metadata.model, "model");
92955
+ const subscriptionPlan = input.llmConfig.native_subscription_plans?.[sourceKey]?.find(
92956
+ (plan) => plan.id !== "pay_as_you_go" && plan.base_url.replace(/\/+$/, "") === baseUrl.replace(/\/+$/, "")
92957
+ );
92958
+ if (subscriptionPlan?.model_ids && !subscriptionPlan.model_ids.includes(model)) {
92959
+ throw new Error(`Model ${model} is not available on ${subscriptionPlan.display_name}.`);
92960
+ }
92641
92961
  return {
92642
- baseUrl: requireText(endpoints[`${sourceKey}_base_url`], `${sourceKey} base URL`),
92962
+ baseUrl,
92643
92963
  apiKey: requireText(input.secrets[secretField], `${sourceKey} API key`),
92644
92964
  provider: sourceKey,
92645
92965
  transport: "headless_openai_compatible",
@@ -93008,6 +93328,7 @@ var init_headless_local_worker = __esm({
93008
93328
  mistral: "mistral",
93009
93329
  together: "together",
93010
93330
  fireworks: "fireworks",
93331
+ byteplus: "byteplus",
93011
93332
  cerebras: "cerebras",
93012
93333
  moonshot: "moonshot",
93013
93334
  alibaba_cloud_model_studio: "alibaba_cloud_model_studio",
@@ -93583,6 +93904,7 @@ Global options:
93583
93904
  "mistral_api_key",
93584
93905
  "together_api_key",
93585
93906
  "fireworks_api_key",
93907
+ "byteplus_api_key",
93586
93908
  "cerebras_api_key",
93587
93909
  "moonshot_api_key",
93588
93910
  "alibaba_cloud_model_studio_api_key",