@vtxmacro/cli 2026.9.43 → 2026.9.45

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.43",
80
+ package_version: "2026.9.45",
81
81
  codex_package_name: "@openai/codex",
82
82
  codex_version: "0.153.3",
83
83
  copilot_sdk_package_name: "@github/copilot-sdk",
@@ -15532,6 +15532,7 @@ var init_external_inference_contract = __esm({
15532
15532
  );
15533
15533
  agentTurnReceiptSchema = external_exports.strictObject({
15534
15534
  terminal_status: external_exports.enum(["completed", "failed"]),
15535
+ provider_http_status: external_exports.number().int().min(400).max(599).optional(),
15535
15536
  failure_code: safeCodeSchema.nullable(),
15536
15537
  grok_tool_validation: grokToolValidationDiagnosticSchema.optional(),
15537
15538
  grok_response_identity: grokResponseIdentityDiagnosticSchema.optional(),
@@ -15552,7 +15553,10 @@ var init_external_inference_contract = __esm({
15552
15553
  { message: "Agent decision operation IDs must be unique." }
15553
15554
  )
15554
15555
  }).refine(
15555
- (value) => value.grok_tool_validation === void 0 ? value.grok_response_identity !== void 0 || value.dispatch_outcome === void 0 : value.grok_response_identity === void 0 && value.terminal_status === "failed" && value.failure_code === `grok_tool_isolation_${value.grok_tool_validation.reason}` && value.dispatch_outcome === (value.grok_tool_validation.prior_dispatch ? "outcome_unknown" : "not_dispatched") && value.effective_model === null && value.effective_reasoning_effort === null && value.adapter_request_id === null && value.adapter_response_id === null && value.usage.availability === "unavailable",
15556
+ (value) => value.provider_http_status === void 0 || value.terminal_status === "failed",
15557
+ { message: "Provider HTTP status requires a failed Agent turn." }
15558
+ ).refine(
15559
+ (value) => value.grok_tool_validation === void 0 ? value.grok_response_identity !== void 0 || value.provider_http_status !== void 0 || value.dispatch_outcome === void 0 : value.grok_response_identity === void 0 && value.terminal_status === "failed" && value.failure_code === `grok_tool_isolation_${value.grok_tool_validation.reason}` && value.dispatch_outcome === (value.grok_tool_validation.prior_dispatch ? "outcome_unknown" : "not_dispatched") && value.effective_model === null && value.effective_reasoning_effort === null && value.adapter_request_id === null && value.adapter_response_id === null && value.usage.availability === "unavailable",
15556
15560
  { message: "Grok diagnostics must match the failed Agent turn and dispatch outcome." }
15557
15561
  ).refine(
15558
15562
  (value) => value.grok_response_identity === void 0 || value.terminal_status === "failed" && value.failure_code === "grok_provider_identity_mismatch" && value.dispatch_outcome === "outcome_unknown" && value.grok_tool_validation === void 0 && value.effective_model === null && value.effective_reasoning_effort === null && value.adapter_request_id === null && value.adapter_response_id === null && value.usage.availability === "unavailable",
@@ -16080,6 +16084,7 @@ var init_external_inference_contract = __esm({
16080
16084
  adapter_result_ready_at: timestampSchema.optional(),
16081
16085
  provider_dispatch_freshness_remaining_ms: nonNegativeSafeIntegerSchema.nullable().optional(),
16082
16086
  process_exit: codexProcessExitDiagnosticsSchema.nullable().optional(),
16087
+ provider_http_status: external_exports.number().int().min(400).max(599).optional(),
16083
16088
  grok_tool_validation: grokToolValidationDiagnosticSchema.optional(),
16084
16089
  grok_response_identity: grokResponseIdentityDiagnosticSchema.optional(),
16085
16090
  membership_disposition: external_exports.enum([
@@ -17185,18 +17190,18 @@ function parseValue(ctx, integersAsBigInt, end) {
17185
17190
  throw new TomlError("leading zeroes are not allowed", err);
17186
17191
  }
17187
17192
  value = value.replace(/_/g, "");
17188
- let numeric = +value;
17189
- if (isNaN(numeric)) {
17193
+ let numeric2 = +value;
17194
+ if (isNaN(numeric2)) {
17190
17195
  throw new TomlError("invalid number", err);
17191
17196
  }
17192
17197
  if (isInt) {
17193
- if ((isInt = !Number.isSafeInteger(numeric)) && !integersAsBigInt) {
17198
+ if ((isInt = !Number.isSafeInteger(numeric2)) && !integersAsBigInt) {
17194
17199
  throw new TomlError("integer value cannot be represented losslessly", err);
17195
17200
  }
17196
17201
  if (isInt || integersAsBigInt === true)
17197
- numeric = BigInt(value);
17202
+ numeric2 = BigInt(value);
17198
17203
  }
17199
- return numeric;
17204
+ return numeric2;
17200
17205
  }
17201
17206
  const date5 = new TomlDate(value);
17202
17207
  if (!date5.isValid())
@@ -18346,17 +18351,17 @@ while(($line=[Console]::In.ReadLine()) -ne $null) {
18346
18351
  clearTimeout(this.idleTimer);
18347
18352
  this.idleTimer = null;
18348
18353
  }
18349
- const pending2 = this.pending;
18354
+ const pending3 = this.pending;
18350
18355
  this.pending = null;
18351
- if (pending2) {
18352
- clearTimeout(pending2.timer);
18353
- pending2.reject(error48);
18356
+ if (pending3) {
18357
+ clearTimeout(pending3.timer);
18358
+ pending3.reject(error48);
18354
18359
  }
18355
18360
  child.kill("SIGKILL");
18356
18361
  }
18357
18362
  acceptLine(child, line) {
18358
- const pending2 = this.pending;
18359
- if (!pending2 || !line || line.length > 4096) {
18363
+ const pending3 = this.pending;
18364
+ if (!pending3 || !line || line.length > 4096) {
18360
18365
  this.failChild(child, new Error("Windows private ACL broker returned malformed output."));
18361
18366
  return;
18362
18367
  }
@@ -18365,7 +18370,7 @@ while(($line=[Console]::In.ReadLine()) -ne $null) {
18365
18370
  const parsed = JSON.parse(line);
18366
18371
  const status = String(parsed.status);
18367
18372
  const expectedKeys = status === "error" ? "error_code\0id\0status" : "id\0status";
18368
- 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" && ![
18369
18374
  "request_validation",
18370
18375
  "path_lookup",
18371
18376
  "principal_resolution",
@@ -18382,16 +18387,16 @@ while(($line=[Console]::In.ReadLine()) -ne $null) {
18382
18387
  return;
18383
18388
  }
18384
18389
  this.pending = null;
18385
- clearTimeout(pending2.timer);
18390
+ clearTimeout(pending3.timer);
18386
18391
  if (response.status === "ok") {
18387
- pending2.resolve();
18392
+ pending3.resolve();
18388
18393
  } else if (response.status === "missing") {
18389
18394
  const error48 = new Error("Windows private path no longer exists.");
18390
18395
  error48.code = "ENOENT";
18391
- pending2.reject(error48);
18396
+ pending3.reject(error48);
18392
18397
  } else {
18393
- pending2.reject(new Error(
18394
- `Windows private ACL ${pending2.mode} failed (${response.error_code}).`
18398
+ pending3.reject(new Error(
18399
+ `Windows private ACL ${pending3.mode} failed (${response.error_code}).`
18395
18400
  ));
18396
18401
  }
18397
18402
  this.scheduleIdleShutdown();
@@ -18702,10 +18707,10 @@ while(($line=[Console]::In.ReadLine()) -ne $null) {
18702
18707
  }
18703
18708
  return `${platform}:${identity2}`;
18704
18709
  };
18705
- const pending2 = read();
18706
- if (platform === process.platform) cachedSystemBootIdentity = pending2;
18710
+ const pending3 = read();
18711
+ if (platform === process.platform) cachedSystemBootIdentity = pending3;
18707
18712
  try {
18708
- return await pending2;
18713
+ return await pending3;
18709
18714
  } catch (error48) {
18710
18715
  if (platform === process.platform) cachedSystemBootIdentity = null;
18711
18716
  throw error48;
@@ -21037,8 +21042,21 @@ var init_mcp_client = __esm({
21037
21042
  #initialized = false;
21038
21043
  #providerQuotaRecoverySupported = false;
21039
21044
  #runtimeRecoveryDiagnosticsSupported = false;
21045
+ #providerHttpStatusTools = /* @__PURE__ */ new Set();
21040
21046
  #grokToolValidationTools = /* @__PURE__ */ new Set();
21041
21047
  #grokResponseIdentityTools = /* @__PURE__ */ new Set();
21048
+ supportsProviderHttpStatusDiagnostics(tool) {
21049
+ return this.#providerHttpStatusTools.has(tool);
21050
+ }
21051
+ async refreshProviderHttpStatusSupport(tool, options = {}) {
21052
+ if (this.supportsProviderHttpStatusDiagnostics(tool)) return true;
21053
+ try {
21054
+ await this.initialize(options);
21055
+ } catch {
21056
+ return false;
21057
+ }
21058
+ return this.supportsProviderHttpStatusDiagnostics(tool);
21059
+ }
21042
21060
  supportsGrokToolValidationDiagnostics(tool) {
21043
21061
  return this.#grokToolValidationTools.has(tool);
21044
21062
  }
@@ -21145,6 +21163,13 @@ var init_mcp_client = __esm({
21145
21163
  }
21146
21164
  return Array.isArray(node.anyOf) && node.anyOf.some((branch) => advertisesDiagnosticReceipt(branch, field, depth + 1));
21147
21165
  };
21166
+ this.#providerHttpStatusTools.clear();
21167
+ if (advertisesFields("inference.job.fail", ["provider_http_status"])) {
21168
+ this.#providerHttpStatusTools.add("inference.job.fail");
21169
+ }
21170
+ if (advertisesDiagnosticReceipt(heartbeatSchema?.properties?.turn_receipt, "provider_http_status")) {
21171
+ this.#providerHttpStatusTools.add("inference.agent.assignment.heartbeat");
21172
+ }
21148
21173
  if (advertisesDiagnosticReceipt(heartbeatSchema?.properties?.turn_receipt, "grok_tool_validation")) {
21149
21174
  this.#grokToolValidationTools.add("inference.agent.assignment.heartbeat");
21150
21175
  }
@@ -28776,8 +28801,8 @@ child.once('close', async (code, signal) => {
28776
28801
  }
28777
28802
  const id2 = message.id;
28778
28803
  if (typeof id2 === "number" && Number.isSafeInteger(id2) && !("method" in message)) {
28779
- const pending2 = this.pending.get(id2);
28780
- if (!pending2) {
28804
+ const pending3 = this.pending.get(id2);
28805
+ if (!pending3) {
28781
28806
  const retiredMethod = this.retiredResponseIds.get(id2);
28782
28807
  this.retiredResponseIds.delete(id2);
28783
28808
  if (retiredMethod && LATE_RESPONSE_SAFE_METHODS.has(retiredMethod)) {
@@ -28791,11 +28816,11 @@ child.once('close', async (code, signal) => {
28791
28816
  return;
28792
28817
  }
28793
28818
  this.pending.delete(id2);
28794
- if (pending2.timer) clearTimeout(pending2.timer);
28795
- pending2.abortCleanup?.();
28819
+ if (pending3.timer) clearTimeout(pending3.timer);
28820
+ pending3.abortCleanup?.();
28796
28821
  const error48 = objectOrNull(message.error);
28797
28822
  if (error48) {
28798
- pending2.reject(new CodexAppServerError({
28823
+ pending3.reject(new CodexAppServerError({
28799
28824
  message: "Codex app-server rejected a request.",
28800
28825
  category: "adapter",
28801
28826
  code: "rpc_rejected",
@@ -28805,7 +28830,7 @@ child.once('close', async (code, signal) => {
28805
28830
  }
28806
28831
  const result2 = objectOrNull(message.result);
28807
28832
  if (!result2) {
28808
- pending2.reject(new CodexAppServerError({
28833
+ pending3.reject(new CodexAppServerError({
28809
28834
  message: "Codex app-server returned an invalid result.",
28810
28835
  category: "adapter",
28811
28836
  code: "invalid_rpc_result",
@@ -28813,7 +28838,7 @@ child.once('close', async (code, signal) => {
28813
28838
  }));
28814
28839
  return;
28815
28840
  }
28816
- pending2.resolve(result2);
28841
+ pending3.resolve(result2);
28817
28842
  return;
28818
28843
  }
28819
28844
  const method = typeof message.method === "string" ? message.method : "";
@@ -28898,10 +28923,10 @@ child.once('close', async (code, signal) => {
28898
28923
  retryable: true,
28899
28924
  processExit
28900
28925
  });
28901
- for (const pending2 of this.pending.values()) {
28902
- if (pending2.timer) clearTimeout(pending2.timer);
28903
- pending2.abortCleanup?.();
28904
- 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);
28905
28930
  }
28906
28931
  this.pending.clear();
28907
28932
  for (const listener of this.fatalListeners) listener(this.fatalError);
@@ -28960,11 +28985,11 @@ child.once('close', async (code, signal) => {
28960
28985
  });
28961
28986
  }
28962
28987
  return await new Promise((resolve12, reject) => {
28963
- const pending2 = { resolve: resolve12, reject, timer: null, abortCleanup: null };
28964
- pending2.timer = setTimeout(() => {
28988
+ const pending3 = { resolve: resolve12, reject, timer: null, abortCleanup: null };
28989
+ pending3.timer = setTimeout(() => {
28965
28990
  this.pending.delete(id2);
28966
28991
  this.retireResponseId(id2, method);
28967
- pending2.abortCleanup?.();
28992
+ pending3.abortCleanup?.();
28968
28993
  reject(new CodexAppServerError({
28969
28994
  message: "Codex app-server request timed out.",
28970
28995
  category: "timeout",
@@ -28976,8 +29001,8 @@ child.once('close', async (code, signal) => {
28976
29001
  const onAbort = () => {
28977
29002
  this.pending.delete(id2);
28978
29003
  this.retireResponseId(id2, method);
28979
- if (pending2.timer) clearTimeout(pending2.timer);
28980
- pending2.abortCleanup?.();
29004
+ if (pending3.timer) clearTimeout(pending3.timer);
29005
+ pending3.abortCleanup?.();
28981
29006
  reject(new CodexAppServerError({
28982
29007
  message: "Codex request was cancelled.",
28983
29008
  category: "cancelled",
@@ -28986,16 +29011,16 @@ child.once('close', async (code, signal) => {
28986
29011
  }));
28987
29012
  };
28988
29013
  options.signal.addEventListener("abort", onAbort, { once: true });
28989
- pending2.abortCleanup = () => options.signal?.removeEventListener("abort", onAbort);
29014
+ pending3.abortCleanup = () => options.signal?.removeEventListener("abort", onAbort);
28990
29015
  }
28991
- this.pending.set(id2, pending2);
29016
+ this.pending.set(id2, pending3);
28992
29017
  try {
28993
29018
  this.write(params === void 0 ? { id: id2, method } : { id: id2, method, params });
28994
29019
  options.onWritten?.(id2);
28995
29020
  } catch (error48) {
28996
29021
  this.pending.delete(id2);
28997
- if (pending2.timer) clearTimeout(pending2.timer);
28998
- pending2.abortCleanup?.();
29022
+ if (pending3.timer) clearTimeout(pending3.timer);
29023
+ pending3.abortCleanup?.();
28999
29024
  reject(error48);
29000
29025
  }
29001
29026
  });
@@ -30510,15 +30535,15 @@ var init_agent_state = __esm({
30510
30535
  }
30511
30536
  }
30512
30537
  if (state.pending_decision !== null) {
30513
- const pending2 = assertPlainObject(state.pending_decision, message);
30514
- if (!hasExactKeys(pending2, [
30538
+ const pending3 = assertPlainObject(state.pending_decision, message);
30539
+ if (!hasExactKeys(pending3, [
30515
30540
  "operation_id",
30516
30541
  "candidate",
30517
30542
  "observed_at",
30518
30543
  "provenance",
30519
30544
  "first_transmit_at",
30520
30545
  "last_status_check_at"
30521
- ]) || 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);
30522
30547
  }
30523
30548
  return state;
30524
30549
  };
@@ -30569,18 +30594,18 @@ var init_agent_state = __esm({
30569
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);
30570
30595
  if (state.assignment !== null) assertRuntimeAssignment(state.assignment, message);
30571
30596
  if (state.pending_next !== null) {
30572
- const pending2 = assertPlainObject(state.pending_next, message);
30573
- 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);
30574
30599
  }
30575
30600
  if (state.pending_decision !== null) {
30576
30601
  if (state.assignment === null) throw new Error(message);
30577
- const pending2 = assertPlainObject(state.pending_decision, message);
30578
- if (!hasExactKeys(pending2, [
30602
+ const pending3 = assertPlainObject(state.pending_decision, message);
30603
+ if (!hasExactKeys(pending3, [
30579
30604
  "request",
30580
30605
  "first_transmit_at",
30581
30606
  "last_status_check_at"
30582
30607
  ])) throw new Error(message);
30583
- const request = assertPlainObject(pending2.request, message);
30608
+ const request = assertPlainObject(pending3.request, message);
30584
30609
  if (!hasExactKeys(request, [
30585
30610
  "assignment_id",
30586
30611
  "assignment_generation",
@@ -30588,7 +30613,7 @@ var init_agent_state = __esm({
30588
30613
  "candidate",
30589
30614
  "observed_at",
30590
30615
  "provenance"
30591
- ]) || 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);
30592
30617
  }
30593
30618
  return state;
30594
30619
  };
@@ -30638,12 +30663,12 @@ var init_agent_state = __esm({
30638
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))) {
30639
30664
  throw new Error("Agent-driven inference attempt state is invalid.");
30640
30665
  }
30641
- const pending2 = record5.pending_terminal;
30642
- if (pending2 !== null) {
30643
- 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)) {
30644
30669
  throw new Error("Agent-driven inference terminal recovery state is invalid.");
30645
30670
  }
30646
- const terminal = pending2;
30671
+ const terminal = pending3;
30647
30672
  if (Object.keys(terminal).sort().join("\0") !== ["kind", "request"].sort().join("\0")) {
30648
30673
  throw new Error("Agent-driven inference terminal recovery state is invalid.");
30649
30674
  }
@@ -30696,7 +30721,7 @@ function createDefaultInferenceHostRunnerDependencies(options) {
30696
30721
  envelopePublicKey: options.envelopePublicKey
30697
30722
  };
30698
30723
  }
30699
- var import_ajv, terminalFailureRequiresManualRecovery, canReplayFencedAgentTerminal, RUNTIME_RECEIPT_SCHEMA_VERSION, ATTEMPT_RECEIPT_SCHEMA_VERSION, CLAIM_DISPATCH_BATCH_SIZE, DEFAULT_ADVERTISEMENT_TTL_MS, DEFAULT_ADVERTISEMENT_REFRESH_LEAD_MS, DEFAULT_HOST_HEARTBEAT_MS, DEFAULT_PROVIDER_RATE_LIMIT_REFRESH_MS, DEFAULT_ATTEMPT_HEARTBEAT_MS, DEFAULT_DRAIN_TIMEOUT_MS, DEFAULT_REMOTE_RETRY_LIMIT, MIN_SLEEP_MS, MIN_HOST_HEARTBEAT_GAP_DIAGNOSTIC_MS, HOST_HEARTBEAT_GAP_DIAGNOSTIC_FACTOR, DEFAULT_CODEX_ACCOUNT_COOLDOWN_MS, DEFAULT_AGENT_RATE_LIMIT_COOLDOWN_MS, DEFAULT_AGENT_QUOTA_COOLDOWN_MS, DEFAULT_AGENT_TRANSIENT_COOLDOWN_MS, MIN_CLAIM_START_WINDOW_MS, MAX_ATTEMPT_START_RETRY_DELAY_MS, UNBOUNDED_AVAILABLE_SLOTS, buildInferenceAdvertisedModels, summarizeInferenceHostRuntimeRecovery, FileInferenceHostRuntimeReceiptStore, InferenceHostRecoveryRequiredError, InferenceHostRunnerError, defaultSleep, abortError, settlesWithin, defaultRegisterSignalHandlers, safeInteger, exactObjectKeys, validIso, validateAttemptReceipt, validateRuntimeReceipt, sha256, stableOperationId, buildAttemptStartRequest, isoAt, providerWeeklyQuotaFromRateLimits, usableProviderQuotaSnapshot, finitePositiveOption, validateRunnerOptions, assertLocalCredentialIdentity, retryableRemoteError, remoteRetryAfterMs, controlPlaneFatal, defaultValidateOutput, objectRecord, positiveUtf8ByteLimit, assertCompilableOutputSchema, parseOutputContract, serverProviderDispatchNotAfterMs, membershipFailureDisposition, safeFailureCode, publicServerFailureCode, attemptStartRetryFallbackMs, exactJson2, runnerIdentityMismatch, assertAdvertisementResult, assertHostHeartbeatResult, assertClaimResult, assertStartResult, assertJobHeartbeatResult, assertTerminalResult, isDefinitiveCompletionEvidenceExpiry, classifyFailure, ambiguousHeartbeatTransport, reportedTokenUsage, reportedUsage, InferenceHostRunner, createInferenceAgentControlClient, INFERENCE_AGENT_WAKE_SCHEMA, parseInferenceAgentWake, InferenceAgentRuntime;
30724
+ var import_ajv, providerHttpStatus, terminalFailureRequiresManualRecovery, canReplayFencedAgentTerminal, RUNTIME_RECEIPT_SCHEMA_VERSION, ATTEMPT_RECEIPT_SCHEMA_VERSION, CLAIM_DISPATCH_BATCH_SIZE, DEFAULT_ADVERTISEMENT_TTL_MS, DEFAULT_ADVERTISEMENT_REFRESH_LEAD_MS, DEFAULT_HOST_HEARTBEAT_MS, DEFAULT_PROVIDER_RATE_LIMIT_REFRESH_MS, DEFAULT_ATTEMPT_HEARTBEAT_MS, DEFAULT_DRAIN_TIMEOUT_MS, DEFAULT_REMOTE_RETRY_LIMIT, MIN_SLEEP_MS, MIN_HOST_HEARTBEAT_GAP_DIAGNOSTIC_MS, HOST_HEARTBEAT_GAP_DIAGNOSTIC_FACTOR, DEFAULT_CODEX_ACCOUNT_COOLDOWN_MS, DEFAULT_AGENT_RATE_LIMIT_COOLDOWN_MS, DEFAULT_AGENT_QUOTA_COOLDOWN_MS, DEFAULT_AGENT_TRANSIENT_COOLDOWN_MS, MIN_CLAIM_START_WINDOW_MS, MAX_ATTEMPT_START_RETRY_DELAY_MS, UNBOUNDED_AVAILABLE_SLOTS, buildInferenceAdvertisedModels, summarizeInferenceHostRuntimeRecovery, FileInferenceHostRuntimeReceiptStore, InferenceHostRecoveryRequiredError, InferenceHostRunnerError, defaultSleep, abortError, settlesWithin, defaultRegisterSignalHandlers, safeInteger, exactObjectKeys, validIso, validateAttemptReceipt, validateRuntimeReceipt, sha256, stableOperationId, buildAttemptStartRequest, isoAt, providerWeeklyQuotaFromRateLimits, usableProviderQuotaSnapshot, finitePositiveOption, validateRunnerOptions, assertLocalCredentialIdentity, retryableRemoteError, remoteRetryAfterMs, controlPlaneFatal, defaultValidateOutput, objectRecord, positiveUtf8ByteLimit, assertCompilableOutputSchema, parseOutputContract, serverProviderDispatchNotAfterMs, membershipFailureDisposition, safeFailureCode, publicServerFailureCode, attemptStartRetryFallbackMs, exactJson2, runnerIdentityMismatch, assertAdvertisementResult, assertHostHeartbeatResult, assertClaimResult, assertStartResult, assertJobHeartbeatResult, assertTerminalResult, isDefinitiveCompletionEvidenceExpiry, classifyFailure, ambiguousHeartbeatTransport, reportedTokenUsage, reportedUsage, InferenceHostRunner, createInferenceAgentControlClient, INFERENCE_AGENT_WAKE_SCHEMA, parseInferenceAgentWake, InferenceAgentRuntime;
30700
30725
  var init_runner = __esm({
30701
30726
  "lib/inference-host/runner.ts"() {
30702
30727
  "use strict";
@@ -30713,8 +30738,13 @@ var init_runner = __esm({
30713
30738
  init_mcp_client();
30714
30739
  init_config();
30715
30740
  init_oauth();
30741
+ providerHttpStatus = (error48) => {
30742
+ if (!(error48 instanceof CodexAppServerError)) return null;
30743
+ const status = error48.httpStatusCode;
30744
+ return typeof status === "number" && Number.isInteger(status) && status >= 400 && status <= 599 ? status : null;
30745
+ };
30716
30746
  terminalFailureRequiresManualRecovery = (error48) => (error48.terminalEvidence !== null || error48.grokToolValidation != null || error48.grokResponseIdentity != null) && !error48.retryable && error48.category !== "auth" && !["quota_exceeded", "codex_rate_limited", "provider_rate_limited"].includes(error48.code);
30717
- canReplayFencedAgentTerminal = (state, fence) => state?.schema_version === "vtx_inference_agent_runtime_v3" && state.adapter_id === fence.adapter_id && state.host_id === fence.host_id && state.assignment.assignment_id === fence.assignment_id && state.pending_turn?.terminal_receipt?.terminal_status === "failed" && state.pending_turn.terminal_receipt.failure_code === fence.failure_code && (fence.dispatch_outcome !== "outcome_unknown" || (state.pending_turn.terminal_receipt.grok_tool_validation?.prior_dispatch === true || state.pending_turn.terminal_receipt.grok_response_identity != null) && state.pending_turn.terminal_receipt.dispatch_outcome === "outcome_unknown");
30747
+ canReplayFencedAgentTerminal = (state, fence) => state?.schema_version === "vtx_inference_agent_runtime_v3" && state.adapter_id === fence.adapter_id && state.host_id === fence.host_id && state.assignment.assignment_id === fence.assignment_id && state.pending_turn?.terminal_receipt?.terminal_status === "failed" && state.pending_turn.terminal_receipt.failure_code === fence.failure_code && (fence.dispatch_outcome !== "outcome_unknown" || (state.pending_turn.terminal_receipt.grok_tool_validation?.prior_dispatch === true || state.pending_turn.terminal_receipt.grok_response_identity != null || state.pending_turn.terminal_receipt.provider_http_status !== void 0) && state.pending_turn.terminal_receipt.dispatch_outcome === "outcome_unknown");
30718
30748
  RUNTIME_RECEIPT_SCHEMA_VERSION = "vtx_inference_host_runtime_v1";
30719
30749
  ATTEMPT_RECEIPT_SCHEMA_VERSION = "vtx_inference_attempt_receipt_v1";
30720
30750
  CLAIM_DISPATCH_BATCH_SIZE = 16;
@@ -33918,6 +33948,11 @@ var init_runner = __esm({
33918
33948
  signal,
33919
33949
  deadlineAtMs: Date.parse(jobInput.evidence_expires_at)
33920
33950
  }) === true);
33951
+ const httpStatus = heartbeatFailure === void 0 ? providerHttpStatus(effectiveError) : null;
33952
+ const sendHttpStatus = httpStatus !== null && (mcp.supportsProviderHttpStatusDiagnostics?.("inference.job.fail") === true || await mcp.refreshProviderHttpStatusSupport?.("inference.job.fail", {
33953
+ signal,
33954
+ deadlineAtMs: Date.parse(jobInput.evidence_expires_at)
33955
+ }) === true);
33921
33956
  const failureRequest = jobFailRequestSchema.parse({
33922
33957
  schema_version: "external_inference_job_fail_v1",
33923
33958
  contract_version: EXTERNAL_INFERENCE_CONTRACT_VERSION,
@@ -33958,6 +33993,7 @@ var init_runner = __esm({
33958
33993
  ...adapterResultReadyAt === null ? {} : { adapter_result_ready_at: adapterResultReadyAt },
33959
33994
  provider_dispatch_freshness_remaining_ms: providerDispatchFreshnessRemainingMs,
33960
33995
  ...processExit ? { process_exit: processExit } : {},
33996
+ ...sendHttpStatus ? { provider_http_status: httpStatus } : {},
33961
33997
  ...sendGrokDiagnostic ? { grok_tool_validation: grokDiagnostic } : {},
33962
33998
  ...sendIdentityDiagnostic ? { grok_response_identity: identityDiagnostic } : {},
33963
33999
  membership_disposition: membershipFailureDisposition({
@@ -34032,6 +34068,7 @@ var init_runner = __esm({
34032
34068
  }
34033
34069
  };
34034
34070
  createInferenceAgentControlClient = (mcp) => ({
34071
+ supportsProviderHttpStatusDiagnostics: async (options = {}) => mcp.supportsProviderHttpStatusDiagnostics?.("inference.agent.assignment.heartbeat") === true || await mcp.refreshProviderHttpStatusSupport?.("inference.agent.assignment.heartbeat", options) === true,
34035
34072
  supportsGrokResponseIdentityDiagnostics: async (options = {}) => mcp.supportsGrokResponseIdentityDiagnostics?.("inference.agent.assignment.heartbeat") === true || await mcp.refreshGrokResponseIdentitySupport?.("inference.agent.assignment.heartbeat", options) === true,
34036
34073
  supportsGrokToolValidationDiagnostics: async (options = {}) => mcp.supportsGrokToolValidationDiagnostics?.("inference.agent.assignment.heartbeat") === true || await mcp.refreshGrokToolValidationSupport?.("inference.agent.assignment.heartbeat", options) === true,
34037
34074
  nextAssignment: async (request, options) => {
@@ -34277,7 +34314,7 @@ var init_runner = __esm({
34277
34314
  if (terminal.terminal_receipt.terminal_status === "failed") {
34278
34315
  state = { ...state, pending_turn: null, updated_at: nowIso() };
34279
34316
  await writeInferenceAgentRuntimeState(this.options.statePath, state);
34280
- if (terminal.terminal_receipt.dispatch_outcome === "outcome_unknown") {
34317
+ if (terminal.terminal_receipt.dispatch_outcome === "outcome_unknown" || terminal.terminal_receipt.provider_http_status !== void 0 && failureFence?.retry_at === null) {
34281
34318
  throw new InferenceHostRunnerError(
34282
34319
  "agent_terminal_failure_fenced",
34283
34320
  "The diagnostic receipt was acknowledged; upstream outcome remains unknown and model redispatch is fenced."
@@ -34436,7 +34473,7 @@ var init_runner = __esm({
34436
34473
  if (state.pending_decision) {
34437
34474
  return { success: false, value: { error: "decision_outcome_unresolved" } };
34438
34475
  }
34439
- const pending2 = {
34476
+ const pending3 = {
34440
34477
  operation_id: randomUUID(),
34441
34478
  candidate,
34442
34479
  observed_at: nowIso(),
@@ -34455,17 +34492,17 @@ var init_runner = __esm({
34455
34492
  if (state.pending_turn.decision_operation_ids.length >= 128) {
34456
34493
  return { success: false, value: { error: "agent_turn_decision_limit" } };
34457
34494
  }
34458
- state = { ...state, pending_decision: pending2, pending_turn: {
34495
+ state = { ...state, pending_decision: pending3, pending_turn: {
34459
34496
  ...state.pending_turn,
34460
34497
  decision_operation_ids: [
34461
34498
  ...state.pending_turn.decision_operation_ids,
34462
- pending2.operation_id
34499
+ pending3.operation_id
34463
34500
  ]
34464
34501
  }, updated_at: nowIso() };
34465
34502
  await writeInferenceAgentRuntimeState(this.options.statePath, state);
34466
34503
  state = {
34467
34504
  ...state,
34468
- pending_decision: { ...pending2, first_transmit_at: nowIso() },
34505
+ pending_decision: { ...pending3, first_transmit_at: nowIso() },
34469
34506
  updated_at: nowIso()
34470
34507
  };
34471
34508
  await writeInferenceAgentRuntimeState(this.options.statePath, state);
@@ -34474,10 +34511,10 @@ var init_runner = __esm({
34474
34511
  submitStatus = await this.options.controlClient.submitDecision({
34475
34512
  assignment_id: assignment.assignment_id,
34476
34513
  assignment_generation: assignment.assignment_generation,
34477
- operation_id: pending2.operation_id,
34478
- candidate: pending2.candidate,
34479
- observed_at: pending2.observed_at,
34480
- provenance: pending2.provenance
34514
+ operation_id: pending3.operation_id,
34515
+ candidate: pending3.candidate,
34516
+ observed_at: pending3.observed_at,
34517
+ provenance: pending3.provenance
34481
34518
  }, { signal: turnAbort.signal });
34482
34519
  } catch {
34483
34520
  const recovery = {};
@@ -34585,17 +34622,24 @@ var init_runner = __esm({
34585
34622
  } catch (error48) {
34586
34623
  const diagnostic = error48 instanceof CodexAppServerError && error48.grokToolValidation && error48.code === `grok_tool_isolation_${error48.grokToolValidation.reason}` && error48.dispatchOutcome === (error48.grokToolValidation.prior_dispatch ? "outcome_unknown" : "not_dispatched") && await this.options.controlClient.supportsGrokToolValidationDiagnostics?.({}) === true ? error48.grokToolValidation : null;
34587
34624
  const identityDiagnostic = error48 instanceof CodexAppServerError && error48.grokResponseIdentity && error48.code === "grok_provider_identity_mismatch" && error48.dispatchOutcome === "outcome_unknown" && await this.options.controlClient.supportsGrokResponseIdentityDiagnostics?.({}) === true ? error48.grokResponseIdentity : null;
34625
+ const httpStatus = providerHttpStatus(error48);
34626
+ const sendHttpStatus = httpStatus !== null && await this.options.controlClient.supportsProviderHttpStatusDiagnostics?.({}) === true;
34588
34627
  const hasDiagnostic = diagnostic != null || identityDiagnostic != null;
34589
- if (error48 instanceof CodexAppServerError && error48.dispatchOutcome === "not_dispatched" && error48.terminalEvidence === null && !hasDiagnostic) {
34628
+ const hasFailureEvidence = hasDiagnostic || sendHttpStatus;
34629
+ if (error48 instanceof CodexAppServerError && error48.dispatchOutcome === "not_dispatched" && error48.terminalEvidence === null && !hasFailureEvidence) {
34590
34630
  state = { ...state, pending_turn: null, updated_at: nowIso() };
34591
34631
  await writeInferenceAgentRuntimeState(this.options.statePath, state);
34592
34632
  }
34593
- if (state.pending_turn && !state.pending_turn.terminal_receipt && error48 instanceof CodexAppServerError && (hasDiagnostic || error48.terminalEvidence !== null || error48.dispatchOutcome === "confirmed_dispatched" && ["provider_rate_limited", "codex_rate_limited", "quota_exceeded"].includes(error48.code))) {
34633
+ if (state.pending_turn && !state.pending_turn.terminal_receipt && error48 instanceof CodexAppServerError && (hasFailureEvidence || error48.terminalEvidence !== null || error48.dispatchOutcome === "confirmed_dispatched" && ["provider_rate_limited", "codex_rate_limited", "quota_exceeded"].includes(error48.code))) {
34594
34634
  state = { ...state, pending_turn: {
34595
34635
  ...state.pending_turn,
34596
34636
  terminal_receipt: {
34597
34637
  terminal_status: "failed",
34598
34638
  failure_code: error48.code,
34639
+ ...sendHttpStatus ? {
34640
+ provider_http_status: httpStatus,
34641
+ ...error48.dispatchOutcome === "confirmed_dispatched" ? {} : { dispatch_outcome: error48.dispatchOutcome }
34642
+ } : {},
34599
34643
  turn_id: state.pending_turn.turn_id,
34600
34644
  agent_run_id: state.thread?.threadId ?? state.pending_turn.turn_id,
34601
34645
  requested_model: assignment.model_id,
@@ -34622,7 +34666,7 @@ var init_runner = __esm({
34622
34666
  } : {}
34623
34667
  }
34624
34668
  }, updated_at: nowIso() };
34625
- if (terminalFailureRequiresManualRecovery(error48)) {
34669
+ if (terminalFailureRequiresManualRecovery(error48) || sendHttpStatus && (error48.dispatchOutcome === "outcome_unknown" || error48.dispatchOutcome === "confirmed_dispatched" && error48.terminalEvidence === null && !["provider_rate_limited", "codex_rate_limited", "quota_exceeded"].includes(error48.code))) {
34626
34670
  await writeInferenceAgentFailureFence(this.options.statePath, {
34627
34671
  schema_version: "vtx_inference_agent_failure_fence_v1",
34628
34672
  adapter_id: this.options.adapterId,
@@ -34672,12 +34716,12 @@ var init_runner = __esm({
34672
34716
  return null;
34673
34717
  }
34674
34718
  async resolveLegacyPendingDecision(state, signal) {
34675
- const pending2 = state.pending_decision;
34676
- if (!pending2) return state;
34719
+ const pending3 = state.pending_decision;
34720
+ if (!pending3) return state;
34677
34721
  const checkedAt = new Date(this.now()).toISOString();
34678
34722
  const checking = {
34679
34723
  ...state,
34680
- pending_decision: { ...pending2, last_status_check_at: checkedAt },
34724
+ pending_decision: { ...pending3, last_status_check_at: checkedAt },
34681
34725
  updated_at: checkedAt
34682
34726
  };
34683
34727
  await writeInferenceAgentRuntimeState(this.options.statePath, checking);
@@ -34685,7 +34729,7 @@ var init_runner = __esm({
34685
34729
  host_id: this.options.hostId,
34686
34730
  assignment_id: state.assignment.assignment_id,
34687
34731
  assignment_generation: state.assignment.assignment_generation,
34688
- operation_id: pending2.operation_id
34732
+ operation_id: pending3.operation_id
34689
34733
  }, { signal });
34690
34734
  if (status.status !== "applied" && status.status !== "not_applied") return checking;
34691
34735
  const resolved = {
@@ -34697,12 +34741,12 @@ var init_runner = __esm({
34697
34741
  return resolved;
34698
34742
  }
34699
34743
  async resolvePendingDecision(state, signal, onStatus) {
34700
- const pending2 = state.pending_decision;
34701
- if (!pending2) return state;
34744
+ const pending3 = state.pending_decision;
34745
+ if (!pending3) return state;
34702
34746
  const checkedAt = new Date(this.now()).toISOString();
34703
34747
  const checking = {
34704
34748
  ...state,
34705
- pending_decision: { ...pending2, last_status_check_at: checkedAt },
34749
+ pending_decision: { ...pending3, last_status_check_at: checkedAt },
34706
34750
  updated_at: checkedAt
34707
34751
  };
34708
34752
  await writeInferenceAgentRuntimeState(this.options.statePath, checking);
@@ -34710,7 +34754,7 @@ var init_runner = __esm({
34710
34754
  host_id: this.options.hostId,
34711
34755
  assignment_id: state.assignment.assignment_id,
34712
34756
  assignment_generation: state.assignment.assignment_generation,
34713
- operation_id: pending2.operation_id
34757
+ operation_id: pending3.operation_id
34714
34758
  }, { signal });
34715
34759
  onStatus?.(status);
34716
34760
  if (status.status !== "applied" && status.status !== "not_applied") return checking;
@@ -34924,18 +34968,18 @@ async function reauthorizeInferenceHost(options) {
34924
34968
  return options.state;
34925
34969
  }
34926
34970
  const pair = generateExternalInferenceEnvelopeKeyPair();
34927
- const pending2 = await (options.beginLogin ?? beginInferenceOAuthLogin)({
34971
+ const pending3 = await (options.beginLogin ?? beginInferenceOAuthLogin)({
34928
34972
  apiUrl: config2.apiUrl,
34929
34973
  hostId: previous.host_id,
34930
34974
  keyGeneration: previous.key_generation + 1,
34931
34975
  x25519PrivateKey: pair.private_key,
34932
34976
  store: stagedStore
34933
34977
  });
34934
- options.emitAuthorization(pending2.authorizationUrl);
34978
+ options.emitAuthorization(pending3.authorizationUrl);
34935
34979
  try {
34936
- access5 = await pending2.completion;
34980
+ access5 = await pending3.completion;
34937
34981
  } catch (error48) {
34938
- await pending2.cancel().catch(() => void 0);
34982
+ await pending3.cancel().catch(() => void 0);
34939
34983
  throw error48;
34940
34984
  }
34941
34985
  candidate = await store.readRecovery();
@@ -35466,9 +35510,9 @@ var init_codex_adapter = __esm({
35466
35510
  return document2.attempts;
35467
35511
  }
35468
35512
  enqueue(operation) {
35469
- const pending2 = this.queue.then(operation, operation);
35470
- this.queue = pending2.then(() => void 0, () => void 0);
35471
- return pending2;
35513
+ const pending3 = this.queue.then(operation, operation);
35514
+ this.queue = pending3.then(() => void 0, () => void 0);
35515
+ return pending3;
35472
35516
  }
35473
35517
  async load(attemptId) {
35474
35518
  await this.queue;
@@ -37668,6 +37712,7 @@ var init_deepseek_transport_proxy = __esm({
37668
37712
  this.upstreamRequestStartedValue = false;
37669
37713
  this.providerResponseObservedValue = false;
37670
37714
  this.unansweredUpstreamRequestsValue = 0;
37715
+ this.providerHttpStatusValue = null;
37671
37716
  this.latestReceiptValue = null;
37672
37717
  }
37673
37718
  get baseUrl() {
@@ -37677,6 +37722,9 @@ var init_deepseek_transport_proxy = __esm({
37677
37722
  get receipts() {
37678
37723
  return [...this.receiptsValue];
37679
37724
  }
37725
+ get providerHttpStatus() {
37726
+ return this.providerHttpStatusValue;
37727
+ }
37680
37728
  get lastReceipt() {
37681
37729
  return this.latestReceiptValue;
37682
37730
  }
@@ -37693,6 +37741,7 @@ var init_deepseek_transport_proxy = __esm({
37693
37741
  if (this.server) return;
37694
37742
  this.server = createServer2(async (request, response) => {
37695
37743
  try {
37744
+ this.providerHttpStatusValue = null;
37696
37745
  const prefix = `/${this.token}`;
37697
37746
  const requestUrl = request.url ?? "";
37698
37747
  if (request.method !== "POST" || requestUrl !== `${prefix}/chat/completions`) {
@@ -37737,6 +37786,7 @@ var init_deepseek_transport_proxy = __esm({
37737
37786
  );
37738
37787
  this.unansweredUpstreamRequestsValue -= 1;
37739
37788
  this.providerResponseObservedValue = true;
37789
+ this.providerHttpStatusValue = upstream.status >= 400 && upstream.status <= 599 ? upstream.status : null;
37740
37790
  const headers = {};
37741
37791
  upstream.headers.forEach((value, name) => {
37742
37792
  if (!["connection", "transfer-encoding", "content-length"].includes(name)) {
@@ -37760,7 +37810,7 @@ var init_deepseek_transport_proxy = __esm({
37760
37810
  }
37761
37811
  const reader = upstream.body.getReader();
37762
37812
  const decoder2 = new TextDecoder();
37763
- let pending2 = "";
37813
+ let pending3 = "";
37764
37814
  let observedId = "";
37765
37815
  let observedModel = "";
37766
37816
  let terminalObserved = false;
@@ -37795,13 +37845,13 @@ var init_deepseek_transport_proxy = __esm({
37795
37845
  while (true) {
37796
37846
  const part = await reader.read();
37797
37847
  if (part.done) break;
37798
- pending2 += decoder2.decode(part.value, { stream: true });
37799
- const lines = pending2.split(/\r?\n/u);
37800
- pending2 = lines.pop() ?? "";
37848
+ pending3 += decoder2.decode(part.value, { stream: true });
37849
+ const lines = pending3.split(/\r?\n/u);
37850
+ pending3 = lines.pop() ?? "";
37801
37851
  for (const line of lines) forwardLine(line);
37802
37852
  }
37803
- pending2 += decoder2.decode();
37804
- if (pending2) forwardLine(pending2);
37853
+ pending3 += decoder2.decode();
37854
+ if (pending3) forwardLine(pending3);
37805
37855
  if (!terminalObserved) {
37806
37856
  throw new Error("deepseek_provider_receipt_missing_or_mismatched");
37807
37857
  }
@@ -37975,7 +38025,7 @@ var init_deepseek_harness_adapter = __esm({
37975
38025
  code,
37976
38026
  retryable: transport && !quota,
37977
38027
  dispatchOutcome: options.dispatchOutcome,
37978
- httpStatusCode: failure2.status ?? null,
38028
+ httpStatusCode: options.providerHttpStatus,
37979
38029
  retryAtMs: failure2.providerRetryAfterMs === void 0 ? null : Date.now() + failure2.providerRetryAfterMs,
37980
38030
  cause: options.error
37981
38031
  });
@@ -38191,7 +38241,8 @@ ${input.outputSchemaJson}`,
38191
38241
  error: error48,
38192
38242
  cancelled,
38193
38243
  deadline,
38194
- dispatchOutcome: proxyDispatchOutcome(proxy)
38244
+ dispatchOutcome: proxyDispatchOutcome(proxy),
38245
+ providerHttpStatus: proxy.providerHttpStatus
38195
38246
  });
38196
38247
  input.onTerminalDispatchOutcome?.(mapped.dispatchOutcome);
38197
38248
  throw mapped;
@@ -38475,7 +38526,8 @@ ${JSON.stringify(input.outputSchema)}`,
38475
38526
  error: error48,
38476
38527
  cancelled: input.signal?.aborted === true,
38477
38528
  deadline: input.signal?.aborted !== true && boundary.signal.aborted,
38478
- dispatchOutcome: proxyDispatchOutcome(proxy)
38529
+ dispatchOutcome: proxyDispatchOutcome(proxy),
38530
+ providerHttpStatus: proxy.providerHttpStatus
38479
38531
  });
38480
38532
  } finally {
38481
38533
  removeAgentAbortListener();
@@ -38554,6 +38606,7 @@ var init_pi_transport = __esm({
38554
38606
  this.responded = false;
38555
38607
  this.terminalFailure = null;
38556
38608
  this.rejectionStatus = null;
38609
+ this.providerHttpStatus = null;
38557
38610
  this.requests = [];
38558
38611
  this.fetch = async (url2, init2) => {
38559
38612
  const target = new URL(url2 instanceof Request ? url2.url : String(url2));
@@ -38563,8 +38616,10 @@ var init_pi_transport = __esm({
38563
38616
  this.dispatched = true;
38564
38617
  const request = { terminal: false };
38565
38618
  this.requests.push(request);
38619
+ this.providerHttpStatus = null;
38566
38620
  const response = await this.options.fetch(url2, { ...init2, redirect: "error" });
38567
38621
  this.responded = true;
38622
+ this.providerHttpStatus = response.status >= 400 && response.status <= 599 ? response.status : null;
38568
38623
  if (response.status === 401 || response.status === 429) {
38569
38624
  request.terminal = true;
38570
38625
  this.rejectionStatus = response.status;
@@ -38588,7 +38643,7 @@ var init_pi_transport = __esm({
38588
38643
  reasoningEffortChanged: false
38589
38644
  };
38590
38645
  this.receipts.push(receipt);
38591
- let pending2 = "";
38646
+ let pending3 = "";
38592
38647
  const decoder2 = new TextDecoder();
38593
38648
  const inspect3 = (data4) => {
38594
38649
  if (!data4.trim() || data4.trim() === "[DONE]") return;
@@ -38649,9 +38704,9 @@ var init_pi_transport = __esm({
38649
38704
  }
38650
38705
  };
38651
38706
  const consume = (flush = false) => {
38652
- if (pending2.length > 2e6) throw new Error("pi_receipt_event_too_large");
38653
- const events = pending2.split(/\r?\n\r?\n/u);
38654
- 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();
38655
38710
  for (const event of events) {
38656
38711
  const data4 = event.split(/\r?\n/u).filter((line) => line.startsWith("data:")).map((line) => line.slice(5).trimStart()).join("\n");
38657
38712
  if (data4) inspect3(data4);
@@ -38659,12 +38714,12 @@ var init_pi_transport = __esm({
38659
38714
  };
38660
38715
  const stream = response.body.pipeThrough(new TransformStream({
38661
38716
  transform: (chunk, controller) => {
38662
- pending2 += decoder2.decode(chunk, { stream: true });
38717
+ pending3 += decoder2.decode(chunk, { stream: true });
38663
38718
  consume();
38664
38719
  controller.enqueue(chunk);
38665
38720
  },
38666
38721
  flush: () => {
38667
- pending2 += decoder2.decode();
38722
+ pending3 += decoder2.decode();
38668
38723
  consume(true);
38669
38724
  }
38670
38725
  }));
@@ -39165,7 +39220,7 @@ var init_pi_adapter = __esm({
39165
39220
  dispatchOutcome: outcome,
39166
39221
  usage,
39167
39222
  terminalEvidence,
39168
- httpStatusCode: transport?.rejectionStatus ?? null
39223
+ httpStatusCode: transport?.providerHttpStatus ?? null
39169
39224
  });
39170
39225
  } finally {
39171
39226
  if (timer) clearTimeout(timer);
@@ -39346,18 +39401,18 @@ var init_grok_policy = __esm({
39346
39401
  init_dist();
39347
39402
  validateGrokPolicy = (value) => {
39348
39403
  if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Grok runtime policy is missing.");
39349
- const policy = value;
39350
- 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));
39351
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.");
39352
39407
  for (const key of ["maximum_transport_request_bytes", "maximum_transport_response_bytes"]) {
39353
- 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) {
39354
39409
  throw new Error("Grok transport bounds are missing or invalid.");
39355
39410
  }
39356
39411
  }
39357
39412
  return Object.freeze({
39358
39413
  subscription_proxy_base_url: url2.href,
39359
- maximum_transport_request_bytes: Number(policy.maximum_transport_request_bytes),
39360
- 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)
39361
39416
  });
39362
39417
  };
39363
39418
  loadGrokPolicy = async () => {
@@ -39735,7 +39790,7 @@ var init_grok_transport_proxy = __esm({
39735
39790
  const reader = upstream.body.getReader();
39736
39791
  const decoder2 = new TextDecoder();
39737
39792
  let bytes3 = 0;
39738
- let pending2 = "";
39793
+ let pending3 = "";
39739
39794
  let eventData = [];
39740
39795
  let id2 = "";
39741
39796
  let model = "";
@@ -39847,9 +39902,9 @@ var init_grok_transport_proxy = __esm({
39847
39902
  bytes3 += part.value.byteLength;
39848
39903
  if (bytes3 > this.options.maxResponseBytes) throw new Error("grok_response_too_large");
39849
39904
  if (route) {
39850
- pending2 += decoder2.decode(part.value, { stream: true });
39851
- const lines = pending2.split(/\r?\n/u);
39852
- pending2 = lines.pop() ?? "";
39905
+ pending3 += decoder2.decode(part.value, { stream: true });
39906
+ const lines = pending3.split(/\r?\n/u);
39907
+ pending3 = lines.pop() ?? "";
39853
39908
  for (const line of lines) {
39854
39909
  if (!line) inspect3();
39855
39910
  else if (line.startsWith("data:")) eventData.push(line.slice(5));
@@ -39858,8 +39913,8 @@ var init_grok_transport_proxy = __esm({
39858
39913
  if (!response.write(part.value)) await once(response, "drain", { signal });
39859
39914
  }
39860
39915
  if (route) {
39861
- pending2 += decoder2.decode();
39862
- if (pending2.startsWith("data:")) eventData.push(pending2.slice(5));
39916
+ pending3 += decoder2.decode();
39917
+ if (pending3.startsWith("data:")) eventData.push(pending3.slice(5));
39863
39918
  inspect3();
39864
39919
  if (!terminal || !id2 || !model) throw new Error("grok_provider_terminal_missing");
39865
39920
  }
@@ -40559,11 +40614,11 @@ var init_grok_adapter = __esm({
40559
40614
  try {
40560
40615
  signal.throwIfAborted();
40561
40616
  const deadline = Date.now() + 3e4;
40562
- const policy = this.options.policy ?? await loadGrokPolicy();
40617
+ const policy2 = this.options.policy ?? await loadGrokPolicy();
40563
40618
  proxy = await createGrokTransportProxy({
40564
- upstreamBaseUrl: policy.subscription_proxy_base_url,
40565
- maxRequestBytes: policy.maximum_transport_request_bytes,
40566
- 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,
40567
40622
  metadataOnly: true,
40568
40623
  requestedModel: "",
40569
40624
  requestedReasoningEffort: "none",
@@ -40638,7 +40693,7 @@ var init_grok_adapter = __esm({
40638
40693
  input.signal.throwIfAborted();
40639
40694
  const startedAt = Date.now();
40640
40695
  const binary = await this.binary();
40641
- const policy = this.options.policy ?? await loadGrokPolicy();
40696
+ const policy2 = this.options.policy ?? await loadGrokPolicy();
40642
40697
  input.signal.throwIfAborted();
40643
40698
  const workspace = agent?.durableThread ? await validateGrokOwnedThread(this.stateOptions, agent.durableThread) : await createGrokOwnedWorkspace(this.stateOptions, agent ? "agent" : "attempt");
40644
40699
  let mcp = null;
@@ -40688,9 +40743,9 @@ var init_grok_adapter = __esm({
40688
40743
  return result3;
40689
40744
  } }) : null;
40690
40745
  proxy = await createGrokTransportProxy({
40691
- upstreamBaseUrl: policy.subscription_proxy_base_url,
40692
- maxRequestBytes: policy.maximum_transport_request_bytes,
40693
- 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,
40694
40749
  expectedSystemPrompt: input.systemPrompt,
40695
40750
  requestedModel: input.requestedModel,
40696
40751
  requestedReasoningEffort: input.requestedReasoningEffort,
@@ -40901,7 +40956,7 @@ var init_grok_auth = __esm({
40901
40956
  stdio: ["ignore", "pipe", "pipe"],
40902
40957
  windowsHide: true
40903
40958
  });
40904
- let pending2 = "";
40959
+ let pending3 = "";
40905
40960
  let bytes3 = 0;
40906
40961
  let verificationUrl = "";
40907
40962
  let userCode = "";
@@ -40919,9 +40974,9 @@ var init_grok_auth = __esm({
40919
40974
  stop();
40920
40975
  return;
40921
40976
  }
40922
- pending2 += chunk.toString("utf8");
40923
- const lines = pending2.split(/\r?\n/u);
40924
- pending2 = lines.pop() ?? "";
40977
+ pending3 += chunk.toString("utf8");
40978
+ const lines = pending3.split(/\r?\n/u);
40979
+ pending3 = lines.pop() ?? "";
40925
40980
  for (const line of lines) {
40926
40981
  const clean = line.replace(/\x1b\[[0-9;]*[A-Za-z]/gu, "").trim();
40927
40982
  if (/^https:\/\//u.test(clean)) {
@@ -41348,7 +41403,6 @@ var init_exo_adapter = __esm({
41348
41403
  retryable: false,
41349
41404
  dispatchOutcome: outcome,
41350
41405
  usage: receiptUsage(evidence?.usage),
41351
- httpStatusCode: ["quota_exceeded", "provider_rate_limited"].includes(code) ? 429 : null,
41352
41406
  retryAtMs: completed && Number.isSafeInteger(evidence?.retryAtMs) && Number(evidence?.retryAtMs) > Date.now() ? Number(evidence?.retryAtMs) : null,
41353
41407
  terminalEvidence: completed ? {
41354
41408
  effectiveModel: identityQualified ? `${provider}/${evidence.providerModel}` : null,
@@ -41390,16 +41444,16 @@ var init_exo_policy = __esm({
41390
41444
  init_define_VTX_PI_MODEL_POLICY();
41391
41445
  init_dist();
41392
41446
  validateExoPolicy = (value) => {
41393
- const policy = value;
41394
- 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) {
41395
41449
  throw new Error("Exo runtime policy is missing or invalid.");
41396
41450
  }
41397
- if (!policy.endpoints || Object.keys(policy.endpoints).sort().join(",") !== "openai,venice") throw new Error("Exo provider endpoints are invalid.");
41398
- 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)) {
41399
41453
  const url2 = new URL(endpoint);
41400
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.");
41401
41455
  }
41402
- const models = policy.models.map((model) => {
41456
+ const models = policy2.models.map((model) => {
41403
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")) {
41404
41458
  throw new Error("Exo model qualification policy is invalid.");
41405
41459
  }
@@ -41408,7 +41462,7 @@ var init_exo_policy = __esm({
41408
41462
  if (new Set(models.map((model) => model.model)).size !== models.length) {
41409
41463
  throw new Error("Exo policy contains duplicate model identities.");
41410
41464
  }
41411
- 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) });
41412
41466
  };
41413
41467
  loadExoPolicy = async () => {
41414
41468
  if (typeof define_VTX_EXO_POLICY_default !== "undefined") return validateExoPolicy(define_VTX_EXO_POLICY_default);
@@ -41974,6 +42028,11 @@ var init_runtime_policy_generated = __esm({
41974
42028
  performance_defaults: {
41975
42029
  default_timeframe: "30d"
41976
42030
  },
42031
+ execution_metadata_retry: {
42032
+ max_attempts: 3,
42033
+ base_delay_milliseconds: 2e3,
42034
+ max_delay_milliseconds: 3e4
42035
+ },
41977
42036
  auth_bootstrap_retry: {
41978
42037
  max_attempts: 3,
41979
42038
  jitter_milliseconds: 750,
@@ -42083,6 +42142,54 @@ var init_runtime_policy_generated = __esm({
42083
42142
  max_inflight: 16,
42084
42143
  max_queue: 64
42085
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
+ }
42086
42193
  }
42087
42194
  };
42088
42195
  }
@@ -43254,11 +43361,11 @@ ${result2.stderr}`)) {
43254
43361
  let stdout = "";
43255
43362
  let cooperativeStopTimedOut = false;
43256
43363
  let cooperativeStopTimer = null;
43257
- const pending2 = { stdout: "", stderr: "" };
43364
+ const pending3 = { stdout: "", stderr: "" };
43258
43365
  const writeTaggedOutput = (stream, text, flush = false) => {
43259
- const lines = `${pending2[stream]}${text}`.split(/\r?\n/u);
43366
+ const lines = `${pending3[stream]}${text}`.split(/\r?\n/u);
43260
43367
  const remainder = lines.pop() ?? "";
43261
- pending2[stream] = flush ? "" : remainder;
43368
+ pending3[stream] = flush ? "" : remainder;
43262
43369
  if (flush && remainder) lines.push(remainder);
43263
43370
  if (flush && lines.at(-1) === "") lines.pop();
43264
43371
  for (const line of lines) {
@@ -44563,7 +44670,7 @@ Waiting for approval...
44563
44670
  }
44564
44671
  }
44565
44672
  };
44566
- const pending2 = await beginLogin({
44673
+ const pending3 = await beginLogin({
44567
44674
  apiUrl: config2.apiUrl,
44568
44675
  hostId,
44569
44676
  x25519PrivateKey: keyPair.private_key,
@@ -44573,23 +44680,23 @@ Waiting for approval...
44573
44680
  const emitStdout = dependencies.emitStdout ?? ((text) => {
44574
44681
  process.stdout.write(text);
44575
44682
  });
44576
- emitStdout(parsed.json ? `${JSON.stringify({ authorizationUrl: pending2.authorizationUrl })}
44683
+ emitStdout(parsed.json ? `${JSON.stringify({ authorizationUrl: pending3.authorizationUrl })}
44577
44684
  ` : `Open this URL to authorize the VTX inference host:
44578
- ${pending2.authorizationUrl}
44685
+ ${pending3.authorizationUrl}
44579
44686
 
44580
44687
  Waiting for approval...
44581
44688
  `);
44582
44689
  if (!parsed.json && Boolean(process.stdout.isTTY) && Boolean(process.stdin.isTTY)) {
44583
44690
  try {
44584
- (dependencies.openBrowser ?? defaultOpenBrowser)(pending2.authorizationUrl);
44691
+ (dependencies.openBrowser ?? defaultOpenBrowser)(pending3.authorizationUrl);
44585
44692
  } catch {
44586
44693
  }
44587
44694
  }
44588
44695
  let access5;
44589
44696
  try {
44590
- access5 = await pending2.completion;
44697
+ access5 = await pending3.completion;
44591
44698
  } catch (error48) {
44592
- await pending2.cancel().catch(() => void 0);
44699
+ await pending3.cancel().catch(() => void 0);
44593
44700
  throw error48;
44594
44701
  }
44595
44702
  const state = {
@@ -45549,13 +45656,13 @@ Waiting for approval...
45549
45656
  };
45550
45657
  await writeInferenceForegroundAgentControlState(config2.statePath, state);
45551
45658
  }
45552
- const pending2 = state.pending_next;
45659
+ const pending3 = state.pending_next;
45553
45660
  let result2;
45554
45661
  try {
45555
45662
  result2 = await session.client.callTool("inference.agent.assignment.next", {
45556
- operation_id: pending2.operation_id,
45663
+ operation_id: pending3.operation_id,
45557
45664
  host_id: session.localState.host_id,
45558
- requested_at: pending2.requested_at,
45665
+ requested_at: pending3.requested_at,
45559
45666
  contract_version: "agent_assignment_v2",
45560
45667
  ...state.assignment ? {
45561
45668
  assignment_id: state.assignment.assignment_id,
@@ -46096,23 +46203,23 @@ Waiting for approval...
46096
46203
  });
46097
46204
  const stopAt = now().getTime() + parsed.waitSeconds * 1e3;
46098
46205
  while (true) {
46099
- let pending2 = await readInferenceAgentNextState(config2.statePath);
46100
- if (!pending2) {
46101
- pending2 = {
46206
+ let pending3 = await readInferenceAgentNextState(config2.statePath);
46207
+ if (!pending3) {
46208
+ pending3 = {
46102
46209
  schema_version: "vtx_inference_agent_next_v1",
46103
46210
  operation_id: agentOperationId("agent-next"),
46104
46211
  requested_at: now().toISOString()
46105
46212
  };
46106
- await writeInferenceAgentNextState(config2.statePath, pending2);
46213
+ await writeInferenceAgentNextState(config2.statePath, pending3);
46107
46214
  }
46108
46215
  let result2;
46109
46216
  const callStartedAtMs = now().getTime();
46110
46217
  const callStartedMonotonicMs = performance.now();
46111
46218
  try {
46112
46219
  result2 = await session.client.callTool("inference.agent.next", {
46113
- operation_id: pending2.operation_id,
46220
+ operation_id: pending3.operation_id,
46114
46221
  host_id: session.localState.host_id,
46115
- requested_at: pending2.requested_at,
46222
+ requested_at: pending3.requested_at,
46116
46223
  provider_dispatch_freshness_contract: "foreground_v1"
46117
46224
  });
46118
46225
  } catch (error48) {
@@ -46134,7 +46241,7 @@ Waiting for approval...
46134
46241
  const conservativeDeadline = Math.min(
46135
46242
  Date.parse(result2.provider_dispatch_not_after),
46136
46243
  receivedAtMs + Number(result2.provider_dispatch_freshness_remaining_ms) - roundTripMs,
46137
- 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),
46138
46245
  active?.provider_dispatch_local_not_after ? Date.parse(active.provider_dispatch_local_not_after) : Number.POSITIVE_INFINITY
46139
46246
  );
46140
46247
  localDispatchDeadline = new Date(conservativeDeadline).toISOString();
@@ -47836,6 +47943,491 @@ var init_hyperliquid_market_symbol = __esm({
47836
47943
  }
47837
47944
  });
47838
47945
 
47946
+ // lib/runtime/abort.ts
47947
+ var ABORT_MESSAGE_TOKENS, readAbortLikeMessage, isAbortLikeError;
47948
+ var init_abort = __esm({
47949
+ "lib/runtime/abort.ts"() {
47950
+ "use strict";
47951
+ init_define_VTX_EXO_POLICY();
47952
+ init_define_VTX_GROK_POLICY();
47953
+ init_define_VTX_PI_MODEL_POLICY();
47954
+ ABORT_MESSAGE_TOKENS = [
47955
+ "the operation was aborted",
47956
+ "the user aborted a request",
47957
+ "request was aborted",
47958
+ "request aborted",
47959
+ "signal is aborted",
47960
+ "client runtime stop requested"
47961
+ ];
47962
+ readAbortLikeMessage = (error48) => {
47963
+ if (error48 instanceof Error) {
47964
+ return error48.message;
47965
+ }
47966
+ if (typeof error48 === "string") {
47967
+ return error48;
47968
+ }
47969
+ if (error48 && typeof error48 === "object" && typeof error48.message === "string") {
47970
+ return String(error48.message);
47971
+ }
47972
+ return "";
47973
+ };
47974
+ isAbortLikeError = (error48) => {
47975
+ if (typeof DOMException !== "undefined" && error48 instanceof DOMException) {
47976
+ return error48.name === "AbortError";
47977
+ }
47978
+ if (error48 instanceof Error && error48.name === "AbortError") {
47979
+ return true;
47980
+ }
47981
+ if (error48 && typeof error48 === "object" && error48.name === "AbortError") {
47982
+ return true;
47983
+ }
47984
+ const normalized = readAbortLikeMessage(error48).trim().toLowerCase();
47985
+ if (!normalized) {
47986
+ return false;
47987
+ }
47988
+ return ABORT_MESSAGE_TOKENS.some((token) => normalized.includes(token));
47989
+ };
47990
+ }
47991
+ });
47992
+
47993
+ // lib/runtime/runtime-redaction.ts
47994
+ 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;
47995
+ var init_runtime_redaction = __esm({
47996
+ "lib/runtime/runtime-redaction.ts"() {
47997
+ "use strict";
47998
+ init_define_VTX_EXO_POLICY();
47999
+ init_define_VTX_GROK_POLICY();
48000
+ init_define_VTX_PI_MODEL_POLICY();
48001
+ init_abort();
48002
+ REDACTED_VALUE = "[REDACTED]";
48003
+ SECRET_QUERY_PARAM_PATTERN = /([?&](?:access_token|api(?:_|-)?key|auth|authorization|key|private_key|secret|sig|signature|token)=)[^&#\s]*/gi;
48004
+ BEARER_TOKEN_PATTERN = /\b(Bearer)\s+[A-Za-z0-9._:-]+\b/gi;
48005
+ 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;
48006
+ SECRET_KEYWORD_VALUE_PATTERN = /((?:private(?:_|-|\s)?key|signing(?:_|-|\s)?key)\s*[:=]\s*['"]?)(0x[a-fA-F0-9]{64}|[^'"\s,}]+)/gi;
48007
+ OPENAI_STYLE_KEY_PATTERN = /\bsk-[A-Za-z0-9._-]+\b/g;
48008
+ VERTEX_EXPRESS_KEY_PATTERN = /\bAQ\.[A-Za-z0-9._-]+\b/g;
48009
+ sanitizeRuntimeDiagnosticValue = (value) => {
48010
+ const normalized = String(value || "");
48011
+ if (!normalized) {
48012
+ return normalized;
48013
+ }
48014
+ 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);
48015
+ };
48016
+ sanitizeRuntimeNetworkPath = (value) => {
48017
+ const normalized = String(value || "").trim();
48018
+ if (!normalized) {
48019
+ return "/";
48020
+ }
48021
+ const withoutFragment = normalized.split("#", 1)[0] || normalized;
48022
+ const withoutQuery = withoutFragment.split("?", 1)[0] || withoutFragment;
48023
+ const sanitized = sanitizeRuntimeDiagnosticValue(withoutQuery.trim());
48024
+ return sanitized || "/";
48025
+ };
48026
+ getSanitizedRuntimeErrorMessage = (error48) => {
48027
+ const message = error48 instanceof Error ? error48.message : typeof error48 === "string" ? error48 : error48 == null ? null : String(error48);
48028
+ if (message == null) {
48029
+ return null;
48030
+ }
48031
+ return sanitizeRuntimeDiagnosticValue(message);
48032
+ };
48033
+ toSanitizedRuntimeError = (error48) => {
48034
+ const message = getSanitizedRuntimeErrorMessage(error48) || "Unknown runtime error.";
48035
+ if (error48 instanceof Error && error48.message === message) {
48036
+ if (isAbortLikeError(error48) && error48.name !== "AbortError") {
48037
+ error48.name = "AbortError";
48038
+ }
48039
+ return error48;
48040
+ }
48041
+ const sanitized = new Error(message);
48042
+ if (isAbortLikeError(error48)) {
48043
+ sanitized.name = "AbortError";
48044
+ } else if (error48 instanceof Error && error48.name) {
48045
+ sanitized.name = error48.name;
48046
+ }
48047
+ return sanitized;
48048
+ };
48049
+ }
48050
+ });
48051
+
48052
+ // lib/runtime-policy.generated.json
48053
+ var runtime_policy_generated_default2;
48054
+ var init_runtime_policy_generated2 = __esm({
48055
+ "lib/runtime-policy.generated.json"() {
48056
+ runtime_policy_generated_default2 = {
48057
+ ui: {
48058
+ performance_defaults: {
48059
+ default_timeframe: "30d"
48060
+ },
48061
+ execution_metadata_retry: {
48062
+ max_attempts: 3,
48063
+ base_delay_milliseconds: 2e3,
48064
+ max_delay_milliseconds: 3e4
48065
+ },
48066
+ auth_bootstrap_retry: {
48067
+ max_attempts: 3,
48068
+ jitter_milliseconds: 750,
48069
+ base_delay_milliseconds: 500,
48070
+ min_delay_milliseconds: 250,
48071
+ max_delay_milliseconds: 1e4
48072
+ }
48073
+ },
48074
+ ai_dashboard: {
48075
+ market_news_bounds: {
48076
+ max_items_min: 1,
48077
+ max_items_max: 100,
48078
+ lookback_hours_min: 1,
48079
+ lookback_hours_max: 168,
48080
+ max_items_steps: [
48081
+ 1,
48082
+ 2,
48083
+ 3,
48084
+ 4,
48085
+ 5,
48086
+ 6,
48087
+ 7,
48088
+ 8,
48089
+ 9,
48090
+ 10,
48091
+ 15,
48092
+ 20,
48093
+ 25,
48094
+ 30,
48095
+ 40,
48096
+ 50,
48097
+ 60,
48098
+ 75,
48099
+ 90,
48100
+ 100
48101
+ ],
48102
+ lookback_hours_steps: [
48103
+ 1,
48104
+ 2,
48105
+ 4,
48106
+ 8,
48107
+ 12,
48108
+ 24,
48109
+ 48,
48110
+ 72,
48111
+ 168
48112
+ ]
48113
+ }
48114
+ },
48115
+ trading: {
48116
+ engine: {
48117
+ client_runtime: {
48118
+ recovery: {
48119
+ resume_retry_base_delay_ms: 1e3,
48120
+ resume_retry_max_delay_ms: 3e4,
48121
+ transient_load_min_delay_ms: 3e4,
48122
+ transient_load_max_delay_ms: 12e4,
48123
+ rate_limit_buffer_ms: 1e3,
48124
+ rate_limit_max_delay_ms: 3e5,
48125
+ engine_stop_settle_retry_delay_ms: 250,
48126
+ recoverable_reset_settle_retry_delay_ms: 1500,
48127
+ local_ai_preflight_timeout_ms: 3e3,
48128
+ surge_stagger_max_ms: 6e4,
48129
+ surge_stagger_min_ms: 2e3,
48130
+ surge_stagger_min_candidates: 4,
48131
+ stagger_deadline_ttl_ms: 3e5,
48132
+ server_active_reprobe_delay_ms: 6e4,
48133
+ transient_load_jitter_ms: 1e4,
48134
+ cross_host_completed_ttl_ms: 15e3,
48135
+ telemetry_dedupe_ttl_ms: 5e3,
48136
+ browser_presence_heartbeat_interval_ms: 3e4,
48137
+ host_liveness_heartbeat_interval_ms: 3e4,
48138
+ host_liveness_recovery_nudge_ttl_ms: 1e4
48139
+ }
48140
+ }
48141
+ }
48142
+ },
48143
+ external_inference: {
48144
+ service: {
48145
+ update_check_interval_ms: 3e5,
48146
+ update_registry_timeout_ms: 15e3,
48147
+ startup_max_attempts: 40,
48148
+ startup_poll_interval_ms: 250,
48149
+ restart_stable_uptime_ms: 6e4,
48150
+ restart_backoff_base_ms: 1e3,
48151
+ restart_backoff_max_ms: 3e4,
48152
+ restart_exponent_max: 5
48153
+ }
48154
+ },
48155
+ desktop: {
48156
+ runtime_watchdog: {
48157
+ ping_interval_milliseconds: 15e3,
48158
+ telemetry_interval_milliseconds: 3e5
48159
+ }
48160
+ },
48161
+ screener: {
48162
+ resource_scheduler: {
48163
+ client_lock_ttl_milliseconds: 12e4,
48164
+ client_poll_interval_milliseconds: 250
48165
+ }
48166
+ },
48167
+ deployment: {
48168
+ cutover_buffer: {
48169
+ target_timeout_ms: 3e3,
48170
+ retired_timeout_ms: 45e3,
48171
+ max_body_bytes: 33554432,
48172
+ max_inflight: 16,
48173
+ max_queue: 64
48174
+ }
48175
+ },
48176
+ exchange: {
48177
+ hyperliquid: {
48178
+ client_public_read_budget: {
48179
+ max_weight: 900,
48180
+ window_seconds: 60,
48181
+ cooldown_seconds: 60,
48182
+ metadata_ttl_seconds: 300,
48183
+ user_fees_ttl_seconds: 300,
48184
+ account_mode_ttl_seconds: 30,
48185
+ default_request_weight: 20,
48186
+ cache_max_entries: 512
48187
+ },
48188
+ read_budget: {
48189
+ weights: {
48190
+ exchangeStatus: 2,
48191
+ clearinghouseState: 2,
48192
+ spotClearinghouseState: 2,
48193
+ l2Book: 2,
48194
+ allMids: 2,
48195
+ userFills: 120,
48196
+ userFillsByTime: 120,
48197
+ historicalOrders: 120,
48198
+ twapHistory: 120,
48199
+ userTwapSliceFills: 120,
48200
+ userFunding: 45,
48201
+ userNonFundingLedgerUpdates: 45,
48202
+ candleSnapshot: 104,
48203
+ userRole: 60,
48204
+ userAbstraction: 20,
48205
+ userDexAbstraction: 20,
48206
+ userActiveAssetData: 20,
48207
+ activeAssetData: 20,
48208
+ openOrders: 20,
48209
+ orderStatus: 2,
48210
+ portfolio: 20,
48211
+ userFees: 20,
48212
+ metaAndAssetCtxs: 20,
48213
+ meta: 20,
48214
+ perpDexs: 20,
48215
+ spotMeta: 20,
48216
+ approvedAgents: 20,
48217
+ authorizedAgents: 20,
48218
+ agents: 20,
48219
+ apiWallets: 20
48220
+ }
48221
+ }
48222
+ }
48223
+ }
48224
+ };
48225
+ }
48226
+ });
48227
+
48228
+ // lib/runtime/hyperliquid-public-read.ts
48229
+ var policy, weights, budgets, unpersistedBudgets, cache, pending2, PREFIX, abortError2, checkAbort, wait, storage, loadBudget, saveBudget, withBudgetLock, admit, cooldown, reserveHyperliquidPublicReads, readHyperliquidPublicInfo;
48230
+ var init_hyperliquid_public_read = __esm({
48231
+ "lib/runtime/hyperliquid-public-read.ts"() {
48232
+ "use strict";
48233
+ init_define_VTX_EXO_POLICY();
48234
+ init_define_VTX_GROK_POLICY();
48235
+ init_define_VTX_PI_MODEL_POLICY();
48236
+ init_runtime_redaction();
48237
+ init_runtime_policy_generated2();
48238
+ policy = runtime_policy_generated_default2.exchange.hyperliquid.client_public_read_budget;
48239
+ weights = runtime_policy_generated_default2.exchange.hyperliquid.read_budget.weights;
48240
+ budgets = /* @__PURE__ */ new Map();
48241
+ unpersistedBudgets = /* @__PURE__ */ new Set();
48242
+ cache = /* @__PURE__ */ new Map();
48243
+ pending2 = /* @__PURE__ */ new Map();
48244
+ PREFIX = "vtx:hl-public-read-budget:v1:";
48245
+ abortError2 = (signal) => signal?.reason instanceof Error ? signal.reason : new DOMException("Aborted", "AbortError");
48246
+ checkAbort = (signal) => {
48247
+ if (signal?.aborted) throw abortError2(signal);
48248
+ };
48249
+ wait = (ms, signal) => new Promise((resolve12, reject) => {
48250
+ checkAbort(signal);
48251
+ const aborted2 = () => {
48252
+ clearTimeout(timer);
48253
+ reject(abortError2(signal));
48254
+ };
48255
+ const timer = setTimeout(() => {
48256
+ signal?.removeEventListener("abort", aborted2);
48257
+ resolve12();
48258
+ }, Math.min(ms, 2147483647));
48259
+ signal?.addEventListener("abort", aborted2, { once: true });
48260
+ });
48261
+ storage = () => {
48262
+ try {
48263
+ return typeof localStorage === "undefined" ? null : localStorage;
48264
+ } catch {
48265
+ return null;
48266
+ }
48267
+ };
48268
+ loadBudget = (key) => {
48269
+ const memory = budgets.get(key) ?? { reservations: [], cooldownUntil: 0 };
48270
+ if (unpersistedBudgets.has(key)) return memory;
48271
+ try {
48272
+ const target = storage();
48273
+ if (target && target.getItem(key) == null) return { reservations: [], cooldownUntil: 0 };
48274
+ const stored = JSON.parse(target?.getItem(key) ?? "null");
48275
+ 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;
48276
+ } catch {
48277
+ }
48278
+ return memory;
48279
+ };
48280
+ saveBudget = (key, budget) => {
48281
+ budgets.set(key, budget);
48282
+ try {
48283
+ const target = storage();
48284
+ if (!target) {
48285
+ unpersistedBudgets.add(key);
48286
+ return;
48287
+ }
48288
+ target.setItem(key, JSON.stringify(budget));
48289
+ unpersistedBudgets.delete(key);
48290
+ } catch {
48291
+ unpersistedBudgets.add(key);
48292
+ }
48293
+ };
48294
+ withBudgetLock = async (key, signal, work) => {
48295
+ checkAbort(signal);
48296
+ if (typeof navigator !== "undefined" && navigator.locks?.request) {
48297
+ return navigator.locks.request(key, { ...signal ? { signal } : {} }, work);
48298
+ }
48299
+ return work();
48300
+ };
48301
+ admit = async (apiUrl, requestType, signal, bundleWeight, bundleId) => {
48302
+ const key = `${PREFIX}${apiUrl}`;
48303
+ const weight = bundleWeight ?? weights[requestType] ?? policy.default_request_weight;
48304
+ if (!(weight > 0 && weight <= policy.max_weight)) throw new Error("Invalid Hyperliquid public read weight.");
48305
+ for (; ; ) {
48306
+ checkAbort(signal);
48307
+ const delay2 = await withBudgetLock(key, signal, () => {
48308
+ const now = Date.now();
48309
+ const budget = loadBudget(key);
48310
+ budget.reservations = budget.reservations.filter((r) => r.at > now - policy.window_seconds * 1e3);
48311
+ if (budget.cooldownUntil > now) throw Object.assign(new Error("Hyperliquid public read rate-limit cooldown."), { status: 429, requestType });
48312
+ let used = budget.reservations.reduce((sum, r) => sum + r.weight, 0);
48313
+ if (used + weight <= policy.max_weight) {
48314
+ budget.reservations.push({ at: now, weight, ...bundleId ? { id: bundleId } : {} });
48315
+ saveBudget(key, budget);
48316
+ return 0;
48317
+ }
48318
+ for (const reservation of budget.reservations) {
48319
+ used -= reservation.weight;
48320
+ if (used + weight <= policy.max_weight) return Math.max(1, reservation.at + policy.window_seconds * 1e3 - now);
48321
+ }
48322
+ throw new Error("Invalid Hyperliquid public read budget.");
48323
+ });
48324
+ if (!delay2) return;
48325
+ if (bundleWeight != null) throw Object.assign(new Error("Hyperliquid public read bundle budget exhausted."), { code: "public_budget_exhausted" });
48326
+ await wait(delay2, signal);
48327
+ }
48328
+ };
48329
+ cooldown = async (apiUrl, retryAfter) => {
48330
+ const key = `${PREFIX}${apiUrl}`;
48331
+ await withBudgetLock(key, void 0, () => {
48332
+ const now = Date.now();
48333
+ const seconds = retryAfter == null ? NaN : Number(retryAfter);
48334
+ const providerUntil = Number.isFinite(seconds) ? now + seconds * 1e3 : Date.parse(retryAfter ?? "");
48335
+ const budget = loadBudget(key);
48336
+ budget.cooldownUntil = Math.max(budget.cooldownUntil, now + policy.cooldown_seconds * 1e3, Number.isFinite(providerUntil) ? providerUntil : 0);
48337
+ saveBudget(key, budget);
48338
+ });
48339
+ };
48340
+ reserveHyperliquidPublicReads = async (endpoint, bodies, signal) => {
48341
+ const apiUrl = endpoint.replace(/\/$/, "");
48342
+ const weight = bodies.reduce((sum, body) => sum + (weights[String(body.type)] ?? policy.default_request_weight), 0);
48343
+ const id2 = crypto.randomUUID();
48344
+ const admittedAtMs = Date.now();
48345
+ await admit(apiUrl, "bundle", signal, weight, id2);
48346
+ const remaining = /* @__PURE__ */ new Map();
48347
+ for (const body of bodies) {
48348
+ const key = JSON.stringify(body);
48349
+ remaining.set(key, (remaining.get(key) ?? 0) + 1);
48350
+ }
48351
+ return { id: id2, endpoint: apiUrl, expiresAtMs: admittedAtMs + policy.window_seconds * 1e3, remaining };
48352
+ };
48353
+ readHyperliquidPublicInfo = async (endpoint, body, options = {}) => {
48354
+ const apiUrl = endpoint.replace(/\/$/, "");
48355
+ const requestType = String(body.type ?? "info");
48356
+ 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;
48357
+ const key = `${apiUrl}:${JSON.stringify(body)}`;
48358
+ checkAbort(options.signal);
48359
+ if (ttlSeconds) {
48360
+ for (; ; ) {
48361
+ const existing = cache.get(key);
48362
+ if (existing && Date.now() - existing.fetchedAtMs >= 0 && Date.now() - existing.fetchedAtMs < ttlSeconds * 500) return existing;
48363
+ const running = pending2.get(key);
48364
+ if (!running) break;
48365
+ await new Promise((resolve12, reject) => {
48366
+ const aborted2 = () => {
48367
+ options.signal?.removeEventListener("abort", aborted2);
48368
+ reject(abortError2(options.signal));
48369
+ };
48370
+ options.signal?.addEventListener("abort", aborted2, { once: true });
48371
+ running.then(() => {
48372
+ options.signal?.removeEventListener("abort", aborted2);
48373
+ resolve12();
48374
+ });
48375
+ });
48376
+ checkAbort(options.signal);
48377
+ }
48378
+ }
48379
+ let settled;
48380
+ if (ttlSeconds) pending2.set(key, new Promise((resolve12) => {
48381
+ settled = resolve12;
48382
+ }));
48383
+ try {
48384
+ const reservedKey = JSON.stringify(body);
48385
+ const remaining = options.reservation?.remaining.get(reservedKey) ?? 0;
48386
+ if (options.reservation?.endpoint === apiUrl && remaining > 0) {
48387
+ if (Date.now() >= options.reservation.expiresAtMs) throw Object.assign(new Error("Hyperliquid public read reservation expired."), { code: "public_budget_exhausted" });
48388
+ await withBudgetLock(`${PREFIX}${apiUrl}`, options.signal, () => {
48389
+ const budget = loadBudget(`${PREFIX}${apiUrl}`);
48390
+ const row = budget.reservations.find((entry) => entry.id === options.reservation.id);
48391
+ if (!row || Date.now() >= options.reservation.expiresAtMs) throw Object.assign(new Error("Hyperliquid public read reservation expired."), { code: "public_budget_exhausted" });
48392
+ row.at = Date.now();
48393
+ budget.reservations.sort((a, b2) => a.at - b2.at);
48394
+ saveBudget(`${PREFIX}${apiUrl}`, budget);
48395
+ });
48396
+ options.reservation.remaining.set(reservedKey, remaining - 1);
48397
+ } else await admit(apiUrl, requestType, options.signal);
48398
+ checkAbort(options.signal);
48399
+ if (loadBudget(`${PREFIX}${apiUrl}`).cooldownUntil > Date.now()) throw Object.assign(new Error("Hyperliquid public read rate-limit cooldown."), { status: 429, requestType });
48400
+ const response = await fetch(`${apiUrl}/info`, {
48401
+ method: "POST",
48402
+ headers: { "Content-Type": "application/json" },
48403
+ body: JSON.stringify(body),
48404
+ signal: options.signal
48405
+ });
48406
+ if (response.status === 429) await cooldown(apiUrl, response.headers.get("Retry-After"));
48407
+ const payload = await response.json().catch(() => ({}));
48408
+ if (!response.ok) {
48409
+ const detail = sanitizeRuntimeDiagnosticValue(typeof payload?.response === "string" ? payload.response : typeof payload?.detail === "string" ? payload.detail : "");
48410
+ throw Object.assign(new Error(`Hyperliquid info request failed (${response.status}) request_type=${requestType}.${detail ? ` ${detail}` : ""}`), {
48411
+ status: response.status,
48412
+ requestType
48413
+ });
48414
+ }
48415
+ const result2 = { payload, fetchedAtMs: Date.now() };
48416
+ if (ttlSeconds) {
48417
+ cache.set(key, result2);
48418
+ while (cache.size > policy.cache_max_entries) cache.delete(cache.keys().next().value);
48419
+ }
48420
+ return result2;
48421
+ } finally {
48422
+ if (ttlSeconds) {
48423
+ pending2.delete(key);
48424
+ settled?.();
48425
+ }
48426
+ }
48427
+ };
48428
+ }
48429
+ });
48430
+
47839
48431
  // lib/sort-utils.ts
47840
48432
  function compareCaseInsensitive(left, right) {
47841
48433
  return String(left ?? "").localeCompare(String(right ?? ""), void 0, { sensitivity: "base" });
@@ -47993,17 +48585,17 @@ var init_hyperliquid_account_contract = __esm({
47993
48585
  init_define_VTX_PI_MODEL_POLICY();
47994
48586
  init_hyperliquid_account_mode_contract();
47995
48587
  toNumber = (value, fallback = 0) => {
47996
- const numeric = Number(value);
47997
- return Number.isFinite(numeric) ? numeric : fallback;
48588
+ const numeric2 = Number(value);
48589
+ return Number.isFinite(numeric2) ? numeric2 : fallback;
47998
48590
  };
47999
48591
  firstNumber = (values, fallback = 0) => {
48000
48592
  for (const value of values) {
48001
48593
  if (value == null || typeof value === "string" && value.trim() === "") {
48002
48594
  continue;
48003
48595
  }
48004
- const numeric = Number(value);
48005
- if (Number.isFinite(numeric)) {
48006
- return numeric;
48596
+ const numeric2 = Number(value);
48597
+ if (Number.isFinite(numeric2)) {
48598
+ return numeric2;
48007
48599
  }
48008
48600
  }
48009
48601
  return fallback;
@@ -48199,14 +48791,14 @@ var init_server_prompt_rescue_account_contract = __esm({
48199
48791
  init_hyperliquid_account_mode_contract();
48200
48792
  STABLE_SYMBOLS = /* @__PURE__ */ new Set(["USDC", "USD", "USDT"]);
48201
48793
  toNumber2 = (value, fallback = 0) => {
48202
- const numeric = Number(value);
48203
- return Number.isFinite(numeric) ? numeric : fallback;
48794
+ const numeric2 = Number(value);
48795
+ return Number.isFinite(numeric2) ? numeric2 : fallback;
48204
48796
  };
48205
48797
  firstNumber2 = (values, fallback = 0) => {
48206
48798
  for (const value of values) {
48207
48799
  if (value == null || value === "") continue;
48208
- const numeric = Number(value);
48209
- if (Number.isFinite(numeric)) return numeric;
48800
+ const numeric2 = Number(value);
48801
+ if (Number.isFinite(numeric2)) return numeric2;
48210
48802
  }
48211
48803
  return fallback;
48212
48804
  };
@@ -48414,108 +49006,48 @@ var init_server_prompt_rescue_account_contract = __esm({
48414
49006
  }
48415
49007
  });
48416
49008
 
48417
- // lib/runtime/abort.ts
48418
- var ABORT_MESSAGE_TOKENS, readAbortLikeMessage, isAbortLikeError;
48419
- var init_abort = __esm({
48420
- "lib/runtime/abort.ts"() {
49009
+ // lib/runtime/hyperliquid-fee-contract.ts
49010
+ var numeric, effectiveHyperliquidTakerRates;
49011
+ var init_hyperliquid_fee_contract = __esm({
49012
+ "lib/runtime/hyperliquid-fee-contract.ts"() {
48421
49013
  "use strict";
48422
49014
  init_define_VTX_EXO_POLICY();
48423
49015
  init_define_VTX_GROK_POLICY();
48424
49016
  init_define_VTX_PI_MODEL_POLICY();
48425
- ABORT_MESSAGE_TOKENS = [
48426
- "the operation was aborted",
48427
- "the user aborted a request",
48428
- "request was aborted",
48429
- "request aborted",
48430
- "signal is aborted",
48431
- "client runtime stop requested"
48432
- ];
48433
- readAbortLikeMessage = (error48) => {
48434
- if (error48 instanceof Error) {
48435
- return error48.message;
48436
- }
48437
- if (typeof error48 === "string") {
48438
- return error48;
48439
- }
48440
- if (error48 && typeof error48 === "object" && typeof error48.message === "string") {
48441
- return String(error48.message);
48442
- }
48443
- return "";
48444
- };
48445
- isAbortLikeError = (error48) => {
48446
- if (typeof DOMException !== "undefined" && error48 instanceof DOMException) {
48447
- return error48.name === "AbortError";
48448
- }
48449
- if (error48 instanceof Error && error48.name === "AbortError") {
48450
- return true;
48451
- }
48452
- if (error48 && typeof error48 === "object" && error48.name === "AbortError") {
48453
- return true;
48454
- }
48455
- const normalized = readAbortLikeMessage(error48).trim().toLowerCase();
48456
- if (!normalized) {
48457
- return false;
48458
- }
48459
- return ABORT_MESSAGE_TOKENS.some((token) => normalized.includes(token));
48460
- };
48461
- }
48462
- });
48463
-
48464
- // lib/runtime/runtime-redaction.ts
48465
- 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;
48466
- var init_runtime_redaction = __esm({
48467
- "lib/runtime/runtime-redaction.ts"() {
48468
- "use strict";
48469
- init_define_VTX_EXO_POLICY();
48470
- init_define_VTX_GROK_POLICY();
48471
- init_define_VTX_PI_MODEL_POLICY();
48472
- init_abort();
48473
- REDACTED_VALUE = "[REDACTED]";
48474
- SECRET_QUERY_PARAM_PATTERN = /([?&](?:access_token|api(?:_|-)?key|auth|authorization|key|private_key|secret|sig|signature|token)=)[^&#\s]*/gi;
48475
- BEARER_TOKEN_PATTERN = /\b(Bearer)\s+[A-Za-z0-9._:-]+\b/gi;
48476
- 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;
48477
- SECRET_KEYWORD_VALUE_PATTERN = /((?:private(?:_|-|\s)?key|signing(?:_|-|\s)?key)\s*[:=]\s*['"]?)(0x[a-fA-F0-9]{64}|[^'"\s,}]+)/gi;
48478
- OPENAI_STYLE_KEY_PATTERN = /\bsk-[A-Za-z0-9._-]+\b/g;
48479
- VERTEX_EXPRESS_KEY_PATTERN = /\bAQ\.[A-Za-z0-9._-]+\b/g;
48480
- sanitizeRuntimeDiagnosticValue = (value) => {
48481
- const normalized = String(value || "");
48482
- if (!normalized) {
48483
- return normalized;
48484
- }
48485
- 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);
48486
- };
48487
- sanitizeRuntimeNetworkPath = (value) => {
48488
- const normalized = String(value || "").trim();
48489
- if (!normalized) {
48490
- return "/";
48491
- }
48492
- const withoutFragment = normalized.split("#", 1)[0] || normalized;
48493
- const withoutQuery = withoutFragment.split("?", 1)[0] || withoutFragment;
48494
- const sanitized = sanitizeRuntimeDiagnosticValue(withoutQuery.trim());
48495
- return sanitized || "/";
48496
- };
48497
- getSanitizedRuntimeErrorMessage = (error48) => {
48498
- const message = error48 instanceof Error ? error48.message : typeof error48 === "string" ? error48 : error48 == null ? null : String(error48);
48499
- if (message == null) {
48500
- return null;
48501
- }
48502
- return sanitizeRuntimeDiagnosticValue(message);
49017
+ init_hyperliquid_market_symbol();
49018
+ numeric = (value) => {
49019
+ if (typeof value !== "number" && typeof value !== "string" || typeof value === "string" && !value.trim()) return null;
49020
+ const parsed = Number(value);
49021
+ return Number.isFinite(parsed) ? parsed : null;
48503
49022
  };
48504
- toSanitizedRuntimeError = (error48) => {
48505
- const message = getSanitizedRuntimeErrorMessage(error48) || "Unknown runtime error.";
48506
- if (error48 instanceof Error && error48.message === message) {
48507
- if (isAbortLikeError(error48) && error48.name !== "AbortError") {
48508
- error48.name = "AbortError";
48509
- }
48510
- return error48;
48511
- }
48512
- const sanitized = new Error(message);
48513
- if (isAbortLikeError(error48)) {
48514
- sanitized.name = "AbortError";
48515
- } else if (error48 instanceof Error && error48.name) {
48516
- sanitized.name = error48.name;
48517
- }
48518
- return sanitized;
49023
+ effectiveHyperliquidTakerRates = (symbols, userFees, metaByDex, alignedByToken = {}) => {
49024
+ const base = numeric(userFees.userCrossRate);
49025
+ const discount = numeric(userFees.activeReferralDiscount);
49026
+ return Object.fromEntries([...new Set(symbols.map(normalizeHyperliquidMarketSymbol).filter(Boolean))].sort().map((symbol2) => {
49027
+ const unavailable = [symbol2, null];
49028
+ if (base == null || base < 0 || base >= 1 || discount == null || discount < 0 || discount > 1) return unavailable;
49029
+ const dex = getHyperliquidMarketDex(symbol2);
49030
+ const meta3 = metaByDex[dex];
49031
+ if (!meta3 || !Array.isArray(meta3.universe)) return unavailable;
49032
+ const matches = meta3.universe.filter((asset2) => {
49033
+ return asset2?.name === symbol2;
49034
+ });
49035
+ if (matches.length !== 1) return unavailable;
49036
+ const collateralToken = meta3.collateralToken;
49037
+ if (typeof collateralToken !== "number" || !Number.isInteger(collateralToken) || collateralToken < 0) return unavailable;
49038
+ const aligned = alignedByToken[String(collateralToken)] ?? (collateralToken === 0 ? false : void 0);
49039
+ if (typeof aligned !== "boolean") return unavailable;
49040
+ const asset = matches[0];
49041
+ const scale = dex ? numeric(asset.deployerFeeScale) : 0;
49042
+ const growthMode = dex ? asset.growthMode : "disabled";
49043
+ if (scale == null || scale < 0 || scale > 3 || !["enabled", "disabled", "blocked"].includes(growthMode)) return unavailable;
49044
+ if (growthMode === "enabled" && scale > 1) return unavailable;
49045
+ const multiplier = scale < 1 ? 1 + scale : 2 * scale;
49046
+ const deployerShare = scale < 1 ? scale / (1 + scale) : 0.5;
49047
+ const alignmentMultiplier = aligned ? (1 - deployerShare) * 0.8 + deployerShare : 1;
49048
+ const rate = base * (1 - discount) * multiplier * (growthMode === "enabled" ? 0.1 : 1) * alignmentMultiplier;
49049
+ return [symbol2, Number.isFinite(rate) && rate >= 0 && rate < 1 ? rate : null];
49050
+ }));
48519
49051
  };
48520
49052
  }
48521
49053
  });
@@ -48992,11 +49524,13 @@ var init_hyperliquid_account_state_adapter = __esm({
48992
49524
  init_define_VTX_EXO_POLICY();
48993
49525
  init_define_VTX_GROK_POLICY();
48994
49526
  init_define_VTX_PI_MODEL_POLICY();
49527
+ init_hyperliquid_public_read();
48995
49528
  init_sort_utils();
48996
49529
  init_hyperliquid_account_contract();
48997
49530
  init_hyperliquid_active_asset_contract();
48998
49531
  init_hyperliquid_account_mode_contract();
48999
49532
  init_server_prompt_rescue_account_contract();
49533
+ init_hyperliquid_fee_contract();
49000
49534
  init_hyperliquid_market_symbol();
49001
49535
  init_network_debug();
49002
49536
  unsupportedUserActiveAssetCache = /* @__PURE__ */ new Set();
@@ -49057,24 +49591,24 @@ var init_hyperliquid_account_state_adapter = __esm({
49057
49591
  }
49058
49592
  };
49059
49593
  toPositiveFinite = (value, fallback = 0) => {
49060
- const numeric = Number(value);
49061
- if (!Number.isFinite(numeric) || numeric <= 0) {
49594
+ const numeric2 = Number(value);
49595
+ if (!Number.isFinite(numeric2) || numeric2 <= 0) {
49062
49596
  return fallback;
49063
49597
  }
49064
- return numeric;
49598
+ return numeric2;
49065
49599
  };
49066
49600
  toFinite = (value, fallback = 0) => {
49067
- const numeric = Number(value);
49068
- return Number.isFinite(numeric) ? numeric : fallback;
49601
+ const numeric2 = Number(value);
49602
+ return Number.isFinite(numeric2) ? numeric2 : fallback;
49069
49603
  };
49070
49604
  firstFiniteNumber = (values, fallback = 0) => {
49071
49605
  for (const value of values) {
49072
49606
  if (value == null || typeof value === "string" && value.trim() === "") {
49073
49607
  continue;
49074
49608
  }
49075
- const numeric = Number(value);
49076
- if (Number.isFinite(numeric)) {
49077
- return numeric;
49609
+ const numeric2 = Number(value);
49610
+ if (Number.isFinite(numeric2)) {
49611
+ return numeric2;
49078
49612
  }
49079
49613
  }
49080
49614
  return fallback;
@@ -49112,7 +49646,7 @@ var init_hyperliquid_account_state_adapter = __esm({
49112
49646
  buildUserFillsStorageKey = (cacheKey) => {
49113
49647
  return `${USER_FILLS_CACHE_STORAGE_PREFIX}${cacheKey}`;
49114
49648
  };
49115
- buildAccountStateCacheKey = (apiUrl, walletAddress, symbol2, aggregatePerpDexs, scopeAccountSummaryToSelectedDex, dexNames, includeEffectiveTakerRate, includeExactAccountMode, includeActiveAssetData) => {
49649
+ buildAccountStateCacheKey = (apiUrl, walletAddress, symbol2, aggregatePerpDexs, scopeAccountSummaryToSelectedDex, dexNames, includeEffectiveTakerRate, includeExactAccountMode, includeActiveAssetData, feeSymbols) => {
49116
49650
  return [
49117
49651
  apiUrl.replace(/\/$/, "").toLowerCase(),
49118
49652
  walletAddress.trim().toLowerCase(),
@@ -49122,7 +49656,9 @@ var init_hyperliquid_account_state_adapter = __esm({
49122
49656
  includeEffectiveTakerRate ? "with-effective-taker-rate" : "without-effective-taker-rate",
49123
49657
  includeExactAccountMode ? "with-exact-account-mode" : "without-exact-account-mode",
49124
49658
  includeActiveAssetData ? "with-active-asset" : "without-active-asset",
49125
- ...dexNames.map(normalizePerpDexName).sort()
49659
+ ...dexNames.map(normalizePerpDexName).sort(),
49660
+ "fee-symbols",
49661
+ ...feeSymbols
49126
49662
  ].join("::");
49127
49663
  };
49128
49664
  buildAccountStateStorageKey = (cacheKey) => {
@@ -49216,11 +49752,11 @@ var init_hyperliquid_account_state_adapter = __esm({
49216
49752
  writeInfoRateLimitCooldown(apiUrl, requestType, staleIf429MaxAgeMs, nowMs);
49217
49753
  };
49218
49754
  requireNonNegativeConfigSeconds = (value, path) => {
49219
- const numeric = Number(value);
49220
- if (!Number.isFinite(numeric) || numeric < 0) {
49755
+ const numeric2 = Number(value);
49756
+ if (!Number.isFinite(numeric2) || numeric2 < 0) {
49221
49757
  throw new Error(`Missing required client runtime config: ${path}`);
49222
49758
  }
49223
- return numeric;
49759
+ return numeric2;
49224
49760
  };
49225
49761
  requireAccountStateCacheConfig = (config2) => {
49226
49762
  const readCacheConfig = config2.client_runtime_hyperliquid_read_cache;
@@ -49333,6 +49869,7 @@ var init_hyperliquid_account_state_adapter = __esm({
49333
49869
  availableToTrade: { ...result2.availableToTrade },
49334
49870
  positions: result2.positions.map((position) => ({ ...position })),
49335
49871
  ...result2.takerRate == null ? {} : { takerRate: result2.takerRate },
49872
+ ...result2.effectiveTakerRates == null ? {} : { effectiveTakerRates: { ...result2.effectiveTakerRates } },
49336
49873
  ...result2.promptRescueEvidence == null ? {} : { promptRescueEvidence: { ...result2.promptRescueEvidence } }
49337
49874
  });
49338
49875
  withAccountStateEvidence = (result2, source, fetchedAtMs, freshnessLimitMs) => {
@@ -49377,6 +49914,7 @@ var init_hyperliquid_account_state_adapter = __esm({
49377
49914
  availableToTrade: { ...result2.availableToTrade || {} },
49378
49915
  positions: Array.isArray(result2.positions) ? result2.positions.filter((position) => position !== null && typeof position === "object" && !Array.isArray(position)).map((position) => ({ ...position })) : [],
49379
49916
  ...result2.takerRate == null ? {} : { takerRate: Number(result2.takerRate) },
49917
+ ...result2.effectiveTakerRates == null ? {} : { effectiveTakerRates: { ...result2.effectiveTakerRates } },
49380
49918
  ...result2.promptRescueEvidence == null ? {} : { promptRescueEvidence: { ...result2.promptRescueEvidence } }
49381
49919
  }
49382
49920
  };
@@ -49736,40 +50274,14 @@ var init_hyperliquid_account_state_adapter = __esm({
49736
50274
  }
49737
50275
  return true;
49738
50276
  };
49739
- fetchHyperliquidInfoPayload = async (apiUrl, body, signal) => {
49740
- const requestUrl = `${apiUrl.replace(/\/$/, "")}/info`;
49741
- const requestType = String(body?.type || "info").trim() || "info";
49742
- const trace = startRuntimeNetworkDebugTrace({
49743
- kind: "exchange",
49744
- label: `hyperliquid_info:${requestType}`,
49745
- method: "POST",
49746
- url: requestUrl,
49747
- note: `type=${requestType}`
49748
- });
49749
- let response = null;
50277
+ fetchHyperliquidInfoPayload = async (apiUrl, body, signal, reservation) => {
50278
+ const trace = startRuntimeNetworkDebugTrace({ kind: "exchange", label: `hyperliquid_info:${String(body.type)}`, method: "POST", url: `${apiUrl.replace(/\/$/, "")}/info` });
49750
50279
  try {
49751
- response = await fetch(requestUrl, {
49752
- method: "POST",
49753
- headers: {
49754
- "Content-Type": "application/json"
49755
- },
49756
- body: JSON.stringify(body),
49757
- signal
49758
- });
49759
- const payload = await response.json().catch(() => ({}));
49760
- if (!response.ok) {
49761
- const responseDetail = typeof payload?.response === "string" ? payload.response : typeof payload?.detail === "string" ? payload.detail : "";
49762
- 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}.`;
49763
- const requestError = new Error(detail);
49764
- requestError.status = response.status;
49765
- requestError.detail = detail;
49766
- requestError.requestType = requestType;
49767
- throw requestError;
49768
- }
49769
- trace.completeSuccess(response.status);
49770
- return payload;
50280
+ const result2 = await readHyperliquidPublicInfo(apiUrl, body, { signal, reservation });
50281
+ trace.completeSuccess(200);
50282
+ return result2.payload;
49771
50283
  } catch (error48) {
49772
- trace.completeError(error48, response?.status ?? null);
50284
+ trace.completeError(error48, error48?.status ?? null);
49773
50285
  throw error48;
49774
50286
  }
49775
50287
  };
@@ -49835,7 +50347,8 @@ var init_hyperliquid_account_state_adapter = __esm({
49835
50347
  dexNames,
49836
50348
  includeEffectiveTakerRate,
49837
50349
  includeExactAccountMode,
49838
- includeActiveAssetData
50350
+ includeActiveAssetData,
50351
+ [...new Set((input.feeSymbols ?? [symbol2]).map(normalizeHyperliquidMarketSymbol).filter(Boolean))].sort()
49839
50352
  );
49840
50353
  const now = Date.now();
49841
50354
  const cached2 = readBrowserAccountStateCache(cacheKey);
@@ -49903,11 +50416,58 @@ var init_hyperliquid_account_state_adapter = __esm({
49903
50416
  dexNames,
49904
50417
  staleIf429MaxAgeMs
49905
50418
  }) => {
50419
+ const userFeesPromise = input.includeEffectiveTakerRate === true ? (async () => ({
50420
+ ...await readHyperliquidPublicInfo(apiUrl, { type: "userFees", user: walletAddress }, { signal: input.signal }).catch((error48) => {
50421
+ if (input.signal?.aborted) throw error48;
50422
+ return { payload: null, fetchedAtMs: Date.now() };
50423
+ }).then((result2) => ({ payload: result2.payload, capturedAt: new Date(result2.fetchedAtMs).toISOString() }))
50424
+ }))() : Promise.resolve(null);
50425
+ const exactAccountModePromise = input.includeExactAccountMode === true ? (async () => {
50426
+ const abstractionRead = await readHyperliquidPublicInfo(apiUrl, { type: "userAbstraction", user: walletAddress }, { signal: input.signal, cacheAccountMode: true });
50427
+ const userAbstraction = abstractionRead.payload;
50428
+ let capturedAtMs = abstractionRead.fetchedAtMs;
50429
+ const preliminaryMode = extractCanonicalHyperliquidAccountMode(userAbstraction);
50430
+ if (!preliminaryMode) {
50431
+ throw new Error("Exact Hyperliquid userAbstraction response is invalid.");
50432
+ }
50433
+ let userDexAbstraction;
50434
+ if (preliminaryMode === "default" || preliminaryMode === "disabled") {
50435
+ const dexRead = await readHyperliquidPublicInfo(apiUrl, { type: "userDexAbstraction", user: walletAddress }, { signal: input.signal, cacheAccountMode: true });
50436
+ userDexAbstraction = dexRead.payload;
50437
+ capturedAtMs = Math.min(capturedAtMs, dexRead.fetchedAtMs);
50438
+ }
50439
+ return {
50440
+ accountMode: resolveExactHyperliquidAccountMode(
50441
+ userAbstraction,
50442
+ userDexAbstraction
50443
+ ),
50444
+ capturedAt: new Date(capturedAtMs).toISOString()
50445
+ };
50446
+ })() : Promise.resolve(null);
50447
+ await Promise.all([userFeesPromise, exactAccountModePromise]);
50448
+ const metadataByDex = /* @__PURE__ */ new Map();
50449
+ if (input.includeEffectiveTakerRate === true) {
50450
+ await Promise.all(["", ...dexNames].map(async (dex) => {
50451
+ try {
50452
+ metadataByDex.set(dex, await fetchHyperliquidInfoPayload(apiUrl, { type: "meta", ...dex ? { dex } : {} }, input.signal));
50453
+ } catch (error48) {
50454
+ if (input.signal?.aborted) throw error48;
50455
+ metadataByDex.set(dex, null);
50456
+ }
50457
+ }));
50458
+ }
50459
+ const reservation = await reserveHyperliquidPublicReads(apiUrl, [
50460
+ { type: "clearinghouseState", user: walletAddress },
50461
+ ...dexNames.map((dex) => ({ type: "clearinghouseState", user: walletAddress, dex })),
50462
+ { type: "spotClearinghouseState", user: walletAddress },
50463
+ ...input.includeActiveAssetData === false ? [] : activeAssetRequestTypes.map((type) => ({ type, user: walletAddress, coin: symbol2 }))
50464
+ ], input.signal);
49906
50465
  const perpsPromise = (async () => {
49907
50466
  const defaultResponse = await fetchHyperliquidInfoPayload(
49908
50467
  apiUrl,
49909
50468
  { type: "clearinghouseState", user: walletAddress },
49910
- input.signal
50469
+ input.signal,
50470
+ reservation
49911
50471
  );
49912
50472
  if (input.includeEffectiveTakerRate === true) {
49913
50473
  requirePromptClearinghouseState(defaultResponse, "default");
@@ -49917,7 +50477,8 @@ var init_hyperliquid_account_state_adapter = __esm({
49917
50477
  const response = await fetchHyperliquidInfoPayload(
49918
50478
  apiUrl,
49919
50479
  { type: "clearinghouseState", user: walletAddress, dex: dexName },
49920
- input.signal
50480
+ input.signal,
50481
+ reservation
49921
50482
  );
49922
50483
  if (input.includeEffectiveTakerRate === true) {
49923
50484
  requirePromptClearinghouseState(response, dexName);
@@ -49952,7 +50513,8 @@ var init_hyperliquid_account_state_adapter = __esm({
49952
50513
  payload = await fetchHyperliquidInfoPayload(
49953
50514
  apiUrl,
49954
50515
  { type: "spotClearinghouseState", user: walletAddress },
49955
- input.signal
50516
+ input.signal,
50517
+ reservation
49956
50518
  );
49957
50519
  } catch (error48) {
49958
50520
  recordInfoRateLimitCooldownFromError(apiUrl, error48, staleIf429MaxAgeMs);
@@ -49970,12 +50532,14 @@ var init_hyperliquid_account_state_adapter = __esm({
49970
50532
  const payload = await fetchHyperliquidInfoPayload(
49971
50533
  apiUrl,
49972
50534
  { type: typeName, user: walletAddress, coin: symbol2 },
49973
- input.signal
50535
+ input.signal,
50536
+ reservation
49974
50537
  );
49975
50538
  return { payload, type: typeName };
49976
50539
  } catch (error48) {
49977
50540
  lastError = error48;
49978
50541
  recordInfoRateLimitCooldownFromError(apiUrl, error48, staleIf429MaxAgeMs);
50542
+ if (isRateLimitError(error48)) throw error48;
49979
50543
  if (typeName === "userActiveAssetData" && isUnsupportedUserActiveAssetError(error48)) {
49980
50544
  rememberUnsupportedUserActiveAssetKey(activeAssetCacheKey);
49981
50545
  }
@@ -49983,40 +50547,6 @@ var init_hyperliquid_account_state_adapter = __esm({
49983
50547
  }
49984
50548
  throw lastError instanceof Error ? lastError : new Error("Failed to fetch browser active asset data.");
49985
50549
  })();
49986
- const userFeesPromise = input.includeEffectiveTakerRate === true ? (async () => ({
49987
- payload: await fetchHyperliquidInfoPayload(
49988
- apiUrl,
49989
- { type: "userFees", user: walletAddress },
49990
- input.signal
49991
- ),
49992
- capturedAt: (/* @__PURE__ */ new Date()).toISOString()
49993
- }))() : Promise.resolve(null);
49994
- const exactAccountModePromise = input.includeExactAccountMode === true ? (async () => {
49995
- const userAbstraction = await fetchHyperliquidInfoPayload(
49996
- apiUrl,
49997
- { type: "userAbstraction", user: walletAddress },
49998
- input.signal
49999
- );
50000
- const preliminaryMode = extractCanonicalHyperliquidAccountMode(userAbstraction);
50001
- if (!preliminaryMode) {
50002
- throw new Error("Exact Hyperliquid userAbstraction response is invalid.");
50003
- }
50004
- let userDexAbstraction;
50005
- if (preliminaryMode === "default" || preliminaryMode === "disabled") {
50006
- userDexAbstraction = await fetchHyperliquidInfoPayload(
50007
- apiUrl,
50008
- { type: "userDexAbstraction", user: walletAddress },
50009
- input.signal
50010
- );
50011
- }
50012
- return {
50013
- accountMode: resolveExactHyperliquidAccountMode(
50014
- userAbstraction,
50015
- userDexAbstraction
50016
- ),
50017
- capturedAt: (/* @__PURE__ */ new Date()).toISOString()
50018
- };
50019
- })() : Promise.resolve(null);
50020
50550
  const [perpsResult, spotResult, activeAssetResult, userFeesResult, exactAccountMode] = await Promise.all([
50021
50551
  perpsPromise,
50022
50552
  spotPromise,
@@ -50033,18 +50563,26 @@ var init_hyperliquid_account_state_adapter = __esm({
50033
50563
  }
50034
50564
  let takerRate;
50035
50565
  if (input.includeEffectiveTakerRate === true) {
50036
- if (!userFeesResponse || typeof userFeesResponse !== "object" || Array.isArray(userFeesResponse)) {
50037
- throw new Error("Malformed Hyperliquid userFees response for client runtime prompt context.");
50038
- }
50039
- const rawUserCrossRate = userFeesResponse.userCrossRate;
50040
- if (rawUserCrossRate == null || typeof rawUserCrossRate === "string" && rawUserCrossRate.trim() === "") {
50041
- throw new Error("Hyperliquid userFees response is missing userCrossRate for client runtime prompt context.");
50042
- }
50043
- const parsedUserCrossRate = Number(rawUserCrossRate);
50044
- if (!Number.isFinite(parsedUserCrossRate) || parsedUserCrossRate < 0 || parsedUserCrossRate >= 1) {
50045
- throw new Error("Hyperliquid userFees response has an invalid userCrossRate for client runtime prompt context.");
50046
- }
50047
- takerRate = parsedUserCrossRate;
50566
+ const raw = userFeesResponse?.userCrossRate;
50567
+ if ((typeof raw === "number" || typeof raw === "string" && raw.trim() !== "") && Number.isFinite(Number(raw)) && Number(raw) >= 0 && Number(raw) < 1) takerRate = Number(raw);
50568
+ }
50569
+ let effectiveTakerRates;
50570
+ if (input.includeEffectiveTakerRate === true) {
50571
+ const feeSymbols = [...new Set([
50572
+ ...input.feeSymbols ?? [symbol2],
50573
+ ...parseInfoPositions(perpsResponse).filter((position) => Number(position.size) !== 0).map((position) => position.symbol)
50574
+ ].map(normalizeHyperliquidMarketSymbol).filter(Boolean))].sort();
50575
+ const feeDexes = [...new Set(feeSymbols.map(getHyperliquidMarketDex))];
50576
+ const metadata = await Promise.all(feeDexes.map(async (dex) => {
50577
+ try {
50578
+ const payload = metadataByDex.get(dex) ?? null;
50579
+ return [dex, payload];
50580
+ } catch (error48) {
50581
+ if (input.signal?.aborted) throw error48;
50582
+ return [dex, null];
50583
+ }
50584
+ }));
50585
+ effectiveTakerRates = effectiveHyperliquidTakerRates(feeSymbols, userFeesResponse ?? {}, Object.fromEntries(metadata));
50048
50586
  }
50049
50587
  const accountStateConfig = input.config.client_runtime_hyperliquid_account_state;
50050
50588
  const summaryPerpsResponse = exactAccountMode ? { ...accountSummaryPerpsResponse, accountMode: exactAccountMode.accountMode } : accountSummaryPerpsResponse;
@@ -50133,6 +50671,7 @@ var init_hyperliquid_account_state_adapter = __esm({
50133
50671
  availableToTrade,
50134
50672
  positions: parseInfoPositions(perpsResponse),
50135
50673
  ...takerRate == null ? {} : { takerRate },
50674
+ ...effectiveTakerRates == null ? {} : { effectiveTakerRates },
50136
50675
  ...exactAccountMode == null || userFeesResult == null ? {} : {
50137
50676
  promptRescueEvidence: {
50138
50677
  capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -50449,11 +50988,11 @@ function normalizeNonNegativeInt(value) {
50449
50988
  if (value == null) {
50450
50989
  return 0;
50451
50990
  }
50452
- const numeric = Number(value);
50453
- if (!Number.isInteger(numeric) || numeric < 0) {
50991
+ const numeric2 = Number(value);
50992
+ if (!Number.isInteger(numeric2) || numeric2 < 0) {
50454
50993
  return 0;
50455
50994
  }
50456
- return numeric;
50995
+ return numeric2;
50457
50996
  }
50458
50997
  function normalizeSecretVersion(value) {
50459
50998
  if (typeof value !== "string") {
@@ -50483,11 +51022,11 @@ function normalizeClientRuntimeSecretRetryAfterSeconds(value) {
50483
51022
  if (value == null) {
50484
51023
  return 0;
50485
51024
  }
50486
- const numeric = Number(value);
50487
- if (!Number.isFinite(numeric)) {
51025
+ const numeric2 = Number(value);
51026
+ if (!Number.isFinite(numeric2)) {
50488
51027
  return 0;
50489
51028
  }
50490
- const normalized = Math.trunc(numeric);
51029
+ const normalized = Math.trunc(numeric2);
50491
51030
  return normalized >= 0 ? normalized : 0;
50492
51031
  }
50493
51032
  function projectClientRuntimeSecretRateLimit(operation, retryAfterSeconds) {
@@ -50723,129 +51262,6 @@ var init_local_breadcrumbs = __esm({
50723
51262
  }
50724
51263
  });
50725
51264
 
50726
- // lib/runtime-policy.generated.json
50727
- var runtime_policy_generated_default2;
50728
- var init_runtime_policy_generated2 = __esm({
50729
- "lib/runtime-policy.generated.json"() {
50730
- runtime_policy_generated_default2 = {
50731
- ui: {
50732
- performance_defaults: {
50733
- default_timeframe: "30d"
50734
- },
50735
- auth_bootstrap_retry: {
50736
- max_attempts: 3,
50737
- jitter_milliseconds: 750,
50738
- base_delay_milliseconds: 500,
50739
- min_delay_milliseconds: 250,
50740
- max_delay_milliseconds: 1e4
50741
- }
50742
- },
50743
- ai_dashboard: {
50744
- market_news_bounds: {
50745
- max_items_min: 1,
50746
- max_items_max: 100,
50747
- lookback_hours_min: 1,
50748
- lookback_hours_max: 168,
50749
- max_items_steps: [
50750
- 1,
50751
- 2,
50752
- 3,
50753
- 4,
50754
- 5,
50755
- 6,
50756
- 7,
50757
- 8,
50758
- 9,
50759
- 10,
50760
- 15,
50761
- 20,
50762
- 25,
50763
- 30,
50764
- 40,
50765
- 50,
50766
- 60,
50767
- 75,
50768
- 90,
50769
- 100
50770
- ],
50771
- lookback_hours_steps: [
50772
- 1,
50773
- 2,
50774
- 4,
50775
- 8,
50776
- 12,
50777
- 24,
50778
- 48,
50779
- 72,
50780
- 168
50781
- ]
50782
- }
50783
- },
50784
- trading: {
50785
- engine: {
50786
- client_runtime: {
50787
- recovery: {
50788
- resume_retry_base_delay_ms: 1e3,
50789
- resume_retry_max_delay_ms: 3e4,
50790
- transient_load_min_delay_ms: 3e4,
50791
- transient_load_max_delay_ms: 12e4,
50792
- rate_limit_buffer_ms: 1e3,
50793
- rate_limit_max_delay_ms: 3e5,
50794
- engine_stop_settle_retry_delay_ms: 250,
50795
- recoverable_reset_settle_retry_delay_ms: 1500,
50796
- local_ai_preflight_timeout_ms: 3e3,
50797
- surge_stagger_max_ms: 6e4,
50798
- surge_stagger_min_ms: 2e3,
50799
- surge_stagger_min_candidates: 4,
50800
- stagger_deadline_ttl_ms: 3e5,
50801
- server_active_reprobe_delay_ms: 6e4,
50802
- transient_load_jitter_ms: 1e4,
50803
- cross_host_completed_ttl_ms: 15e3,
50804
- telemetry_dedupe_ttl_ms: 5e3,
50805
- browser_presence_heartbeat_interval_ms: 3e4,
50806
- host_liveness_heartbeat_interval_ms: 3e4,
50807
- host_liveness_recovery_nudge_ttl_ms: 1e4
50808
- }
50809
- }
50810
- }
50811
- },
50812
- external_inference: {
50813
- service: {
50814
- update_check_interval_ms: 3e5,
50815
- update_registry_timeout_ms: 15e3,
50816
- startup_max_attempts: 40,
50817
- startup_poll_interval_ms: 250,
50818
- restart_stable_uptime_ms: 6e4,
50819
- restart_backoff_base_ms: 1e3,
50820
- restart_backoff_max_ms: 3e4,
50821
- restart_exponent_max: 5
50822
- }
50823
- },
50824
- desktop: {
50825
- runtime_watchdog: {
50826
- ping_interval_milliseconds: 15e3,
50827
- telemetry_interval_milliseconds: 3e5
50828
- }
50829
- },
50830
- screener: {
50831
- resource_scheduler: {
50832
- client_lock_ttl_milliseconds: 12e4,
50833
- client_poll_interval_milliseconds: 250
50834
- }
50835
- },
50836
- deployment: {
50837
- cutover_buffer: {
50838
- target_timeout_ms: 3e3,
50839
- retired_timeout_ms: 45e3,
50840
- max_body_bytes: 33554432,
50841
- max_inflight: 16,
50842
- max_queue: 64
50843
- }
50844
- }
50845
- };
50846
- }
50847
- });
50848
-
50849
51265
  // lib/api/shared.ts
50850
51266
  function getProfileHeaders(baseHeaders = {}, explicitProfileId) {
50851
51267
  const headers = { ...baseHeaders };
@@ -50853,7 +51269,7 @@ function getProfileHeaders(baseHeaders = {}, explicitProfileId) {
50853
51269
  if (profileId) headers["x-profile-id"] = profileId.toString();
50854
51270
  return headers;
50855
51271
  }
50856
- 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;
51272
+ 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;
50857
51273
  var init_shared = __esm({
50858
51274
  "lib/api/shared.ts"() {
50859
51275
  "use strict";
@@ -50893,6 +51309,14 @@ var init_shared = __esm({
50893
51309
  sleep2 = (ms) => new Promise((resolve12) => setTimeout(resolve12, ms));
50894
51310
  AUTH_BOOTSTRAP_GET_MAX_ATTEMPTS = runtime_policy_generated_default2.ui.auth_bootstrap_retry.max_attempts;
50895
51311
  AUTH_BOOTSTRAP_RETRY_JITTER_MS = runtime_policy_generated_default2.ui.auth_bootstrap_retry.jitter_milliseconds;
51312
+ parseRetryAfterMs2 = (value) => {
51313
+ if (!value) return null;
51314
+ const seconds = Number(value);
51315
+ if (Number.isFinite(seconds) && seconds >= 0) return Math.round(seconds * 1e3);
51316
+ const retryAtMs = Date.parse(value);
51317
+ if (Number.isFinite(retryAtMs)) return Math.max(0, retryAtMs - Date.now());
51318
+ return null;
51319
+ };
50896
51320
  isTransientNetworkFetchError = (error48) => {
50897
51321
  const message = error48 instanceof Error ? error48.message : String(error48 || "");
50898
51322
  const normalized = message.toLowerCase();
@@ -50965,13 +51389,21 @@ async function getExecutionAssetMetadata(exchange, symbol2, options) {
50965
51389
  const response = await fetch(url2, {
50966
51390
  headers: getProfileHeaders({}, options?.profileId),
50967
51391
  credentials: "include",
50968
- cache: "no-store"
51392
+ cache: "no-store",
51393
+ signal: options?.signal
50969
51394
  });
50970
51395
  if (!response.ok) {
50971
- throw new Error(`Failed to fetch execution asset metadata: ${response.status} ${response.statusText}`);
51396
+ const summary = `Failed to fetch execution asset metadata: ${response.status} ${response.statusText}`;
51397
+ const detail = await getErrorMessageFromResponse(response, summary);
51398
+ throw new ExecutionAssetMetadataRequestError(
51399
+ detail === summary ? summary : `${summary}: ${detail}`,
51400
+ response.status,
51401
+ parseRetryAfterMs2(response.headers.get("Retry-After"))
51402
+ );
50972
51403
  }
50973
51404
  return response.json();
50974
51405
  }
51406
+ var ExecutionAssetMetadataRequestError;
50975
51407
  var init_market_data = __esm({
50976
51408
  "lib/api/market-data.ts"() {
50977
51409
  "use strict";
@@ -50981,6 +51413,14 @@ var init_market_data = __esm({
50981
51413
  init_abort();
50982
51414
  init_network_debug();
50983
51415
  init_shared();
51416
+ ExecutionAssetMetadataRequestError = class extends Error {
51417
+ constructor(message, status, retryAfterMs) {
51418
+ super(message);
51419
+ this.status = status;
51420
+ this.retryAfterMs = retryAfterMs;
51421
+ this.name = "ExecutionAssetMetadataRequestError";
51422
+ }
51423
+ };
50984
51424
  }
50985
51425
  });
50986
51426
 
@@ -52074,8 +52514,8 @@ var init_api2 = __esm({
52074
52514
  };
52075
52515
  CLIENT_EXCHANGE_AUTHORITY_DEVICE_KEY = "vtx_client_exchange_authority_device_v1";
52076
52516
  CLIENT_EXCHANGE_AUTHORITY_SESSION_KEY = "vtx_client_exchange_authority_session_v1";
52077
- getOrCreateClientExchangeAuthorityIdentity = (storage, key, label) => {
52078
- const existing = String(storage.getItem(key) || "").trim().toLowerCase();
52517
+ getOrCreateClientExchangeAuthorityIdentity = (storage2, key, label) => {
52518
+ const existing = String(storage2.getItem(key) || "").trim().toLowerCase();
52079
52519
  if (/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(existing)) {
52080
52520
  return existing;
52081
52521
  }
@@ -52083,7 +52523,7 @@ var init_api2 = __esm({
52083
52523
  if (!generated || !/^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/.test(generated)) {
52084
52524
  throw new Error(`Secure ${label} generation is unavailable.`);
52085
52525
  }
52086
- storage.setItem(key, generated);
52526
+ storage2.setItem(key, generated);
52087
52527
  return generated;
52088
52528
  };
52089
52529
  resolveClientExchangeMutationAuthority = (profileId, requiredRuntimeSessionId, explicitRuntimeLeaseToken, explicitRuntimeDeviceId, explicitSchedulerInstanceId) => {
@@ -53378,7 +53818,7 @@ function unpercent(value) {
53378
53818
  return String.fromCharCode(parseInt(code, 16));
53379
53819
  }));
53380
53820
  }
53381
- function wait(delay2) {
53821
+ function wait2(delay2) {
53382
53822
  return new Promise((resolve12) => setTimeout(resolve12, delay2));
53383
53823
  }
53384
53824
  var MAX_ATTEMPTS, SLOT_INTERVAL, defaultGetUrlFunc, reData, reIpfs, locked, Gateways, fetchSignals, FetchCancelSignal, FetchRequest, FetchResponse;
@@ -53741,7 +54181,7 @@ var init_fetch = __esm({
53741
54181
  request: _request
53742
54182
  });
53743
54183
  if (delay2 > 0) {
53744
- await wait(delay2);
54184
+ await wait2(delay2);
53745
54185
  }
53746
54186
  let req = this.clone();
53747
54187
  const scheme = (req.url.split(":")[0] || "").toLowerCase();
@@ -77356,9 +77796,9 @@ var init_provider_socket = __esm({
77356
77796
  */
77357
77797
  _register(filterId, subscriber) {
77358
77798
  this.#subs.set(filterId, subscriber);
77359
- const pending2 = this.#pending.get(filterId);
77360
- if (pending2) {
77361
- for (const message of pending2) {
77799
+ const pending3 = this.#pending.get(filterId);
77800
+ if (pending3) {
77801
+ for (const message of pending3) {
77362
77802
  subscriber._handleMessage(message);
77363
77803
  }
77364
77804
  this.#pending.delete(filterId);
@@ -77410,12 +77850,12 @@ var init_provider_socket = __esm({
77410
77850
  if (subscriber) {
77411
77851
  subscriber._handleMessage(result2.params.result);
77412
77852
  } else {
77413
- let pending2 = this.#pending.get(filterId);
77414
- if (pending2 == null) {
77415
- pending2 = [];
77416
- this.#pending.set(filterId, pending2);
77853
+ let pending3 = this.#pending.get(filterId);
77854
+ if (pending3 == null) {
77855
+ pending3 = [];
77856
+ this.#pending.set(filterId, pending3);
77417
77857
  }
77418
- pending2.push(result2.params.result);
77858
+ pending3.push(result2.params.result);
77419
77859
  }
77420
77860
  } else {
77421
77861
  this.emit("error", makeError("received unexpected message", "UNKNOWN_ERROR", {
@@ -82922,6 +83362,7 @@ var init_hyperliquid_client = __esm({
82922
83362
  init_define_VTX_EXO_POLICY();
82923
83363
  init_define_VTX_GROK_POLICY();
82924
83364
  init_define_VTX_PI_MODEL_POLICY();
83365
+ init_hyperliquid_public_read();
82925
83366
  init_api2();
82926
83367
  init_abort();
82927
83368
  init_hyperliquid_market_symbol();
@@ -83006,11 +83447,11 @@ var init_hyperliquid_client = __esm({
83006
83447
  return 0;
83007
83448
  }
83008
83449
  try {
83009
- const storage = window.localStorage;
83010
- if (!storage) {
83450
+ const storage2 = window.localStorage;
83451
+ if (!storage2) {
83011
83452
  return 0;
83012
83453
  }
83013
- const parsed = Number.parseInt(storage.getItem(HYPERLIQUID_NONCE_STORAGE_KEY) || "0", 10);
83454
+ const parsed = Number.parseInt(storage2.getItem(HYPERLIQUID_NONCE_STORAGE_KEY) || "0", 10);
83014
83455
  return Number.isFinite(parsed) && parsed > 0 ? parsed : 0;
83015
83456
  } catch {
83016
83457
  return 0;
@@ -83021,11 +83462,11 @@ var init_hyperliquid_client = __esm({
83021
83462
  return;
83022
83463
  }
83023
83464
  try {
83024
- const storage = window.localStorage;
83025
- if (!storage) {
83465
+ const storage2 = window.localStorage;
83466
+ if (!storage2) {
83026
83467
  return;
83027
83468
  }
83028
- storage.setItem(HYPERLIQUID_NONCE_STORAGE_KEY, String(nonce));
83469
+ storage2.setItem(HYPERLIQUID_NONCE_STORAGE_KEY, String(nonce));
83029
83470
  } catch {
83030
83471
  }
83031
83472
  };
@@ -83138,11 +83579,11 @@ var init_hyperliquid_client = __esm({
83138
83579
  };
83139
83580
  validateHyperliquidPerpPriceWire = (price, sizeDecimals) => {
83140
83581
  const normalized = normalizeDecimalString(price);
83141
- const numeric = Number(normalized);
83142
- if (!Number.isFinite(numeric) || numeric <= 0) {
83582
+ const numeric2 = Number(normalized);
83583
+ if (!Number.isFinite(numeric2) || numeric2 <= 0) {
83143
83584
  return { valid: false, reason: "price must be positive" };
83144
83585
  }
83145
- if (!Number.isInteger(numeric) && countSignificantDigits(normalized) > 5) {
83586
+ if (!Number.isInteger(numeric2) && countSignificantDigits(normalized) > 5) {
83146
83587
  return { valid: false, reason: "price exceeds 5 significant figures" };
83147
83588
  }
83148
83589
  const maxDecimals = Math.max(0, 6 - sizeDecimals);
@@ -83153,8 +83594,8 @@ var init_hyperliquid_client = __esm({
83153
83594
  };
83154
83595
  validateHyperliquidSizeWire = (size, sizeDecimals) => {
83155
83596
  const normalized = normalizeDecimalString(size);
83156
- const numeric = Number(normalized);
83157
- if (!Number.isFinite(numeric) || numeric <= 0) {
83597
+ const numeric2 = Number(normalized);
83598
+ if (!Number.isFinite(numeric2) || numeric2 <= 0) {
83158
83599
  return { valid: false, reason: "size must be positive" };
83159
83600
  }
83160
83601
  if (countDecimalPlaces(normalized) > sizeDecimals) {
@@ -83188,27 +83629,13 @@ var init_hyperliquid_client = __esm({
83188
83629
  method: "POST",
83189
83630
  url: requestUrl
83190
83631
  });
83191
- let response = null;
83192
83632
  try {
83193
- response = await fetch(requestUrl, {
83194
- method: "POST",
83195
- headers: {
83196
- "Content-Type": "application/json"
83197
- },
83198
- body: JSON.stringify(body),
83199
- signal: input.signal
83200
- });
83201
- const payload = await response.json().catch(() => ({}));
83202
- if (!response.ok) {
83203
- throw new Error(sanitizeRuntimeDiagnosticValue(
83204
- typeof payload?.response === "string" ? String(payload.response) : typeof payload?.detail === "string" ? String(payload.detail) : `Hyperliquid ${label} request failed.`
83205
- ));
83206
- }
83207
- trace.completeSuccess(response.status);
83633
+ const { payload } = await readHyperliquidPublicInfo(apiUrl, body, { signal: input.signal });
83634
+ trace.completeSuccess(200);
83208
83635
  return payload;
83209
83636
  } catch (error48) {
83210
83637
  const sanitizedError = toSanitizedRuntimeError(error48);
83211
- trace.completeError(sanitizedError, response?.status ?? null);
83638
+ trace.completeError(sanitizedError, error48?.status ?? null);
83212
83639
  throw sanitizedError;
83213
83640
  }
83214
83641
  };
@@ -83642,11 +84069,11 @@ var init_hyperliquid_client = __esm({
83642
84069
  ancestors: /* @__PURE__ */ new Set()
83643
84070
  }));
83644
84071
  while (pendingOrders.length > 0) {
83645
- const pending2 = pendingOrders.shift();
83646
- if (pending2 == null) {
84072
+ const pending3 = pendingOrders.shift();
84073
+ if (pending3 == null) {
83647
84074
  break;
83648
84075
  }
83649
- const { raw, inheritedCoin, depth, ancestors } = pending2;
84076
+ const { raw, inheritedCoin, depth, ancestors } = pending3;
83650
84077
  if (raw == null || typeof raw !== "object" || Array.isArray(raw)) {
83651
84078
  throw new Error("Malformed Hyperliquid frontendOpenOrders member.");
83652
84079
  }
@@ -84426,12 +84853,12 @@ var init_hyperliquid_client = __esm({
84426
84853
  };
84427
84854
  };
84428
84855
  loadClientExecutionReferenceEvidence = async (input, executionObservabilityDeadlineMs) => {
84429
- const policy = input.config?.client_runtime_execution_observability;
84430
- if (policy?.enabled !== true || policy.fresh_l2_fallback_enabled !== true || !input.durableMutation) {
84856
+ const policy2 = input.config?.client_runtime_execution_observability;
84857
+ if (policy2?.enabled !== true || policy2.fresh_l2_fallback_enabled !== true || !input.durableMutation) {
84431
84858
  return null;
84432
84859
  }
84433
- const timeoutMs = Number(policy.snapshot_timeout_ms);
84434
- const acceptableAgeMs = Number(policy.acceptable_snapshot_age_ms);
84860
+ const timeoutMs = Number(policy2.snapshot_timeout_ms);
84861
+ const acceptableAgeMs = Number(policy2.acceptable_snapshot_age_ms);
84435
84862
  if (!Number.isInteger(timeoutMs) || timeoutMs <= 0 || !Number.isInteger(acceptableAgeMs) || acceptableAgeMs < 0) {
84436
84863
  return { referenceSourceKind: "policy_unavailable" };
84437
84864
  }
@@ -84478,8 +84905,8 @@ var init_hyperliquid_client = __esm({
84478
84905
  return null;
84479
84906
  }
84480
84907
  const raw = value.px;
84481
- const numeric = Number(raw);
84482
- return Number.isFinite(numeric) && numeric > 0 ? String(raw) : null;
84908
+ const numeric2 = Number(raw);
84909
+ return Number.isFinite(numeric2) && numeric2 > 0 ? String(raw) : null;
84483
84910
  };
84484
84911
  const bid = levelPrice(bids[0]);
84485
84912
  const ask = levelPrice(asks[0]);
@@ -84981,11 +85408,11 @@ function normalizeProviderKeyCount(rawValue, fallback) {
84981
85408
  if (rawValue == null) {
84982
85409
  return fallback;
84983
85410
  }
84984
- const numeric = Number(rawValue);
84985
- if (!Number.isInteger(numeric) || numeric < 0) {
85411
+ const numeric2 = Number(rawValue);
85412
+ if (!Number.isInteger(numeric2) || numeric2 < 0) {
84986
85413
  return fallback;
84987
85414
  }
84988
- return numeric;
85415
+ return numeric2;
84989
85416
  }
84990
85417
  function projectClientRuntimeSecretMetadata(serverHasHyperliquidSigningKey, serverProviderKeys, serverProviderKeyCount) {
84991
85418
  const normalizedProviderKeys = normalizeProviderKeys(serverProviderKeys);
@@ -85121,7 +85548,7 @@ function validateDeviceSecrets(value, options) {
85121
85548
  return [provider, slots];
85122
85549
  }).filter(([, slots]) => slots.some(Boolean))
85123
85550
  );
85124
- const storage = normalizeDeviceSecretStorage(record5.storage);
85551
+ const storage2 = normalizeDeviceSecretStorage(record5.storage);
85125
85552
  const hyperliquidSigningKey = typeof record5.hyperliquidSigningKey === "string" ? record5.hyperliquidSigningKey.trim() || void 0 : void 0;
85126
85553
  const rawLocalAi = record5.localAi && typeof record5.localAi === "object" ? record5.localAi : {};
85127
85554
  const localAi = normalizeLocalAiSecrets({
@@ -85173,7 +85600,7 @@ function validateDeviceSecrets(value, options) {
85173
85600
  ...Object.keys(providerBaseUrlSlots).length > 0 ? { providerBaseUrlSlots } : {},
85174
85601
  ...localAi ? { localAi } : {},
85175
85602
  ...openaiCompatible ? { openaiCompatible } : {},
85176
- storage
85603
+ storage: storage2
85177
85604
  },
85178
85605
  activeProvider,
85179
85606
  hasHyperliquidSigningKey,
@@ -85423,8 +85850,8 @@ var init_vault = __esm({
85423
85850
  mergeHydratedSecrets = (existingLocalSecrets, remoteSecrets, options) => {
85424
85851
  const localNormalized = validateDeviceSecrets(existingLocalSecrets, options).normalized;
85425
85852
  const remoteNormalized = validateDeviceSecrets(remoteSecrets, options).normalized;
85426
- const storage = normalizeDeviceSecretStorage(localNormalized?.storage ?? remoteNormalized?.storage);
85427
- const mergedLocalAi = storage.byok === "device" ? normalizeLocalAiSecrets({
85853
+ const storage2 = normalizeDeviceSecretStorage(localNormalized?.storage ?? remoteNormalized?.storage);
85854
+ const mergedLocalAi = storage2.byok === "device" ? normalizeLocalAiSecrets({
85428
85855
  baseUrl: localNormalized?.localAi?.baseUrl,
85429
85856
  apiKey: localNormalized?.localAi?.apiKey,
85430
85857
  serverType: localNormalized?.localAi?.serverType
@@ -85433,7 +85860,7 @@ var init_vault = __esm({
85433
85860
  apiKey: remoteNormalized?.localAi?.apiKey ?? localNormalized?.localAi?.apiKey,
85434
85861
  serverType: localNormalized?.localAi?.serverType
85435
85862
  });
85436
- const mergedOpenAiCompatible = storage.byok === "device" ? normalizeOpenAiCompatibleSecrets({
85863
+ const mergedOpenAiCompatible = storage2.byok === "device" ? normalizeOpenAiCompatibleSecrets({
85437
85864
  baseUrl: localNormalized?.openaiCompatible?.baseUrl,
85438
85865
  apiKey: localNormalized?.openaiCompatible?.apiKey
85439
85866
  }) : normalizeOpenAiCompatibleSecrets({
@@ -85441,14 +85868,14 @@ var init_vault = __esm({
85441
85868
  apiKey: remoteNormalized?.openaiCompatible?.apiKey ?? localNormalized?.openaiCompatible?.apiKey
85442
85869
  });
85443
85870
  return validateDeviceSecrets({
85444
- hyperliquidSigningKey: storage.hyperliquid === "device" ? localNormalized?.hyperliquidSigningKey : remoteNormalized?.hyperliquidSigningKey,
85445
- providerKeys: storage.byok === "device" ? { ...localNormalized?.providerKeys ?? {} } : { ...remoteNormalized?.providerKeys ?? {} },
85446
- providerKeySlots: storage.byok === "device" ? { ...localNormalized?.providerKeySlots ?? {} } : { ...remoteNormalized?.providerKeySlots ?? {} },
85447
- providerBaseUrls: storage.byok === "device" ? { ...localNormalized?.providerBaseUrls ?? {} } : { ...remoteNormalized?.providerBaseUrls ?? {} },
85448
- providerBaseUrlSlots: storage.byok === "device" ? { ...localNormalized?.providerBaseUrlSlots ?? {} } : { ...remoteNormalized?.providerBaseUrlSlots ?? {} },
85871
+ hyperliquidSigningKey: storage2.hyperliquid === "device" ? localNormalized?.hyperliquidSigningKey : remoteNormalized?.hyperliquidSigningKey,
85872
+ providerKeys: storage2.byok === "device" ? { ...localNormalized?.providerKeys ?? {} } : { ...remoteNormalized?.providerKeys ?? {} },
85873
+ providerKeySlots: storage2.byok === "device" ? { ...localNormalized?.providerKeySlots ?? {} } : { ...remoteNormalized?.providerKeySlots ?? {} },
85874
+ providerBaseUrls: storage2.byok === "device" ? { ...localNormalized?.providerBaseUrls ?? {} } : { ...remoteNormalized?.providerBaseUrls ?? {} },
85875
+ providerBaseUrlSlots: storage2.byok === "device" ? { ...localNormalized?.providerBaseUrlSlots ?? {} } : { ...remoteNormalized?.providerBaseUrlSlots ?? {} },
85449
85876
  ...mergedLocalAi ? { localAi: mergedLocalAi } : {},
85450
85877
  ...mergedOpenAiCompatible ? { openaiCompatible: mergedOpenAiCompatible } : {},
85451
- storage
85878
+ storage: storage2
85452
85879
  }, options).normalized;
85453
85880
  };
85454
85881
  preserveDeviceOnlySecrets = (value, options) => {
@@ -85456,18 +85883,18 @@ var init_vault = __esm({
85456
85883
  if (!normalized) {
85457
85884
  return null;
85458
85885
  }
85459
- const storage = normalizeDeviceSecretStorage(normalized.storage);
85460
- const localAi = storage.byok === "device" ? normalizeLocalAiSecrets(normalized.localAi) : normalizeLocalAiSecrets({ apiKey: normalized.localAi?.apiKey, serverType: normalized.localAi?.serverType });
85461
- const openaiCompatible = storage.byok === "device" ? normalizeOpenAiCompatibleSecrets(normalized.openaiCompatible) : normalizeOpenAiCompatibleSecrets({ apiKey: normalized.openaiCompatible?.apiKey });
85886
+ const storage2 = normalizeDeviceSecretStorage(normalized.storage);
85887
+ const localAi = storage2.byok === "device" ? normalizeLocalAiSecrets(normalized.localAi) : normalizeLocalAiSecrets({ apiKey: normalized.localAi?.apiKey, serverType: normalized.localAi?.serverType });
85888
+ const openaiCompatible = storage2.byok === "device" ? normalizeOpenAiCompatibleSecrets(normalized.openaiCompatible) : normalizeOpenAiCompatibleSecrets({ apiKey: normalized.openaiCompatible?.apiKey });
85462
85889
  return validateDeviceSecrets({
85463
- hyperliquidSigningKey: storage.hyperliquid === "device" ? normalized.hyperliquidSigningKey : void 0,
85464
- providerKeys: storage.byok === "device" ? { ...normalized.providerKeys } : {},
85465
- providerKeySlots: storage.byok === "device" ? { ...normalized.providerKeySlots ?? {} } : {},
85466
- providerBaseUrls: storage.byok === "device" ? { ...normalized.providerBaseUrls ?? {} } : {},
85467
- providerBaseUrlSlots: storage.byok === "device" ? { ...normalized.providerBaseUrlSlots ?? {} } : {},
85890
+ hyperliquidSigningKey: storage2.hyperliquid === "device" ? normalized.hyperliquidSigningKey : void 0,
85891
+ providerKeys: storage2.byok === "device" ? { ...normalized.providerKeys } : {},
85892
+ providerKeySlots: storage2.byok === "device" ? { ...normalized.providerKeySlots ?? {} } : {},
85893
+ providerBaseUrls: storage2.byok === "device" ? { ...normalized.providerBaseUrls ?? {} } : {},
85894
+ providerBaseUrlSlots: storage2.byok === "device" ? { ...normalized.providerBaseUrlSlots ?? {} } : {},
85468
85895
  ...localAi ? { localAi } : {},
85469
85896
  ...openaiCompatible ? { openaiCompatible } : {},
85470
- storage
85897
+ storage: storage2
85471
85898
  }, options).normalized;
85472
85899
  };
85473
85900
  normalizeClientRuntimeSecretProvider = (value) => {
@@ -86440,9 +86867,9 @@ var init_runtime_execution = __esm({
86440
86867
  return null;
86441
86868
  }
86442
86869
  };
86443
- setClientRuntimeProtectionStorage = (storage) => {
86444
- if (clientRuntimeProtectionStorage === storage) return;
86445
- clientRuntimeProtectionStorage = storage;
86870
+ setClientRuntimeProtectionStorage = (storage2) => {
86871
+ if (clientRuntimeProtectionStorage === storage2) return;
86872
+ clientRuntimeProtectionStorage = storage2;
86446
86873
  trailingStopMemory.clear();
86447
86874
  protectiveGroupMemory.clear();
86448
86875
  protectiveGroupReadFailures.clear();
@@ -86453,10 +86880,10 @@ var init_runtime_execution = __esm({
86453
86880
  const key = trailingStopStorageKey(profileId, symbol2);
86454
86881
  const inMemory = trailingStopMemory.get(key);
86455
86882
  let raw = inMemory ?? [];
86456
- const storage = resolveClientRuntimeProtectionStorage();
86457
- if (inMemory === void 0 && storage) {
86883
+ const storage2 = resolveClientRuntimeProtectionStorage();
86884
+ if (inMemory === void 0 && storage2) {
86458
86885
  try {
86459
- const persisted = storage.getItem(key);
86886
+ const persisted = storage2.getItem(key);
86460
86887
  if (persisted !== null) {
86461
86888
  raw = JSON.parse(persisted);
86462
86889
  }
@@ -86490,20 +86917,20 @@ var init_runtime_execution = __esm({
86490
86917
  const key = trailingStopStorageKey(profileId, symbol2);
86491
86918
  if (records.length === 0) {
86492
86919
  trailingStopMemory.set(key, []);
86493
- const storage2 = resolveClientRuntimeProtectionStorage();
86494
- if (storage2) {
86920
+ const storage3 = resolveClientRuntimeProtectionStorage();
86921
+ if (storage3) {
86495
86922
  try {
86496
- storage2.removeItem(key);
86923
+ storage3.removeItem(key);
86497
86924
  } catch {
86498
86925
  }
86499
86926
  }
86500
86927
  return;
86501
86928
  }
86502
86929
  trailingStopMemory.set(key, records);
86503
- const storage = resolveClientRuntimeProtectionStorage();
86504
- if (storage) {
86930
+ const storage2 = resolveClientRuntimeProtectionStorage();
86931
+ if (storage2) {
86505
86932
  try {
86506
- storage.setItem(key, JSON.stringify(records));
86933
+ storage2.setItem(key, JSON.stringify(records));
86507
86934
  } catch {
86508
86935
  }
86509
86936
  }
@@ -86520,10 +86947,10 @@ var init_runtime_execution = __esm({
86520
86947
  const key = protectiveGroupStorageKey(profileId, symbol2);
86521
86948
  const inMemory = protectiveGroupMemory.get(key);
86522
86949
  let raw = inMemory ?? [];
86523
- const storage = resolveClientRuntimeProtectionStorage();
86524
- if (inMemory === void 0 && storage) {
86950
+ const storage2 = resolveClientRuntimeProtectionStorage();
86951
+ if (inMemory === void 0 && storage2) {
86525
86952
  try {
86526
- const persisted = storage.getItem(key);
86953
+ const persisted = storage2.getItem(key);
86527
86954
  if (persisted !== null) {
86528
86955
  raw = JSON.parse(persisted);
86529
86956
  }
@@ -86571,12 +86998,12 @@ var init_runtime_execution = __esm({
86571
86998
  protectiveGroupReadFailures.add(key);
86572
86999
  return [];
86573
87000
  }
86574
- const pending2 = replacementRecord;
86575
- const mutationId = String(pending2.mutationId ?? "").trim().toLowerCase();
86576
- const clientOrderId = String(pending2.clientOrderId ?? "").trim().toLowerCase();
86577
- const previousOrderId = Number(pending2.previousOrderId);
86578
- const replacementTriggerPrice = Number(pending2.triggerPrice);
86579
- const replacementSize = Number(pending2.size);
87001
+ const pending3 = replacementRecord;
87002
+ const mutationId = String(pending3.mutationId ?? "").trim().toLowerCase();
87003
+ const clientOrderId = String(pending3.clientOrderId ?? "").trim().toLowerCase();
87004
+ const previousOrderId = Number(pending3.previousOrderId);
87005
+ const replacementTriggerPrice = Number(pending3.triggerPrice);
87006
+ const replacementSize = Number(pending3.size);
86580
87007
  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) {
86581
87008
  protectiveGroupReadFailures.add(key);
86582
87009
  return [];
@@ -86606,10 +87033,10 @@ var init_runtime_execution = __esm({
86606
87033
  protectiveGroupReadFailures.add(key);
86607
87034
  return [];
86608
87035
  }
86609
- const pending2 = pendingRecord;
86610
- const stopLoss = pending2.stopLoss;
86611
- const takeProfit = pending2.takeProfit;
86612
- 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)) {
87036
+ const pending3 = pendingRecord;
87037
+ const stopLoss = pending3.stopLoss;
87038
+ const takeProfit = pending3.takeProfit;
87039
+ 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)) {
86613
87040
  protectiveGroupReadFailures.add(key);
86614
87041
  return [];
86615
87042
  }
@@ -86620,10 +87047,10 @@ var init_runtime_execution = __esm({
86620
87047
  return [];
86621
87048
  }
86622
87049
  pendingEntry = {
86623
- entryMutationId: pending2.entryMutationId,
86624
- entryClientOrderId: pending2.entryClientOrderId,
86625
- entrySide: pending2.entrySide,
86626
- requestedSize: Number(pending2.requestedSize),
87050
+ entryMutationId: pending3.entryMutationId,
87051
+ entryClientOrderId: pending3.entryClientOrderId,
87052
+ entrySide: pending3.entrySide,
87053
+ requestedSize: Number(pending3.requestedSize),
86627
87054
  stopLoss: {
86628
87055
  enabled: sl.enabled,
86629
87056
  mode: sl.mode,
@@ -86710,16 +87137,16 @@ var init_runtime_execution = __esm({
86710
87137
  };
86711
87138
  writeClientProtectiveGroups = (profileId, symbol2, groups) => {
86712
87139
  const key = protectiveGroupStorageKey(profileId, symbol2);
86713
- const storage = resolveClientRuntimeProtectionStorage();
86714
- if (!storage) {
87140
+ const storage2 = resolveClientRuntimeProtectionStorage();
87141
+ if (!storage2) {
86715
87142
  protectiveGroupMemory.delete(key);
86716
87143
  protectiveGroupReadFailures.add(key);
86717
87144
  return false;
86718
87145
  }
86719
87146
  try {
86720
87147
  if (groups.length === 0) {
86721
- storage.removeItem(key);
86722
- const removed = storage.getItem(key) === null;
87148
+ storage2.removeItem(key);
87149
+ const removed = storage2.getItem(key) === null;
86723
87150
  if (removed) {
86724
87151
  protectiveGroupMemory.set(key, []);
86725
87152
  protectiveGroupReadFailures.delete(key);
@@ -86727,8 +87154,8 @@ var init_runtime_execution = __esm({
86727
87154
  return removed;
86728
87155
  } else {
86729
87156
  const serialized = JSON.stringify(groups);
86730
- storage.setItem(key, serialized);
86731
- const persisted = storage.getItem(key) === serialized;
87157
+ storage2.setItem(key, serialized);
87158
+ const persisted = storage2.getItem(key) === serialized;
86732
87159
  if (persisted) {
86733
87160
  protectiveGroupMemory.set(key, groups);
86734
87161
  protectiveGroupReadFailures.delete(key);
@@ -86956,18 +87383,18 @@ var init_runtime_execution = __esm({
86956
87383
  throw createClientRuntimeWindowHandoffBeforePlanDispatchError(cleanup);
86957
87384
  };
86958
87385
  canPersistClientProtectiveGroups = (profileId, symbol2) => {
86959
- const storage = resolveClientRuntimeProtectionStorage();
86960
- if (!storage) return false;
87386
+ const storage2 = resolveClientRuntimeProtectionStorage();
87387
+ if (!storage2) return false;
86961
87388
  const probeKey = `${protectiveGroupStorageKey(profileId, symbol2)}:probe`;
86962
87389
  const probeValue = `${Date.now()}:${Math.random()}`;
86963
87390
  try {
86964
- storage.setItem(probeKey, probeValue);
86965
- const durable = storage.getItem(probeKey) === probeValue;
86966
- storage.removeItem(probeKey);
87391
+ storage2.setItem(probeKey, probeValue);
87392
+ const durable = storage2.getItem(probeKey) === probeValue;
87393
+ storage2.removeItem(probeKey);
86967
87394
  return durable;
86968
87395
  } catch {
86969
87396
  try {
86970
- storage.removeItem(probeKey);
87397
+ storage2.removeItem(probeKey);
86971
87398
  } catch {
86972
87399
  }
86973
87400
  return false;
@@ -91676,9 +92103,9 @@ var init_usage_contract = __esm({
91676
92103
  isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
91677
92104
  coerceOptionalRuntimeUsageCount = (value) => {
91678
92105
  if (value === null || value === void 0 || typeof value === "boolean") return null;
91679
- const numeric = Number(value);
91680
- if (!Number.isFinite(numeric) || numeric < 0 || numeric > MAX_RUNTIME_USAGE_COUNT) return null;
91681
- return Math.round(numeric);
92106
+ const numeric2 = Number(value);
92107
+ if (!Number.isFinite(numeric2) || numeric2 < 0 || numeric2 > MAX_RUNTIME_USAGE_COUNT) return null;
92108
+ return Math.round(numeric2);
91682
92109
  };
91683
92110
  readOptionalRuntimeUsageCount = (source, keys) => {
91684
92111
  for (const key of keys) {