@vtxmacro/cli 2026.8.59 → 2026.9.1

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
@@ -47,7 +47,7 @@ var init_agent_cli_release = __esm({
47
47
  "agent-cli-release.json"() {
48
48
  agent_cli_release_default = {
49
49
  package_name: "@vtxmacro/cli",
50
- package_version: "2026.8.59",
50
+ package_version: "2026.9.1",
51
51
  codex_package_name: "@openai/codex",
52
52
  codex_version: "0.147.0",
53
53
  copilot_sdk_package_name: "@github/copilot-sdk",
@@ -14827,6 +14827,7 @@ var init_external_inference_contract = __esm({
14827
14827
  authenticated_account_email: authenticatedAccountEmailSchema.nullable().optional(),
14828
14828
  authenticated_account_plan: safeCodeSchema.nullable().optional(),
14829
14829
  protocol_version: protocolVersionSchema,
14830
+ host_runtime_version: protocolVersionSchema.optional(),
14830
14831
  envelope_public_key: base64Url32BytesSchema,
14831
14832
  health: external_exports.enum(["healthy", "degraded", "draining"]),
14832
14833
  advertised_at: timestampSchema,
@@ -15500,6 +15501,7 @@ var init_external_inference_contract = __esm({
15500
15501
  outcome: adapterOutcomeEvidenceSchema,
15501
15502
  latency_ms: nonNegativeSafeIntegerSchema,
15502
15503
  time_to_first_token_ms: nonNegativeSafeIntegerSchema.nullable(),
15504
+ provider_dispatch_freshness_remaining_ms: nonNegativeSafeIntegerSchema.nullable().optional(),
15503
15505
  finish_reason: safeCodeSchema.nullable(),
15504
15506
  refusal_status: external_exports.enum(["none", "refused", "blocked", "unknown"]),
15505
15507
  completed_at: timestampSchema
@@ -15614,6 +15616,7 @@ var init_external_inference_contract = __esm({
15614
15616
  failure_category: safeCodeSchema,
15615
15617
  failure_code: safeCodeSchema,
15616
15618
  retryable: external_exports.boolean(),
15619
+ provider_dispatch_freshness_remaining_ms: nonNegativeSafeIntegerSchema.nullable().optional(),
15617
15620
  process_exit: codexProcessExitDiagnosticsSchema.nullable().optional(),
15618
15621
  membership_disposition: external_exports.enum([
15619
15622
  "retry_same_host",
@@ -18250,7 +18253,8 @@ var init_mcp_client = __esm({
18250
18253
  job_id: identifierSchema2,
18251
18254
  attempt_id: identifierSchema2,
18252
18255
  attempt_index: external_exports.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER),
18253
- state: safeCodeSchema2
18256
+ state: safeCodeSchema2,
18257
+ provider_dispatch_freshness_remaining_ms: external_exports.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER).nullable().optional()
18254
18258
  });
18255
18259
  agentConnectResultSchema = external_exports.strictObject({
18256
18260
  host: hostStatusReadSchema,
@@ -21267,6 +21271,15 @@ child.once('close', async (code, signal) => {
21267
21271
  retryable: false
21268
21272
  });
21269
21273
  }
21274
+ if (options.notAfterMs !== void 0 && Date.now() > options.notAfterMs) {
21275
+ throw new CodexAppServerError({
21276
+ message: "Server account context expired before provider dispatch.",
21277
+ category: "adapter",
21278
+ code: "server_account_context_expired_before_provider_dispatch",
21279
+ retryable: false,
21280
+ dispatchOutcome: "not_dispatched"
21281
+ });
21282
+ }
21270
21283
  return await new Promise((resolve6, reject) => {
21271
21284
  const pending = { resolve: resolve6, reject, timer: null, abortCleanup: null };
21272
21285
  pending.timer = setTimeout(() => {
@@ -22182,6 +22195,7 @@ child.once('close', async (code, signal) => {
22182
22195
  }, {
22183
22196
  timeoutMs: remaining(),
22184
22197
  signal: request.signal,
22198
+ notAfterMs: "providerDispatchNotAfterMs" in request ? request.providerDispatchNotAfterMs : void 0,
22185
22199
  beforeWrite: async (id2) => {
22186
22200
  requestId = id2;
22187
22201
  try {
@@ -22204,6 +22218,7 @@ child.once('close', async (code, signal) => {
22204
22218
  onWritten: (id2) => {
22205
22219
  requestWritten = true;
22206
22220
  requestId = id2;
22221
+ if ("onProviderDispatch" in request) request.onProviderDispatch?.();
22207
22222
  }
22208
22223
  });
22209
22224
  } catch (error48) {
@@ -22994,6 +23009,14 @@ var init_codex_adapter = __esm({
22994
23009
  retryable: false
22995
23010
  });
22996
23011
  }
23012
+ if (input.providerDispatchNotAfterMs !== void 0 && !Number.isSafeInteger(input.providerDispatchNotAfterMs)) {
23013
+ throw new CodexAppServerError({
23014
+ message: "Codex provider-dispatch freshness deadline is invalid.",
23015
+ category: "adapter",
23016
+ code: "server_provider_dispatch_fence_invalid",
23017
+ retryable: false
23018
+ });
23019
+ }
22997
23020
  if (!CODEX_MODEL_NAME_PATTERN.test(input.requestedModel) || !CODEX_REASONING_EFFORT_PATTERN.test(input.requestedReasoningEffort)) {
22998
23021
  throw new CodexAppServerError({
22999
23022
  message: "Codex model selection is not a valid catalog identity.",
@@ -23781,6 +23804,8 @@ var init_codex_adapter = __esm({
23781
23804
  requestedModel: input.requestedModel,
23782
23805
  requestedReasoningEffort: input.requestedReasoningEffort,
23783
23806
  deadlineAtMs: input.deadlineAtMs,
23807
+ providerDispatchNotAfterMs: input.providerDispatchNotAfterMs,
23808
+ onProviderDispatch: input.onProviderDispatch,
23784
23809
  signal: input.signal,
23785
23810
  onDispatchState: async (state) => {
23786
23811
  currentDispatchOutcome = state.dispatchOutcome;
@@ -23823,7 +23848,7 @@ var init_codex_adapter = __esm({
23823
23848
  }
23824
23849
  }
23825
23850
  if (error48 instanceof CodexAppServerError) {
23826
- const dispatchOutcome = error48.dispatchOutcome === "not_dispatched" ? currentDispatchOutcome : error48.dispatchOutcome;
23851
+ const dispatchOutcome = error48.code === "server_account_context_expired_before_provider_dispatch" ? "not_dispatched" : error48.dispatchOutcome === "not_dispatched" ? currentDispatchOutcome : error48.dispatchOutcome;
23827
23852
  if (baseCheckpoint && !completedResult) {
23828
23853
  latestCheckpoint = {
23829
23854
  ...baseCheckpoint,
@@ -24531,6 +24556,16 @@ ${input.outputSchemaJson}`
24531
24556
  void session?.abort().catch(() => void 0);
24532
24557
  };
24533
24558
  input.signal?.addEventListener("abort", onAbort, { once: true });
24559
+ if (input.providerDispatchNotAfterMs !== void 0 && Date.now() > input.providerDispatchNotAfterMs) {
24560
+ throw new CodexAppServerError({
24561
+ message: "Server account context expired before provider dispatch.",
24562
+ category: "adapter",
24563
+ code: "server_account_context_expired_before_provider_dispatch",
24564
+ retryable: false,
24565
+ dispatchOutcome: "not_dispatched"
24566
+ });
24567
+ }
24568
+ input.onProviderDispatch?.();
24534
24569
  dispatchEntered = true;
24535
24570
  let response;
24536
24571
  try {
@@ -25345,6 +25380,14 @@ var init_deepseek_harness_adapter = __esm({
25345
25380
  const blocks = [];
25346
25381
  let usage = null;
25347
25382
  let finish = null;
25383
+ if (input.providerDispatchNotAfterMs !== void 0 && Date.now() > input.providerDispatchNotAfterMs) {
25384
+ throw nonDispatchedError(
25385
+ "Server account context expired before provider dispatch.",
25386
+ "transport",
25387
+ "server_account_context_expired_before_provider_dispatch"
25388
+ );
25389
+ }
25390
+ input.onProviderDispatch?.();
25348
25391
  for await (const chunk of adapter.stream({
25349
25392
  provider: "deepseek-official",
25350
25393
  model: input.requestedModel,
@@ -32458,7 +32501,7 @@ function createDefaultInferenceHostRunnerDependencies(options) {
32458
32501
  envelopePublicKey: options.envelopePublicKey
32459
32502
  };
32460
32503
  }
32461
- var import_ajv, RUNTIME_RECEIPT_SCHEMA_VERSION, ATTEMPT_RECEIPT_SCHEMA_VERSION, 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, finitePositiveOption, validateRunnerOptions, assertLocalCredentialIdentity, retryableRemoteError, remoteRetryAfterMs, controlPlaneFatal, defaultValidateOutput, objectRecord, positiveUtf8ByteLimit, assertCompilableOutputSchema, parseOutputContract, membershipFailureDisposition, safeFailureCode, publicServerFailureCode, attemptStartRetryFallbackMs, exactJson2, runnerIdentityMismatch, assertAdvertisementResult, assertHostHeartbeatResult, assertClaimResult, assertStartResult, assertJobHeartbeatResult, assertTerminalResult, isDefinitiveCompletionEvidenceExpiry, classifyFailure, ambiguousHeartbeatTransport, reportedTokenUsage, reportedUsage, InferenceHostRunner, createInferenceAgentControlClient, INFERENCE_AGENT_SYSTEM_PROMPT, INFERENCE_AGENT_WAKE_SCHEMA, parseInferenceAgentWake, InferenceAgentRuntime;
32504
+ var import_ajv, RUNTIME_RECEIPT_SCHEMA_VERSION, ATTEMPT_RECEIPT_SCHEMA_VERSION, 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, 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_SYSTEM_PROMPT, INFERENCE_AGENT_WAKE_SCHEMA, parseInferenceAgentWake, InferenceAgentRuntime;
32462
32505
  var init_runner = __esm({
32463
32506
  "lib/inference-host/runner.ts"() {
32464
32507
  "use strict";
@@ -32815,7 +32858,7 @@ var init_runner = __esm({
32815
32858
  if (!options.displayName.trim() || options.displayName.length > 128) {
32816
32859
  throw new InferenceHostRunnerError("invalid_configuration", "Inference host display name is invalid.");
32817
32860
  }
32818
- if (!options.protocolVersion.trim() || !options.adapterRuntimeVersion.trim()) {
32861
+ if (!options.protocolVersion.trim() || !options.adapterRuntimeVersion.trim() || options.hostRuntimeVersion !== void 0 && !options.hostRuntimeVersion.trim()) {
32819
32862
  throw new InferenceHostRunnerError("invalid_configuration", "Inference host version metadata is required.");
32820
32863
  }
32821
32864
  const advertisementTtlMs = finitePositiveOption(
@@ -32836,6 +32879,7 @@ var init_runner = __esm({
32836
32879
  }
32837
32880
  return {
32838
32881
  adapterId,
32882
+ hostRuntimeVersion: options.hostRuntimeVersion ?? options.adapterRuntimeVersion,
32839
32883
  usageSource: options.usageSource ?? (adapterId === "codex" ? "codex_app_server" : adapterId),
32840
32884
  sameAttemptRecovery: options.sameAttemptRecovery ?? adapterId === "codex",
32841
32885
  agentRuntime: options.agentRuntime ?? null,
@@ -33023,10 +33067,37 @@ var init_runner = __esm({
33023
33067
  providerReasoningSummarySupported
33024
33068
  };
33025
33069
  };
33070
+ serverProviderDispatchNotAfterMs = (jobInput) => {
33071
+ if (jobInput.execution_mode !== "server") return void 0;
33072
+ let context;
33073
+ try {
33074
+ context = JSON.parse(jobInput.context_json);
33075
+ } catch {
33076
+ throw new InferenceHostRunnerError(
33077
+ "server_provider_dispatch_fence_invalid",
33078
+ "The Server provider-dispatch freshness fence is invalid."
33079
+ );
33080
+ }
33081
+ const contextObject = objectRecord(context);
33082
+ if (!contextObject || !("server_provider_dispatch_fence" in contextObject)) {
33083
+ return void 0;
33084
+ }
33085
+ const fence = objectRecord(contextObject.server_provider_dispatch_fence);
33086
+ const rawNotAfter = fence?.provider_dispatch_not_after;
33087
+ const notAfterMs = typeof rawNotAfter === "string" ? Date.parse(rawNotAfter) : NaN;
33088
+ if (!Number.isFinite(notAfterMs)) {
33089
+ throw new InferenceHostRunnerError(
33090
+ "server_provider_dispatch_fence_invalid",
33091
+ "The Server provider-dispatch freshness deadline is invalid."
33092
+ );
33093
+ }
33094
+ return notAfterMs;
33095
+ };
33026
33096
  membershipFailureDisposition = (failure) => {
33027
33097
  if (failure.dispatchOutcome === "outcome_unknown") return "quarantine_ambiguous";
33028
33098
  if (failure.category === "auth" || ["auth_expired", "managed_chatgpt_auth_required", "invalid_account_metadata"].includes(failure.code)) return "cascade_disable";
33029
33099
  if (failure.category === "quota" || ["quota_exceeded", "codex_rate_limited", "provider_rate_limited"].includes(failure.code)) return "cascade_cooldown";
33100
+ if (failure.code === "codex_server_overloaded") return "cascade_cooldown";
33030
33101
  if (failure.retryable && (["adapter", "network", "transport"].includes(failure.category) || failure.code === "rpc_timeout")) return "retry_same_host";
33031
33102
  if (["model_unavailable", "reasoning_effort_unavailable"].includes(failure.code)) return "cascade_cooldown";
33032
33103
  if ([
@@ -33534,6 +33605,7 @@ var init_runner = __esm({
33534
33605
  authenticated_account_email: this.options.authenticatedAccountEmail ?? null,
33535
33606
  authenticated_account_plan: this.options.authenticatedAccountPlan ?? null,
33536
33607
  protocol_version: this.options.protocolVersion,
33608
+ host_runtime_version: settings.hostRuntimeVersion,
33537
33609
  envelope_public_key: envelopePublicKey,
33538
33610
  health,
33539
33611
  advertised_at: isoAt(advertisedAt),
@@ -33724,13 +33796,14 @@ var init_runner = __esm({
33724
33796
  const heartbeatAttemptedAt = now();
33725
33797
  const attemptedAdvertisementGeneration = receipt.advertisement_generation;
33726
33798
  try {
33727
- const expiresAt = receipt.advertisement_expires_at ? Date.parse(receipt.advertisement_expires_at) : 0;
33728
- const refreshPendingAcrossExpiry = receipt.pending_advertisement !== null && expiresAt <= heartbeatAttemptedAt;
33729
33799
  await hostHeartbeat(
33730
33800
  "healthy",
33731
33801
  { signal: hostHeartbeatAbort.signal },
33732
33802
  false,
33733
- refreshPendingAcrossExpiry,
33803
+ // The server evaluates advertisement expiry when it receives
33804
+ // the heartbeat. A request sent just before expiry can therefore
33805
+ // truthfully return offline; the advertisement loop owns repair.
33806
+ true,
33734
33807
  0,
33735
33808
  attemptedAdvertisementGeneration
33736
33809
  );
@@ -33884,6 +33957,15 @@ var init_runner = __esm({
33884
33957
  active_attempts: active.size
33885
33958
  });
33886
33959
  },
33960
+ onProviderDispatch: (observation) => {
33961
+ emitDiagnostic("provider_dispatch_freshness_passed", {
33962
+ ...observation,
33963
+ job_id: claim.job_id,
33964
+ attempt_id: attemptId,
33965
+ requested_model: claim.requested_model,
33966
+ active_attempts: active.size
33967
+ });
33968
+ },
33887
33969
  startRetryCount: nextStartRetryCount,
33888
33970
  onAttemptStartRetry: (observation) => {
33889
33971
  attemptStartRetryCounts.set(attemptId, observation.retry_count);
@@ -34288,6 +34370,11 @@ var init_runner = __esm({
34288
34370
  credential.x25519_private_key,
34289
34371
  claim
34290
34372
  );
34373
+ const serverProviderDispatchDeadlineMs = serverProviderDispatchNotAfterMs(jobInput);
34374
+ let providerDispatchNotAfterMs = serverProviderDispatchDeadlineMs === void 0 ? void 0 : now() - 1;
34375
+ let serverReportedFreshnessRemainingMs = null;
34376
+ let startRoundTripMs = 0;
34377
+ let providerDispatchFreshnessRemainingMs = null;
34291
34378
  const startRequest = options.resumeReceipt?.start_request ?? buildAttemptStartRequest(claim, attemptId, isoAt(now()));
34292
34379
  let attemptReceipt = options.resumeReceipt ? validateAttemptReceipt(options.resumeReceipt) : {
34293
34380
  schema_version: ATTEMPT_RECEIPT_SCHEMA_VERSION,
@@ -34357,6 +34444,7 @@ var init_runner = __esm({
34357
34444
  return "failed";
34358
34445
  }
34359
34446
  let startResult;
34447
+ const startCallStartedAtMs = now();
34360
34448
  try {
34361
34449
  startResult = await retryExact(() => mcp.callTool(
34362
34450
  "inference.job.start",
@@ -34364,6 +34452,16 @@ var init_runner = __esm({
34364
34452
  { signal, deadlineAtMs: attemptDeadlineAtMs }
34365
34453
  ), { signal, deadlineAtMs: attemptDeadlineAtMs });
34366
34454
  } catch (error48) {
34455
+ if (error48 instanceof ExternalInferenceMcpError && error48.serverFailureCode === "server_account_context_expired_before_provider_dispatch") {
34456
+ await removeAttempt();
34457
+ options.onAttemptOutcome?.({
34458
+ outcome: "freshness_rejected_before_provider_dispatch",
34459
+ failure_category: "freshness",
34460
+ failure_code: error48.serverFailureCode,
34461
+ dispatch_outcome: "not_dispatched"
34462
+ });
34463
+ return "failed";
34464
+ }
34367
34465
  if (attemptDeadlineAtMs <= now() + MIN_CLAIM_START_WINDOW_MS) {
34368
34466
  await removeAttempt();
34369
34467
  return "failed";
@@ -34399,6 +34497,23 @@ var init_runner = __esm({
34399
34497
  return "retry_claimed";
34400
34498
  }
34401
34499
  assertStartResult(startRequest, startResult);
34500
+ if (serverProviderDispatchDeadlineMs !== void 0) {
34501
+ const serverRemaining = startResult.provider_dispatch_freshness_remaining_ms;
34502
+ if (!Number.isSafeInteger(serverRemaining) || Number(serverRemaining) < 0) {
34503
+ throw new InferenceHostRunnerError(
34504
+ "provider_dispatch_freshness_receipt_invalid",
34505
+ "The Server provider-dispatch freshness receipt is unavailable."
34506
+ );
34507
+ }
34508
+ const startCallCompletedAtMs = now();
34509
+ startRoundTripMs = Math.max(0, startCallCompletedAtMs - startCallStartedAtMs);
34510
+ serverReportedFreshnessRemainingMs = Number(serverRemaining);
34511
+ const conservativeRemainingMs = Math.max(
34512
+ 0,
34513
+ serverReportedFreshnessRemainingMs - startRoundTripMs
34514
+ );
34515
+ providerDispatchNotAfterMs = startCallCompletedAtMs + conservativeRemainingMs;
34516
+ }
34402
34517
  await updateAttempt({ phase: "started" });
34403
34518
  }
34404
34519
  let adapterResult;
@@ -34490,6 +34605,21 @@ var init_runner = __esm({
34490
34605
  requestedModel: jobInput.requested_model,
34491
34606
  requestedReasoningEffort: jobInput.requested_reasoning_effort,
34492
34607
  deadlineAtMs: Date.parse(jobInput.deadline_at),
34608
+ ...providerDispatchNotAfterMs === void 0 ? {} : { providerDispatchNotAfterMs },
34609
+ ...providerDispatchNotAfterMs === void 0 ? {} : {
34610
+ onProviderDispatch: () => {
34611
+ providerDispatchFreshnessRemainingMs = Math.max(
34612
+ 0,
34613
+ providerDispatchNotAfterMs - now()
34614
+ );
34615
+ options.onProviderDispatch?.({
34616
+ cycle_id: jobInput.runtime_binding?.cycle_id ?? "unavailable",
34617
+ freshness_remaining_ms: providerDispatchFreshnessRemainingMs,
34618
+ server_reported_remaining_ms: serverReportedFreshnessRemainingMs ?? 0,
34619
+ start_round_trip_ms: startRoundTripMs
34620
+ });
34621
+ }
34622
+ },
34493
34623
  signal: attemptAbort.signal
34494
34624
  });
34495
34625
  await updateAttempt({
@@ -34598,6 +34728,7 @@ var init_runner = __esm({
34598
34728
  },
34599
34729
  latency_ms: adapterResult.latencyMs,
34600
34730
  time_to_first_token_ms: adapterResult.timeToFirstTokenMs,
34731
+ provider_dispatch_freshness_remaining_ms: providerDispatchFreshnessRemainingMs,
34601
34732
  finish_reason: finishReason,
34602
34733
  refusal_status: refusalStatus,
34603
34734
  completed_at: isoAt(now())
@@ -34727,6 +34858,7 @@ var init_runner = __esm({
34727
34858
  failure_category: failure.category,
34728
34859
  failure_code: failure.code,
34729
34860
  retryable: failure.retryable,
34861
+ provider_dispatch_freshness_remaining_ms: providerDispatchFreshnessRemainingMs,
34730
34862
  ...processExit ? { process_exit: processExit } : {},
34731
34863
  membership_disposition: membershipFailureDisposition({
34732
34864
  ...failure,
@@ -37494,6 +37626,7 @@ Durable service:
37494
37626
  codexModelCapabilities: options.codexModelCapabilities,
37495
37627
  protocolVersion: EXTERNAL_INFERENCE_CONTRACT_VERSION,
37496
37628
  adapterRuntimeVersion: INFERENCE_HOST_CLI_VERSION,
37629
+ hostRuntimeVersion: INFERENCE_HOST_CLI_VERSION,
37497
37630
  maxConcurrency: options.maxConcurrency,
37498
37631
  once: options.once,
37499
37632
  emitDiagnosticEvent: options.emitDiagnosticEvent,
@@ -37549,6 +37682,7 @@ Durable service:
37549
37682
  codexModelCapabilities: options.preflight.modelCapabilities,
37550
37683
  protocolVersion: EXTERNAL_INFERENCE_CONTRACT_VERSION,
37551
37684
  adapterRuntimeVersion: options.preflight.runtimeVersion,
37685
+ hostRuntimeVersion: INFERENCE_HOST_CLI_VERSION,
37552
37686
  maxConcurrency: options.maxConcurrency,
37553
37687
  once: options.once,
37554
37688
  emitDiagnosticEvent: options.emitDiagnosticEvent,
@@ -43421,8 +43555,142 @@ var init_local_breadcrumbs = __esm({
43421
43555
  }
43422
43556
  });
43423
43557
 
43558
+ // lib/api/shared.ts
43559
+ function getProfileHeaders(baseHeaders = {}, explicitProfileId) {
43560
+ const headers = { ...baseHeaders };
43561
+ const profileId = explicitProfileId !== void 0 ? explicitProfileId : activeProfileId;
43562
+ if (profileId) headers["x-profile-id"] = profileId.toString();
43563
+ return headers;
43564
+ }
43565
+ var getApiUrl, API_URL, sleep2, isTransientNetworkFetchError, createIdempotencyKey, getErrorMessage, getErrorPayloadOrEmpty, getErrorPayloadOrFallbackDetail, getErrorMessageFromResponse, activeProfileId, PROFILE_STORAGE_KEY;
43566
+ var init_shared = __esm({
43567
+ "lib/api/shared.ts"() {
43568
+ "use strict";
43569
+ init_abort();
43570
+ getApiUrl = () => {
43571
+ if (typeof window === "undefined") {
43572
+ return process.env.API_URL_SERVER || process.env.NEXT_PUBLIC_API_URL || "http://api:8000";
43573
+ }
43574
+ if (process.env.NODE_ENV === "development") {
43575
+ const hostname3 = window.location.hostname;
43576
+ const isLocalNetworkIP = hostname3.startsWith("192.168.") || hostname3.startsWith("10.") || hostname3.startsWith("172.") && parseInt(hostname3.split(".")[1]) >= 16 && parseInt(hostname3.split(".")[1]) <= 31;
43577
+ if (isLocalNetworkIP) {
43578
+ return `http://${hostname3}:8000`;
43579
+ }
43580
+ if (hostname3 === "localhost" || hostname3 === "127.0.0.1") {
43581
+ return `http://${hostname3}:8000`;
43582
+ }
43583
+ }
43584
+ if (process.env.NEXT_PUBLIC_API_URL) {
43585
+ return process.env.NEXT_PUBLIC_API_URL;
43586
+ }
43587
+ try {
43588
+ const hostname3 = window.location.hostname;
43589
+ const protocol = window.location.protocol;
43590
+ const baseHost = hostname3.startsWith("www.") ? hostname3.slice(4) : hostname3;
43591
+ const apiHost = baseHost.startsWith("api.") ? baseHost : `api.${baseHost}`;
43592
+ return `${protocol}//${apiHost}`;
43593
+ } catch {
43594
+ return "http://localhost:8000";
43595
+ }
43596
+ };
43597
+ API_URL = getApiUrl();
43598
+ sleep2 = (ms) => new Promise((resolve6) => setTimeout(resolve6, ms));
43599
+ isTransientNetworkFetchError = (error48) => {
43600
+ const message = error48 instanceof Error ? error48.message : String(error48 || "");
43601
+ const normalized = message.toLowerCase();
43602
+ return message === "Failed to fetch" || message === "TypeError: Failed to fetch" || normalized.includes("network error") || normalized.includes("failed to fetch");
43603
+ };
43604
+ createIdempotencyKey = (action) => {
43605
+ const suffix = typeof crypto !== "undefined" && typeof crypto.randomUUID === "function" ? crypto.randomUUID() : `${Date.now()}-${Math.random().toString(16).slice(2)}`;
43606
+ return `web-${action}-${suffix}`;
43607
+ };
43608
+ getErrorMessage = (error48, defaultMessage) => {
43609
+ const extractRateLimitMessage = (raw) => {
43610
+ if (!/rate\s*limit|429|cooling\s*down/i.test(raw)) return null;
43611
+ const match = raw.match(/cooling\s*down\s*for\s*([0-9]+(?:\.[0-9]+)?)s/i);
43612
+ return match ? `Hyperliquid is rate-limited. Please retry in ~${match[1]}s.` : "Hyperliquid is rate-limited. Please wait a moment and retry.";
43613
+ };
43614
+ if (error48?.message === "Failed to fetch" || error48?.message === "TypeError: Failed to fetch" || error48?.message?.includes("network error")) {
43615
+ return "Network error. Please check your connection.";
43616
+ }
43617
+ const fromMessage = extractRateLimitMessage(String(error48?.message || ""));
43618
+ if (fromMessage) return fromMessage;
43619
+ if (error48?.detail) {
43620
+ const fromDetail = extractRateLimitMessage(String(error48.detail));
43621
+ if (fromDetail) return fromDetail;
43622
+ if (Array.isArray(error48.detail)) {
43623
+ return error48.detail.map((item) => `${item.loc ? item.loc.join(".") : "Field"}: ${item.msg}`).join(", ");
43624
+ }
43625
+ if (typeof error48.detail === "object") {
43626
+ const detailMessage = error48.detail.message;
43627
+ if (typeof detailMessage === "string" && detailMessage.trim()) return detailMessage;
43628
+ }
43629
+ return typeof error48.detail === "string" ? error48.detail : JSON.stringify(error48.detail);
43630
+ }
43631
+ return defaultMessage;
43632
+ };
43633
+ getErrorPayloadOrEmpty = async (response) => response.json().catch(() => ({}));
43634
+ getErrorPayloadOrFallbackDetail = async (response, fallbackDetail) => response.json().catch(() => ({ detail: fallbackDetail }));
43635
+ getErrorMessageFromResponse = async (response, defaultMessage, options) => {
43636
+ const error48 = options?.fallbackDetail ? await getErrorPayloadOrFallbackDetail(response, defaultMessage) : await getErrorPayloadOrEmpty(response);
43637
+ return getErrorMessage(error48, defaultMessage);
43638
+ };
43639
+ activeProfileId = null;
43640
+ PROFILE_STORAGE_KEY = "vtx_active_profile_id";
43641
+ if (typeof window !== "undefined") {
43642
+ const stored = sessionStorage.getItem(PROFILE_STORAGE_KEY);
43643
+ if (stored) {
43644
+ const parsed = parseInt(stored, 10);
43645
+ if (Number.isFinite(parsed) && parsed > 0) activeProfileId = parsed;
43646
+ }
43647
+ }
43648
+ }
43649
+ });
43650
+
43651
+ // lib/api/billing.ts
43652
+ var init_billing = __esm({
43653
+ "lib/api/billing.ts"() {
43654
+ "use strict";
43655
+ init_shared();
43656
+ }
43657
+ });
43658
+
43659
+ // lib/api/market-data.ts
43660
+ async function getExecutionAssetMetadata(exchange, symbol2, options) {
43661
+ const params = new URLSearchParams();
43662
+ if (options?.includePrivateContext) params.set("include_private_context", "true");
43663
+ const query = params.size > 0 ? `?${params.toString()}` : "";
43664
+ const url2 = `${API_URL}/trading/execution-metadata/${encodeURIComponent(exchange)}/${encodeURIComponent(symbol2)}${query}`;
43665
+ const response = await fetch(url2, {
43666
+ headers: getProfileHeaders({}, options?.profileId),
43667
+ credentials: "include",
43668
+ cache: "no-store"
43669
+ });
43670
+ if (!response.ok) {
43671
+ throw new Error(`Failed to fetch execution asset metadata: ${response.status} ${response.statusText}`);
43672
+ }
43673
+ return response.json();
43674
+ }
43675
+ var init_market_data = __esm({
43676
+ "lib/api/market-data.ts"() {
43677
+ "use strict";
43678
+ init_abort();
43679
+ init_network_debug();
43680
+ init_shared();
43681
+ }
43682
+ });
43683
+
43684
+ // lib/api/screener.ts
43685
+ var init_screener = __esm({
43686
+ "lib/api/screener.ts"() {
43687
+ "use strict";
43688
+ init_shared();
43689
+ }
43690
+ });
43691
+
43424
43692
  // lib/runtime/server-runtime-lease.ts
43425
- var CLIENT_RUNTIME_SERVER_LEASE_STORAGE_KEY, canUseStorage, normalizeProfileId, parseLeaseRecord, readPersistedLeaseMap, writePersistedLeaseMap, isLeaseExpired, getPersistedClientRuntimeServerLease, persistExistingClientRuntimeServerLease, persistClientRuntimeServerLease, clearPersistedClientRuntimeServerLease;
43693
+ var CLIENT_RUNTIME_SERVER_LEASE_STORAGE_KEY, canUseStorage, normalizeProfileId, normalizeLeaseGeneration, parseLeaseRecord, readPersistedLeaseMap, writePersistedLeaseMap, isLeaseExpired, getPersistedClientRuntimeServerLease, persistExistingClientRuntimeServerLease, persistClientRuntimeServerLease, clearPersistedClientRuntimeServerLease;
43426
43694
  var init_server_runtime_lease = __esm({
43427
43695
  "lib/runtime/server-runtime-lease.ts"() {
43428
43696
  "use strict";
@@ -43431,6 +43699,10 @@ var init_server_runtime_lease = __esm({
43431
43699
  normalizeProfileId = (profileId) => {
43432
43700
  return String(profileId ?? "").trim();
43433
43701
  };
43702
+ normalizeLeaseGeneration = (value) => {
43703
+ const generation = Number(value);
43704
+ return Number.isSafeInteger(generation) && generation > 0 ? generation : null;
43705
+ };
43434
43706
  parseLeaseRecord = (value, profileId) => {
43435
43707
  if (!value || typeof value !== "object" || Array.isArray(value)) {
43436
43708
  return null;
@@ -43475,8 +43747,10 @@ var init_server_runtime_lease = __esm({
43475
43747
  leaseId: String(record2.leaseId),
43476
43748
  runtimeSessionId: String(record2.runtimeSessionId),
43477
43749
  deviceId: String(record2.deviceId),
43750
+ schedulerInstanceId: String(record2.schedulerInstanceId ?? "").trim() || null,
43478
43751
  mode: record2.mode,
43479
43752
  scope: "trade-runtime",
43753
+ leaseGeneration: normalizeLeaseGeneration(record2.leaseGeneration),
43480
43754
  issuedAt: String(record2.issuedAt),
43481
43755
  expiresAt: String(record2.expiresAt),
43482
43756
  renewableUntil: String(record2.renewableUntil),
@@ -43579,8 +43853,10 @@ var init_server_runtime_lease = __esm({
43579
43853
  leaseId: String(lease.lease_id),
43580
43854
  runtimeSessionId: String(lease.runtime_session_id),
43581
43855
  deviceId: String(lease.device_id),
43856
+ schedulerInstanceId: String(lease.scheduler_instance_id ?? "").trim() || null,
43582
43857
  mode: lease.mode,
43583
43858
  scope: "trade-runtime",
43859
+ leaseGeneration: normalizeLeaseGeneration(lease.lease_generation),
43584
43860
  issuedAt: String(lease.issued_at),
43585
43861
  expiresAt: String(lease.expires_at),
43586
43862
  renewableUntil: String(lease.renewable_until),
@@ -43592,6 +43868,21 @@ var init_server_runtime_lease = __esm({
43592
43868
  savedAt: Date.now()
43593
43869
  };
43594
43870
  const leaseMap = readPersistedLeaseMap();
43871
+ const existingLease = leaseMap[profileId] ?? null;
43872
+ if (existingLease && record2.leaseId !== existingLease.leaseId) {
43873
+ const incomingGeneration = record2.leaseGeneration ?? null;
43874
+ const existingGeneration = existingLease.leaseGeneration ?? null;
43875
+ if (existingGeneration !== null && incomingGeneration === null || existingGeneration !== null && incomingGeneration !== null && incomingGeneration <= existingGeneration) {
43876
+ return existingLease;
43877
+ }
43878
+ if (existingGeneration === null && incomingGeneration === null) {
43879
+ const incomingIssuedAtMs = Date.parse(record2.issuedAt);
43880
+ const existingIssuedAtMs = Date.parse(existingLease.issuedAt);
43881
+ if (Number.isFinite(incomingIssuedAtMs) && Number.isFinite(existingIssuedAtMs) && incomingIssuedAtMs < existingIssuedAtMs) {
43882
+ return existingLease;
43883
+ }
43884
+ }
43885
+ }
43595
43886
  leaseMap[profileId] = record2;
43596
43887
  writePersistedLeaseMap(leaseMap);
43597
43888
  return record2;
@@ -43613,31 +43904,6 @@ var init_server_runtime_lease = __esm({
43613
43904
  });
43614
43905
 
43615
43906
  // lib/api.ts
43616
- async function getExecutionAssetMetadata(exchange, symbol2, options) {
43617
- const params = new URLSearchParams();
43618
- if (options?.includePrivateContext) {
43619
- params.set("include_private_context", "true");
43620
- }
43621
- const query = params.size > 0 ? `?${params.toString()}` : "";
43622
- const url2 = `${API_URL}/trading/execution-metadata/${encodeURIComponent(exchange)}/${encodeURIComponent(symbol2)}${query}`;
43623
- const response = await fetch(url2, {
43624
- headers: getProfileHeaders({}, options?.profileId),
43625
- credentials: "include",
43626
- cache: "no-store"
43627
- });
43628
- if (!response.ok) {
43629
- throw new Error(`Failed to fetch execution asset metadata: ${response.status} ${response.statusText}`);
43630
- }
43631
- return response.json();
43632
- }
43633
- function getProfileHeaders(baseHeaders = {}, explicitProfileId) {
43634
- const headers = { ...baseHeaders };
43635
- const pid = explicitProfileId !== void 0 ? explicitProfileId : _activeProfileId;
43636
- if (pid) {
43637
- headers["x-profile-id"] = pid.toString();
43638
- }
43639
- return headers;
43640
- }
43641
43907
  async function getClientRuntimeSecrets(profileId, options) {
43642
43908
  const params = new URLSearchParams();
43643
43909
  if (options?.activeProvider) {
@@ -43683,7 +43949,9 @@ async function postClientRuntime(path, profileId, body, options) {
43683
43949
  const signal = options?.signal;
43684
43950
  const parsedRequestTimeoutMs = Number(options?.requestTimeoutMs);
43685
43951
  const requestTimeoutMs = Number.isFinite(parsedRequestTimeoutMs) && parsedRequestTimeoutMs > 0 ? Math.round(parsedRequestTimeoutMs) : null;
43686
- const maxAttempts = keepalive ? 1 : 3;
43952
+ const parsedDeadlineAtMs = Number(options?.deadlineAtMs);
43953
+ const deadlineAtMs = path === "/runtime/decision" && Number.isFinite(parsedDeadlineAtMs) && parsedDeadlineAtMs > 0 ? Math.round(parsedDeadlineAtMs) : null;
43954
+ let maxAttempts = keepalive ? 1 : deadlineAtMs === null ? 3 : Math.max(3, Math.ceil(Math.max(0, deadlineAtMs - Date.now()) / 250) + 1);
43687
43955
  const requestContext = parseClientRuntimeRequestContext(body);
43688
43956
  const explicitIdempotencyKey = String(options?.idempotencyKey ?? "").trim();
43689
43957
  const idempotencyKey = shouldAttachRuntimeIdempotencyKey(path) ? explicitIdempotencyKey || createIdempotencyKey(`runtime-${path.replace(/\//g, "-")}`) : null;
@@ -43695,19 +43963,64 @@ async function postClientRuntime(path, profileId, body, options) {
43695
43963
  options?.runtimeLeaseToken,
43696
43964
  options?.omitRuntimeLeaseToken
43697
43965
  );
43966
+ const resolvedSchedulerInstanceId = String(
43967
+ options?.schedulerInstanceId ?? requestContext.schedulerInstanceId ?? ""
43968
+ ).trim() || null;
43969
+ const persistedRuntimeLease = getPersistedClientRuntimeServerLease(numericProfileId);
43970
+ if (resolvedRuntimeLeaseToken && persistedRuntimeLease?.schedulerInstanceId && !resolvedSchedulerInstanceId) {
43971
+ resolvedRuntimeLeaseToken = void 0;
43972
+ }
43698
43973
  attachRuntimeLeaseHeader(requestHeaders, resolvedRuntimeLeaseToken);
43974
+ attachRuntimeSchedulerInstanceHeader(
43975
+ requestHeaders,
43976
+ resolvedSchedulerInstanceId
43977
+ );
43699
43978
  if (idempotencyKey) {
43700
43979
  requestHeaders["X-Idempotency-Key"] = idempotencyKey;
43701
43980
  }
43702
43981
  let lastNetworkError = null;
43703
43982
  let missingRuntimeLeaseRecoveryAttempted = false;
43983
+ let replacementLeaseRetryUsed = false;
43984
+ const deadlineError = (attempt, cause) => annotateRuntimeRequestError(
43985
+ Object.assign(
43986
+ new Error("Client runtime decision persistence deadline exceeded after the AI run completed."),
43987
+ cause && (typeof cause === "object" || typeof cause === "function") ? { cause } : {}
43988
+ ),
43989
+ {
43990
+ path,
43991
+ method: "POST",
43992
+ attempt,
43993
+ maxAttempts: null,
43994
+ status: Number.isFinite(Number(cause?.status)) ? Number(cause.status) : null,
43995
+ keepalive,
43996
+ hadRuntimeLeaseToken: Boolean(resolvedRuntimeLeaseToken),
43997
+ deadlineAtMs,
43998
+ deadlineExceeded: true
43999
+ }
44000
+ );
44001
+ const waitBeforeRetry = async (delayMs, attempt, cause) => {
44002
+ if (deadlineAtMs === null) {
44003
+ await sleep2(delayMs);
44004
+ return;
44005
+ }
44006
+ const remainingMs = deadlineAtMs - Date.now();
44007
+ if (remainingMs <= delayMs) {
44008
+ throw deadlineError(attempt, cause);
44009
+ }
44010
+ await sleep2(delayMs);
44011
+ };
43704
44012
  for (let attempt = 1; attempt <= maxAttempts; attempt += 1) {
44013
+ const deadlineRemainingMs = deadlineAtMs === null ? null : deadlineAtMs - Date.now();
44014
+ if (deadlineRemainingMs !== null && deadlineRemainingMs <= 0) {
44015
+ throw deadlineError(Math.max(0, attempt - 1), lastNetworkError);
44016
+ }
43705
44017
  let response = null;
43706
44018
  let requestTimedOut = false;
43707
44019
  let timeoutId = null;
43708
44020
  let relayCallerAbort = null;
43709
44021
  let requestSignal = signal;
43710
- if (requestTimeoutMs !== null) {
44022
+ const attemptTimeoutMs = deadlineRemainingMs === null ? requestTimeoutMs : requestTimeoutMs === null ? deadlineRemainingMs : Math.min(requestTimeoutMs, deadlineRemainingMs);
44023
+ if (attemptTimeoutMs !== null) {
43711
44024
  const timeoutController = new AbortController();
43712
44025
  relayCallerAbort = () => timeoutController.abort(signal?.reason);
43713
44026
  if (signal?.aborted) {
@@ -43718,7 +44031,7 @@ async function postClientRuntime(path, profileId, body, options) {
43718
44031
  timeoutId = globalThis.setTimeout(() => {
43719
44032
  requestTimedOut = true;
43720
44033
  timeoutController.abort(new DOMException("Runtime request timeout reached.", "TimeoutError"));
43721
- }, requestTimeoutMs);
44034
+ }, Math.max(1, attemptTimeoutMs));
43722
44035
  requestSignal = timeoutController.signal;
43723
44036
  }
43724
44037
  const trace = startRuntimeNetworkDebugTrace({
@@ -43752,19 +44065,41 @@ async function postClientRuntime(path, profileId, body, options) {
43752
44065
  continue;
43753
44066
  }
43754
44067
  }
43755
- const shouldClearLease = Boolean(
44068
+ const leaseInvalidatingError = Boolean(
43756
44069
  resolvedRuntimeLeaseToken && shouldClearPersistedRuntimeLeaseOnError(response.status, error48.message)
43757
44070
  );
43758
- if (shouldClearLease) {
43759
- clearPersistedClientRuntimeServerLease(numericProfileId);
44071
+ let leaseCleared = false;
44072
+ if (leaseInvalidatingError) {
44073
+ const currentLease = getPersistedClientRuntimeServerLease(numericProfileId);
44074
+ const replacementLeaseToken = currentLease?.runtimeSessionId === requestContext.sessionId && currentLease.deviceId === requestContext.deviceId && currentLease.mode === (requestContext.mode ?? "trader") && currentLease.runtimeLeaseToken !== resolvedRuntimeLeaseToken ? currentLease.runtimeLeaseToken : null;
44075
+ if (replacementLeaseToken) {
44076
+ resolvedRuntimeLeaseToken = replacementLeaseToken;
44077
+ attachRuntimeLeaseHeader(requestHeaders, resolvedRuntimeLeaseToken);
44078
+ if (attempt >= maxAttempts && !replacementLeaseRetryUsed) {
44079
+ replacementLeaseRetryUsed = true;
44080
+ maxAttempts += 1;
44081
+ }
44082
+ if (attempt >= maxAttempts) {
44083
+ throw error48;
44084
+ }
44085
+ continue;
44086
+ }
44087
+ if (currentLease?.runtimeLeaseToken === resolvedRuntimeLeaseToken) {
44088
+ clearPersistedClientRuntimeServerLease(numericProfileId);
44089
+ leaseCleared = true;
44090
+ }
43760
44091
  }
43761
44092
  recordRuntimeAuthFailureBreadcrumb(path, numericProfileId, requestContext, response.status, error48.message, {
43762
44093
  keepalive,
43763
44094
  hadRuntimeLeaseToken: Boolean(resolvedRuntimeLeaseToken),
43764
- leaseCleared: shouldClearLease
44095
+ leaseCleared
43765
44096
  });
43766
- if (!keepalive && attempt < maxAttempts && !shouldClearLease && (shouldRetryClientRuntimeHttpStatus(path, response.status) || isRuntimeIdempotencyInProgressError(response.status, error48.message) || Boolean(idempotencyKey) && isRetryableRuntimeConflictError(response.status, error48))) {
43767
- await sleep2(resolveClientRuntimeRetryDelayMs(attempt, response.headers.get("Retry-After")));
44097
+ if (!keepalive && attempt < maxAttempts && !leaseInvalidatingError && (shouldRetryClientRuntimeHttpStatus(path, response.status) || isRuntimeIdempotencyInProgressError(response.status, error48.message) || Boolean(idempotencyKey) && isRetryableRuntimeConflictError(response.status, error48))) {
44098
+ await waitBeforeRetry(
44099
+ resolveClientRuntimeRetryDelayMs(attempt, response.headers.get("Retry-After")),
44100
+ attempt,
44101
+ error48
44102
+ );
43768
44103
  continue;
43769
44104
  }
43770
44105
  throw error48;
@@ -43781,18 +44116,26 @@ async function postClientRuntime(path, profileId, body, options) {
43781
44116
  const requestError = requestTimedOut && !signal?.aborted ? new TypeError("Runtime request timeout reached.") : error48;
43782
44117
  lastNetworkError = requestError;
43783
44118
  trace.completeError(requestError, response?.status ?? null);
44119
+ if (deadlineAtMs !== null && Date.now() >= deadlineAtMs) {
44120
+ throw deadlineError(attempt, requestError);
44121
+ }
43784
44122
  if (signal?.aborted || !requestTimedOut && !isTransientNetworkFetchError(requestError) || attempt >= maxAttempts) {
43785
44123
  throw annotateRuntimeRequestError(requestError, {
43786
44124
  path,
43787
44125
  method: "POST",
43788
44126
  attempt,
43789
- maxAttempts,
44127
+ maxAttempts: deadlineAtMs === null ? maxAttempts : null,
43790
44128
  status: response?.status ?? null,
43791
44129
  keepalive,
43792
- hadRuntimeLeaseToken: Boolean(resolvedRuntimeLeaseToken)
44130
+ hadRuntimeLeaseToken: Boolean(resolvedRuntimeLeaseToken),
44131
+ deadlineAtMs
43793
44132
  });
43794
44133
  }
43795
- await sleep2(resolveClientRuntimeRetryDelayMs(attempt, null));
44134
+ await waitBeforeRetry(
44135
+ resolveClientRuntimeRetryDelayMs(attempt, null),
44136
+ attempt,
44137
+ requestError
44138
+ );
43796
44139
  continue;
43797
44140
  } finally {
43798
44141
  if (timeoutId !== null) {
@@ -43808,20 +44151,22 @@ async function postClientRuntime(path, profileId, body, options) {
43808
44151
  path,
43809
44152
  method: "POST",
43810
44153
  attempt: maxAttempts,
43811
- maxAttempts,
44154
+ maxAttempts: deadlineAtMs === null ? maxAttempts : null,
43812
44155
  status: Number.isFinite(Number(lastNetworkError.status)) ? Number(lastNetworkError.status) : null,
43813
44156
  keepalive,
43814
- hadRuntimeLeaseToken: Boolean(resolvedRuntimeLeaseToken)
44157
+ hadRuntimeLeaseToken: Boolean(resolvedRuntimeLeaseToken),
44158
+ deadlineAtMs
43815
44159
  });
43816
44160
  }
43817
44161
  throw new Error("Client runtime request failed");
43818
44162
  }
43819
- async function beginClientRuntimeExchangeMutation(profileId, payload, requiredRuntimeSessionId, explicitRuntimeLeaseToken, explicitRuntimeDeviceId) {
44163
+ async function beginClientRuntimeExchangeMutation(profileId, payload, requiredRuntimeSessionId, explicitRuntimeLeaseToken, explicitRuntimeDeviceId, explicitSchedulerInstanceId) {
43820
44164
  const authority = resolveClientExchangeMutationAuthority(
43821
44165
  profileId,
43822
44166
  requiredRuntimeSessionId,
43823
44167
  explicitRuntimeLeaseToken,
43824
- explicitRuntimeDeviceId
44168
+ explicitRuntimeDeviceId,
44169
+ explicitSchedulerInstanceId
43825
44170
  );
43826
44171
  const requestBegin = () => postClientRuntime(
43827
44172
  "/runtime/exchange-mutations/begin",
@@ -43902,12 +44247,13 @@ async function beginClientRuntimeExchangeMutation(profileId, payload, requiredRu
43902
44247
  }
43903
44248
  return result2;
43904
44249
  }
43905
- async function reportClientRuntimeExchangeAttemptTransition(profileId, mutationId, payload, signal, requiredRuntimeSessionId, explicitRuntimeLeaseToken, explicitRuntimeDeviceId) {
44250
+ async function reportClientRuntimeExchangeAttemptTransition(profileId, mutationId, payload, signal, requiredRuntimeSessionId, explicitRuntimeLeaseToken, explicitRuntimeDeviceId, explicitSchedulerInstanceId) {
43906
44251
  const authority = resolveClientExchangeMutationAuthority(
43907
44252
  profileId,
43908
44253
  requiredRuntimeSessionId,
43909
44254
  explicitRuntimeLeaseToken,
43910
- explicitRuntimeDeviceId
44255
+ explicitRuntimeDeviceId,
44256
+ explicitSchedulerInstanceId
43911
44257
  );
43912
44258
  return postClientRuntime(
43913
44259
  `/runtime/exchange-mutations/${encodeURIComponent(mutationId)}/attempt`,
@@ -43923,12 +44269,13 @@ async function reportClientRuntimeExchangeAttemptTransition(profileId, mutationI
43923
44269
  }
43924
44270
  );
43925
44271
  }
43926
- async function settleClientRuntimeExchangeMutation(profileId, mutationId, payload, requiredRuntimeSessionId, explicitRuntimeLeaseToken, explicitRuntimeDeviceId) {
44272
+ async function settleClientRuntimeExchangeMutation(profileId, mutationId, payload, requiredRuntimeSessionId, explicitRuntimeLeaseToken, explicitRuntimeDeviceId, explicitSchedulerInstanceId) {
43927
44273
  const authority = resolveClientExchangeMutationAuthority(
43928
44274
  profileId,
43929
44275
  requiredRuntimeSessionId,
43930
44276
  explicitRuntimeLeaseToken,
43931
- explicitRuntimeDeviceId
44277
+ explicitRuntimeDeviceId,
44278
+ explicitSchedulerInstanceId
43932
44279
  );
43933
44280
  try {
43934
44281
  const result2 = await postClientRuntime(
@@ -44003,7 +44350,7 @@ async function reconcileActiveClientRuntimeExchangeMutation(profileId, requestOp
44003
44350
  }
44004
44351
  return rememberCompletedDeferredClientRuntimeStop(profileId, result2);
44005
44352
  }
44006
- var getApiUrl, API_URL, sleep2, isTransientNetworkFetchError, createIdempotencyKey, getErrorMessage, getErrorPayloadOrEmpty, getErrorPayloadOrFallbackDetail, getErrorMessageFromResponse, _activeProfileId, PROFILE_STORAGE_KEY, preferencesWriteQueue, CLIENT_SUPPORTED_PROMPT_CONTRACT_VERSION, completedDeferredClientRuntimeStops, rememberCompletedDeferredClientRuntimeStop, toNumericProfileId, shouldAttachRuntimeIdempotencyKey, attachRuntimeLeaseHeader, resolveRuntimeLeaseToken, persistRuntimeLeaseFromPayload, persistRuntimeLeaseStatusMetadata, shouldClearPersistedRuntimeLeaseOnError, isMissingRuntimeLeaseError, createRuntimeRequestError, parseClientRuntimeRequestContext, recordRuntimeAuthFailureBreadcrumb, classifyRuntimeRequestError, annotateRuntimeRequestError, parseRuntimeRetryAfterMs, shouldRecoverMissingRuntimeLease, recoverMissingRuntimeLease, isRetryableClientRuntimeStatus, shouldRetryClientRuntimeHttpStatus, isRuntimeIdempotencyInProgressError, isRetryableRuntimeConflictError, resolveClientRuntimeRetryDelayMs, CLIENT_EXCHANGE_AUTHORITY_DEVICE_KEY, CLIENT_EXCHANGE_AUTHORITY_SESSION_KEY, getOrCreateClientExchangeAuthorityIdentity, resolveClientExchangeMutationAuthority, clientExchangeMutationAuthorityBody, isPendingClientExchangeMutationError, clientExchangeMutationReconciliationTimers, MAX_CLIENT_EXCHANGE_RECONCILIATION_DELAY_MS, CLIENT_EXCHANGE_RECONCILIATION_CLOCK_SKEW_MS, ClientExchangeMutationRebuildRequiredError, isTerminalClientExchangeMutation, clientExchangeMutationReconciliationKey, clearScheduledClientExchangeMutationReconciliation, snapshotClientExchangeMutationReconciliationAuthority, postClientExchangeMutationReconciliation, scheduleClientExchangeMutationReconciliation;
44353
+ var preferencesWriteQueue, CLIENT_SUPPORTED_PROMPT_CONTRACT_VERSION, completedDeferredClientRuntimeStops, rememberCompletedDeferredClientRuntimeStop, toNumericProfileId, shouldAttachRuntimeIdempotencyKey, attachRuntimeLeaseHeader, attachRuntimeSchedulerInstanceHeader, resolveRuntimeLeaseToken, persistRuntimeLeaseFromPayload, persistRuntimeLeaseStatusMetadata, shouldClearPersistedRuntimeLeaseOnError, isMissingRuntimeLeaseError, createRuntimeRequestError, parseClientRuntimeRequestContext, recordRuntimeAuthFailureBreadcrumb, classifyRuntimeRequestError, annotateRuntimeRequestError, parseRuntimeRetryAfterMs, shouldRecoverMissingRuntimeLease, runtimeLeaseRecoveries, recoverMissingRuntimeLeaseDirect, recoverMissingRuntimeLease, isRetryableClientRuntimeStatus, shouldRetryClientRuntimeHttpStatus, isRuntimeIdempotencyInProgressError, isRetryableRuntimeConflictError, resolveClientRuntimeRetryDelayMs, CLIENT_EXCHANGE_AUTHORITY_DEVICE_KEY, CLIENT_EXCHANGE_AUTHORITY_SESSION_KEY, getOrCreateClientExchangeAuthorityIdentity, resolveClientExchangeMutationAuthority, clientExchangeMutationAuthorityBody, isPendingClientExchangeMutationError, clientExchangeMutationReconciliationTimers, MAX_CLIENT_EXCHANGE_RECONCILIATION_DELAY_MS, CLIENT_EXCHANGE_RECONCILIATION_CLOCK_SKEW_MS, ClientExchangeMutationRebuildRequiredError, isTerminalClientExchangeMutation, clientExchangeMutationReconciliationKey, clearScheduledClientExchangeMutationReconciliation, snapshotClientExchangeMutationReconciliationAuthority, postClientExchangeMutationReconciliation, scheduleClientExchangeMutationReconciliation;
44007
44354
  var init_api2 = __esm({
44008
44355
  "lib/api.ts"() {
44009
44356
  "use strict";
@@ -44019,99 +44366,12 @@ var init_api2 = __esm({
44019
44366
  init_network_debug();
44020
44367
  init_local_breadcrumbs();
44021
44368
  init_abort();
44369
+ init_shared();
44370
+ init_shared();
44371
+ init_billing();
44372
+ init_market_data();
44373
+ init_screener();
44022
44374
  init_server_runtime_lease();
44023
- getApiUrl = () => {
44024
- if (typeof window === "undefined") {
44025
- return process.env.API_URL_SERVER || process.env.NEXT_PUBLIC_API_URL || "http://api:8000";
44026
- }
44027
- if (process.env.NODE_ENV === "development") {
44028
- const hostname3 = window.location.hostname;
44029
- const isLocalNetworkIP = hostname3.startsWith("192.168.") || hostname3.startsWith("10.") || hostname3.startsWith("172.") && parseInt(hostname3.split(".")[1]) >= 16 && parseInt(hostname3.split(".")[1]) <= 31;
44030
- if (isLocalNetworkIP) {
44031
- return `http://${hostname3}:8000`;
44032
- }
44033
- if (hostname3 === "localhost" || hostname3 === "127.0.0.1") {
44034
- return `http://${hostname3}:8000`;
44035
- }
44036
- }
44037
- if (process.env.NEXT_PUBLIC_API_URL) {
44038
- return process.env.NEXT_PUBLIC_API_URL;
44039
- }
44040
- try {
44041
- const hostname3 = window.location.hostname;
44042
- const protocol = window.location.protocol;
44043
- const baseHost = hostname3.startsWith("www.") ? hostname3.slice(4) : hostname3;
44044
- const apiHost = baseHost.startsWith("api.") ? baseHost : `api.${baseHost}`;
44045
- return `${protocol}//${apiHost}`;
44046
- } catch {
44047
- return "http://localhost:8000";
44048
- }
44049
- };
44050
- API_URL = getApiUrl();
44051
- sleep2 = (ms) => new Promise((resolve6) => setTimeout(resolve6, ms));
44052
- isTransientNetworkFetchError = (error48) => {
44053
- const message = error48 instanceof Error ? error48.message : String(error48 || "");
44054
- const normalized = message.toLowerCase();
44055
- return message === "Failed to fetch" || message === "TypeError: Failed to fetch" || normalized.includes("network error") || normalized.includes("failed to fetch");
44056
- };
44057
- createIdempotencyKey = (action) => {
44058
- const suffix = typeof crypto !== "undefined" && typeof crypto.randomUUID === "function" ? crypto.randomUUID() : `${Date.now()}-${Math.random().toString(16).slice(2)}`;
44059
- return `web-${action}-${suffix}`;
44060
- };
44061
- getErrorMessage = (error48, defaultMessage) => {
44062
- const extractRateLimitMessage = (raw) => {
44063
- if (!/rate\s*limit|429|cooling\s*down/i.test(raw)) return null;
44064
- const cooldownMatch = raw.match(/cooling\s*down\s*for\s*([0-9]+(?:\.[0-9]+)?)s/i);
44065
- if (cooldownMatch) {
44066
- return `Hyperliquid is rate-limited. Please retry in ~${cooldownMatch[1]}s.`;
44067
- }
44068
- return "Hyperliquid is rate-limited. Please wait a moment and retry.";
44069
- };
44070
- if (error48?.message === "Failed to fetch" || error48?.message === "TypeError: Failed to fetch" || error48?.message?.includes("network error")) {
44071
- return "Network error. Please check your connection.";
44072
- }
44073
- const fromMessage = extractRateLimitMessage(String(error48?.message || ""));
44074
- if (fromMessage) return fromMessage;
44075
- if (error48?.detail) {
44076
- const fromDetail = extractRateLimitMessage(String(error48.detail));
44077
- if (fromDetail) return fromDetail;
44078
- if (Array.isArray(error48.detail)) {
44079
- return error48.detail.map((err) => {
44080
- const field = err.loc ? err.loc.join(".") : "Field";
44081
- return `${field}: ${err.msg}`;
44082
- }).join(", ");
44083
- }
44084
- if (typeof error48.detail === "object") {
44085
- const detailMessage = error48.detail.message;
44086
- if (typeof detailMessage === "string" && detailMessage.trim()) {
44087
- return detailMessage;
44088
- }
44089
- }
44090
- return typeof error48.detail === "string" ? error48.detail : JSON.stringify(error48.detail);
44091
- }
44092
- return defaultMessage;
44093
- };
44094
- getErrorPayloadOrEmpty = async (response) => {
44095
- return response.json().catch(() => ({}));
44096
- };
44097
- getErrorPayloadOrFallbackDetail = async (response, fallbackDetail) => {
44098
- return response.json().catch(() => ({ detail: fallbackDetail }));
44099
- };
44100
- getErrorMessageFromResponse = async (response, defaultMessage, options) => {
44101
- const error48 = options?.fallbackDetail ? await getErrorPayloadOrFallbackDetail(response, defaultMessage) : await getErrorPayloadOrEmpty(response);
44102
- return getErrorMessage(error48, defaultMessage);
44103
- };
44104
- _activeProfileId = null;
44105
- PROFILE_STORAGE_KEY = "vtx_active_profile_id";
44106
- if (typeof window !== "undefined") {
44107
- const stored = sessionStorage.getItem(PROFILE_STORAGE_KEY);
44108
- if (stored) {
44109
- const parsed = parseInt(stored, 10);
44110
- if (Number.isFinite(parsed) && parsed > 0) {
44111
- _activeProfileId = parsed;
44112
- }
44113
- }
44114
- }
44115
44375
  preferencesWriteQueue = Promise.resolve();
44116
44376
  CLIENT_SUPPORTED_PROMPT_CONTRACT_VERSION = String(
44117
44377
  process.env.NEXT_PUBLIC_CLIENT_RUNTIME_PROMPT_CONTRACT_VERSION || "2026-08-24.1"
@@ -44140,6 +44400,13 @@ var init_api2 = __esm({
44140
44400
  }
44141
44401
  requestHeaders["x-client-runtime-lease"] = normalized;
44142
44402
  };
44403
+ attachRuntimeSchedulerInstanceHeader = (requestHeaders, schedulerInstanceId) => {
44404
+ const normalized = String(schedulerInstanceId ?? "").trim();
44405
+ if (!normalized) {
44406
+ return;
44407
+ }
44408
+ requestHeaders["x-client-runtime-instance"] = normalized;
44409
+ };
44143
44410
  resolveRuntimeLeaseToken = (profileId, runtimeLeaseToken, omitRuntimeLeaseToken) => {
44144
44411
  if (omitRuntimeLeaseToken === true) {
44145
44412
  return void 0;
@@ -44229,11 +44496,13 @@ var init_api2 = __esm({
44229
44496
  const parsed = JSON.parse(body);
44230
44497
  const sessionId = typeof parsed.session_id === "string" && parsed.session_id.trim().length > 0 ? parsed.session_id.trim() : null;
44231
44498
  const deviceId = typeof parsed.device_id === "string" && parsed.device_id.trim().length > 0 ? parsed.device_id.trim() : null;
44499
+ const schedulerInstanceId = typeof parsed.scheduler_instance_id === "string" && parsed.scheduler_instance_id.trim().length > 0 ? parsed.scheduler_instance_id.trim() : null;
44232
44500
  const mode = parsed.mode === "assistant" ? "assistant" : parsed.mode === "trader" ? "trader" : null;
44233
44501
  const lastRunAt = typeof parsed.last_run_at === "string" && parsed.last_run_at.trim().length > 0 ? parsed.last_run_at.trim() : null;
44234
44502
  return {
44235
44503
  sessionId,
44236
44504
  deviceId,
44505
+ schedulerInstanceId,
44237
44506
  mode,
44238
44507
  lastRunAt
44239
44508
  };
@@ -44241,6 +44510,7 @@ var init_api2 = __esm({
44241
44510
  return {
44242
44511
  sessionId: null,
44243
44512
  deviceId: null,
44513
+ schedulerInstanceId: null,
44244
44514
  mode: null,
44245
44515
  lastRunAt: null
44246
44516
  };
@@ -44297,6 +44567,12 @@ var init_api2 = __esm({
44297
44567
  target.runtimeRequestTransientNetwork = isTransientNetworkFetchError(error48);
44298
44568
  target.runtimeRequestKeepalive = metadata.keepalive;
44299
44569
  target.runtimeRequestHadLeaseToken = metadata.hadRuntimeLeaseToken;
44570
+ if (metadata.deadlineAtMs !== void 0) {
44571
+ target.runtimeRequestDeadlineAtMs = metadata.deadlineAtMs;
44572
+ }
44573
+ if (metadata.deadlineExceeded !== void 0) {
44574
+ target.runtimeRequestDeadlineExceeded = metadata.deadlineExceeded;
44575
+ }
44300
44576
  return error48;
44301
44577
  };
44302
44578
  parseRuntimeRetryAfterMs = (value) => {
@@ -44322,7 +44598,8 @@ var init_api2 = __esm({
44322
44598
  }
44323
44599
  return path === "/runtime/heartbeat" || path === "/runtime/analyze" || path === "/runtime/prompt-contract/metadata" || path === "/runtime/prompt-contract/derived-context" || path === "/runtime/prompt" || path === "/runtime/decision" || path === "/runtime/error" || path === "/runtime/trade-sync";
44324
44600
  };
44325
- recoverMissingRuntimeLease = async (profileId, requestContext, signal) => {
44601
+ runtimeLeaseRecoveries = /* @__PURE__ */ new Map();
44602
+ recoverMissingRuntimeLeaseDirect = async (profileId, requestContext, signal) => {
44326
44603
  if (!requestContext.sessionId || !requestContext.deviceId) {
44327
44604
  return null;
44328
44605
  }
@@ -44330,6 +44607,7 @@ var init_api2 = __esm({
44330
44607
  "Content-Type": "application/json",
44331
44608
  "X-Idempotency-Key": createIdempotencyKey("runtime-lease-recovery")
44332
44609
  }, profileId);
44610
+ attachRuntimeSchedulerInstanceHeader(headers, requestContext.schedulerInstanceId);
44333
44611
  let payload;
44334
44612
  try {
44335
44613
  const response = await fetch(`${getApiUrl()}/trading/ai/runtime/session/start`, {
@@ -44341,6 +44619,7 @@ var init_api2 = __esm({
44341
44619
  body: JSON.stringify({
44342
44620
  session_id: requestContext.sessionId,
44343
44621
  device_id: requestContext.deviceId,
44622
+ ...requestContext.schedulerInstanceId ? { scheduler_instance_id: requestContext.schedulerInstanceId } : {},
44344
44623
  mode: requestContext.mode ?? null,
44345
44624
  last_run_at: requestContext.lastRunAt ?? null,
44346
44625
  force_takeover: false,
@@ -44357,14 +44636,100 @@ var init_api2 = __esm({
44357
44636
  }
44358
44637
  return null;
44359
44638
  }
44360
- persistRuntimeLeaseFromPayload(payload);
44639
+ const recoveredLease = payload?.lease;
44640
+ if (!recoveredLease || typeof recoveredLease !== "object" || Array.isArray(recoveredLease)) {
44641
+ return null;
44642
+ }
44643
+ const recoveredLeasePayload = recoveredLease;
44644
+ const expectedMode = requestContext.mode ?? "trader";
44645
+ const recoveredToken = String(recoveredLeasePayload.runtime_lease_token ?? "").trim();
44646
+ if (!recoveredToken || Number(recoveredLeasePayload.profile_id) !== profileId || String(recoveredLeasePayload.runtime_session_id ?? "").trim() !== requestContext.sessionId || String(recoveredLeasePayload.device_id ?? "").trim() !== requestContext.deviceId || String(recoveredLeasePayload.mode ?? "").trim().toLowerCase() !== expectedMode || requestContext.schedulerInstanceId != null && String(recoveredLeasePayload.scheduler_instance_id ?? "").trim() !== requestContext.schedulerInstanceId) {
44647
+ return null;
44648
+ }
44649
+ const currentLease = getPersistedClientRuntimeServerLease(profileId);
44650
+ if (currentLease && (currentLease.runtimeSessionId !== requestContext.sessionId || currentLease.deviceId !== requestContext.deviceId || currentLease.mode !== expectedMode || requestContext.schedulerInstanceId != null && currentLease.schedulerInstanceId !== requestContext.schedulerInstanceId)) {
44651
+ return null;
44652
+ }
44653
+ const selectedLease = persistClientRuntimeServerLease(
44654
+ recoveredLease
44655
+ );
44361
44656
  persistRuntimeLeaseStatusMetadata(profileId, payload);
44362
- const lease = getPersistedClientRuntimeServerLease(profileId);
44363
- if (lease?.runtimeSessionId === requestContext.sessionId && lease.deviceId === requestContext.deviceId && lease.runtimeLeaseToken) {
44364
- return lease.runtimeLeaseToken;
44657
+ if (selectedLease?.runtimeSessionId === requestContext.sessionId && selectedLease.deviceId === requestContext.deviceId && selectedLease.mode === expectedMode && (requestContext.schedulerInstanceId == null || selectedLease.schedulerInstanceId === requestContext.schedulerInstanceId) && selectedLease.runtimeLeaseToken) {
44658
+ return selectedLease.runtimeLeaseToken;
44365
44659
  }
44366
44660
  return null;
44367
44661
  };
44662
+ recoverMissingRuntimeLease = async (profileId, requestContext, signal) => {
44663
+ if (!requestContext.sessionId || !requestContext.deviceId) {
44664
+ return null;
44665
+ }
44666
+ const recoveryKey = JSON.stringify([
44667
+ profileId,
44668
+ requestContext.sessionId,
44669
+ requestContext.deviceId,
44670
+ requestContext.mode ?? "trader",
44671
+ requestContext.schedulerInstanceId
44672
+ ]);
44673
+ let recovery = runtimeLeaseRecoveries.get(recoveryKey);
44674
+ if (!recovery) {
44675
+ const controller = new AbortController();
44676
+ const created = {
44677
+ controller,
44678
+ promise: Promise.resolve(null),
44679
+ waiters: 0
44680
+ };
44681
+ created.promise = (async () => {
44682
+ try {
44683
+ return await recoverMissingRuntimeLeaseDirect(
44684
+ profileId,
44685
+ requestContext,
44686
+ controller.signal
44687
+ );
44688
+ } finally {
44689
+ if (runtimeLeaseRecoveries.get(recoveryKey) === created) {
44690
+ runtimeLeaseRecoveries.delete(recoveryKey);
44691
+ }
44692
+ }
44693
+ })();
44694
+ runtimeLeaseRecoveries.set(recoveryKey, created);
44695
+ recovery = created;
44696
+ }
44697
+ recovery.waiters += 1;
44698
+ try {
44699
+ if (!signal) {
44700
+ return await recovery.promise;
44701
+ }
44702
+ if (signal.aborted) {
44703
+ throw signal.reason ?? new DOMException("Runtime lease recovery aborted.", "AbortError");
44704
+ }
44705
+ return await new Promise((resolve6, reject) => {
44706
+ let settled = false;
44707
+ const finish = (callback) => {
44708
+ if (settled) {
44709
+ return;
44710
+ }
44711
+ settled = true;
44712
+ signal.removeEventListener("abort", onAbort);
44713
+ callback();
44714
+ };
44715
+ const onAbort = () => finish(() => reject(
44716
+ signal.reason ?? new DOMException("Runtime lease recovery aborted.", "AbortError")
44717
+ ));
44718
+ signal.addEventListener("abort", onAbort, { once: true });
44719
+ recovery.promise.then(
44720
+ (token) => finish(() => resolve6(token)),
44721
+ (error48) => finish(() => reject(error48))
44722
+ );
44723
+ });
44724
+ } finally {
44725
+ recovery.waiters = Math.max(0, recovery.waiters - 1);
44726
+ if (recovery.waiters === 0 && runtimeLeaseRecoveries.get(recoveryKey) === recovery && !recovery.controller.signal.aborted) {
44727
+ recovery.controller.abort(
44728
+ signal?.reason ?? new DOMException("Runtime lease recovery has no active waiters.", "AbortError")
44729
+ );
44730
+ }
44731
+ }
44732
+ };
44368
44733
  isRetryableClientRuntimeStatus = (status) => status === 408 || status === 429 || status === 500 || status === 502 || status === 503 || status === 504;
44369
44734
  shouldRetryClientRuntimeHttpStatus = (path, status) => {
44370
44735
  if (!isRetryableClientRuntimeStatus(status)) {
@@ -44376,7 +44741,7 @@ var init_api2 = __esm({
44376
44741
  return true;
44377
44742
  };
44378
44743
  isRuntimeIdempotencyInProgressError = (status, message) => status === 409 && (message.toLowerCase().includes("duplicate request already in progress") || message.toLowerCase().includes("duplicate request in-flight"));
44379
- isRetryableRuntimeConflictError = (status, error48) => status === 409 && error48.retryable === true && (error48.code === "profile_runtime_contract_busy" || error48.code === "runtime_trade_sync_finalizing");
44744
+ isRetryableRuntimeConflictError = (status, error48) => status === 409 && error48.retryable === true && (error48.code === "profile_runtime_contract_busy" || error48.code === "runtime_decision_finalizing" || error48.code === "runtime_trade_sync_finalizing");
44380
44745
  resolveClientRuntimeRetryDelayMs = (attempt, retryAfterHeader) => {
44381
44746
  const retryAfterMs = parseRuntimeRetryAfterMs(retryAfterHeader);
44382
44747
  if (retryAfterMs != null) {
@@ -44398,12 +44763,13 @@ var init_api2 = __esm({
44398
44763
  storage.setItem(key, generated);
44399
44764
  return generated;
44400
44765
  };
44401
- resolveClientExchangeMutationAuthority = (profileId, requiredRuntimeSessionId, explicitRuntimeLeaseToken, explicitRuntimeDeviceId) => {
44766
+ resolveClientExchangeMutationAuthority = (profileId, requiredRuntimeSessionId, explicitRuntimeLeaseToken, explicitRuntimeDeviceId, explicitSchedulerInstanceId) => {
44402
44767
  const numericProfileId = toNumericProfileId(profileId);
44403
44768
  const lease = getPersistedClientRuntimeServerLease(numericProfileId);
44404
44769
  const requiredSessionId = String(requiredRuntimeSessionId ?? "").trim();
44405
44770
  const explicitLeaseToken = String(explicitRuntimeLeaseToken ?? "").trim();
44406
44771
  const explicitDeviceId = String(explicitRuntimeDeviceId ?? "").trim();
44772
+ const schedulerInstanceId = String(explicitSchedulerInstanceId ?? "").trim();
44407
44773
  if (requiredSessionId && explicitLeaseToken && explicitDeviceId) {
44408
44774
  return {
44409
44775
  numericProfileId,
@@ -44411,18 +44777,20 @@ var init_api2 = __esm({
44411
44777
  deviceId: explicitDeviceId,
44412
44778
  mode: "trader",
44413
44779
  requestOptions: {
44414
- runtimeLeaseToken: explicitLeaseToken
44780
+ runtimeLeaseToken: explicitLeaseToken,
44781
+ schedulerInstanceId: schedulerInstanceId || void 0
44415
44782
  }
44416
44783
  };
44417
44784
  }
44418
- if (lease?.runtimeLeaseToken && lease.runtimeSessionId && lease.deviceId && lease.mode === "trader" && (!requiredSessionId || lease.runtimeSessionId === requiredSessionId)) {
44785
+ if (lease?.runtimeLeaseToken && lease.runtimeSessionId && lease.deviceId && lease.mode === "trader" && !lease.schedulerInstanceId && (!requiredSessionId || lease.runtimeSessionId === requiredSessionId)) {
44419
44786
  return {
44420
44787
  numericProfileId,
44421
44788
  sessionId: lease.runtimeSessionId,
44422
44789
  deviceId: lease.deviceId,
44423
44790
  mode: lease.mode,
44424
44791
  requestOptions: {
44425
- runtimeLeaseToken: lease.runtimeLeaseToken
44792
+ runtimeLeaseToken: lease.runtimeLeaseToken,
44793
+ schedulerInstanceId: schedulerInstanceId || void 0
44426
44794
  }
44427
44795
  };
44428
44796
  }
@@ -44454,11 +44822,15 @@ var init_api2 = __esm({
44454
44822
  }
44455
44823
  };
44456
44824
  };
44457
- clientExchangeMutationAuthorityBody = (authority) => ({
44458
- session_id: authority.sessionId,
44459
- device_id: authority.deviceId,
44460
- mode: authority.mode
44461
- });
44825
+ clientExchangeMutationAuthorityBody = (authority) => {
44826
+ const schedulerInstanceId = String(authority.requestOptions.schedulerInstanceId ?? "").trim();
44827
+ return {
44828
+ session_id: authority.sessionId,
44829
+ device_id: authority.deviceId,
44830
+ mode: authority.mode,
44831
+ ...schedulerInstanceId ? { scheduler_instance_id: schedulerInstanceId } : {}
44832
+ };
44833
+ };
44462
44834
  isPendingClientExchangeMutationError = (error48) => {
44463
44835
  const status = Number(error48?.status);
44464
44836
  const message = error48 instanceof Error ? error48.message : String(error48 ?? "");
@@ -44481,7 +44853,8 @@ var init_api2 = __esm({
44481
44853
  };
44482
44854
  snapshotClientExchangeMutationReconciliationAuthority = (requestOptions) => {
44483
44855
  const runtimeLeaseToken = String(requestOptions?.runtimeLeaseToken ?? "").trim();
44484
- return runtimeLeaseToken ? { runtimeLeaseToken } : { omitRuntimeLeaseToken: true };
44856
+ const schedulerInstanceId = String(requestOptions?.schedulerInstanceId ?? "").trim();
44857
+ return runtimeLeaseToken ? { runtimeLeaseToken, schedulerInstanceId: schedulerInstanceId || void 0 } : { omitRuntimeLeaseToken: true, schedulerInstanceId: schedulerInstanceId || void 0 };
44485
44858
  };
44486
44859
  postClientExchangeMutationReconciliation = async (profileId, mutationId, requestOptions) => {
44487
44860
  const result2 = await postClientRuntime(
@@ -54249,14 +54622,19 @@ var init_hyperliquid_client = __esm({
54249
54622
  const runtimeSessionId = String(durableMutation.requiredRuntimeSessionId ?? "").trim();
54250
54623
  const runtimeLeaseToken = String(durableMutation.runtimeLeaseToken ?? "").trim();
54251
54624
  const runtimeDeviceId = String(durableMutation.runtimeDeviceId ?? "").trim();
54252
- const presentCount = [runtimeSessionId, runtimeLeaseToken, runtimeDeviceId].filter(Boolean).length;
54253
- if (presentCount === 0) {
54625
+ const schedulerInstanceId = String(durableMutation.schedulerInstanceId ?? "").trim();
54626
+ const coreAuthority = [runtimeSessionId, runtimeLeaseToken, runtimeDeviceId];
54627
+ const corePresentCount = coreAuthority.filter(Boolean).length;
54628
+ if (corePresentCount === 0 && !schedulerInstanceId) {
54254
54629
  return [];
54255
54630
  }
54256
- if (presentCount !== 3) {
54631
+ if (corePresentCount !== 3) {
54257
54632
  throw new Error("Incomplete client runtime mutation authority.");
54258
54633
  }
54259
- return [runtimeSessionId, runtimeLeaseToken, runtimeDeviceId];
54634
+ if (!schedulerInstanceId) {
54635
+ return [runtimeSessionId, runtimeLeaseToken, runtimeDeviceId];
54636
+ }
54637
+ return [runtimeSessionId, runtimeLeaseToken, runtimeDeviceId, schedulerInstanceId];
54260
54638
  };
54261
54639
  assertFreshPreparedExecutionContext = (preparedContext) => {
54262
54640
  if (!preparedContext) {
@@ -57147,6 +57525,7 @@ var init_browser_trading = __esm({
57147
57525
  requiredRuntimeSessionId: input.runtimeSessionId,
57148
57526
  runtimeLeaseToken: input.runtimeLeaseToken,
57149
57527
  runtimeDeviceId: input.runtimeDeviceId,
57528
+ schedulerInstanceId: input.schedulerInstanceId,
57150
57529
  mutationId: mutation.mutationId,
57151
57530
  operationKind: "leverage",
57152
57531
  symbol: input.symbol
@@ -57185,6 +57564,7 @@ var init_browser_trading = __esm({
57185
57564
  requiredRuntimeSessionId: input.runtimeSessionId,
57186
57565
  runtimeLeaseToken: input.runtimeLeaseToken,
57187
57566
  runtimeDeviceId: input.runtimeDeviceId,
57567
+ schedulerInstanceId: input.schedulerInstanceId,
57188
57568
  mutationId: mutation.mutationId,
57189
57569
  operationKind: "order",
57190
57570
  symbol: input.symbol,
@@ -57221,6 +57601,7 @@ var init_browser_trading = __esm({
57221
57601
  requiredRuntimeSessionId: input.runtimeSessionId,
57222
57602
  runtimeLeaseToken: input.runtimeLeaseToken,
57223
57603
  runtimeDeviceId: input.runtimeDeviceId,
57604
+ schedulerInstanceId: input.schedulerInstanceId,
57224
57605
  mutationId: mutation.mutationId,
57225
57606
  operationKind: "order",
57226
57607
  symbol: input.symbol,
@@ -57251,6 +57632,7 @@ var init_browser_trading = __esm({
57251
57632
  requiredRuntimeSessionId: input.runtimeSessionId,
57252
57633
  runtimeLeaseToken: input.runtimeLeaseToken,
57253
57634
  runtimeDeviceId: input.runtimeDeviceId,
57635
+ schedulerInstanceId: input.schedulerInstanceId,
57254
57636
  mutationId: mutation.mutationId,
57255
57637
  operationKind: "order",
57256
57638
  symbol: input.symbol,
@@ -57291,6 +57673,7 @@ var init_browser_trading = __esm({
57291
57673
  requiredRuntimeSessionId: input.runtimeSessionId,
57292
57674
  runtimeLeaseToken: input.runtimeLeaseToken,
57293
57675
  runtimeDeviceId: input.runtimeDeviceId,
57676
+ schedulerInstanceId: input.schedulerInstanceId,
57294
57677
  mutationId: mutation.mutationId,
57295
57678
  operationKind: "order",
57296
57679
  symbol: input.symbol,
@@ -57320,6 +57703,7 @@ var init_browser_trading = __esm({
57320
57703
  requiredRuntimeSessionId: input.runtimeSessionId,
57321
57704
  runtimeLeaseToken: input.runtimeLeaseToken,
57322
57705
  runtimeDeviceId: input.runtimeDeviceId,
57706
+ schedulerInstanceId: input.schedulerInstanceId,
57323
57707
  mutationId: mutation.mutationId,
57324
57708
  operationKind: "cancel",
57325
57709
  symbol: input.symbol,
@@ -57349,6 +57733,7 @@ var init_browser_trading = __esm({
57349
57733
  runtimeSessionId: input.runtimeSessionId,
57350
57734
  runtimeLeaseToken: input.runtimeLeaseToken,
57351
57735
  runtimeDeviceId: input.runtimeDeviceId,
57736
+ schedulerInstanceId: input.schedulerInstanceId,
57352
57737
  walletAddress: input.walletAddress,
57353
57738
  config: input.config ?? null,
57354
57739
  signal: input.signal,
@@ -58610,6 +58995,7 @@ var init_runtime_execution = __esm({
58610
58995
  runtimeSessionId: request.sessionId || "__missing_runtime_session__",
58611
58996
  runtimeLeaseToken: request.runtimeLeaseToken,
58612
58997
  runtimeDeviceId: request.runtimeDeviceId,
58998
+ schedulerInstanceId: request.schedulerInstanceId,
58613
58999
  walletAddress: request.executionContext.walletAddress,
58614
59000
  config: request.config ?? null,
58615
59001
  signal: request.signal,
@@ -59005,6 +59391,7 @@ var init_runtime_execution = __esm({
59005
59391
  runtimeSessionId: request.sessionId || "__missing_runtime_session__",
59006
59392
  runtimeLeaseToken: request.runtimeLeaseToken,
59007
59393
  runtimeDeviceId: request.runtimeDeviceId,
59394
+ schedulerInstanceId: request.schedulerInstanceId,
59008
59395
  walletAddress: request.executionContext.walletAddress,
59009
59396
  config: request.config ?? null,
59010
59397
  signal: request.signal,
@@ -59037,6 +59424,7 @@ var init_runtime_execution = __esm({
59037
59424
  runtimeSessionId: request.sessionId || "__missing_runtime_session__",
59038
59425
  runtimeLeaseToken: request.runtimeLeaseToken,
59039
59426
  runtimeDeviceId: request.runtimeDeviceId,
59427
+ schedulerInstanceId: request.schedulerInstanceId,
59040
59428
  walletAddress: request.executionContext.walletAddress,
59041
59429
  config: request.config ?? null,
59042
59430
  signal: request.signal,
@@ -60042,6 +60430,7 @@ var init_runtime_execution = __esm({
60042
60430
  runtimeSessionId: request.sessionId || "__missing_runtime_session__",
60043
60431
  runtimeLeaseToken: request.runtimeLeaseToken,
60044
60432
  runtimeDeviceId: request.runtimeDeviceId,
60433
+ schedulerInstanceId: request.schedulerInstanceId,
60045
60434
  walletAddress: request.executionContext.walletAddress,
60046
60435
  config: request.config ?? null,
60047
60436
  signal: request.signal,
@@ -60740,6 +61129,7 @@ var init_runtime_execution = __esm({
60740
61129
  runtimeSessionId: request.sessionId || "__missing_runtime_session__",
60741
61130
  runtimeLeaseToken: request.runtimeLeaseToken,
60742
61131
  runtimeDeviceId: request.runtimeDeviceId,
61132
+ schedulerInstanceId: request.schedulerInstanceId,
60743
61133
  walletAddress: request.executionContext.walletAddress,
60744
61134
  config: request.config ?? null,
60745
61135
  signal: request.signal,
@@ -61179,6 +61569,7 @@ var init_runtime_execution = __esm({
61179
61569
  runtimeSessionId: request.sessionId || "__missing_runtime_session__",
61180
61570
  runtimeLeaseToken: request.runtimeLeaseToken,
61181
61571
  runtimeDeviceId: request.runtimeDeviceId,
61572
+ schedulerInstanceId: request.schedulerInstanceId,
61182
61573
  walletAddress: request.executionContext.walletAddress,
61183
61574
  config: request.config ?? null,
61184
61575
  signal: request.signal,
@@ -61705,6 +62096,7 @@ var init_runtime_execution = __esm({
61705
62096
  runtimeSessionId: input.sessionId || "__missing_runtime_session__",
61706
62097
  runtimeLeaseToken: input.runtimeLeaseToken,
61707
62098
  runtimeDeviceId: input.runtimeDeviceId,
62099
+ schedulerInstanceId: input.schedulerInstanceId,
61708
62100
  walletAddress: input.executionContext.walletAddress,
61709
62101
  config: input.config ?? null,
61710
62102
  signal: input.signal,
@@ -61722,6 +62114,7 @@ var init_runtime_execution = __esm({
61722
62114
  runtimeSessionId: input.sessionId || "__missing_runtime_session__",
61723
62115
  runtimeLeaseToken: input.runtimeLeaseToken,
61724
62116
  runtimeDeviceId: input.runtimeDeviceId,
62117
+ schedulerInstanceId: input.schedulerInstanceId,
61725
62118
  walletAddress: input.executionContext.walletAddress,
61726
62119
  config: input.config ?? null,
61727
62120
  signal: input.signal,
@@ -61793,6 +62186,7 @@ var init_runtime_execution = __esm({
61793
62186
  runtimeSessionId: input.sessionId || "__missing_runtime_session__",
61794
62187
  runtimeLeaseToken: input.runtimeLeaseToken,
61795
62188
  runtimeDeviceId: input.runtimeDeviceId,
62189
+ schedulerInstanceId: input.schedulerInstanceId,
61796
62190
  walletAddress: input.executionContext.walletAddress,
61797
62191
  config: input.config ?? null,
61798
62192
  signal: input.signal,
@@ -61911,6 +62305,7 @@ var init_runtime_execution = __esm({
61911
62305
  runtimeSessionId: input.sessionId || "__missing_runtime_session__",
61912
62306
  runtimeLeaseToken: input.runtimeLeaseToken,
61913
62307
  runtimeDeviceId: input.runtimeDeviceId,
62308
+ schedulerInstanceId: input.schedulerInstanceId,
61914
62309
  walletAddress: input.executionContext.walletAddress,
61915
62310
  config: input.config ?? null,
61916
62311
  signal: input.signal,
@@ -62069,6 +62464,7 @@ var init_runtime_execution = __esm({
62069
62464
  runtimeSessionId: input.sessionId || "__missing_runtime_session__",
62070
62465
  runtimeLeaseToken: input.runtimeLeaseToken,
62071
62466
  runtimeDeviceId: input.runtimeDeviceId,
62467
+ schedulerInstanceId: input.schedulerInstanceId,
62072
62468
  walletAddress: input.executionContext.walletAddress,
62073
62469
  config: input.config ?? null,
62074
62470
  signal: input.signal,
@@ -62392,6 +62788,7 @@ var init_runtime_execution = __esm({
62392
62788
  runtimeSessionId: input.sessionId || "__missing_runtime_session__",
62393
62789
  runtimeLeaseToken: input.runtimeLeaseToken,
62394
62790
  runtimeDeviceId: input.runtimeDeviceId,
62791
+ schedulerInstanceId: input.schedulerInstanceId,
62395
62792
  walletAddress: input.executionContext.walletAddress,
62396
62793
  config: input.config ?? null,
62397
62794
  signal: input.signal,