@vtxmacro/cli 2026.9.42 → 2026.9.44

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.
@@ -16,7 +16,7 @@ import { fileURLToPath } from "node:url";
16
16
  // agent-cli-release.json
17
17
  var agent_cli_release_default = {
18
18
  package_name: "@vtxmacro/cli",
19
- package_version: "2026.9.42",
19
+ package_version: "2026.9.44",
20
20
  codex_package_name: "@openai/codex",
21
21
  codex_version: "0.153.3",
22
22
  copilot_sdk_package_name: "@github/copilot-sdk",
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.42",
80
+ package_version: "2026.9.44",
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())
@@ -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
  }
@@ -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."
@@ -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,
@@ -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)) {
@@ -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;
@@ -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);
@@ -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,
@@ -47620,13 +47674,27 @@ async function runAndReportLocalWorkCycle(options, state, leaseToken, context) {
47620
47674
  ...buildRuntimePayload(state),
47621
47675
  last_run_at: lastRunAt
47622
47676
  };
47677
+ let decisionResponse = null;
47623
47678
  if (result2.decision) {
47624
- await options.client.reportRuntimeDecision(options.profileId, {
47679
+ decisionResponse = await options.client.reportRuntimeDecision(options.profileId, {
47625
47680
  ...basePayload,
47626
47681
  ...result2.decision
47627
47682
  }, leaseToken);
47628
47683
  }
47629
- const deferredTradeSync = result2.afterDecision ? await result2.afterDecision() : null;
47684
+ let deferredTradeSync = null;
47685
+ if (result2.afterDecision) {
47686
+ const runtime = objectOrNull2(objectOrNull2(decisionResponse)?.runtime);
47687
+ const decision = runtime?.last_decision;
47688
+ const units = runtime?.last_units;
47689
+ const requestedUnits = Number(result2.decision?.units);
47690
+ if (!result2.decision || !["BUY", "SELL", "HOLD"].includes(String(decision)) || decision !== result2.decision.decision || typeof units !== "number" || !Number.isSafeInteger(units) || units < 0 || !Number.isSafeInteger(requestedUnits) || units > requestedUnits || (decision === "HOLD" ? units !== 0 : units <= 0)) {
47691
+ throw new Error("Runtime decision acceptance is unavailable or inconsistent; execution skipped.");
47692
+ }
47693
+ deferredTradeSync = await result2.afterDecision({
47694
+ decision,
47695
+ units
47696
+ });
47697
+ }
47630
47698
  const tradeSync = deferredTradeSync ? { ...result2.tradeSync ?? {}, ...deferredTradeSync } : result2.tradeSync;
47631
47699
  if (tradeSync) {
47632
47700
  await options.client.reportRuntimeTradeSync(options.profileId, {
@@ -47979,17 +48047,17 @@ var init_hyperliquid_account_contract = __esm({
47979
48047
  init_define_VTX_PI_MODEL_POLICY();
47980
48048
  init_hyperliquid_account_mode_contract();
47981
48049
  toNumber = (value, fallback = 0) => {
47982
- const numeric = Number(value);
47983
- return Number.isFinite(numeric) ? numeric : fallback;
48050
+ const numeric2 = Number(value);
48051
+ return Number.isFinite(numeric2) ? numeric2 : fallback;
47984
48052
  };
47985
48053
  firstNumber = (values, fallback = 0) => {
47986
48054
  for (const value of values) {
47987
48055
  if (value == null || typeof value === "string" && value.trim() === "") {
47988
48056
  continue;
47989
48057
  }
47990
- const numeric = Number(value);
47991
- if (Number.isFinite(numeric)) {
47992
- return numeric;
48058
+ const numeric2 = Number(value);
48059
+ if (Number.isFinite(numeric2)) {
48060
+ return numeric2;
47993
48061
  }
47994
48062
  }
47995
48063
  return fallback;
@@ -48185,14 +48253,14 @@ var init_server_prompt_rescue_account_contract = __esm({
48185
48253
  init_hyperliquid_account_mode_contract();
48186
48254
  STABLE_SYMBOLS = /* @__PURE__ */ new Set(["USDC", "USD", "USDT"]);
48187
48255
  toNumber2 = (value, fallback = 0) => {
48188
- const numeric = Number(value);
48189
- return Number.isFinite(numeric) ? numeric : fallback;
48256
+ const numeric2 = Number(value);
48257
+ return Number.isFinite(numeric2) ? numeric2 : fallback;
48190
48258
  };
48191
48259
  firstNumber2 = (values, fallback = 0) => {
48192
48260
  for (const value of values) {
48193
48261
  if (value == null || value === "") continue;
48194
- const numeric = Number(value);
48195
- if (Number.isFinite(numeric)) return numeric;
48262
+ const numeric2 = Number(value);
48263
+ if (Number.isFinite(numeric2)) return numeric2;
48196
48264
  }
48197
48265
  return fallback;
48198
48266
  };
@@ -48400,6 +48468,52 @@ var init_server_prompt_rescue_account_contract = __esm({
48400
48468
  }
48401
48469
  });
48402
48470
 
48471
+ // lib/runtime/hyperliquid-fee-contract.ts
48472
+ var numeric, effectiveHyperliquidTakerRates;
48473
+ var init_hyperliquid_fee_contract = __esm({
48474
+ "lib/runtime/hyperliquid-fee-contract.ts"() {
48475
+ "use strict";
48476
+ init_define_VTX_EXO_POLICY();
48477
+ init_define_VTX_GROK_POLICY();
48478
+ init_define_VTX_PI_MODEL_POLICY();
48479
+ init_hyperliquid_market_symbol();
48480
+ numeric = (value) => {
48481
+ if (typeof value !== "number" && typeof value !== "string" || typeof value === "string" && !value.trim()) return null;
48482
+ const parsed = Number(value);
48483
+ return Number.isFinite(parsed) ? parsed : null;
48484
+ };
48485
+ effectiveHyperliquidTakerRates = (symbols, userFees, metaByDex, alignedByToken = {}) => {
48486
+ const base = numeric(userFees.userCrossRate);
48487
+ const discount = numeric(userFees.activeReferralDiscount);
48488
+ return Object.fromEntries([...new Set(symbols.map(normalizeHyperliquidMarketSymbol).filter(Boolean))].sort().map((symbol2) => {
48489
+ const unavailable = [symbol2, null];
48490
+ if (base == null || base < 0 || base >= 1 || discount == null || discount < 0 || discount > 1) return unavailable;
48491
+ const dex = getHyperliquidMarketDex(symbol2);
48492
+ const meta3 = metaByDex[dex];
48493
+ if (!meta3 || !Array.isArray(meta3.universe)) return unavailable;
48494
+ const matches = meta3.universe.filter((asset2) => {
48495
+ return asset2?.name === symbol2;
48496
+ });
48497
+ if (matches.length !== 1) return unavailable;
48498
+ const collateralToken = meta3.collateralToken;
48499
+ if (typeof collateralToken !== "number" || !Number.isInteger(collateralToken) || collateralToken < 0) return unavailable;
48500
+ const aligned = alignedByToken[String(collateralToken)] ?? (collateralToken === 0 ? false : void 0);
48501
+ if (typeof aligned !== "boolean") return unavailable;
48502
+ const asset = matches[0];
48503
+ const scale = dex ? numeric(asset.deployerFeeScale) : 0;
48504
+ const growthMode = dex ? asset.growthMode : "disabled";
48505
+ if (scale == null || scale < 0 || scale > 3 || !["enabled", "disabled", "blocked"].includes(growthMode)) return unavailable;
48506
+ if (growthMode === "enabled" && scale > 1) return unavailable;
48507
+ const multiplier = scale < 1 ? 1 + scale : 2 * scale;
48508
+ const deployerShare = scale < 1 ? scale / (1 + scale) : 0.5;
48509
+ const alignmentMultiplier = aligned ? (1 - deployerShare) * 0.8 + deployerShare : 1;
48510
+ const rate = base * (1 - discount) * multiplier * (growthMode === "enabled" ? 0.1 : 1) * alignmentMultiplier;
48511
+ return [symbol2, Number.isFinite(rate) && rate >= 0 && rate < 1 ? rate : null];
48512
+ }));
48513
+ };
48514
+ }
48515
+ });
48516
+
48403
48517
  // lib/runtime/abort.ts
48404
48518
  var ABORT_MESSAGE_TOKENS, readAbortLikeMessage, isAbortLikeError;
48405
48519
  var init_abort = __esm({
@@ -48983,6 +49097,7 @@ var init_hyperliquid_account_state_adapter = __esm({
48983
49097
  init_hyperliquid_active_asset_contract();
48984
49098
  init_hyperliquid_account_mode_contract();
48985
49099
  init_server_prompt_rescue_account_contract();
49100
+ init_hyperliquid_fee_contract();
48986
49101
  init_hyperliquid_market_symbol();
48987
49102
  init_network_debug();
48988
49103
  unsupportedUserActiveAssetCache = /* @__PURE__ */ new Set();
@@ -49043,24 +49158,24 @@ var init_hyperliquid_account_state_adapter = __esm({
49043
49158
  }
49044
49159
  };
49045
49160
  toPositiveFinite = (value, fallback = 0) => {
49046
- const numeric = Number(value);
49047
- if (!Number.isFinite(numeric) || numeric <= 0) {
49161
+ const numeric2 = Number(value);
49162
+ if (!Number.isFinite(numeric2) || numeric2 <= 0) {
49048
49163
  return fallback;
49049
49164
  }
49050
- return numeric;
49165
+ return numeric2;
49051
49166
  };
49052
49167
  toFinite = (value, fallback = 0) => {
49053
- const numeric = Number(value);
49054
- return Number.isFinite(numeric) ? numeric : fallback;
49168
+ const numeric2 = Number(value);
49169
+ return Number.isFinite(numeric2) ? numeric2 : fallback;
49055
49170
  };
49056
49171
  firstFiniteNumber = (values, fallback = 0) => {
49057
49172
  for (const value of values) {
49058
49173
  if (value == null || typeof value === "string" && value.trim() === "") {
49059
49174
  continue;
49060
49175
  }
49061
- const numeric = Number(value);
49062
- if (Number.isFinite(numeric)) {
49063
- return numeric;
49176
+ const numeric2 = Number(value);
49177
+ if (Number.isFinite(numeric2)) {
49178
+ return numeric2;
49064
49179
  }
49065
49180
  }
49066
49181
  return fallback;
@@ -49098,7 +49213,7 @@ var init_hyperliquid_account_state_adapter = __esm({
49098
49213
  buildUserFillsStorageKey = (cacheKey) => {
49099
49214
  return `${USER_FILLS_CACHE_STORAGE_PREFIX}${cacheKey}`;
49100
49215
  };
49101
- buildAccountStateCacheKey = (apiUrl, walletAddress, symbol2, aggregatePerpDexs, scopeAccountSummaryToSelectedDex, dexNames, includeEffectiveTakerRate, includeExactAccountMode, includeActiveAssetData) => {
49216
+ buildAccountStateCacheKey = (apiUrl, walletAddress, symbol2, aggregatePerpDexs, scopeAccountSummaryToSelectedDex, dexNames, includeEffectiveTakerRate, includeExactAccountMode, includeActiveAssetData, feeSymbols) => {
49102
49217
  return [
49103
49218
  apiUrl.replace(/\/$/, "").toLowerCase(),
49104
49219
  walletAddress.trim().toLowerCase(),
@@ -49108,7 +49223,9 @@ var init_hyperliquid_account_state_adapter = __esm({
49108
49223
  includeEffectiveTakerRate ? "with-effective-taker-rate" : "without-effective-taker-rate",
49109
49224
  includeExactAccountMode ? "with-exact-account-mode" : "without-exact-account-mode",
49110
49225
  includeActiveAssetData ? "with-active-asset" : "without-active-asset",
49111
- ...dexNames.map(normalizePerpDexName).sort()
49226
+ ...dexNames.map(normalizePerpDexName).sort(),
49227
+ "fee-symbols",
49228
+ ...feeSymbols
49112
49229
  ].join("::");
49113
49230
  };
49114
49231
  buildAccountStateStorageKey = (cacheKey) => {
@@ -49202,11 +49319,11 @@ var init_hyperliquid_account_state_adapter = __esm({
49202
49319
  writeInfoRateLimitCooldown(apiUrl, requestType, staleIf429MaxAgeMs, nowMs);
49203
49320
  };
49204
49321
  requireNonNegativeConfigSeconds = (value, path) => {
49205
- const numeric = Number(value);
49206
- if (!Number.isFinite(numeric) || numeric < 0) {
49322
+ const numeric2 = Number(value);
49323
+ if (!Number.isFinite(numeric2) || numeric2 < 0) {
49207
49324
  throw new Error(`Missing required client runtime config: ${path}`);
49208
49325
  }
49209
- return numeric;
49326
+ return numeric2;
49210
49327
  };
49211
49328
  requireAccountStateCacheConfig = (config2) => {
49212
49329
  const readCacheConfig = config2.client_runtime_hyperliquid_read_cache;
@@ -49319,6 +49436,7 @@ var init_hyperliquid_account_state_adapter = __esm({
49319
49436
  availableToTrade: { ...result2.availableToTrade },
49320
49437
  positions: result2.positions.map((position) => ({ ...position })),
49321
49438
  ...result2.takerRate == null ? {} : { takerRate: result2.takerRate },
49439
+ ...result2.effectiveTakerRates == null ? {} : { effectiveTakerRates: { ...result2.effectiveTakerRates } },
49322
49440
  ...result2.promptRescueEvidence == null ? {} : { promptRescueEvidence: { ...result2.promptRescueEvidence } }
49323
49441
  });
49324
49442
  withAccountStateEvidence = (result2, source, fetchedAtMs, freshnessLimitMs) => {
@@ -49363,6 +49481,7 @@ var init_hyperliquid_account_state_adapter = __esm({
49363
49481
  availableToTrade: { ...result2.availableToTrade || {} },
49364
49482
  positions: Array.isArray(result2.positions) ? result2.positions.filter((position) => position !== null && typeof position === "object" && !Array.isArray(position)).map((position) => ({ ...position })) : [],
49365
49483
  ...result2.takerRate == null ? {} : { takerRate: Number(result2.takerRate) },
49484
+ ...result2.effectiveTakerRates == null ? {} : { effectiveTakerRates: { ...result2.effectiveTakerRates } },
49366
49485
  ...result2.promptRescueEvidence == null ? {} : { promptRescueEvidence: { ...result2.promptRescueEvidence } }
49367
49486
  }
49368
49487
  };
@@ -49821,7 +49940,8 @@ var init_hyperliquid_account_state_adapter = __esm({
49821
49940
  dexNames,
49822
49941
  includeEffectiveTakerRate,
49823
49942
  includeExactAccountMode,
49824
- includeActiveAssetData
49943
+ includeActiveAssetData,
49944
+ [...new Set((input.feeSymbols ?? [symbol2]).map(normalizeHyperliquidMarketSymbol).filter(Boolean))].sort()
49825
49945
  );
49826
49946
  const now = Date.now();
49827
49947
  const cached2 = readBrowserAccountStateCache(cacheKey);
@@ -49974,7 +50094,10 @@ var init_hyperliquid_account_state_adapter = __esm({
49974
50094
  apiUrl,
49975
50095
  { type: "userFees", user: walletAddress },
49976
50096
  input.signal
49977
- ),
50097
+ ).catch((error48) => {
50098
+ if (input.signal?.aborted) throw error48;
50099
+ return null;
50100
+ }),
49978
50101
  capturedAt: (/* @__PURE__ */ new Date()).toISOString()
49979
50102
  }))() : Promise.resolve(null);
49980
50103
  const exactAccountModePromise = input.includeExactAccountMode === true ? (async () => {
@@ -50019,18 +50142,30 @@ var init_hyperliquid_account_state_adapter = __esm({
50019
50142
  }
50020
50143
  let takerRate;
50021
50144
  if (input.includeEffectiveTakerRate === true) {
50022
- if (!userFeesResponse || typeof userFeesResponse !== "object" || Array.isArray(userFeesResponse)) {
50023
- throw new Error("Malformed Hyperliquid userFees response for client runtime prompt context.");
50024
- }
50025
- const rawUserCrossRate = userFeesResponse.userCrossRate;
50026
- if (rawUserCrossRate == null || typeof rawUserCrossRate === "string" && rawUserCrossRate.trim() === "") {
50027
- throw new Error("Hyperliquid userFees response is missing userCrossRate for client runtime prompt context.");
50028
- }
50029
- const parsedUserCrossRate = Number(rawUserCrossRate);
50030
- if (!Number.isFinite(parsedUserCrossRate) || parsedUserCrossRate < 0 || parsedUserCrossRate >= 1) {
50031
- throw new Error("Hyperliquid userFees response has an invalid userCrossRate for client runtime prompt context.");
50032
- }
50033
- takerRate = parsedUserCrossRate;
50145
+ const raw = userFeesResponse?.userCrossRate;
50146
+ if ((typeof raw === "number" || typeof raw === "string" && raw.trim() !== "") && Number.isFinite(Number(raw)) && Number(raw) >= 0 && Number(raw) < 1) takerRate = Number(raw);
50147
+ }
50148
+ let effectiveTakerRates;
50149
+ if (input.includeEffectiveTakerRate === true) {
50150
+ const feeSymbols = [...new Set([
50151
+ ...input.feeSymbols ?? [symbol2],
50152
+ ...parseInfoPositions(perpsResponse).filter((position) => Number(position.size) !== 0).map((position) => position.symbol)
50153
+ ].map(normalizeHyperliquidMarketSymbol).filter(Boolean))].sort();
50154
+ const feeDexes = [...new Set(feeSymbols.map(getHyperliquidMarketDex))];
50155
+ const metadata = await Promise.all(feeDexes.map(async (dex) => {
50156
+ try {
50157
+ const payload = await fetchHyperliquidInfoPayload(
50158
+ apiUrl,
50159
+ { type: "meta", ...dex ? { dex } : {} },
50160
+ input.signal
50161
+ );
50162
+ return [dex, payload];
50163
+ } catch (error48) {
50164
+ if (input.signal?.aborted) throw error48;
50165
+ return [dex, null];
50166
+ }
50167
+ }));
50168
+ effectiveTakerRates = effectiveHyperliquidTakerRates(feeSymbols, userFeesResponse ?? {}, Object.fromEntries(metadata));
50034
50169
  }
50035
50170
  const accountStateConfig = input.config.client_runtime_hyperliquid_account_state;
50036
50171
  const summaryPerpsResponse = exactAccountMode ? { ...accountSummaryPerpsResponse, accountMode: exactAccountMode.accountMode } : accountSummaryPerpsResponse;
@@ -50119,6 +50254,7 @@ var init_hyperliquid_account_state_adapter = __esm({
50119
50254
  availableToTrade,
50120
50255
  positions: parseInfoPositions(perpsResponse),
50121
50256
  ...takerRate == null ? {} : { takerRate },
50257
+ ...effectiveTakerRates == null ? {} : { effectiveTakerRates },
50122
50258
  ...exactAccountMode == null || userFeesResult == null ? {} : {
50123
50259
  promptRescueEvidence: {
50124
50260
  capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -50435,11 +50571,11 @@ function normalizeNonNegativeInt(value) {
50435
50571
  if (value == null) {
50436
50572
  return 0;
50437
50573
  }
50438
- const numeric = Number(value);
50439
- if (!Number.isInteger(numeric) || numeric < 0) {
50574
+ const numeric2 = Number(value);
50575
+ if (!Number.isInteger(numeric2) || numeric2 < 0) {
50440
50576
  return 0;
50441
50577
  }
50442
- return numeric;
50578
+ return numeric2;
50443
50579
  }
50444
50580
  function normalizeSecretVersion(value) {
50445
50581
  if (typeof value !== "string") {
@@ -50469,11 +50605,11 @@ function normalizeClientRuntimeSecretRetryAfterSeconds(value) {
50469
50605
  if (value == null) {
50470
50606
  return 0;
50471
50607
  }
50472
- const numeric = Number(value);
50473
- if (!Number.isFinite(numeric)) {
50608
+ const numeric2 = Number(value);
50609
+ if (!Number.isFinite(numeric2)) {
50474
50610
  return 0;
50475
50611
  }
50476
- const normalized = Math.trunc(numeric);
50612
+ const normalized = Math.trunc(numeric2);
50477
50613
  return normalized >= 0 ? normalized : 0;
50478
50614
  }
50479
50615
  function projectClientRuntimeSecretRateLimit(operation, retryAfterSeconds) {
@@ -83124,11 +83260,11 @@ var init_hyperliquid_client = __esm({
83124
83260
  };
83125
83261
  validateHyperliquidPerpPriceWire = (price, sizeDecimals) => {
83126
83262
  const normalized = normalizeDecimalString(price);
83127
- const numeric = Number(normalized);
83128
- if (!Number.isFinite(numeric) || numeric <= 0) {
83263
+ const numeric2 = Number(normalized);
83264
+ if (!Number.isFinite(numeric2) || numeric2 <= 0) {
83129
83265
  return { valid: false, reason: "price must be positive" };
83130
83266
  }
83131
- if (!Number.isInteger(numeric) && countSignificantDigits(normalized) > 5) {
83267
+ if (!Number.isInteger(numeric2) && countSignificantDigits(normalized) > 5) {
83132
83268
  return { valid: false, reason: "price exceeds 5 significant figures" };
83133
83269
  }
83134
83270
  const maxDecimals = Math.max(0, 6 - sizeDecimals);
@@ -83139,8 +83275,8 @@ var init_hyperliquid_client = __esm({
83139
83275
  };
83140
83276
  validateHyperliquidSizeWire = (size, sizeDecimals) => {
83141
83277
  const normalized = normalizeDecimalString(size);
83142
- const numeric = Number(normalized);
83143
- if (!Number.isFinite(numeric) || numeric <= 0) {
83278
+ const numeric2 = Number(normalized);
83279
+ if (!Number.isFinite(numeric2) || numeric2 <= 0) {
83144
83280
  return { valid: false, reason: "size must be positive" };
83145
83281
  }
83146
83282
  if (countDecimalPlaces(normalized) > sizeDecimals) {
@@ -84464,8 +84600,8 @@ var init_hyperliquid_client = __esm({
84464
84600
  return null;
84465
84601
  }
84466
84602
  const raw = value.px;
84467
- const numeric = Number(raw);
84468
- return Number.isFinite(numeric) && numeric > 0 ? String(raw) : null;
84603
+ const numeric2 = Number(raw);
84604
+ return Number.isFinite(numeric2) && numeric2 > 0 ? String(raw) : null;
84469
84605
  };
84470
84606
  const bid = levelPrice(bids[0]);
84471
84607
  const ask = levelPrice(asks[0]);
@@ -84967,11 +85103,11 @@ function normalizeProviderKeyCount(rawValue, fallback) {
84967
85103
  if (rawValue == null) {
84968
85104
  return fallback;
84969
85105
  }
84970
- const numeric = Number(rawValue);
84971
- if (!Number.isInteger(numeric) || numeric < 0) {
85106
+ const numeric2 = Number(rawValue);
85107
+ if (!Number.isInteger(numeric2) || numeric2 < 0) {
84972
85108
  return fallback;
84973
85109
  }
84974
- return numeric;
85110
+ return numeric2;
84975
85111
  }
84976
85112
  function projectClientRuntimeSecretMetadata(serverHasHyperliquidSigningKey, serverProviderKeys, serverProviderKeyCount) {
84977
85113
  const normalizedProviderKeys = normalizeProviderKeys(serverProviderKeys);
@@ -91386,6 +91522,167 @@ var init_runtime_execution = __esm({
91386
91522
  }
91387
91523
  });
91388
91524
 
91525
+ // lib/runtime/decision-contract.ts
91526
+ var VISIBLE_REASONING_KEYS, VISIBLE_REASONING_KEY_SET, VISIBLE_REASONING_ALIAS_KEY_SET, normalizeDecisionUnits, normalizeDecisionValue;
91527
+ var init_decision_contract = __esm({
91528
+ "lib/runtime/decision-contract.ts"() {
91529
+ "use strict";
91530
+ init_define_VTX_EXO_POLICY();
91531
+ init_define_VTX_GROK_POLICY();
91532
+ init_define_VTX_PI_MODEL_POLICY();
91533
+ VISIBLE_REASONING_KEYS = [
91534
+ "reasoning",
91535
+ "final_reasoning",
91536
+ "final_answer",
91537
+ "answer",
91538
+ "output_text",
91539
+ "text",
91540
+ "content"
91541
+ ];
91542
+ VISIBLE_REASONING_KEY_SET = new Set(VISIBLE_REASONING_KEYS);
91543
+ VISIBLE_REASONING_ALIAS_KEY_SET = new Set([
91544
+ ...VISIBLE_REASONING_KEYS,
91545
+ "reason"
91546
+ ].map((key) => key.replace(/[^a-z0-9]+/gi, "").toLowerCase()));
91547
+ normalizeDecisionUnits = (rawUnits, decision) => {
91548
+ const parsedUnits = Number(rawUnits);
91549
+ if (Number.isFinite(parsedUnits) && parsedUnits >= 0) {
91550
+ return Math.trunc(parsedUnits);
91551
+ }
91552
+ return 0;
91553
+ };
91554
+ normalizeDecisionValue = (rawDecision) => {
91555
+ const decisionValue = String(rawDecision || "").trim().toUpperCase();
91556
+ return decisionValue === "BUY" || decisionValue === "SELL" ? decisionValue : "HOLD";
91557
+ };
91558
+ }
91559
+ });
91560
+
91561
+ // lib/runtime/constraint-contract.ts
91562
+ var normalizeOptionalInt, evaluateRuntimeDecisionAcceptance;
91563
+ var init_constraint_contract = __esm({
91564
+ "lib/runtime/constraint-contract.ts"() {
91565
+ "use strict";
91566
+ init_define_VTX_EXO_POLICY();
91567
+ init_define_VTX_GROK_POLICY();
91568
+ init_define_VTX_PI_MODEL_POLICY();
91569
+ init_execution_guard_contract();
91570
+ init_decision_contract();
91571
+ normalizeOptionalInt = (value) => {
91572
+ if (value === null || value === void 0) {
91573
+ return null;
91574
+ }
91575
+ const parsed = Number.parseInt(String(value), 10);
91576
+ return Number.isFinite(parsed) ? parsed : null;
91577
+ };
91578
+ evaluateRuntimeDecisionAcceptance = (input) => {
91579
+ const decision = normalizeDecisionValue(input.decision);
91580
+ const units = normalizeDecisionUnits(input.units, decision);
91581
+ if (decision === "HOLD") {
91582
+ return {
91583
+ accepted: true,
91584
+ decision,
91585
+ normalized_units: 0,
91586
+ reason_code: null
91587
+ };
91588
+ }
91589
+ if (input.constraints.runtime_disabled) {
91590
+ return {
91591
+ accepted: false,
91592
+ decision,
91593
+ normalized_units: 0,
91594
+ reason_code: "runtime_disabled"
91595
+ };
91596
+ }
91597
+ if (input.constraints.kill_switch_active) {
91598
+ return {
91599
+ accepted: false,
91600
+ decision,
91601
+ normalized_units: 0,
91602
+ reason_code: "kill_switch_active"
91603
+ };
91604
+ }
91605
+ if (!input.constraints.model_allowed) {
91606
+ return {
91607
+ accepted: false,
91608
+ decision,
91609
+ normalized_units: 0,
91610
+ reason_code: "model_ineligible"
91611
+ };
91612
+ }
91613
+ if (!input.constraints.provider_allowed) {
91614
+ return {
91615
+ accepted: false,
91616
+ decision,
91617
+ normalized_units: 0,
91618
+ reason_code: "provider_ineligible"
91619
+ };
91620
+ }
91621
+ if (units <= 0) {
91622
+ return {
91623
+ accepted: false,
91624
+ decision,
91625
+ normalized_units: 0,
91626
+ reason_code: "invalid_units"
91627
+ };
91628
+ }
91629
+ const maxPerPrompt = Math.max(Math.trunc(Number(input.constraints.max_trades_per_prompt) || 0), 0);
91630
+ if (maxPerPrompt === 0) {
91631
+ return {
91632
+ accepted: false,
91633
+ decision,
91634
+ normalized_units: 0,
91635
+ reason_code: "max_per_prompt_zero"
91636
+ };
91637
+ }
91638
+ const remainingGlobal = normalizeOptionalInt(input.constraints.remaining_global_units);
91639
+ const remainingExchange = normalizeOptionalInt(input.constraints.remaining_exchange_units);
91640
+ const remainingAsset = normalizeOptionalInt(input.constraints.remaining_asset_units);
91641
+ const currentSymbolSignedUnits = normalizeOptionalInt(input.constraints.current_symbol_signed_units) ?? 0;
91642
+ let cappedUnits = Math.min(units, maxPerPrompt);
91643
+ const exposureIncrease = (candidateUnits) => {
91644
+ const classified = classifyExecutionIntent(decision, candidateUnits, currentSymbolSignedUnits);
91645
+ return Math.max(
91646
+ 0,
91647
+ Math.abs(classified.targetSignedUnits) - Math.abs(currentSymbolSignedUnits)
91648
+ );
91649
+ };
91650
+ const fitsCapacity = (candidateUnits) => {
91651
+ const increase = exposureIncrease(candidateUnits);
91652
+ if (remainingGlobal !== null && increase > Math.max(remainingGlobal, 0)) {
91653
+ return false;
91654
+ }
91655
+ if (remainingExchange !== null && increase > Math.max(remainingExchange, 0)) {
91656
+ return false;
91657
+ }
91658
+ if (remainingAsset !== null && increase > Math.max(remainingAsset, 0)) {
91659
+ return false;
91660
+ }
91661
+ return true;
91662
+ };
91663
+ while (cappedUnits > 0 && !fitsCapacity(cappedUnits)) {
91664
+ cappedUnits -= 1;
91665
+ }
91666
+ if (cappedUnits <= 0) {
91667
+ const requestedExposureIncrease = exposureIncrease(Math.min(units, maxPerPrompt));
91668
+ const reasonCode = requestedExposureIncrease > 0 && remainingGlobal !== null && remainingGlobal <= 0 ? "global_capacity_reached" : requestedExposureIncrease > 0 && remainingExchange !== null && remainingExchange <= 0 ? "exchange_capacity_reached" : requestedExposureIncrease > 0 && remainingAsset !== null && remainingAsset <= 0 ? "asset_capacity_reached" : "capacity_reached";
91669
+ return {
91670
+ accepted: false,
91671
+ decision,
91672
+ normalized_units: 0,
91673
+ reason_code: reasonCode
91674
+ };
91675
+ }
91676
+ return {
91677
+ accepted: true,
91678
+ decision,
91679
+ normalized_units: cappedUnits,
91680
+ reason_code: cappedUnits < units ? "units_capped" : null
91681
+ };
91682
+ };
91683
+ }
91684
+ });
91685
+
91389
91686
  // lib/runtime/provider-observability.ts
91390
91687
  var record4, identifier, count3, normalizeProviderDiagnostics;
91391
91688
  var init_provider_observability = __esm({
@@ -91501,9 +91798,9 @@ var init_usage_contract = __esm({
91501
91798
  isRecord = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
91502
91799
  coerceOptionalRuntimeUsageCount = (value) => {
91503
91800
  if (value === null || value === void 0 || typeof value === "boolean") return null;
91504
- const numeric = Number(value);
91505
- if (!Number.isFinite(numeric) || numeric < 0 || numeric > MAX_RUNTIME_USAGE_COUNT) return null;
91506
- return Math.round(numeric);
91801
+ const numeric2 = Number(value);
91802
+ if (!Number.isFinite(numeric2) || numeric2 < 0 || numeric2 > MAX_RUNTIME_USAGE_COUNT) return null;
91803
+ return Math.round(numeric2);
91507
91804
  };
91508
91805
  readOptionalRuntimeUsageCount = (source, keys) => {
91509
91806
  for (const key of keys) {
@@ -92566,6 +92863,46 @@ function createHeadlessLocalWorker(options) {
92566
92863
  message: `Tradability ${providerDecision.tradability ?? "missing"} is below the ${classifiedIntent === "open" ? "Open" : "Add"} minimum of ${applicableMinimum}. No order was placed.`
92567
92864
  }
92568
92865
  } : null;
92866
+ let executionDecision = { decision: providerDecision.decision, units: providerDecision.units };
92867
+ if (localHyperliquidContext && providerDecision.decision !== "HOLD") {
92868
+ const constraints = objectOrNull3(metadata.constraint_contract) ?? {};
92869
+ const limit = (key) => {
92870
+ const raw = key === "max_trades_per_exchange" && !Object.hasOwn(promptKnobs, key) ? promptKnobs.max_trades_global : promptKnobs[key];
92871
+ if (raw == null) throw new Error(`Missing headless runtime ${key}.`);
92872
+ const value = requireFiniteNumber(raw, key);
92873
+ if (!Number.isSafeInteger(value) || value < 0) throw new Error(`Invalid headless runtime ${key}.`);
92874
+ return value;
92875
+ };
92876
+ const unitSize = localHyperliquidContext.executionContext.unitSizeUsdc;
92877
+ const venue = getHyperliquidMarketDex(symbol2);
92878
+ let globalUsage = 0;
92879
+ let exchangeUsage = 0;
92880
+ let currentSignedUnits = 0;
92881
+ for (const position of localHyperliquidContext.accountState.positions) {
92882
+ if (Number(position.size) === 0) continue;
92883
+ const entryPrice = requirePositiveNumber2(position.entry_price, "position entry price");
92884
+ const signedUnits = signedUnitsFromPosition(Number(position.size), entryPrice, unitSize);
92885
+ globalUsage += Math.abs(signedUnits);
92886
+ if (getHyperliquidMarketDex(position.symbol) === venue) exchangeUsage += Math.abs(signedUnits);
92887
+ if (normalizeRuntimeSymbol(position.symbol) === normalizeRuntimeSymbol(symbol2)) currentSignedUnits = signedUnits;
92888
+ }
92889
+ const accepted = evaluateRuntimeDecisionAcceptance({
92890
+ ...executionDecision,
92891
+ constraints: {
92892
+ runtime_disabled: constraints.runtime_disabled === true,
92893
+ kill_switch_active: constraints.kill_switch_active === true,
92894
+ max_trades_per_prompt: limit("max_trades_per_prompt"),
92895
+ remaining_global_units: limit("max_trades_global") - globalUsage,
92896
+ remaining_exchange_units: limit("max_trades_per_exchange") - exchangeUsage,
92897
+ remaining_asset_units: limit("max_trades_per_asset") - Math.abs(currentSignedUnits),
92898
+ current_symbol_signed_units: currentSignedUnits,
92899
+ model_allowed: constraints.model_allowed !== false,
92900
+ provider_allowed: constraints.provider_allowed !== false
92901
+ }
92902
+ });
92903
+ if (!accepted.accepted) throw new Error(`Headless runtime decision rejected: ${accepted.reason_code}`);
92904
+ executionDecision = { decision: accepted.decision, units: accepted.normalized_units };
92905
+ }
92569
92906
  const envelope = metadata.envelope ?? {};
92570
92907
  const baseTradeSync = {
92571
92908
  analysis_run_id: analysisRunId,
@@ -92585,8 +92922,8 @@ function createHeadlessLocalWorker(options) {
92585
92922
  contract_version: requireText(envelope.contract_version, "contract version"),
92586
92923
  contract_hash: requireText(envelope.contract_hash, "contract hash"),
92587
92924
  policy_generation_id: requireText(envelope.policy_generation_id, "policy generation id"),
92588
- decision: providerDecision.decision,
92589
- units: providerDecision.units,
92925
+ decision: executionDecision.decision,
92926
+ units: executionDecision.units,
92590
92927
  final_tradability: providerDecision.tradability,
92591
92928
  reasoning: providerDecision.reasoning,
92592
92929
  model: requireText(prompt.model ?? metadata.model, "model"),
@@ -92612,7 +92949,7 @@ function createHeadlessLocalWorker(options) {
92612
92949
  execution_snapshot_id: tradabilityBlockExecution ? decisionSnapshotId : void 0,
92613
92950
  executions: tradabilityBlockExecution ? [tradabilityBlockExecution] : []
92614
92951
  },
92615
- afterDecision: localHyperliquidContext ? async () => {
92952
+ afterDecision: localHyperliquidContext ? async (accepted) => {
92616
92953
  const freshProfile = objectOrNull3(await options.client.getSecretStatus(input.profileId));
92617
92954
  const freshWalletAddress = requireText(
92618
92955
  freshProfile?.hyperliquid_wallet_address,
@@ -92631,8 +92968,8 @@ function createHeadlessLocalWorker(options) {
92631
92968
  cycleId: analysisRunId,
92632
92969
  signingKey: localHyperliquidContext.signingKey,
92633
92970
  config: buildHeadlessExchangeConfig(llmConfig),
92634
- decision: providerDecision.decision,
92635
- units: providerDecision.units,
92971
+ decision: accepted.decision,
92972
+ units: accepted.units,
92636
92973
  executionContext: localHyperliquidContext.executionContext
92637
92974
  });
92638
92975
  return {
@@ -92655,6 +92992,7 @@ var init_headless_local_worker = __esm({
92655
92992
  init_hyperliquid_account_state_adapter();
92656
92993
  init_hyperliquid_market_symbol();
92657
92994
  init_runtime_execution();
92995
+ init_constraint_contract();
92658
92996
  init_protection_storage();
92659
92997
  init_execution_guard_contract();
92660
92998
  init_inference_observability();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vtxmacro/cli",
3
- "version": "2026.9.42",
3
+ "version": "2026.9.44",
4
4
  "description": "VTX Macro CLI, MCP server, and durable external inference host.",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",