@vtxmacro/cli 2026.10.17 → 2026.10.18

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
@@ -113,7 +113,7 @@ var init_routing = __esm({
113
113
  var agent_cli_release_default;
114
114
  var init_agent_cli_release = __esm({
115
115
  "agent-cli-release.json"() {
116
- agent_cli_release_default = { package_name: "@vtxmacro/cli", package_version: "2026.10.17", codex_package_name: "@openai/codex", codex_version: "0.155.0", copilot_sdk_package_name: "@github/copilot-sdk", copilot_sdk_version: "1.0.0-beta.8", copilot_cli_package_name: "@github/copilot", copilot_cli_version: "1.0.80", deepseek_harness_version: "0.1.1-rc.2", deepseek_harness_packages: ["@deepseek-ai/dsh-agent", "@deepseek-ai/dsh-agent-instructions", "@deepseek-ai/dsh-agent-loop", "@deepseek-ai/dsh-agent-spine-demo", "@deepseek-ai/dsh-anonymous-user-id", "@deepseek-ai/dsh-atomic-write", "@deepseek-ai/dsh-attachment", "@deepseek-ai/dsh-brand", "@deepseek-ai/dsh-code-runtime", "@deepseek-ai/dsh-credentials", "@deepseek-ai/dsh-fs", "@deepseek-ai/dsh-goal", "@deepseek-ai/dsh-goal-round-driver", "@deepseek-ai/dsh-home-paths", "@deepseek-ai/dsh-invariants", "@deepseek-ai/dsh-jobs", "@deepseek-ai/dsh-jobs-local", "@deepseek-ai/dsh-launch-environment", "@deepseek-ai/dsh-llm", "@deepseek-ai/dsh-llm-deepseek", "@deepseek-ai/dsh-llm-retry", "@deepseek-ai/dsh-output-retention", "@deepseek-ai/dsh-sandbox", "@deepseek-ai/dsh-sandbox-policy", "@deepseek-ai/dsh-scope", "@deepseek-ai/dsh-session", "@deepseek-ai/dsh-session-checkpoint-policy", "@deepseek-ai/dsh-session-persistence", "@deepseek-ai/dsh-session-persistence-jsonl", "@deepseek-ai/dsh-session-projection", "@deepseek-ai/dsh-session-title", "@deepseek-ai/dsh-settings", "@deepseek-ai/dsh-shell", "@deepseek-ai/dsh-shell-env", "@deepseek-ai/dsh-skill", "@deepseek-ai/dsh-skill-filesystem", "@deepseek-ai/dsh-subprocess", "@deepseek-ai/dsh-system-prompt", "@deepseek-ai/dsh-timeout", "@deepseek-ai/dsh-tool-bash", "@deepseek-ai/dsh-tool-goal", "@deepseek-ai/dsh-tool-jobs", "@deepseek-ai/dsh-tool-skill", "@deepseek-ai/dsh-tools", "@deepseek-ai/dsh-typert-protocol", "@deepseek-ai/dsh-user-approval"], deepseek_cordis_package_name: "@deepseek-ai/cordis", deepseek_cordis_version: "4.0.1", deepseek_support_packages: { "@deepseek-ai/cordis-plugin-timer": "1.1.3" }, platforms: { "linux-x64": { package_name: "@openai/codex-linux-x64", target: "x86_64-unknown-linux-musl", binary_name: "codex", sha256: "660e159a49e823ac8e5986cb238f73158ce4b957d40d9292f8de90862644b501" }, "win32-x64": { package_name: "@openai/codex-win32-x64", target: "x86_64-pc-windows-msvc", binary_name: "codex.exe", sha256: "e4c11374bd9de8ad5c3b7617fd4654bb7839901edb0863f9930666863c7a021b" } }, pi_coding_agent_package_name: "@earendil-works/pi-coding-agent", pi_ai_package_name: "@earendil-works/pi-ai", pi_version: "0.85.1", pi_support_packages: ["@earendil-works/pi-agent-core", "@earendil-works/pi-telemetry", "@earendil-works/pi-tui", "@earendil-works/chord"], grok_version: "1.0.30", grok_platforms: { "linux-x64": { package_name: "@xai-official/grok-linux-x64", binary_name: "grok", sha256: "504dd6546ab991b75d36698242875ce461489cd1f8cd84285873cb55bd5c7d54" }, "win32-x64": { package_name: "@xai-official/grok-win32-x64", binary_name: "grok.exe", sha256: "48736d1a4342a801ea26d0ecde4c516b653f791399065adaa55973f83abd8867" } } };
116
+ agent_cli_release_default = { package_name: "@vtxmacro/cli", package_version: "2026.10.18", codex_package_name: "@openai/codex", codex_version: "0.155.0", copilot_sdk_package_name: "@github/copilot-sdk", copilot_sdk_version: "1.0.0-beta.8", copilot_cli_package_name: "@github/copilot", copilot_cli_version: "1.0.80", deepseek_harness_version: "0.1.1-rc.2", deepseek_harness_packages: ["@deepseek-ai/dsh-agent", "@deepseek-ai/dsh-agent-instructions", "@deepseek-ai/dsh-agent-loop", "@deepseek-ai/dsh-agent-spine-demo", "@deepseek-ai/dsh-anonymous-user-id", "@deepseek-ai/dsh-atomic-write", "@deepseek-ai/dsh-attachment", "@deepseek-ai/dsh-brand", "@deepseek-ai/dsh-code-runtime", "@deepseek-ai/dsh-credentials", "@deepseek-ai/dsh-fs", "@deepseek-ai/dsh-goal", "@deepseek-ai/dsh-goal-round-driver", "@deepseek-ai/dsh-home-paths", "@deepseek-ai/dsh-invariants", "@deepseek-ai/dsh-jobs", "@deepseek-ai/dsh-jobs-local", "@deepseek-ai/dsh-launch-environment", "@deepseek-ai/dsh-llm", "@deepseek-ai/dsh-llm-deepseek", "@deepseek-ai/dsh-llm-retry", "@deepseek-ai/dsh-output-retention", "@deepseek-ai/dsh-sandbox", "@deepseek-ai/dsh-sandbox-policy", "@deepseek-ai/dsh-scope", "@deepseek-ai/dsh-session", "@deepseek-ai/dsh-session-checkpoint-policy", "@deepseek-ai/dsh-session-persistence", "@deepseek-ai/dsh-session-persistence-jsonl", "@deepseek-ai/dsh-session-projection", "@deepseek-ai/dsh-session-title", "@deepseek-ai/dsh-settings", "@deepseek-ai/dsh-shell", "@deepseek-ai/dsh-shell-env", "@deepseek-ai/dsh-skill", "@deepseek-ai/dsh-skill-filesystem", "@deepseek-ai/dsh-subprocess", "@deepseek-ai/dsh-system-prompt", "@deepseek-ai/dsh-timeout", "@deepseek-ai/dsh-tool-bash", "@deepseek-ai/dsh-tool-goal", "@deepseek-ai/dsh-tool-jobs", "@deepseek-ai/dsh-tool-skill", "@deepseek-ai/dsh-tools", "@deepseek-ai/dsh-typert-protocol", "@deepseek-ai/dsh-user-approval"], deepseek_cordis_package_name: "@deepseek-ai/cordis", deepseek_cordis_version: "4.0.1", deepseek_support_packages: { "@deepseek-ai/cordis-plugin-timer": "1.1.3" }, platforms: { "linux-x64": { package_name: "@openai/codex-linux-x64", target: "x86_64-unknown-linux-musl", binary_name: "codex", sha256: "660e159a49e823ac8e5986cb238f73158ce4b957d40d9292f8de90862644b501" }, "win32-x64": { package_name: "@openai/codex-win32-x64", target: "x86_64-pc-windows-msvc", binary_name: "codex.exe", sha256: "e4c11374bd9de8ad5c3b7617fd4654bb7839901edb0863f9930666863c7a021b" } }, pi_coding_agent_package_name: "@earendil-works/pi-coding-agent", pi_ai_package_name: "@earendil-works/pi-ai", pi_version: "0.85.1", pi_support_packages: ["@earendil-works/pi-agent-core", "@earendil-works/pi-telemetry", "@earendil-works/pi-tui", "@earendil-works/chord"], grok_version: "1.0.30", grok_platforms: { "linux-x64": { package_name: "@xai-official/grok-linux-x64", binary_name: "grok", sha256: "504dd6546ab991b75d36698242875ce461489cd1f8cd84285873cb55bd5c7d54" }, "win32-x64": { package_name: "@xai-official/grok-win32-x64", binary_name: "grok.exe", sha256: "48736d1a4342a801ea26d0ecde4c516b653f791399065adaa55973f83abd8867" } } };
117
117
  }
118
118
  });
119
119
 
@@ -1254,6 +1254,7 @@ var init_runtime_policy_generated = __esm({
1254
1254
  public_recovery: {
1255
1255
  fallback_initial_seconds: 2,
1256
1256
  fallback_max_seconds: 60,
1257
+ fallback_jitter_min_factor: 0.5,
1257
1258
  permit_lease_seconds: 60,
1258
1259
  recovery_initial_concurrency: 1,
1259
1260
  recovery_max_concurrency: 8,
@@ -1456,7 +1457,7 @@ var init_runtime_policy_generated = __esm({
1456
1457
  });
1457
1458
 
1458
1459
  // lib/constants.ts
1459
- var MS_PER_SECOND, SECONDS_PER_MINUTE, MINUTES_PER_HOUR, HOURS_PER_DAY, DAYS_PER_WEEK, MS_PER_MINUTE, SECONDS_PER_HOUR, SECONDS_PER_DAY, SECONDS_PER_WEEK, MINUTES_PER_DAY, MINUTES_PER_WEEK, MS_PER_HOUR, MS_PER_DAY, READ_STAMP_TIE_MS, READ_STAMP_STEP_BACK_MS, CLOCK_FIELD_DIGITS, BACKOFF_GROWTH_FACTOR, BYTES_PER_KIB, BYTES_PER_MIB, BITS_PER_BYTE, BYTE_MASK, OWNER_ONLY_FILE_MODE, OWNER_ONLY_DIRECTORY_MODE, GROUP_OTHER_PERMISSION_BITS, DECIMAL_RADIX, HEX_RADIX, BASE36_RADIX, BYTE_HEX_DIGITS, UINT32_HEX_DIGITS, RANDOM_FRACTION_PREFIX_LENGTH, PERCENT_SCALE, MIDPOINT_DIVISOR, SQUARE_EXPONENT, FNV1A_32_OFFSET_BASIS, FNV1A_32_PRIME, JSON_INDENT_SPACES, INT32_MIN, INT32_MAX, SET_TIMEOUT_MAX_DELAY_MS, POSITION_SIZE_EPSILON, CANDLE_TIMEFRAME_SECONDS, HTTP_STATUS, HTTP_STATUS_MIN, HTTP_STATUS_MAX, HTTP_CLIENT_ERROR_MIN, HTTP_SERVER_ERROR_MIN, AI_COST_ESTIMATE_PERIOD_DAYS, SECONDS_PER_AI_COST_ESTIMATE_PERIOD, DATE_FIELD_DIGITS, EXTERNAL_INFERENCE_LIMITS, NODE_ARGV_COMMAND_ARGS_START, EXIT_CODE_TEMPFAIL, SHA256_INITIAL_STATE, SHA256_ROUND_CONSTANTS, SHA256, UINT64_HIGH_WORD_DIVISOR, CANONICAL_BASE64URL, INFERENCE_ENVELOPE_CRYPTO, EXTERNAL_INFERENCE_SCHEMA_BOUNDS, JSON_RPC_ERROR_CODES, INFERENCE_MCP_SCHEMA_PROBE_MAX_DEPTH, INFERENCE_HOST_PROCESS_LOCK_RECORD_SCHEMA_VERSION, INFERENCE_HOST_RECLAIM_GUARD_CREATE_PASSES, LINUX_PROC_STAT_COMM_TERMINATOR_CHARS, INFERENCE_HOST_RANDOM_BYTES, INFERENCE_OAUTH_TOKEN_MAX_LENGTH, INFERENCE_CREDENTIAL_WINDOWS_NOT_FOUND_EXIT_CODE, MACOS_SECURITY_ITEM_NOT_FOUND_EXIT_CODE, INFERENCE_CREDENTIAL_LABEL_ACCOUNT_KEY_CHARS, INFERENCE_HOST_STABLE_OPERATION_ID_HASH_CHARS, INFERENCE_HOST_DRAIN_PRIORITY, INFERENCE_JOB_CLAIM_SCHEMA_VERSION, INFERENCE_HOST_WINDOWS_TASK_IDENTITY_MAX_CHARS, INFERENCE_HOST_OWNER_ONLY_EXECUTABLE_MODE, WINDOWS_TASKKILL_PROCESS_NOT_FOUND_EXIT_CODE, INFERENCE_HOST_CLI_MAX_SERVICE_POSITIONALS, INFERENCE_HOST_CLI_MAX_COMMAND_POSITIONALS, INFERENCE_HOST_DISPLAY_NAME_MAX_CHARS, INFERENCE_HOST_REVOCATION_CHECKPOINT_MAX_CHARS, INFERENCE_HOST_MODEL_ID_MAX_CHARS, CODEX_RECOVERY_RECEIPT_MAX_CHARS, CODEX_HOSTED_ATTEMPT_PATH_SEGMENTS, CODEX_GUARDIAN_PROCESS_TOKEN_BYTES, CODEX_RATE_LIMIT_EXHAUSTED_PERCENT, INFERENCE_HOST_PROXY_TOKEN_BYTES, GROK_TOOL_SERVER_TOKEN_BYTES, GROK_NATIVE_SESSION_GROUP_NAME_MAX_CHARS, GROK_POLICY_TRANSPORT_MAX_BYTES, EXO_POLICY_MAX_TOOL_ROUNDS, EXO_POLICY_MAX_MODELS, EXO_POLICY_MODEL_NAME_MAX_CHARS, EXO_RUNTIME_VERSION_COMMIT_CHARS, PI_QUALIFIED_MODEL_ID_MAX_CHARS, PI_STRUCTURED_OUTPUT_MAX_DEPTH, PI_STRUCTURED_OUTPUT_MAX_PROPERTIES, INFERENCE_HOST_API_KEY_MIN_CHARS, INFERENCE_HOST_API_KEY_MAX_BYTES, INFERENCE_HOST_API_KEY_IDENTITY_HEX_CHARS, DEEPSEEK_HARNESS_NODE_LTS_MAJOR, DEEPSEEK_HARNESS_NODE_LTS_MIN_MINOR, DEEPSEEK_HARNESS_NODE_CURRENT_MAJOR, PROMPT_FIXED_DIGITS, PROMPT_SIGNIFICANT_DIGITS, PROMPT_NUMBER_MAX_DIGITS, PROMPT_PRICE_INTEGER_THRESHOLD, PROMPT_MARGIN_UTILIZATION_DECIMALS, PROMPT_SYMBOL_MAX_CHARS, PROMPT_PARTIAL_UNIT_ROUND_UP_FRACTION, HALF_UP_ROUNDING_OFFSET, PROMPT_ENTRY_PRICE_MATCH_ABS_TOLERANCE, PROMPT_ENTRY_PRICE_MATCH_REL_TOLERANCE, DECISION_OUTPUT_EXAMPLE_TRADABILITY, INDICATOR_RSI_PERIOD, INDICATOR_ATR_PERIOD, INDICATOR_MACD_FAST_PERIOD, INDICATOR_MACD_SLOW_PERIOD, INDICATOR_MACD_SIGNAL_PERIOD, INDICATOR_BOLLINGER_PERIOD, INDICATOR_BOLLINGER_STD_DEV, INDICATOR_OSCILLATOR_MAX, EMA_SMOOTHING_NUMERATOR, PROMPT_EMA_PERIODS, JSON_UNICODE_ESCAPE_PREFIX_LENGTH, JSON_UNICODE_ESCAPE_HEX_DIGITS, JSON_CONTROL_CHARACTER_MAX, RUNTIME_DEBUG_SNIPPET_CHARS, RUNTIME_DEBUG_PROMPT_SNIPPET_CHARS, RUNTIME_DEBUG_TOKEN_PREFIX_CHARS, RUNTIME_DEBUG_USD_DECIMALS, REVIEW_FAILURE_DETAIL_MAX_CHARS, RUNTIME_LATENCY_SECONDS_DECIMALS, AI_SCHEDULE_CLOCK_PARTS, ESTIMATED_CHARS_PER_TOKEN, PROVIDER_ERROR_RAW_TEXT_MAX_CHARS, AI_CALL_COST_DECIMALS, PROVIDER_DIAGNOSTIC_LIMITS, AI_INVOCATION_CONTRACT_VERSION, AI_INVOCATION_TELEMETRY_LIMITS, PROVIDER_USAGE_DETAIL_LIMITS, HYPERLIQUID_EXCHANGE_SPECIFICATION, HYPERLIQUID_TPSL_BATCH_MIN_ORDERS, HYPERLIQUID_USER_FILLS_PROVIDER_PAGE_CAP, HYPERLIQUID_META_AND_ASSET_CTXS_PARTS, HYPERLIQUID_SIDE_PAIR_LENGTH, HYPERLIQUID_SIGNED_SIZE_MATCH_EXTRA_DECIMALS, HYPERLIQUID_OPEN_ORDERS_MAX_NESTING_DEPTH, ACCOUNT_PAYLOAD_MODE_SEARCH_MAX_DEPTH, HYPERLIQUID_ACCOUNT_ROUNDING_DECIMALS, HYPERLIQUID_UNREALIZED_PNL_ZERO_TOLERANCE, HYPERLIQUID_MAX_DEPLOYER_FEE_SCALE, HYPERLIQUID_DEPLOYER_FEE_SCALE_MULTIPLIER, HYPERLIQUID_GROWTH_MODE_FEE_FACTOR, HYPERLIQUID_ALIGNED_QUOTE_NON_DEPLOYER_FEE_FACTOR, HYPERLIQUID_CLOSE_SIZE_RELATIVE_TOLERANCE, HYPERLIQUID_POSITION_SIZE_MATCH_ABS_TOLERANCE, HYPERLIQUID_POSITION_SIZE_MATCH_RELATIVE_TOLERANCE, HYPERLIQUID_LOT_FLOOR_NOISE_DECIMALS, HYPERLIQUID_RECOVERY_BACKOFF_MAX_EXPONENT, HYPERLIQUID_RECOVERY_JITTER_MIN_FACTOR, HYPERLIQUID_RECOVERY_CONCURRENCY_GROWTH_FACTOR, UUID_BYTES, UUID_HEX_GROUP_ENDS, MSGPACK, CLIENT_RUNTIME_DEFAULT_RETRY_SECONDS, CLIENT_RUNTIME_PROVIDER_ATTEMPT_SUMMARY_MAX_CHARS, CLIENT_RUNTIME_HL_REQUEST_TYPE_MAX_CHARS, CLIENT_RUNTIME_DRAWDOWN_DEBUG_DECIMALS, CLIENT_PROTECTIVE_GROUP_VERSION, CLIENT_PROTECTIVE_TPSL_PAIR_LEGS, CLIENT_PROTECTIVE_FILL_MATCH_ABS_TOLERANCE, CLIENT_PROTECTIVE_FILL_MATCH_REL_TOLERANCE, CLIENT_CLOSE_FILL_EPSILON_ULPS, COPY_TRADING_SIZE_EPSILON, COPY_TRADING_RELATIVE_SIZE_TOLERANCE, COPY_TRADING_NOTIONAL_CAP_TOLERANCE_USD, CLIENT_ACCOUNT_PNL_NONZERO_MIN_USD, RUNTIME_PORTFOLIO_PERIOD_ENTRY_LENGTH, CLIENT_EXCHANGE_RECONCILIATION_MAX_DELAY_MS, RFC1918_172_BLOCK_SECOND_OCTET, AGENT_CLI_TAKEOVER_REQUIRED_EXIT_CODE, EXIT_CODE_INTERRUPTED, EXIT_CODE_SIGNAL_BASE, BYOK_PROVIDER_DISPLAY_ORDER_STEP, TOKENS_PER_MILLION, RENDER_DEBUG_ID_RANDOM_CHARS;
1460
+ var MS_PER_SECOND, SECONDS_PER_MINUTE, MINUTES_PER_HOUR, HOURS_PER_DAY, DAYS_PER_WEEK, MS_PER_MINUTE, SECONDS_PER_HOUR, SECONDS_PER_DAY, SECONDS_PER_WEEK, MINUTES_PER_DAY, MINUTES_PER_WEEK, MS_PER_HOUR, MS_PER_DAY, READ_STAMP_TIE_MS, READ_STAMP_STEP_BACK_MS, CLOCK_FIELD_DIGITS, BACKOFF_GROWTH_FACTOR, BYTES_PER_KIB, BYTES_PER_MIB, BITS_PER_BYTE, BYTE_MASK, OWNER_ONLY_FILE_MODE, OWNER_ONLY_DIRECTORY_MODE, GROUP_OTHER_PERMISSION_BITS, DECIMAL_RADIX, HEX_RADIX, BASE36_RADIX, BYTE_HEX_DIGITS, UINT32_HEX_DIGITS, RANDOM_FRACTION_PREFIX_LENGTH, PERCENT_SCALE, MIDPOINT_DIVISOR, SQUARE_EXPONENT, FNV1A_32_OFFSET_BASIS, FNV1A_32_PRIME, JSON_INDENT_SPACES, INT32_MIN, INT32_MAX, SET_TIMEOUT_MAX_DELAY_MS, POSITION_SIZE_EPSILON, CANDLE_TIMEFRAME_SECONDS, HTTP_STATUS, HTTP_STATUS_MIN, HTTP_STATUS_MAX, HTTP_CLIENT_ERROR_MIN, HTTP_SERVER_ERROR_MIN, AI_COST_ESTIMATE_PERIOD_DAYS, SECONDS_PER_AI_COST_ESTIMATE_PERIOD, DATE_FIELD_DIGITS, EXTERNAL_INFERENCE_LIMITS, NODE_ARGV_COMMAND_ARGS_START, EXIT_CODE_TEMPFAIL, SHA256_INITIAL_STATE, SHA256_ROUND_CONSTANTS, SHA256, UINT64_HIGH_WORD_DIVISOR, CANONICAL_BASE64URL, INFERENCE_ENVELOPE_CRYPTO, EXTERNAL_INFERENCE_SCHEMA_BOUNDS, JSON_RPC_ERROR_CODES, INFERENCE_MCP_SCHEMA_PROBE_MAX_DEPTH, INFERENCE_HOST_PROCESS_LOCK_RECORD_SCHEMA_VERSION, INFERENCE_HOST_RECLAIM_GUARD_CREATE_PASSES, LINUX_PROC_STAT_COMM_TERMINATOR_CHARS, INFERENCE_HOST_RANDOM_BYTES, INFERENCE_OAUTH_TOKEN_MAX_LENGTH, INFERENCE_CREDENTIAL_WINDOWS_NOT_FOUND_EXIT_CODE, MACOS_SECURITY_ITEM_NOT_FOUND_EXIT_CODE, INFERENCE_CREDENTIAL_LABEL_ACCOUNT_KEY_CHARS, INFERENCE_HOST_STABLE_OPERATION_ID_HASH_CHARS, INFERENCE_HOST_DRAIN_PRIORITY, INFERENCE_JOB_CLAIM_SCHEMA_VERSION, INFERENCE_HOST_WINDOWS_TASK_IDENTITY_MAX_CHARS, INFERENCE_HOST_OWNER_ONLY_EXECUTABLE_MODE, WINDOWS_TASKKILL_PROCESS_NOT_FOUND_EXIT_CODE, INFERENCE_HOST_CLI_MAX_SERVICE_POSITIONALS, INFERENCE_HOST_CLI_MAX_COMMAND_POSITIONALS, INFERENCE_HOST_DISPLAY_NAME_MAX_CHARS, INFERENCE_HOST_REVOCATION_CHECKPOINT_MAX_CHARS, INFERENCE_HOST_MODEL_ID_MAX_CHARS, CODEX_RECOVERY_RECEIPT_MAX_CHARS, CODEX_HOSTED_ATTEMPT_PATH_SEGMENTS, CODEX_GUARDIAN_PROCESS_TOKEN_BYTES, CODEX_RATE_LIMIT_EXHAUSTED_PERCENT, INFERENCE_HOST_PROXY_TOKEN_BYTES, GROK_TOOL_SERVER_TOKEN_BYTES, GROK_NATIVE_SESSION_GROUP_NAME_MAX_CHARS, GROK_POLICY_TRANSPORT_MAX_BYTES, EXO_POLICY_MAX_TOOL_ROUNDS, EXO_POLICY_MAX_MODELS, EXO_POLICY_MODEL_NAME_MAX_CHARS, EXO_RUNTIME_VERSION_COMMIT_CHARS, PI_QUALIFIED_MODEL_ID_MAX_CHARS, PI_STRUCTURED_OUTPUT_MAX_DEPTH, PI_STRUCTURED_OUTPUT_MAX_PROPERTIES, INFERENCE_HOST_API_KEY_MIN_CHARS, INFERENCE_HOST_API_KEY_MAX_BYTES, INFERENCE_HOST_API_KEY_IDENTITY_HEX_CHARS, DEEPSEEK_HARNESS_NODE_LTS_MAJOR, DEEPSEEK_HARNESS_NODE_LTS_MIN_MINOR, DEEPSEEK_HARNESS_NODE_CURRENT_MAJOR, PROMPT_FIXED_DIGITS, PROMPT_SIGNIFICANT_DIGITS, PROMPT_NUMBER_MAX_DIGITS, PROMPT_PRICE_INTEGER_THRESHOLD, PROMPT_MARGIN_UTILIZATION_DECIMALS, PROMPT_SYMBOL_MAX_CHARS, PROMPT_PARTIAL_UNIT_ROUND_UP_FRACTION, HALF_UP_ROUNDING_OFFSET, PROMPT_ENTRY_PRICE_MATCH_ABS_TOLERANCE, PROMPT_ENTRY_PRICE_MATCH_REL_TOLERANCE, DECISION_OUTPUT_EXAMPLE_TRADABILITY, INDICATOR_RSI_PERIOD, INDICATOR_ATR_PERIOD, INDICATOR_MACD_FAST_PERIOD, INDICATOR_MACD_SLOW_PERIOD, INDICATOR_MACD_SIGNAL_PERIOD, INDICATOR_BOLLINGER_PERIOD, INDICATOR_BOLLINGER_STD_DEV, INDICATOR_OSCILLATOR_MAX, EMA_SMOOTHING_NUMERATOR, PROMPT_EMA_PERIODS, JSON_UNICODE_ESCAPE_PREFIX_LENGTH, JSON_UNICODE_ESCAPE_HEX_DIGITS, JSON_CONTROL_CHARACTER_MAX, RUNTIME_DEBUG_SNIPPET_CHARS, RUNTIME_DEBUG_PROMPT_SNIPPET_CHARS, RUNTIME_DEBUG_TOKEN_PREFIX_CHARS, RUNTIME_DEBUG_USD_DECIMALS, REVIEW_FAILURE_DETAIL_MAX_CHARS, RUNTIME_LATENCY_SECONDS_DECIMALS, AI_SCHEDULE_CLOCK_PARTS, ESTIMATED_CHARS_PER_TOKEN, PROVIDER_ERROR_RAW_TEXT_MAX_CHARS, AI_CALL_COST_DECIMALS, PROVIDER_DIAGNOSTIC_LIMITS, AI_INVOCATION_CONTRACT_VERSION, AI_INVOCATION_TELEMETRY_LIMITS, PROVIDER_USAGE_DETAIL_LIMITS, HYPERLIQUID_EXCHANGE_SPECIFICATION, HYPERLIQUID_TPSL_BATCH_MIN_ORDERS, HYPERLIQUID_USER_FILLS_PROVIDER_PAGE_CAP, HYPERLIQUID_ROW_WEIGHTED_INFO_REQUESTS, HYPERLIQUID_INFO_ROWS_PER_EXTRA_WEIGHT, HYPERLIQUID_META_AND_ASSET_CTXS_PARTS, HYPERLIQUID_SIDE_PAIR_LENGTH, HYPERLIQUID_SIGNED_SIZE_MATCH_EXTRA_DECIMALS, HYPERLIQUID_OPEN_ORDERS_MAX_NESTING_DEPTH, ACCOUNT_PAYLOAD_MODE_SEARCH_MAX_DEPTH, HYPERLIQUID_ACCOUNT_ROUNDING_DECIMALS, HYPERLIQUID_UNREALIZED_PNL_ZERO_TOLERANCE, HYPERLIQUID_MAX_DEPLOYER_FEE_SCALE, HYPERLIQUID_DEPLOYER_FEE_SCALE_MULTIPLIER, HYPERLIQUID_GROWTH_MODE_FEE_FACTOR, HYPERLIQUID_ALIGNED_QUOTE_NON_DEPLOYER_FEE_FACTOR, HYPERLIQUID_CLOSE_SIZE_RELATIVE_TOLERANCE, HYPERLIQUID_POSITION_SIZE_MATCH_ABS_TOLERANCE, HYPERLIQUID_POSITION_SIZE_MATCH_RELATIVE_TOLERANCE, HYPERLIQUID_LOT_FLOOR_NOISE_DECIMALS, HYPERLIQUID_RECOVERY_BACKOFF_MAX_EXPONENT, HYPERLIQUID_RECOVERY_CONCURRENCY_GROWTH_FACTOR, UUID_BYTES, UUID_HEX_GROUP_ENDS, MSGPACK, CLIENT_RUNTIME_DEFAULT_RETRY_SECONDS, CLIENT_RUNTIME_PROVIDER_ATTEMPT_SUMMARY_MAX_CHARS, CLIENT_RUNTIME_HL_REQUEST_TYPE_MAX_CHARS, CLIENT_RUNTIME_DRAWDOWN_DEBUG_DECIMALS, CLIENT_PROTECTIVE_GROUP_VERSION, CLIENT_PROTECTIVE_TPSL_PAIR_LEGS, CLIENT_PROTECTIVE_FILL_MATCH_ABS_TOLERANCE, CLIENT_PROTECTIVE_FILL_MATCH_REL_TOLERANCE, CLIENT_CLOSE_FILL_EPSILON_ULPS, COPY_TRADING_SIZE_EPSILON, COPY_TRADING_RELATIVE_SIZE_TOLERANCE, COPY_TRADING_NOTIONAL_CAP_TOLERANCE_USD, CLIENT_ACCOUNT_PNL_NONZERO_MIN_USD, RUNTIME_PORTFOLIO_PERIOD_ENTRY_LENGTH, CLIENT_EXCHANGE_RECONCILIATION_MAX_DELAY_MS, RFC1918_172_BLOCK_SECOND_OCTET, AGENT_CLI_TAKEOVER_REQUIRED_EXIT_CODE, EXIT_CODE_INTERRUPTED, EXIT_CODE_SIGNAL_BASE, BYOK_PROVIDER_DISPLAY_ORDER_STEP, TOKENS_PER_MILLION, RENDER_DEBUG_ID_RANDOM_CHARS;
1460
1461
  var init_constants = __esm({
1461
1462
  "lib/constants.ts"() {
1462
1463
  "use strict";
@@ -1903,6 +1904,16 @@ var init_constants = __esm({
1903
1904
  };
1904
1905
  HYPERLIQUID_TPSL_BATCH_MIN_ORDERS = 2;
1905
1906
  HYPERLIQUID_USER_FILLS_PROVIDER_PAGE_CAP = 2e3;
1907
+ HYPERLIQUID_ROW_WEIGHTED_INFO_REQUESTS = [
1908
+ "userFills",
1909
+ "userFillsByTime",
1910
+ "historicalOrders",
1911
+ "twapHistory",
1912
+ "userTwapSliceFills",
1913
+ "userFunding",
1914
+ "userNonFundingLedgerUpdates"
1915
+ ];
1916
+ HYPERLIQUID_INFO_ROWS_PER_EXTRA_WEIGHT = 20;
1906
1917
  HYPERLIQUID_META_AND_ASSET_CTXS_PARTS = 2;
1907
1918
  HYPERLIQUID_SIDE_PAIR_LENGTH = 2;
1908
1919
  HYPERLIQUID_SIGNED_SIZE_MATCH_EXTRA_DECIMALS = 4;
@@ -1919,7 +1930,6 @@ var init_constants = __esm({
1919
1930
  HYPERLIQUID_POSITION_SIZE_MATCH_RELATIVE_TOLERANCE = 1e-8;
1920
1931
  HYPERLIQUID_LOT_FLOOR_NOISE_DECIMALS = 6;
1921
1932
  HYPERLIQUID_RECOVERY_BACKOFF_MAX_EXPONENT = 30;
1922
- HYPERLIQUID_RECOVERY_JITTER_MIN_FACTOR = 0.5;
1923
1933
  HYPERLIQUID_RECOVERY_CONCURRENCY_GROWTH_FACTOR = 2;
1924
1934
  UUID_BYTES = 16;
1925
1935
  UUID_HEX_GROUP_ENDS = [8, 12, 16, 20, 32];
@@ -21049,6 +21059,7 @@ var init_runtime_policy_generated2 = __esm({
21049
21059
  public_recovery: {
21050
21060
  fallback_initial_seconds: 2,
21051
21061
  fallback_max_seconds: 60,
21062
+ fallback_jitter_min_factor: 0.5,
21052
21063
  permit_lease_seconds: 60,
21053
21064
  recovery_initial_concurrency: 1,
21054
21065
  recovery_max_concurrency: 8,
@@ -54243,6 +54254,101 @@ var init_monotonic_clock = __esm({
54243
54254
  }
54244
54255
  });
54245
54256
 
54257
+ // lib/runtime/hyperliquid-market-symbol.ts
54258
+ var configuredCaseSensitiveSymbols, isHyperliquidSpotSymbol, normalizeCaseSensitiveSymbols, configureHyperliquidMarketSymbolCasing, canonicalBaseSymbol, normalizeHyperliquidMarketSymbol, getHyperliquidMarketDex;
54259
+ var init_hyperliquid_market_symbol = __esm({
54260
+ "lib/runtime/hyperliquid-market-symbol.ts"() {
54261
+ "use strict";
54262
+ init_define_VTX_EXO_POLICY();
54263
+ init_define_VTX_GROK_POLICY();
54264
+ init_define_VTX_PI_MODEL_POLICY();
54265
+ configuredCaseSensitiveSymbols = [];
54266
+ isHyperliquidSpotSymbol = (value) => {
54267
+ const symbol2 = typeof value === "string" ? value.trim() : "";
54268
+ return symbol2.startsWith("@") || symbol2.includes("/");
54269
+ };
54270
+ normalizeCaseSensitiveSymbols = (symbols) => {
54271
+ if (!Array.isArray(symbols)) return [];
54272
+ const out = [];
54273
+ const seen = /* @__PURE__ */ new Set();
54274
+ for (const item of symbols) {
54275
+ const value = String(item ?? "").trim();
54276
+ if (!value) continue;
54277
+ const key = value.toUpperCase();
54278
+ if (seen.has(key)) continue;
54279
+ seen.add(key);
54280
+ out.push(value);
54281
+ }
54282
+ return out;
54283
+ };
54284
+ configureHyperliquidMarketSymbolCasing = (symbols) => {
54285
+ configuredCaseSensitiveSymbols = normalizeCaseSensitiveSymbols(symbols);
54286
+ };
54287
+ canonicalBaseSymbol = (base) => {
54288
+ const trimmed = base.trim();
54289
+ if (!trimmed) return "";
54290
+ const upper = trimmed.toUpperCase();
54291
+ for (const candidate of configuredCaseSensitiveSymbols) {
54292
+ if (candidate.toUpperCase() === upper) {
54293
+ return candidate;
54294
+ }
54295
+ }
54296
+ return upper;
54297
+ };
54298
+ normalizeHyperliquidMarketSymbol = (value) => {
54299
+ const raw = String(value ?? "").trim();
54300
+ if (!raw) return "";
54301
+ if (!raw.includes(":")) return canonicalBaseSymbol(raw);
54302
+ const [dex, ...rest] = raw.split(":");
54303
+ const base = rest.join(":").trim();
54304
+ const normalizedDex = dex.trim().toLowerCase();
54305
+ if (!normalizedDex || !base) return "";
54306
+ return `${normalizedDex}:${canonicalBaseSymbol(base)}`;
54307
+ };
54308
+ getHyperliquidMarketDex = (value) => {
54309
+ const normalized = normalizeHyperliquidMarketSymbol(value);
54310
+ if (!normalized.includes(":")) return "";
54311
+ return normalized.split(":", 1)[0];
54312
+ };
54313
+ }
54314
+ });
54315
+
54316
+ // lib/runtime/bot-exchanges.ts
54317
+ var exchangesByProfile, profileKey, dexList, recordBotExchanges, recordStatusExchanges;
54318
+ var init_bot_exchanges = __esm({
54319
+ "lib/runtime/bot-exchanges.ts"() {
54320
+ "use strict";
54321
+ init_define_VTX_EXO_POLICY();
54322
+ init_define_VTX_GROK_POLICY();
54323
+ init_define_VTX_PI_MODEL_POLICY();
54324
+ init_hyperliquid_market_symbol();
54325
+ exchangesByProfile = /* @__PURE__ */ new Map();
54326
+ profileKey = (profileId) => {
54327
+ const id2 = Number(profileId);
54328
+ return Number.isInteger(id2) && id2 > 0 ? id2 : null;
54329
+ };
54330
+ dexList = (value) => Array.isArray(value) && value.every((dex) => typeof dex === "string") ? value.map((dex) => dex.trim().toLowerCase()) : null;
54331
+ recordBotExchanges = (profileId, equityVenues, readVenues) => {
54332
+ const id2 = profileKey(profileId);
54333
+ if (id2 === null) return;
54334
+ const equity = dexList(equityVenues);
54335
+ const read = readVenues === void 0 ? equity : dexList(readVenues);
54336
+ if (!equity || !read) {
54337
+ exchangesByProfile.delete(id2);
54338
+ return;
54339
+ }
54340
+ exchangesByProfile.set(id2, { equity, read });
54341
+ };
54342
+ recordStatusExchanges = (status) => {
54343
+ const fields = status;
54344
+ if (fields && typeof fields === "object" && "equity_venues" in fields) {
54345
+ recordBotExchanges(fields.profile_id, fields.equity_venues, fields.read_venues);
54346
+ }
54347
+ return status;
54348
+ };
54349
+ }
54350
+ });
54351
+
54246
54352
  // lib/runtime/local-breadcrumbs.ts
54247
54353
  var LOCAL_RUNTIME_BREADCRUMBS_STORAGE_KEY, DEVICE_DIAGNOSTICS2, LOCAL_RUNTIME_BREADCRUMBS_MAX_ENTRIES, LOCAL_RUNTIME_BREADCRUMBS_MAX_DETAIL_LENGTH, TRUNCATION_ELLIPSIS, safeWindow, sanitizeText, sanitizeOptionalString, clonePayload, buildBreadcrumbId, coerceBreadcrumb, readLocalRuntimeBreadcrumbs, writeLocalRuntimeBreadcrumbs, buildLocalRuntimeEnvironmentSnapshot, appendClientRuntimeLocalBreadcrumb, clearLocalRuntimeBreadcrumbs, flushLocalRuntimeBreadcrumbs;
54248
54354
  var init_local_breadcrumbs = __esm({
@@ -54755,6 +54861,17 @@ var init_updates = __esm({
54755
54861
  }
54756
54862
  });
54757
54863
 
54864
+ // lib/api/profile-emoji.ts
54865
+ var init_profile_emoji = __esm({
54866
+ "lib/api/profile-emoji.ts"() {
54867
+ "use strict";
54868
+ init_define_VTX_EXO_POLICY();
54869
+ init_define_VTX_GROK_POLICY();
54870
+ init_define_VTX_PI_MODEL_POLICY();
54871
+ init_shared();
54872
+ }
54873
+ });
54874
+
54758
54875
  // lib/runtime/host-storage.ts
54759
54876
  function configureRuntimeHostStorage(storage3) {
54760
54877
  configuredStorage = storage3;
@@ -55361,7 +55478,7 @@ var init_hyperliquid_order_status = __esm({
55361
55478
  });
55362
55479
 
55363
55480
  // lib/runtime/hyperliquid-public-read.ts
55364
- var policy, weights, recoveryPolicy, budgets, unpersistedBudgets, cache, pending2, PREFIX, priorityRank, createHyperliquidPublicPriorityScope, promoteHyperliquidPublicPriority, hostTransport, abortError2, checkAbort, wait, waitUnlessPromoted, storage, loadBudget, saveBudget, withBudgetLock, HyperliquidPublicReadError, getHyperliquidPublicReadBudget, cooldownError, recoveryWaitError, nonTradingWeightCap, nonTradingWaitMs, fallbackDelayMs, admit, cooldown, finishHyperliquidRecoveryRequest, assertHyperliquidRecoveryDispatch, validateHyperliquidRecoveryDispatch, cacheTtlMs, eligibleCache, reserveHyperliquidPublicReads, releaseHyperliquidPublicReadReservation, admitHyperliquidExchangeRequest, recordHyperliquidExchangeResponse, readHyperliquidPublicInfo;
55481
+ var policy, weights, recoveryPolicy, budgets, unpersistedBudgets, cache, pending2, PREFIX, priorityRank, createHyperliquidPublicPriorityScope, promoteHyperliquidPublicPriority, hostTransport, abortError2, checkAbort, wait, waitUnlessPromoted, storage, loadBudget, saveBudget, withBudgetLock, HyperliquidPublicReadError, getHyperliquidPublicReadBudget, cooldownError, recoveryWaitError, nonTradingWeightCap, nonTradingWaitMs, fallbackDelayMs, admit, settleRowWeightedReservation, cooldown, finishHyperliquidRecoveryRequest, assertHyperliquidRecoveryDispatch, validateHyperliquidRecoveryDispatch, cacheTtlMs, eligibleCache, reserveHyperliquidPublicReads, releaseHyperliquidPublicReadReservation, admitHyperliquidExchangeRequest, recordHyperliquidExchangeResponse, readHyperliquidPublicInfo;
55365
55482
  var init_hyperliquid_public_read = __esm({
55366
55483
  "lib/runtime/hyperliquid-public-read.ts"() {
55367
55484
  "use strict";
@@ -55517,9 +55634,9 @@ var init_hyperliquid_public_read = __esm({
55517
55634
  };
55518
55635
  fallbackDelayMs = (failures) => Math.min(
55519
55636
  recoveryPolicy.fallback_max_seconds * MS_PER_SECOND,
55520
- recoveryPolicy.fallback_initial_seconds * MS_PER_SECOND * BACKOFF_GROWTH_FACTOR ** Math.min(HYPERLIQUID_RECOVERY_BACKOFF_MAX_EXPONENT, Math.max(0, failures - 1)) * (HYPERLIQUID_RECOVERY_JITTER_MIN_FACTOR + Math.random())
55637
+ recoveryPolicy.fallback_initial_seconds * MS_PER_SECOND * BACKOFF_GROWTH_FACTOR ** Math.min(HYPERLIQUID_RECOVERY_BACKOFF_MAX_EXPONENT, Math.max(0, failures - 1)) * (recoveryPolicy.fallback_jitter_min_factor + Math.random())
55521
55638
  );
55522
- admit = async (apiUrl, requestType, signal, weightOverride, deadlineMs, priority) => {
55639
+ admit = async (apiUrl, requestType, signal, weightOverride, deadlineMs, priority, reservationId) => {
55523
55640
  const key = `${PREFIX}${apiUrl}`;
55524
55641
  const weight = weightOverride ?? weights[requestType] ?? policy.default_request_weight;
55525
55642
  const ticket = crypto.randomUUID();
@@ -55578,7 +55695,7 @@ var init_hyperliquid_public_read = __esm({
55578
55695
  permit = { endpoint: apiUrl, id: ticket, generation: recovery.generation, expiresAt };
55579
55696
  }
55580
55697
  budget.reservations = budget.reservations.filter((entry) => entry.at > now - policy.window_seconds * MS_PER_SECOND);
55581
- budget.reservations.push({ at: now, weight });
55698
+ budget.reservations.push({ at: now, weight, ...reservationId ? { id: reservationId } : {} });
55582
55699
  saveBudget(key, budget);
55583
55700
  return { ready: true, permit, waitMs: 0 };
55584
55701
  });
@@ -55598,9 +55715,20 @@ var init_hyperliquid_public_read = __esm({
55598
55715
  });
55599
55716
  }
55600
55717
  };
55601
- cooldown = async (apiUrl, retryAfter, requestType) => {
55718
+ settleRowWeightedReservation = async (apiUrl, reservationId, rows) => {
55719
+ const key = `${PREFIX}${apiUrl}`;
55720
+ const charged = policy.default_request_weight + Math.floor(rows / HYPERLIQUID_INFO_ROWS_PER_EXTRA_WEIGHT);
55721
+ await withBudgetLock(key, void 0, () => {
55722
+ const budget = loadBudget(key);
55723
+ const reservation = budget.reservations.find((entry) => entry.id === reservationId);
55724
+ if (!reservation || charged >= reservation.weight) return;
55725
+ reservation.weight = charged;
55726
+ saveBudget(key, budget);
55727
+ });
55728
+ };
55729
+ cooldown = async (apiUrl, retryAfter, requestType, priority) => {
55602
55730
  if (hostTransport) {
55603
- await hostTransport.admission.record429(retryAfter, requestType);
55731
+ await hostTransport.admission.record429(retryAfter, requestType, priority);
55604
55732
  return;
55605
55733
  }
55606
55734
  const key = `${PREFIX}${apiUrl}`;
@@ -55706,8 +55834,8 @@ var init_hyperliquid_public_read = __esm({
55706
55834
  const weight = weights.exchange + Math.floor(batchLength / runtime_policy_generated_default2.exchange.hyperliquid.read_budget.exchange_action_batch_size);
55707
55835
  return admit(endpoint.replace(/\/$/, ""), "exchange", signal, weight, void 0, createHyperliquidPublicPriorityScope(priority));
55708
55836
  };
55709
- recordHyperliquidExchangeResponse = async (endpoint, response, permit) => {
55710
- if (response.status === HTTP_STATUS.TOO_MANY_REQUESTS) await cooldown(endpoint.replace(/\/$/, ""), response.headers.get("Retry-After"), "exchange");
55837
+ recordHyperliquidExchangeResponse = async (endpoint, response, permit, priority) => {
55838
+ if (response.status === HTTP_STATUS.TOO_MANY_REQUESTS) await cooldown(endpoint.replace(/\/$/, ""), response.headers.get("Retry-After"), "exchange", priority);
55711
55839
  await finishHyperliquidRecoveryRequest(permit, response.status < HTTP_CLIENT_ERROR_MIN ? "success" : "failure");
55712
55840
  };
55713
55841
  readHyperliquidPublicInfo = async (endpoint, body, options) => {
@@ -55737,6 +55865,7 @@ var init_hyperliquid_public_read = __esm({
55737
55865
  };
55738
55866
  armDeadline(deadline);
55739
55867
  let permit = null;
55868
+ const rowWeightedReservationId = !hostTransport && HYPERLIQUID_ROW_WEIGHTED_INFO_REQUESTS.includes(requestType) ? crypto.randomUUID() : void 0;
55740
55869
  let outcome = "cancelled";
55741
55870
  let settled;
55742
55871
  let acquiring = false;
@@ -55791,12 +55920,15 @@ var init_hyperliquid_public_read = __esm({
55791
55920
  if (!privateRoute) {
55792
55921
  acquiring = true;
55793
55922
  setPendingPhase("admission");
55794
- permit = await admit(apiUrl, requestType, signal, void 0, deadline, priority);
55923
+ permit = await admit(apiUrl, requestType, signal, void 0, deadline, priority, rowWeightedReservationId);
55795
55924
  acquiring = false;
55796
55925
  armDeadline(Math.min(deadline, permit?.expiresAt ?? Infinity));
55797
55926
  checkAbort(signal);
55798
55927
  if (options.reservation?.closed) throw new DOMException("Hyperliquid account read was cancelled.", "AbortError");
55799
55928
  await validateHyperliquidRecoveryDispatch(apiUrl, permit, requestType);
55929
+ checkAbort(signal);
55930
+ if (options.reservation?.closed) throw new DOMException("Hyperliquid account read was cancelled.", "AbortError");
55931
+ hostTransport?.onPublicInfoSent?.(body);
55800
55932
  }
55801
55933
  outcome = "failure";
55802
55934
  let transportAborted;
@@ -55819,7 +55951,7 @@ var init_hyperliquid_public_read = __esm({
55819
55951
  checkAbort(signal);
55820
55952
  if (received.status === HTTP_STATUS.TOO_MANY_REQUESTS) {
55821
55953
  observedRateLimit = new HyperliquidPublicReadError("public_rate_limited", "Hyperliquid public API returned HTTP 429.", requestType, HTTP_STATUS.TOO_MANY_REQUESTS);
55822
- if (!privateRoute) await cooldown(apiUrl, received.headers.get("Retry-After"), requestType);
55954
+ if (!privateRoute) await cooldown(apiUrl, received.headers.get("Retry-After"), requestType, priority.value);
55823
55955
  throw observedRateLimit;
55824
55956
  }
55825
55957
  let receivedText;
@@ -55854,6 +55986,12 @@ var init_hyperliquid_public_read = __esm({
55854
55986
  });
55855
55987
  }
55856
55988
  outcome = "success";
55989
+ if (rowWeightedReservationId && !privateRoute && Array.isArray(payload)) {
55990
+ try {
55991
+ await settleRowWeightedReservation(apiUrl, rowWeightedReservationId, payload.length);
55992
+ } catch {
55993
+ }
55994
+ }
55857
55995
  const result = { payload, fetchedAtMs: Date.now(), ...bodyText !== void 0 ? { bodyText } : {} };
55858
55996
  if (ttlMs) {
55859
55997
  cache.set(key, result);
@@ -55922,65 +56060,6 @@ var init_hyperliquid_exchange_rejections = __esm({
55922
56060
  }
55923
56061
  });
55924
56062
 
55925
- // lib/runtime/hyperliquid-market-symbol.ts
55926
- var configuredCaseSensitiveSymbols, isHyperliquidSpotSymbol, normalizeCaseSensitiveSymbols, configureHyperliquidMarketSymbolCasing, canonicalBaseSymbol, normalizeHyperliquidMarketSymbol, getHyperliquidMarketDex;
55927
- var init_hyperliquid_market_symbol = __esm({
55928
- "lib/runtime/hyperliquid-market-symbol.ts"() {
55929
- "use strict";
55930
- init_define_VTX_EXO_POLICY();
55931
- init_define_VTX_GROK_POLICY();
55932
- init_define_VTX_PI_MODEL_POLICY();
55933
- configuredCaseSensitiveSymbols = [];
55934
- isHyperliquidSpotSymbol = (value) => {
55935
- const symbol2 = typeof value === "string" ? value.trim() : "";
55936
- return symbol2.startsWith("@") || symbol2.includes("/");
55937
- };
55938
- normalizeCaseSensitiveSymbols = (symbols) => {
55939
- if (!Array.isArray(symbols)) return [];
55940
- const out = [];
55941
- const seen = /* @__PURE__ */ new Set();
55942
- for (const item of symbols) {
55943
- const value = String(item ?? "").trim();
55944
- if (!value) continue;
55945
- const key = value.toUpperCase();
55946
- if (seen.has(key)) continue;
55947
- seen.add(key);
55948
- out.push(value);
55949
- }
55950
- return out;
55951
- };
55952
- configureHyperliquidMarketSymbolCasing = (symbols) => {
55953
- configuredCaseSensitiveSymbols = normalizeCaseSensitiveSymbols(symbols);
55954
- };
55955
- canonicalBaseSymbol = (base) => {
55956
- const trimmed = base.trim();
55957
- if (!trimmed) return "";
55958
- const upper = trimmed.toUpperCase();
55959
- for (const candidate of configuredCaseSensitiveSymbols) {
55960
- if (candidate.toUpperCase() === upper) {
55961
- return candidate;
55962
- }
55963
- }
55964
- return upper;
55965
- };
55966
- normalizeHyperliquidMarketSymbol = (value) => {
55967
- const raw = String(value ?? "").trim();
55968
- if (!raw) return "";
55969
- if (!raw.includes(":")) return canonicalBaseSymbol(raw);
55970
- const [dex, ...rest] = raw.split(":");
55971
- const base = rest.join(":").trim();
55972
- const normalizedDex = dex.trim().toLowerCase();
55973
- if (!normalizedDex || !base) return "";
55974
- return `${normalizedDex}:${canonicalBaseSymbol(base)}`;
55975
- };
55976
- getHyperliquidMarketDex = (value) => {
55977
- const normalized = normalizeHyperliquidMarketSymbol(value);
55978
- if (!normalized.includes(":")) return "";
55979
- return normalized.split(":", 1)[0];
55980
- };
55981
- }
55982
- });
55983
-
55984
56063
  // lib/runtime/exchange-mutation-fence.ts
55985
56064
  var activeSettlementsByScope, normalizeScope, trackBrowserExchangeMutation, waitForBrowserExchangeMutationSettlement;
55986
56065
  var init_exchange_mutation_fence = __esm({
@@ -89555,7 +89634,7 @@ var init_hyperliquid_client = __esm({
89555
89634
  });
89556
89635
  if (transportController.signal.aborted) throw transportController.signal.reason;
89557
89636
  responseStatus = received.status;
89558
- await recordHyperliquidExchangeResponse(apiUrl, received);
89637
+ await recordHyperliquidExchangeResponse(apiUrl, received, void 0, input.publicRequestPriority);
89559
89638
  const body = await received.json().catch(() => ({}));
89560
89639
  if (transportController.signal.aborted) throw transportController.signal.reason;
89561
89640
  return { response: received, payload: body };
@@ -90092,7 +90171,7 @@ async function getAiTradingStatus(cookie, profileId, options) {
90092
90171
  const message = await getErrorMessageFromResponse(response, "Failed to get AI Trader status", { fallbackDetail: true });
90093
90172
  throw new Error(message);
90094
90173
  }
90095
- return response.json();
90174
+ return recordStatusExchanges(await response.json());
90096
90175
  }, { cookie });
90097
90176
  }
90098
90177
  async function postClientRuntime(path, profileId, body, options) {
@@ -90668,7 +90747,7 @@ async function recordServerHostExecutionAudit(profileId, payload, signal, requir
90668
90747
  { ...authority.requestOptions, signal }
90669
90748
  );
90670
90749
  }
90671
- async function checkServerHostExecutionCapacity(profileId, plans, signal, requiredRuntimeSessionId, explicitRuntimeLeaseToken, explicitRuntimeDeviceId, explicitSchedulerInstanceId) {
90750
+ async function checkServerHostExecutionCapacity(profileId, plans, signal, requiredRuntimeSessionId, explicitRuntimeLeaseToken, explicitRuntimeDeviceId, explicitSchedulerInstanceId, cycleStartedAt) {
90672
90751
  const authority = resolveClientExchangeMutationAuthority(
90673
90752
  profileId,
90674
90753
  requiredRuntimeSessionId,
@@ -90681,7 +90760,9 @@ async function checkServerHostExecutionCapacity(profileId, plans, signal, requir
90681
90760
  authority.numericProfileId,
90682
90761
  JSON.stringify({
90683
90762
  ...clientExchangeMutationAuthorityBody(authority),
90684
- plans
90763
+ plans,
90764
+ cycle_started_at: cycleStartedAt || void 0
90765
+ // an order VTX sent since then refuses the batch
90685
90766
  }),
90686
90767
  { ...authority.requestOptions, signal }
90687
90768
  );
@@ -91325,6 +91406,7 @@ var init_api2 = __esm({
91325
91406
  init_google_auth_url();
91326
91407
  init_network_debug();
91327
91408
  init_monotonic_clock();
91409
+ init_bot_exchanges();
91328
91410
  init_local_breadcrumbs();
91329
91411
  init_abort();
91330
91412
  init_client_runtime_ownership_errors();
@@ -91337,6 +91419,7 @@ var init_api2 = __esm({
91337
91419
  init_client_host_commands();
91338
91420
  init_insights_access_center();
91339
91421
  init_updates();
91422
+ init_profile_emoji();
91340
91423
  init_server_runtime_lease();
91341
91424
  clientRuntimeSecretHeaders = (profileId) => {
91342
91425
  const headers = getProfileHeaders({}, profileId);
@@ -93876,7 +93959,7 @@ var init_hyperliquid_fee_contract = __esm({
93876
93959
  });
93877
93960
 
93878
93961
  // lib/runtime/hyperliquid-account-state-adapter.ts
93879
- var USER_FILLS_CACHE_STORAGE_PREFIX, ACCOUNT_STATE_CACHE_STORAGE_PREFIX, browserUserFillsCache, browserUserFillsInFlight, browserAccountStateCache, browserAccountStateInFlight, toPositiveFinite, toFinite, firstFiniteNumber2, parseFundingUsdcFromInfoPosition2, buildUserFillsCacheKey, buildUserFillsStorageKey, buildAccountStateCacheKey, buildAccountStateStorageKey, hasActiveInfoRateLimitCooldown, requireNonNegativeConfigSeconds, requireAccountStateCacheConfig, requireUserFillsCacheConfig, normalizeFillSymbol, buildSymbolFilter, filterFillsBySymbols, readBrowserUserFillsCache, writeBrowserUserFillsCache, cloneBrowserAccountStateResult, withAccountStateEvidence, readBrowserAccountStateCache, writeBrowserAccountStateCache, isRateLimitError, createAbortError, waitForSharedBrowserRequest, waitForSharedBrowserUserFills, normalizeHyperliquidErrorDetail, parseInfoPositions, requireFinitePromptMetric, requirePromptClearinghouseState, requirePromptSpotState, normalizePerpDexName, listConfiguredPerpDexs, listPerpDexsForAccountState, prefixHip3PositionCoins, aggregateClearinghouseResponses, hasCompletePerpDexAccountMetrics, normalizeBrowserFillToTradeHistory, isPerpFill, settleAccountReads, fetchHyperliquidInfoRead, fetchHyperliquidInfoPayload, requireHyperliquidApiUrl, requireWalletAddress3, parseInfoPositionSnapshot, fetchBrowserAccountState2, fetchBrowserAccountStateUncached, fetchBrowserUserFills, fetchBrowserPositionSnapshot;
93962
+ var USER_FILLS_CACHE_STORAGE_PREFIX, ACCOUNT_STATE_CACHE_STORAGE_PREFIX, browserUserFillsCache, browserUserFillsPages, browserUserFillsInFlight, browserAccountStateCache, browserAccountStateInFlight, toPositiveFinite, toFinite, firstFiniteNumber2, parseFundingUsdcFromInfoPosition2, buildUserFillsCacheKey, buildUserFillsStorageKey, buildAccountStateCacheKey, buildAccountStateStorageKey, hasActiveInfoRateLimitCooldown, requireNonNegativeConfigSeconds, requireAccountStateCacheConfig, requireUserFillsCacheConfig, normalizeFillSymbol, buildSymbolFilter, filterFillsBySymbols, readBrowserUserFillsCache, writeBrowserUserFillsCache, cloneBrowserAccountStateResult, withAccountStateEvidence, readBrowserAccountStateCache, writeBrowserAccountStateCache, isRateLimitError, createAbortError, waitForSharedBrowserRequest, waitForSharedBrowserUserFills, normalizeHyperliquidErrorDetail, parseInfoPositions, requireFinitePromptMetric, requirePromptClearinghouseState, requirePromptSpotState, normalizePerpDexName, listConfiguredPerpDexs, listPerpDexsForAccountState, prefixHip3PositionCoins, aggregateClearinghouseResponses, hasCompletePerpDexAccountMetrics, normalizeBrowserFillToTradeHistory, isPerpFill, settleAccountReads, fetchHyperliquidInfoRead, fetchHyperliquidInfoPayload, requireHyperliquidApiUrl, requireWalletAddress3, parseInfoPositionSnapshot, fetchBrowserAccountState2, fetchBrowserAccountStateUncached, mergeNewerUserFills, fetchBrowserUserFills, fetchBrowserPositionSnapshot;
93880
93963
  var init_hyperliquid_account_state_adapter = __esm({
93881
93964
  "lib/runtime/hyperliquid-account-state-adapter.ts"() {
93882
93965
  "use strict";
@@ -93897,6 +93980,7 @@ var init_hyperliquid_account_state_adapter = __esm({
93897
93980
  USER_FILLS_CACHE_STORAGE_PREFIX = "vtx:hyperliquid:user-fills:v1:";
93898
93981
  ACCOUNT_STATE_CACHE_STORAGE_PREFIX = "vtx:hyperliquid:account-state:v1:";
93899
93982
  browserUserFillsCache = /* @__PURE__ */ new Map();
93983
+ browserUserFillsPages = /* @__PURE__ */ new Map();
93900
93984
  browserUserFillsInFlight = /* @__PURE__ */ new Map();
93901
93985
  browserAccountStateCache = /* @__PURE__ */ new Map();
93902
93986
  browserAccountStateInFlight = /* @__PURE__ */ new Map();
@@ -94891,6 +94975,24 @@ var init_hyperliquid_account_state_adapter = __esm({
94891
94975
  await releaseHyperliquidPublicReadReservation(reservation);
94892
94976
  }
94893
94977
  };
94978
+ mergeNewerUserFills = (page, newer) => {
94979
+ const startTime = Number(page[0]?.time);
94980
+ if (!Number.isSafeInteger(startTime) || newer.length >= HYPERLIQUID_USER_FILLS_PROVIDER_PAGE_CAP) return null;
94981
+ const overlap = page.filter((fill) => Number(fill.time) === startTime).reverse();
94982
+ if (newer.length < overlap.length) return null;
94983
+ const added = [];
94984
+ for (const [index, fill] of newer.entries()) {
94985
+ if (!fill || typeof fill !== "object" || Array.isArray(fill)) return null;
94986
+ if (index < overlap.length) {
94987
+ if (JSON.stringify(fill) !== JSON.stringify(overlap[index])) return null;
94988
+ continue;
94989
+ }
94990
+ const time3 = Number(fill.time);
94991
+ if (!Number.isSafeInteger(time3) || time3 < startTime) return null;
94992
+ added.push(fill);
94993
+ }
94994
+ return [...added.reverse(), ...page].slice(0, HYPERLIQUID_USER_FILLS_PROVIDER_PAGE_CAP);
94995
+ };
94894
94996
  fetchBrowserUserFills = async (input) => {
94895
94997
  configureHyperliquidMarketSymbolCasing(input.config.client_runtime_hyperliquid_case_sensitive_symbols);
94896
94998
  const apiUrl = requireHyperliquidApiUrl(input.config);
@@ -94953,13 +95055,27 @@ var init_hyperliquid_account_state_adapter = __esm({
94953
95055
  let inFlight = existingFlight?.promise;
94954
95056
  if (!inFlight) {
94955
95057
  let freshRequest;
94956
- freshRequest = fetchHyperliquidInfoPayload(
94957
- apiUrl,
94958
- { type: "userFills", user: walletAddress },
94959
- void 0,
94960
- void 0,
94961
- priority
94962
- ).then((payload) => {
95058
+ const previousPage = browserUserFillsPages.get(cacheKey);
95059
+ freshRequest = (async () => {
95060
+ if (previousPage && previousPage.length > 0) {
95061
+ const newer = await fetchHyperliquidInfoPayload(
95062
+ apiUrl,
95063
+ { type: "userFillsByTime", user: walletAddress, startTime: Number(previousPage[0].time), aggregateByTime: false },
95064
+ void 0,
95065
+ void 0,
95066
+ priority
95067
+ );
95068
+ const page = Array.isArray(newer) ? mergeNewerUserFills(previousPage, newer) : null;
95069
+ if (page) return page;
95070
+ }
95071
+ return fetchHyperliquidInfoPayload(
95072
+ apiUrl,
95073
+ { type: "userFills", user: walletAddress },
95074
+ void 0,
95075
+ void 0,
95076
+ priority
95077
+ );
95078
+ })().then((payload) => {
94963
95079
  const providerRowCount2 = Array.isArray(payload) ? payload.length : 0;
94964
95080
  const rawFills2 = Array.isArray(payload) ? payload.filter(isPerpFill).map((fill) => ({ ...fill })) : [];
94965
95081
  const fillTimes = Array.isArray(payload) ? payload.map((fill) => Number(fill?.time)).filter((time3) => Number.isSafeInteger(time3) && time3 > 0) : [];
@@ -94969,6 +95085,11 @@ var init_hyperliquid_account_state_adapter = __esm({
94969
95085
  providerRowCount: providerRowCount2,
94970
95086
  oldestFillTimeMs: fillTimes.length > 0 ? Math.min(...fillTimes) : null
94971
95087
  };
95088
+ if (Array.isArray(payload) && payload.every((fill) => fill !== null && typeof fill === "object" && !Array.isArray(fill))) {
95089
+ browserUserFillsPages.set(cacheKey, payload);
95090
+ } else {
95091
+ browserUserFillsPages.delete(cacheKey);
95092
+ }
94972
95093
  writeBrowserUserFillsCache(cacheKey, entry);
94973
95094
  return entry;
94974
95095
  }).finally(() => {
@@ -95224,8 +95345,8 @@ var init_protective_evidence = __esm({
95224
95345
  const wallet = String(context.walletAddress ?? "").trim();
95225
95346
  const items = evidenceItems(context.requests ?? []);
95226
95347
  if (items.length === 0 || !wallet) return { reported: 0, nextEvidenceDueAtMs: listedDueAtMs };
95227
- const profileKey = String(context.profileId).trim();
95228
- const backoffUntil = evidenceBackoffUntil.get(profileKey) ?? 0;
95348
+ const profileKey2 = String(context.profileId).trim();
95349
+ const backoffUntil = evidenceBackoffUntil.get(profileKey2) ?? 0;
95229
95350
  if (Date.now() < backoffUntil) {
95230
95351
  return { reported: 0, nextEvidenceDueAtMs: backoffUntil, skipped: "backoff" };
95231
95352
  }
@@ -95268,15 +95389,15 @@ var init_protective_evidence = __esm({
95268
95389
  }
95269
95390
  if (failedCode) {
95270
95391
  const until = Date.now() + EVIDENCE_FAILURE_BACKOFF_MS;
95271
- evidenceBackoffUntil.set(profileKey, until);
95392
+ evidenceBackoffUntil.set(profileKey2, until);
95272
95393
  appendRuntimeDebugEvent({
95273
95394
  label: "client_protective_evidence_rejected",
95274
- note: `profile_id=${profileKey} code=${failedCode}`,
95395
+ note: `profile_id=${profileKey2} code=${failedCode}`,
95275
95396
  outcome: "error"
95276
95397
  });
95277
95398
  return { reported, nextEvidenceDueAtMs: until, failedCode, ...actions ? { actions } : {} };
95278
95399
  }
95279
- evidenceBackoffUntil.delete(profileKey);
95400
+ evidenceBackoffUntil.delete(profileKey2);
95280
95401
  return { reported, nextEvidenceDueAtMs, ...actions ? { actions } : {} };
95281
95402
  },
95282
95403
  () => ({ reported: 0, nextEvidenceDueAtMs: listedDueAtMs, skipped: "reporter_busy" })
@@ -95769,7 +95890,7 @@ var init_client_exchange_mutations = __esm({
95769
95890
  });
95770
95891
 
95771
95892
  // lib/runtime/execution-guard-contract.ts
95772
- var unitsFromPosition, signedUnitsFromPosition, signedUnitsFromEntryPosition, classifyExecutionIntent, resolveExecutionTarget, decisionOrderSizeAsset, flipExecutionLegs;
95893
+ var unitsFromPosition, signedUnitsFromPosition, signedUnitsFromEntryPosition, classifyExecutionIntent, reductionFirstOrder, resolveExecutionTarget, decisionOrderSizeAsset, flipExecutionLegs, executedOrderPositionEvent;
95773
95894
  var init_execution_guard_contract = __esm({
95774
95895
  "lib/runtime/execution-guard-contract.ts"() {
95775
95896
  "use strict";
@@ -95965,6 +96086,10 @@ var init_execution_guard_contract = __esm({
95965
96086
  targetSignedUnits: -(units - Math.abs(snapshotSignedUnits))
95966
96087
  };
95967
96088
  };
96089
+ reductionFirstOrder = (plans) => {
96090
+ const reduces = plans.map((plan) => classifyExecutionIntent(plan.decision, plan.units, plan.signedUnits).reduceOnly);
96091
+ return plans.map((_, index) => index).sort((left, right) => Number(reduces[right]) - Number(reduces[left]));
96092
+ };
95968
96093
  resolveExecutionTarget = (classified, liveSignedUnits, livePositionDirection) => {
95969
96094
  const liveUnits = Number.isFinite(liveSignedUnits) ? Math.trunc(liveSignedUnits) : 0;
95970
96095
  const exactLiveDirection = livePositionDirection == null ? liveUnits > 0 ? 1 : liveUnits < 0 ? -1 : 0 : livePositionDirection;
@@ -96039,11 +96164,24 @@ var init_execution_guard_contract = __esm({
96039
96164
  }
96040
96165
  ];
96041
96166
  };
96167
+ executedOrderPositionEvent = (intent, side, leg) => {
96168
+ if (side !== "buy" && side !== "sell") throw new Error("An executed order's side must be buy or sell");
96169
+ const sideDirection = side === "buy" ? "LONG" : "SHORT";
96170
+ const oppositeDirection = side === "buy" ? "SHORT" : "LONG";
96171
+ if (intent === "open" || intent === "add") return { positionEvent: intent, positionDirection: sideDirection };
96172
+ if (intent === "reduce" || intent === "close") return { positionEvent: intent, positionDirection: oppositeDirection };
96173
+ if (intent === "flip") {
96174
+ const [closeLeg, entryLeg] = flipExecutionLegs(side, "executed");
96175
+ const flipLeg = leg === entryLeg.leg ? entryLeg : closeLeg;
96176
+ return { positionEvent: flipLeg.positionEvent, positionDirection: flipLeg.positionDirection };
96177
+ }
96178
+ return { positionEvent: null, positionDirection: null };
96179
+ };
96042
96180
  }
96043
96181
  });
96044
96182
 
96045
96183
  // lib/runtime/copy-trading-evidence.ts
96046
- var ACCOUNT_MODE_CACHE_MS, dexList, normalizeRequest, openOrderRefs, EvidenceReadFailed, readClientCopyTradingAccountEvidence, accountEvidenceForUpload, readCopyOrderStatusEvidence, orderStatusEvidenceForAck;
96184
+ var ACCOUNT_MODE_CACHE_MS, dexList2, normalizeRequest, openOrderRefs, EvidenceReadFailed, readClientCopyTradingAccountEvidence, accountEvidenceForUpload, readCopyOrderStatusEvidence, orderStatusEvidenceForAck;
96047
96185
  var init_copy_trading_evidence = __esm({
96048
96186
  "lib/runtime/copy-trading-evidence.ts"() {
96049
96187
  "use strict";
@@ -96057,7 +96195,7 @@ var init_copy_trading_evidence = __esm({
96057
96195
  init_monotonic_clock();
96058
96196
  init_protective_evidence();
96059
96197
  ACCOUNT_MODE_CACHE_MS = runtime_policy_generated_default2.exchange.hyperliquid.client_public_read_budget.account_mode_ttl_seconds * MS_PER_SECOND;
96060
- dexList = (value) => {
96198
+ dexList2 = (value) => {
96061
96199
  if (!Array.isArray(value) || value.some((dex) => typeof dex !== "string")) return null;
96062
96200
  return [...new Set(value.map((dex) => dex.trim()))];
96063
96201
  };
@@ -96065,8 +96203,8 @@ var init_copy_trading_evidence = __esm({
96065
96203
  if (!request || typeof request !== "object") return null;
96066
96204
  const requestId = typeof request.request_id === "string" ? request.request_id.trim() : "";
96067
96205
  const walletAddress = typeof request.wallet_address === "string" ? request.wallet_address.trim() : "";
96068
- const dexes = dexList(request.dexes);
96069
- const openOrdersDexes = dexList(request.open_orders_dexes);
96206
+ const dexes = dexList2(request.dexes);
96207
+ const openOrdersDexes = dexList2(request.open_orders_dexes);
96070
96208
  const maxAgeSeconds = Number(request.max_age_seconds);
96071
96209
  if (!requestId || !walletAddress || !dexes || !openOrdersDexes || !Array.isArray(request.order_refs) || !Number.isFinite(maxAgeSeconds) || maxAgeSeconds <= 0) return null;
96072
96210
  const orderRefs = /* @__PURE__ */ new Map();
@@ -101129,7 +101267,7 @@ var init_runtime_execution = __esm({
101129
101267
  isLong: group.isLong,
101130
101268
  positionTpsl: leg.positionTpsl === true
101131
101269
  }] : []));
101132
- if (currentPositionSize === 0) {
101270
+ if (currentPositionSize === 0 || tracked.length === 0) {
101133
101271
  writeTrackedTrailingStops(profileId, symbol2, []);
101134
101272
  return [];
101135
101273
  }
@@ -101598,6 +101736,7 @@ var init_runtime_execution = __esm({
101598
101736
  });
101599
101737
  runtimeProtectionOwners = /* @__PURE__ */ new WeakMap();
101600
101738
  resolveRuntimeProtectionOwner = (request) => {
101739
+ if (request.executionMode === "server") return Promise.resolve("server");
101601
101740
  const cached2 = runtimeProtectionOwners.get(request);
101602
101741
  if (cached2) return cached2;
101603
101742
  const authority = runtimeProtectionAuthority(request);
@@ -101739,7 +101878,7 @@ var init_runtime_execution = __esm({
101739
101878
  () => withClientExecutionMutation(request, work),
101740
101879
  request.signal
101741
101880
  );
101742
- allocateServerExecutionCapacity = async (authority, plans) => {
101881
+ allocateServerExecutionCapacity = async (authority, plans, cycleStartedAt) => {
101743
101882
  if (plans.length === 0) return [];
101744
101883
  try {
101745
101884
  return await checkServerHostExecutionCapacity(
@@ -101749,11 +101888,12 @@ var init_runtime_execution = __esm({
101749
101888
  authority.sessionId,
101750
101889
  authority.runtimeLeaseToken,
101751
101890
  authority.runtimeDeviceId,
101752
- authority.schedulerInstanceId
101891
+ authority.schedulerInstanceId,
101892
+ cycleStartedAt
101753
101893
  );
101754
- } catch {
101894
+ } catch (error48) {
101755
101895
  throwIfAborted2(authority.signal);
101756
- return plans.map(() => "unavailable");
101896
+ return plans.map(() => ({ unavailable: error48 }));
101757
101897
  }
101758
101898
  };
101759
101899
  withClientProtectiveAdoptionMutation = (profileId, work, signal) => withClientExecutionMutation({ profileId: String(profileId).trim(), signal }, work);
@@ -101768,9 +101908,7 @@ var init_runtime_execution = __esm({
101768
101908
  SERVER_AUDIT_RECORDED_ELSEWHERE = /* @__PURE__ */ new Set([
101769
101909
  "suppressed_duplicate_decision",
101770
101910
  "same_intent_cooldown",
101771
- "redis_unavailable",
101772
- "execution_capacity_refused",
101773
- "execution_capacity_unavailable"
101911
+ "execution_capacity_refused"
101774
101912
  ]);
101775
101913
  serverExecutionAuditOutcome = (result) => {
101776
101914
  if (result.status === "executed") {
@@ -102377,10 +102515,10 @@ var init_runtime_execution = __esm({
102377
102515
  });
102378
102516
  const capacity = unsizedInput.serverCapacityAllocation ?? (await allocateServerExecutionCapacity(unsizedInput, [
102379
102517
  { symbol: unsizedInput.executionContext.symbol, decision: unsizedInput.decision, units: requestedUnits }
102380
- ]))[0];
102381
- if (capacity === "unavailable") {
102518
+ ], unsizedInput.executionContext.decisionSnapshotCapturedAt))[0];
102519
+ if ("unavailable" in capacity) {
102382
102520
  throwIfAborted2(unsizedInput.signal);
102383
- return skipped("execution_capacity_unavailable", "Execution skipped: Failed to fetch positions before limit check.");
102521
+ throw capacity.unavailable instanceof Error ? capacity.unavailable : new Error("Positions could not be read before the limit check.");
102384
102522
  }
102385
102523
  if (!capacity.accepted || !(capacity.units > 0)) {
102386
102524
  appendRuntimeDebugEvent({
@@ -102640,6 +102778,9 @@ var init_runtime_execution = __esm({
102640
102778
  input.runtimeDeviceId,
102641
102779
  input.schedulerInstanceId
102642
102780
  );
102781
+ if (!claim.allowed && claim.reason_code === "redis_unavailable") {
102782
+ throw Object.assign(new Error("Execution coordination was unavailable."), { reasonCode: "redis_unavailable" });
102783
+ }
102643
102784
  if (input.serverExecutionAudit && typeof claim.audit_id === "number") {
102644
102785
  input.serverExecutionAudit.auditId = claim.audit_id;
102645
102786
  }
@@ -103163,7 +103304,7 @@ var init_runtime_execution = __esm({
103163
103304
  symbol: input.executionContext.symbol,
103164
103305
  action: classified.side.toUpperCase(),
103165
103306
  status: "executed",
103166
- execution_metadata: classified.intent === "flip" ? { ..._toExecutionMetadata(marketOrderResponse), decision_leg: "entry" } : _toExecutionMetadata(marketOrderResponse)
103307
+ execution_metadata: classified.intent === "flip" ? { ..._toExecutionMetadata(marketOrderResponse), decision_leg: "entry" } : { ..._toExecutionMetadata(marketOrderResponse), entry_began_flat: livePositionDirection === 0 }
103167
103308
  });
103168
103309
  const appendPostEntryProtectionFailure = (error48) => {
103169
103310
  const projection = projectExecutionErrorContract({
@@ -107327,7 +107468,7 @@ var init_client_runtime_status_store = __esm({
107327
107468
  });
107328
107469
 
107329
107470
  // lib/runtime/perp-dex-scope.ts
107330
- var perpDexScopeForSymbols, profileEquityPerpDexScope;
107471
+ var perpDexScopeForSymbols, equityVenuesForSymbols, profileEquityVenues, positionsOnVenues;
107331
107472
  var init_perp_dex_scope = __esm({
107332
107473
  "lib/runtime/perp-dex-scope.ts"() {
107333
107474
  "use strict";
@@ -107344,9 +107485,19 @@ var init_perp_dex_scope = __esm({
107344
107485
  }
107345
107486
  return dexes.size > 0 ? [...dexes].filter(Boolean) : void 0;
107346
107487
  };
107347
- profileEquityPerpDexScope = (tradingSymbols, defaultTradingSymbols) => perpDexScopeForSymbols(
107348
- (Array.isArray(tradingSymbols) && tradingSymbols.length > 0 ? tradingSymbols : defaultTradingSymbols ?? []).map((entry) => String(entry ?? "").trim()).filter(Boolean)
107488
+ equityVenuesForSymbols = (symbols) => {
107489
+ const venues = /* @__PURE__ */ new Set();
107490
+ for (const raw of symbols) {
107491
+ if (!String(raw ?? "").trim()) continue;
107492
+ if (!normalizeHyperliquidMarketSymbol(raw)) return null;
107493
+ venues.add(getHyperliquidMarketDex(raw));
107494
+ }
107495
+ return venues.size > 0 ? [...venues].sort() : null;
107496
+ };
107497
+ profileEquityVenues = (tradingSymbols, defaultTradingSymbols) => equityVenuesForSymbols(
107498
+ Array.isArray(tradingSymbols) && tradingSymbols.length > 0 ? tradingSymbols : defaultTradingSymbols ?? []
107349
107499
  );
107500
+ positionsOnVenues = (positions, venues) => venues ? positions.filter((position) => normalizeHyperliquidMarketSymbol(position.symbol) && venues.includes(getHyperliquidMarketDex(position.symbol))) : [...positions];
107350
107501
  }
107351
107502
  });
107352
107503
 
@@ -107415,6 +107566,7 @@ var init_client_killswitch = __esm({
107415
107566
  }
107416
107567
  const symbol2 = firstConfiguredSymbol(settings, input.config);
107417
107568
  const leverage = toPositiveFinite2(settings.leverage) ?? 1;
107569
+ const equityVenues = profileEquityVenues(settings.trading_symbols, input.config.default_trading_symbols);
107418
107570
  const accountState = await fetchBrowserAccountState2({
107419
107571
  publicRequestPriority: "trading_reduce",
107420
107572
  config: input.config,
@@ -107423,9 +107575,7 @@ var init_client_killswitch = __esm({
107423
107575
  tickerPrice: 0,
107424
107576
  leverage,
107425
107577
  aggregatePerpDexs: true,
107426
- // Only the DEXes the server measures the killswitch on; a trigger's close
107427
- // re-reads every DEX before closing.
107428
- perpDexScope: profileEquityPerpDexScope(settings.trading_symbols, input.config.default_trading_symbols),
107578
+ perpDexScope: equityVenues?.filter(Boolean),
107429
107579
  forceRefresh: true,
107430
107580
  sessionId: input.sessionId,
107431
107581
  signal: input.signal
@@ -107458,7 +107608,8 @@ var init_client_killswitch = __esm({
107458
107608
  context,
107459
107609
  accountState,
107460
107610
  walletAddress,
107461
- symbol: symbol2
107611
+ symbol: symbol2,
107612
+ equityVenues
107462
107613
  };
107463
107614
  }
107464
107615
  if (!context.snapshot_trusted || context.status === "untrusted") {
@@ -107469,7 +107620,8 @@ var init_client_killswitch = __esm({
107469
107620
  context,
107470
107621
  accountState,
107471
107622
  walletAddress,
107472
- symbol: symbol2
107623
+ symbol: symbol2,
107624
+ equityVenues
107473
107625
  };
107474
107626
  }
107475
107627
  const peakEquity = toPositiveFinite2(context.peak_equity);
@@ -107481,7 +107633,8 @@ var init_client_killswitch = __esm({
107481
107633
  context,
107482
107634
  accountState,
107483
107635
  walletAddress,
107484
- symbol: symbol2
107636
+ symbol: symbol2,
107637
+ equityVenues
107485
107638
  };
107486
107639
  }
107487
107640
  const drawdownPercent = calculateClientKillswitchDrawdownPercent(
@@ -107496,11 +107649,12 @@ var init_client_killswitch = __esm({
107496
107649
  context,
107497
107650
  accountState,
107498
107651
  walletAddress,
107499
- symbol: symbol2
107652
+ symbol: symbol2,
107653
+ equityVenues
107500
107654
  };
107501
107655
  };
107502
107656
  closeClientKillswitchPositions = async (input) => {
107503
- const positions = input.positions.filter((position) => {
107657
+ const positions = positionsOnVenues(input.positions, input.venues).filter((position) => {
107504
107658
  const size = Number(position.size);
107505
107659
  return Number.isFinite(size) && size !== 0;
107506
107660
  });
@@ -107635,13 +107789,13 @@ var init_history_evidence = __esm({
107635
107789
  runClientHistoryAsks = async (context) => {
107636
107790
  let asks = normalizeHistoryAsks(context.asks);
107637
107791
  const wallet = String(context.walletAddress ?? "").trim();
107638
- const profileKey = String(context.profileId).trim();
107639
- if (asks.length === 0 || !wallet || !profileKey) return { reported: 0, rounds: 0, nextAsks: asks };
107640
- if (Date.now() < (historyBackoffUntil.get(profileKey) ?? 0)) {
107792
+ const profileKey2 = String(context.profileId).trim();
107793
+ if (asks.length === 0 || !wallet || !profileKey2) return { reported: 0, rounds: 0, nextAsks: asks };
107794
+ if (Date.now() < (historyBackoffUntil.get(profileKey2) ?? 0)) {
107641
107795
  return { reported: 0, rounds: 0, nextAsks: asks, skipped: "backoff" };
107642
107796
  }
107643
- if (runningProfiles.has(profileKey)) return { reported: 0, rounds: 0, nextAsks: asks, skipped: "busy" };
107644
- runningProfiles.add(profileKey);
107797
+ if (runningProfiles.has(profileKey2)) return { reported: 0, rounds: 0, nextAsks: asks, skipped: "busy" };
107798
+ runningProfiles.add(profileKey2);
107645
107799
  let reported = 0;
107646
107800
  let rounds = 0;
107647
107801
  const maxRounds = Math.max(1, Math.floor(context.maxRounds ?? HISTORY_ROUNDS_PER_BEAT));
@@ -107666,24 +107820,24 @@ var init_history_evidence = __esm({
107666
107820
  reported += Number(answer?.accepted ?? 0);
107667
107821
  asks = normalizeHistoryAsks(answer?.history_asks);
107668
107822
  }
107669
- historyBackoffUntil.delete(profileKey);
107823
+ historyBackoffUntil.delete(profileKey2);
107670
107824
  appendRuntimeDebugEvent({
107671
107825
  label: "client_history_evidence_reported",
107672
- note: `profile_id=${profileKey} rounds=${rounds} accepted=${reported} next=${asks.map((ask) => ask.stream).join(",") || "none"}`
107826
+ note: `profile_id=${profileKey2} rounds=${rounds} accepted=${reported} next=${asks.map((ask) => ask.stream).join(",") || "none"}`
107673
107827
  });
107674
107828
  return { reported, rounds, nextAsks: asks };
107675
107829
  } catch (error48) {
107676
107830
  if (context.signal?.aborted) return { reported, rounds, nextAsks: asks };
107677
107831
  const failedCode = errorCode3(error48) || "history_evidence_read_failed";
107678
- historyBackoffUntil.set(profileKey, Date.now() + HISTORY_RETRY_MS);
107832
+ historyBackoffUntil.set(profileKey2, Date.now() + HISTORY_RETRY_MS);
107679
107833
  appendRuntimeDebugEvent({
107680
107834
  label: "client_history_evidence_failed",
107681
- note: `profile_id=${profileKey} rounds=${rounds} code=${failedCode}`,
107835
+ note: `profile_id=${profileKey2} rounds=${rounds} code=${failedCode}`,
107682
107836
  outcome: "error"
107683
107837
  });
107684
107838
  return { reported, rounds, nextAsks: asks, failedCode };
107685
107839
  } finally {
107686
- runningProfiles.delete(profileKey);
107840
+ runningProfiles.delete(profileKey2);
107687
107841
  }
107688
107842
  };
107689
107843
  }
@@ -107729,11 +107883,11 @@ var init_portfolio_evidence = __esm({
107729
107883
  errorCode4 = (error48) => String(error48?.code ?? "").trim();
107730
107884
  runClientPortfolioReport = async (context) => {
107731
107885
  const wallet = String(context.walletAddress ?? "").trim();
107732
- const profileKey = String(context.profileId).trim();
107733
- if (context.due !== true || !wallet || !profileKey) return { reported: false };
107734
- if (Date.now() < (portfolioBackoffUntil.get(profileKey) ?? 0)) return { reported: false, skipped: "backoff" };
107735
- if (runningProfiles2.has(profileKey)) return { reported: false, skipped: "busy" };
107736
- runningProfiles2.add(profileKey);
107886
+ const profileKey2 = String(context.profileId).trim();
107887
+ if (context.due !== true || !wallet || !profileKey2) return { reported: false };
107888
+ if (Date.now() < (portfolioBackoffUntil.get(profileKey2) ?? 0)) return { reported: false, skipped: "backoff" };
107889
+ if (runningProfiles2.has(profileKey2)) return { reported: false, skipped: "busy" };
107890
+ runningProfiles2.add(profileKey2);
107737
107891
  try {
107738
107892
  const startedAtMonotonicMs = monotonicNowMs();
107739
107893
  const body = await fetchBrowserHyperliquidInfoText(
@@ -107749,25 +107903,25 @@ var init_portfolio_evidence = __esm({
107749
107903
  observed_age_ms: monotonicAgeMs(startedAtMonotonicMs),
107750
107904
  body
107751
107905
  });
107752
- portfolioBackoffUntil.delete(profileKey);
107906
+ portfolioBackoffUntil.delete(profileKey2);
107753
107907
  const reported = Number(answer?.accepted ?? 0) > 0;
107754
107908
  appendRuntimeDebugEvent({
107755
107909
  label: "client_portfolio_evidence_reported",
107756
- note: `profile_id=${profileKey} accepted=${String(reported)} published=${String(Boolean(answer?.published))} ignored=${answer?.ignored ?? "none"}`
107910
+ note: `profile_id=${profileKey2} accepted=${String(reported)} published=${String(Boolean(answer?.published))} ignored=${answer?.ignored ?? "none"}`
107757
107911
  });
107758
107912
  return { reported, published: Boolean(answer?.published) };
107759
107913
  } catch (error48) {
107760
107914
  if (context.signal?.aborted) return { reported: false };
107761
107915
  const failedCode = errorCode4(error48) || "portfolio_evidence_read_failed";
107762
- portfolioBackoffUntil.set(profileKey, Date.now() + PORTFOLIO_RETRY_MS);
107916
+ portfolioBackoffUntil.set(profileKey2, Date.now() + PORTFOLIO_RETRY_MS);
107763
107917
  appendRuntimeDebugEvent({
107764
107918
  label: "client_portfolio_evidence_failed",
107765
- note: `profile_id=${profileKey} code=${failedCode}`,
107919
+ note: `profile_id=${profileKey2} code=${failedCode}`,
107766
107920
  outcome: "error"
107767
107921
  });
107768
107922
  return { reported: false, failedCode };
107769
107923
  } finally {
107770
- runningProfiles2.delete(profileKey);
107924
+ runningProfiles2.delete(profileKey2);
107771
107925
  }
107772
107926
  };
107773
107927
  }
@@ -109453,6 +109607,14 @@ function applyNativeRequestParameters(requestBody, parameters, selectedValues, a
109453
109607
  }
109454
109608
  return next;
109455
109609
  }
109610
+ function hasUserSelectedNativeRequestParameters(parameters, selectedValues, apiSurface) {
109611
+ if (!selectedValues) return false;
109612
+ return (parameters || []).some((parameter) => {
109613
+ if (parameter.api_surface !== apiSurface || parameter.app_managed || !parameter.user_visible) return false;
109614
+ const value = selectedValues[nativeParameterIdentity(parameter)];
109615
+ return value !== null && value !== void 0 && value !== "";
109616
+ });
109617
+ }
109456
109618
  function filterNativeRequestParameterValues(parameters, values, options = {}) {
109457
109619
  const selectedValues = values || {};
109458
109620
  const filtered = {};
@@ -109527,7 +109689,7 @@ var init_native_request_parameters = __esm({
109527
109689
  });
109528
109690
 
109529
109691
  // lib/runtime/provider-client.ts
109530
- var mapOpenAiCompatibleNativeRequestPath, isRetryableProviderFailureForFallback, extractRuntimeProviderFailureStatusCode, isModelSpecificProviderFailure, isKeySpecificOrTransientProviderFailure, providerDispatchClockMs, beginProviderDispatch, providerDispatchLatencyMs, attachProviderDispatchFailure, attachProviderFailureTrace, toRuntimeExecutionMode, buildNoneReasoningPayload, normalizeLevelValue, buildRuntimeReasoningPayload, resolveProviderReasoningParameters, requestedReasoningParameters, usesReasoningCompletionTokens, shouldRequestReasoningTrace, normalizeProviderToken, runtimeProviderForByokProvider, findByokProviderForRuntime, findNativeRequestParametersForModel, modelHasNativeRequestApiSurface, setDottedRequestValue, normalizeProviderMaxTokens, applyRuntimeRequestContract, normalizeProvider2, requireProviderEndpoint, SSE_DATA_FIELD_PREFIX2, estimateTokenCount, normalizeUsageCount, buildOpenAiUsagePayload, buildAnthropicUsagePayload, buildGoogleUsagePayload, normalizeProviderUsageMetrics, providerResponseSignals, fetchProvider, readProviderPayload, emitRuntimeDelta, readProviderTextStream, extractOpenAiCompatibleDeltaText, readOpenAiCompatibleTextStream, rawProviderTextForDebug, extractProviderErrorDetail, buildCanonicalProviderFailureMessage, toProviderNetworkDebugError, REASONING_ONLY_CONTENT_TYPES, extractOpenAiContentPartText, extractOpenAiReasoningPartText, extractOpenAiMessageContent, extractOpenAiMessageReasoningContent, extractOpenAiCompatibleText, normalizeRuntimeChatHistory, calculateProviderCost, callOpenAiCompatible, extractOpenAiResponsesText, extractOpenAiResponsesReasoning, callOpenAiResponses, extractAnthropicMessageText, extractAnthropicReasoningContent, callAnthropic, isVertexExpressKey, googlePublicModelIdRegexes, shouldUseGooglePublicEndpointForModel, normalizeGoogleModelId, shouldRetryGoogleVertexRequestPublicly, GOOGLE_VERTEX_PUBLIC_RETRY_NOTE, buildGoogleRequest, isGoogleReasoningPart, extractGoogleMessageText, extractGoogleReasoningContent, extractGoogleSafetyMetadata, GOOGLE_BLOCKED_FINISH_REASONS, googleProviderBlockReason, callGoogle, resolveRuntimeProvider, defaultInvocationContext, defaultProviderTransport, invocationFailureCode, buildBrowserInvocation, resolveProviderSecretKey, resolveNativeProviderCredentialSlots, resolveProviderSecretKeySlots, requireOpenAiCompatibleRuntimeBaseUrl, runtimeSubscriptionPlan, runtimeKeySlotSupportsModel, invokeRuntimeProviderAttempt, runtimeProviderInvoker, invokeRuntimeProvider;
109692
+ var mapOpenAiCompatibleNativeRequestPath, isRetryableProviderFailureForFallback, extractRuntimeProviderFailureStatusCode, isModelSpecificProviderFailure, emptyProviderContentError, isEmptyProviderContentFailure, emptyReplyForInternalAttempt, isEmptyProviderMessageFailure, isRetryableProviderAttemptFailure, providerRejectedRequestError, OPTIONAL_CONTRACT_PARAMETER_TOKENS, OPTIONAL_CONTRACT_REJECTION_TOKENS, OPTIONAL_CONTRACT_GRAMMAR_TOKENS, isOptionalContractParameterRejection, OPTIONAL_CONTRACT_REQUEST_KEYS, OPTIONAL_CONTRACT_EXTRA_BODY_KEYS, resolveEmptyContentRetryPolicy, isKeySpecificOrTransientProviderFailure, providerDispatchClockMs, beginProviderDispatch, providerDispatchLatencyMs, attachProviderDispatchFailure, attachProviderFailureTrace, toRuntimeExecutionMode, buildNoneReasoningPayload, normalizeLevelValue, buildRuntimeReasoningPayload, resolveProviderReasoningParameters, requestedReasoningParameters, usesReasoningCompletionTokens, shouldRequestReasoningTrace, normalizeProviderToken, runtimeProviderForByokProvider, findByokProviderForRuntime, findNativeRequestParametersForModel, modelHasNativeRequestApiSurface, asRequestRecord, setDottedRequestValue, normalizeProviderMaxTokens, applyRuntimeRequestContract, normalizeProvider2, requireProviderEndpoint, SSE_DATA_FIELD_PREFIX2, estimateTokenCount, normalizeUsageCount, buildOpenAiUsagePayload, buildAnthropicUsagePayload, buildGoogleUsagePayload, normalizeProviderUsageMetrics, providerResponseSignals, fetchProvider, readProviderPayload, emitRuntimeDelta, readProviderTextStream, extractOpenAiCompatibleDeltaText, readOpenAiCompatibleTextStream, rawProviderTextForDebug, extractProviderErrorDetail, buildCanonicalProviderFailureMessage, toProviderNetworkDebugError, REASONING_ONLY_CONTENT_TYPES, extractOpenAiContentPartText, extractOpenAiReasoningPartText, extractOpenAiMessageContent, extractOpenAiMessageReasoningContent, extractOpenAiCompatibleText, normalizeRuntimeChatHistory, calculateProviderCost, callOpenAiCompatible, extractOpenAiResponsesText, extractOpenAiResponsesReasoning, callOpenAiResponses, extractAnthropicMessageText, extractAnthropicReasoningContent, callAnthropic, isVertexExpressKey, googlePublicModelIdRegexes, shouldUseGooglePublicEndpointForModel, normalizeGoogleModelId, shouldRetryGoogleVertexRequestPublicly, GOOGLE_VERTEX_PUBLIC_RETRY_NOTE, buildGoogleRequest, isGoogleReasoningPart, extractGoogleMessageText, extractGoogleReasoningContent, extractGoogleSafetyMetadata, GOOGLE_BLOCKED_FINISH_REASONS, googleProviderBlockReason, callGoogle, resolveRuntimeProvider, defaultInvocationContext, defaultProviderTransport, invocationFailureCode, buildBrowserInvocation, resolveProviderSecretKey, resolveNativeProviderCredentialSlots, resolveProviderSecretKeySlots, requireOpenAiCompatibleRuntimeBaseUrl, runtimeSubscriptionPlan, runtimeKeySlotSupportsModel, invokeRuntimeProviderAttempt, runtimeProviderInvoker, invokeRuntimeProvider;
109531
109693
  var init_provider_client = __esm({
109532
109694
  "lib/runtime/provider-client.ts"() {
109533
109695
  "use strict";
@@ -109582,6 +109744,58 @@ var init_provider_client = __esm({
109582
109744
  "no route to model"
109583
109745
  ].some((token) => normalized.includes(token));
109584
109746
  };
109747
+ emptyProviderContentError = (message, reply) => Object.assign(new Error(message), {
109748
+ runtimeEmptyProviderContent: true,
109749
+ // Kept for the in-place retry's own row only (Venice): a model's final
109750
+ // empty reply is recorded with no result and never priced, as in Server Mode.
109751
+ ...reply ? { runtimeEmptyProviderReply: reply.result, runtimeEmptyProviderMessage: reply.emptyMessage } : {}
109752
+ });
109753
+ isEmptyProviderContentFailure = (error48) => error48?.runtimeEmptyProviderContent === true;
109754
+ emptyReplyForInternalAttempt = (error48) => {
109755
+ const reply = error48?.runtimeEmptyProviderReply;
109756
+ return reply ? { ...reply, reasoningContent: null } : null;
109757
+ };
109758
+ isEmptyProviderMessageFailure = (error48) => error48?.runtimeEmptyProviderMessage === true;
109759
+ isRetryableProviderAttemptFailure = (failure2) => failure2.emptyContent || failure2.nativeFailureKind !== void 0 || failure2.statusCode === HTTP_STATUS.REQUEST_TIMEOUT || isRetryableProviderFailureForFallback(failure2.detail);
109760
+ providerRejectedRequestError = (message, detail) => Object.assign(new Error(message), { runtimeProviderRejectionDetail: String(detail || message) });
109761
+ OPTIONAL_CONTRACT_PARAMETER_TOKENS = [
109762
+ "response_format",
109763
+ "venice_parameters",
109764
+ "strip_thinking_response",
109765
+ "disable_thinking",
109766
+ "reasoning_effort",
109767
+ "thinking_budget",
109768
+ "thinking_level",
109769
+ "extra_body"
109770
+ ];
109771
+ OPTIONAL_CONTRACT_REJECTION_TOKENS = [
109772
+ "unexpected keyword argument",
109773
+ "unknown parameter",
109774
+ "unsupported parameter",
109775
+ "not supported",
109776
+ "invalid parameter",
109777
+ "extra fields not permitted",
109778
+ "not permitted"
109779
+ ];
109780
+ OPTIONAL_CONTRACT_GRAMMAR_TOKENS = ["failed to transform json schema into a grammar", "json_schema_converter"];
109781
+ isOptionalContractParameterRejection = (error48) => {
109782
+ const detail = error48?.runtimeProviderRejectionDetail;
109783
+ if (typeof detail !== "string" || !detail) return false;
109784
+ const normalized = detail.toLowerCase();
109785
+ if (OPTIONAL_CONTRACT_GRAMMAR_TOKENS.some((token) => normalized.includes(token))) return true;
109786
+ return OPTIONAL_CONTRACT_PARAMETER_TOKENS.some((token) => normalized.includes(token)) && OPTIONAL_CONTRACT_REJECTION_TOKENS.some((token) => normalized.includes(token));
109787
+ };
109788
+ OPTIONAL_CONTRACT_REQUEST_KEYS = ["response_format", "reasoning_effort", "reasoning_format"];
109789
+ OPTIONAL_CONTRACT_EXTRA_BODY_KEYS = ["thinking_level", "thinking_budget", "reasoning", "include_reasoning", "venice_parameters"];
109790
+ resolveEmptyContentRetryPolicy = (config2) => {
109791
+ const policy2 = config2.empty_content_retry;
109792
+ if (policy2 === void 0 || policy2 === null) return null;
109793
+ const values = [policy2.max_retries, policy2.delay_seconds, policy2.jitter_min_seconds, policy2.jitter_max_seconds];
109794
+ if (values.some((value) => typeof value !== "number" || !Number.isFinite(value) || value < 0) || !Number.isInteger(policy2.max_retries) || policy2.jitter_max_seconds < policy2.jitter_min_seconds) {
109795
+ throw new Error("Missing or invalid config key: empty_content_retry");
109796
+ }
109797
+ return policy2;
109798
+ };
109585
109799
  isKeySpecificOrTransientProviderFailure = (detail) => {
109586
109800
  const normalized = String(detail || "").toLowerCase();
109587
109801
  return isRetryableProviderFailureForFallback(detail) || normalized.includes("http 401") || normalized.includes("http 403") || normalized.includes("(401)") || normalized.includes("(403)") || normalized.includes("unauthorized") || normalized.includes("forbidden") || normalized.includes("permission") || normalized.includes("quota");
@@ -109917,6 +110131,7 @@ var init_provider_client = __esm({
109917
110131
  modelHasNativeRequestApiSurface = (config2, provider, model, apiSurface) => findNativeRequestParametersForModel(config2, provider, model).some(
109918
110132
  (parameter) => parameter.api_surface === apiSurface
109919
110133
  );
110134
+ asRequestRecord = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
109920
110135
  setDottedRequestValue = (target, path, value) => {
109921
110136
  const segments = path.split(".").map((segment) => segment.trim()).filter(Boolean);
109922
110137
  if (segments.length === 0) return;
@@ -110187,7 +110402,7 @@ var init_provider_client = __esm({
110187
110402
  const { payload, rawText: rawText2 } = await readProviderPayload(response);
110188
110403
  onPayload?.(payload);
110189
110404
  const detail = extractProviderErrorDetail(payload, rawText2);
110190
- throw new Error(buildCanonicalProviderFailureMessage({ response, detail, runtimeMode }));
110405
+ throw providerRejectedRequestError(buildCanonicalProviderFailureMessage({ response, detail, runtimeMode }), detail);
110191
110406
  }
110192
110407
  let content = "";
110193
110408
  let reasoningContent = "";
@@ -110246,7 +110461,7 @@ var init_provider_client = __esm({
110246
110461
  });
110247
110462
  const finalContent = content.trim();
110248
110463
  if (!finalContent) {
110249
- throw new Error("Provider response did not include any message content.");
110464
+ throw emptyProviderContentError("Provider response did not include any message content.");
110250
110465
  }
110251
110466
  return {
110252
110467
  rawText,
@@ -110435,12 +110650,9 @@ var init_provider_client = __esm({
110435
110650
  }).filter((call) => Boolean(call));
110436
110651
  if (!response.ok) {
110437
110652
  const detail = extractProviderErrorDetail(payload, rawText);
110438
- throw new Error(buildCanonicalProviderFailureMessage({ response, detail, runtimeMode }));
110653
+ throw providerRejectedRequestError(buildCanonicalProviderFailureMessage({ response, detail, runtimeMode }), detail);
110439
110654
  }
110440
- if (!content && toolCalls.length === 0) {
110441
- throw new Error("Provider response did not include any message content.");
110442
- }
110443
- return {
110655
+ const result = {
110444
110656
  content: content || "",
110445
110657
  reasoningContent,
110446
110658
  toolCalls,
@@ -110459,6 +110671,13 @@ var init_provider_client = __esm({
110459
110671
  refusalStatus: typeof message?.refusal === "string" && message.refusal.trim() ? "refused" : "none",
110460
110672
  reasoningTraceSource: reasoningContent ? "provider_native" : "none"
110461
110673
  };
110674
+ if (!content && toolCalls.length === 0) {
110675
+ throw emptyProviderContentError("Provider response did not include any message content.", {
110676
+ result,
110677
+ emptyMessage: Array.isArray(payload?.choices) && payload.choices.length > 0
110678
+ });
110679
+ }
110680
+ return result;
110462
110681
  };
110463
110682
  normalizeRuntimeChatHistory = (messages) => {
110464
110683
  if (!Array.isArray(messages)) {
@@ -110557,6 +110776,7 @@ var init_provider_client = __esm({
110557
110776
  });
110558
110777
  let response = null;
110559
110778
  let dispatchMarker = null;
110779
+ const internalDispatchAttempts = [];
110560
110780
  try {
110561
110781
  const reasoningParams = resolveProviderReasoningParameters(provider, reasoningPayload);
110562
110782
  const useReasoningCompletionTokens = usesReasoningCompletionTokens(provider, reasoningParams);
@@ -110690,50 +110910,131 @@ var init_provider_client = __esm({
110690
110910
  if (useRelay && configuredPlans?.length && !relayPlan) {
110691
110911
  throw new Error(`The selected ${provider} endpoint does not match a configured plan.`);
110692
110912
  }
110693
- dispatchMarker = beginProviderDispatch(finalRequestBody);
110694
- response = useRelay ? await relayNativeProviderRequest(provider, String(apiKey || "").trim(), finalRequestBody, {
110695
- profileId: profileId == null ? void 0 : Number(profileId),
110696
- signal,
110697
- planId: relayPlan?.id,
110698
- traceId: trace.id
110699
- }) : await fetchProvider(requestUrl, {
110700
- method: "POST",
110701
- headers: requestHeaders,
110702
- body: JSON.stringify(finalRequestBody),
110703
- signal
110704
- });
110705
- const payload = typeof onDelta === "function" ? await readOpenAiCompatibleTextStream(response, runtimeMode, onDelta, (rawPayload) => {
110706
- if (dispatchMarker) Object.assign(dispatchMarker.effectiveReasoningParameters, extractProviderReasoningParameters(rawPayload));
110707
- }).then(({ payload: streamPayload, rawText }) => {
110708
- trace.attachResponse({
110709
- status: response?.status ?? null,
110710
- statusText: response?.statusText ?? "",
110711
- body: null,
110712
- rawText: rawProviderTextForDebug(null, rawText)
110913
+ const dispatch = async (body) => {
110914
+ if (body !== finalRequestBody) trace.attachRequest({ url: requestUrl, method: "POST", headers: requestHeaders, body });
110915
+ response = null;
110916
+ const marker = beginProviderDispatch(body);
110917
+ dispatchMarker = marker;
110918
+ const dispatched = useRelay ? await relayNativeProviderRequest(provider, String(apiKey || "").trim(), body, {
110919
+ profileId: profileId == null ? void 0 : Number(profileId),
110920
+ signal,
110921
+ planId: relayPlan?.id,
110922
+ traceId: trace.id
110923
+ }) : await fetchProvider(requestUrl, {
110924
+ method: "POST",
110925
+ headers: requestHeaders,
110926
+ body: JSON.stringify(body),
110927
+ signal
110713
110928
  });
110714
- return streamPayload;
110715
- }) : await extractOpenAiCompatibleText(response, runtimeMode, (payloadJson, rawText) => {
110716
- dispatchMarker.effectiveReasoningParameters = extractProviderReasoningParameters(payloadJson);
110717
- trace.attachResponse({
110718
- status: response?.status ?? null,
110719
- statusText: response?.statusText ?? "",
110720
- body: payloadJson,
110721
- rawText: rawProviderTextForDebug(payloadJson, rawText)
110929
+ response = dispatched;
110930
+ const payload = typeof onDelta === "function" ? await readOpenAiCompatibleTextStream(dispatched, runtimeMode, onDelta, (rawPayload) => {
110931
+ Object.assign(marker.effectiveReasoningParameters, extractProviderReasoningParameters(rawPayload));
110932
+ }).then(({ payload: streamPayload, rawText }) => {
110933
+ trace.attachResponse({
110934
+ status: dispatched.status,
110935
+ statusText: dispatched.statusText ?? "",
110936
+ body: null,
110937
+ rawText: rawProviderTextForDebug(null, rawText)
110938
+ });
110939
+ return streamPayload;
110940
+ }) : await extractOpenAiCompatibleText(dispatched, runtimeMode, (payloadJson, rawText) => {
110941
+ marker.effectiveReasoningParameters = extractProviderReasoningParameters(payloadJson);
110942
+ trace.attachResponse({
110943
+ status: dispatched.status,
110944
+ statusText: dispatched.statusText ?? "",
110945
+ body: payloadJson,
110946
+ rawText: rawProviderTextForDebug(payloadJson, rawText)
110947
+ });
110948
+ });
110949
+ return {
110950
+ ...payload,
110951
+ sentReasoningParameters: marker.sentReasoningParameters,
110952
+ effectiveReasoningParameters: marker.effectiveReasoningParameters,
110953
+ requestInputTokens: marker.requestInputTokens,
110954
+ providerDiagnostics: marker.providerDiagnostics,
110955
+ providerStatusCode: dispatched.status,
110956
+ dispatchStartedAt: marker.startedAt,
110957
+ dispatchLatencyMs: providerDispatchLatencyMs(marker)
110958
+ };
110959
+ };
110960
+ const attemptDispatch = async (body) => {
110961
+ try {
110962
+ return { ok: true, payload: await dispatch(body) };
110963
+ } catch (error48) {
110964
+ return { ok: false, error: error48 };
110965
+ }
110966
+ };
110967
+ const recordInternalRetry = (error48) => {
110968
+ if (!dispatchMarker) return;
110969
+ internalDispatchAttempts.push({
110970
+ sentReasoningParameters: dispatchMarker.sentReasoningParameters,
110971
+ effectiveReasoningParameters: dispatchMarker.effectiveReasoningParameters,
110972
+ startedAt: dispatchMarker.startedAt,
110973
+ latencyMs: providerDispatchLatencyMs(dispatchMarker),
110974
+ transport: "openai_compatible_chat_completions",
110975
+ requestInputTokens: dispatchMarker.requestInputTokens,
110976
+ providerDiagnostics: dispatchMarker.providerDiagnostics,
110977
+ providerRequestId: providerRequestId(response),
110978
+ errorDetail: getSanitizedRuntimeErrorMessage(error48) || "Provider compatibility dispatch failed.",
110979
+ // An empty reply is an unknown outcome with no status, as in Server Mode.
110980
+ statusCode: isEmptyProviderContentFailure(error48) ? null : response?.status ?? null,
110981
+ retryable: isEmptyProviderContentFailure(error48),
110982
+ response: emptyReplyForInternalAttempt(error48)
110722
110983
  });
110723
- });
110724
- trace.completeSuccess(response.status);
110725
- return {
110726
- ...payload,
110727
- sentReasoningParameters: dispatchMarker.sentReasoningParameters,
110728
- effectiveReasoningParameters: dispatchMarker.effectiveReasoningParameters,
110729
- requestInputTokens: dispatchMarker.requestInputTokens,
110730
- providerDiagnostics: dispatchMarker.providerDiagnostics,
110731
- providerStatusCode: response.status,
110732
- dispatchStartedAt: dispatchMarker.startedAt,
110733
- dispatchLatencyMs: providerDispatchLatencyMs(dispatchMarker)
110734
110984
  };
110985
+ let dispatchedBody = finalRequestBody;
110986
+ let outcome = await attemptDispatch(dispatchedBody);
110987
+ if (!outcome.ok && !signal?.aborted && isOptionalContractParameterRejection(outcome.error)) {
110988
+ const withoutExtraBody = Object.fromEntries(
110989
+ Object.entries(requestBody).filter(([key]) => !OPTIONAL_CONTRACT_EXTRA_BODY_KEYS.includes(key))
110990
+ );
110991
+ const fallbackBody = applyNativeRequestParameters(
110992
+ withoutExtraBody,
110993
+ (nativeRequestParameters ?? []).filter((parameter) => parameter.request_path !== "extra_body" && !parameter.request_path.startsWith("extra_body.")),
110994
+ nativeRequestParameterValues,
110995
+ "openai_compatible_chat_completions",
110996
+ { includeAppManaged: true, mapRequestPath: mapOpenAiCompatibleNativeRequestPath }
110997
+ );
110998
+ for (const key of OPTIONAL_CONTRACT_REQUEST_KEYS) delete fallbackBody[key];
110999
+ const hadOptionalContractArguments = Object.keys(finalRequestBody).some((key) => !(key in fallbackBody));
111000
+ if (hadOptionalContractArguments && !hasUserSelectedNativeRequestParameters(
111001
+ nativeRequestParameters,
111002
+ nativeRequestParameterValues,
111003
+ "openai_compatible_chat_completions"
111004
+ )) {
111005
+ recordInternalRetry(outcome.error);
111006
+ appendRuntimeDebugEvent({
111007
+ label: "optional_contract_arguments_rejected_retry",
111008
+ note: `provider=${provider} model=${model}`,
111009
+ outcome: "error"
111010
+ });
111011
+ dispatchedBody = fallbackBody;
111012
+ outcome = await attemptDispatch(dispatchedBody);
111013
+ }
111014
+ }
111015
+ if (!outcome.ok && provider === "venice" && typeof onDelta !== "function" && !signal?.aborted && isEmptyProviderMessageFailure(outcome.error)) {
111016
+ recordInternalRetry(outcome.error);
111017
+ appendRuntimeDebugEvent({
111018
+ label: "venice_empty_content_thinking_disabled_retry",
111019
+ note: `model=${model}`,
111020
+ outcome: "error"
111021
+ });
111022
+ dispatchedBody = {
111023
+ ...dispatchedBody,
111024
+ venice_parameters: {
111025
+ ...asRequestRecord(dispatchedBody.venice_parameters),
111026
+ strip_thinking_response: true,
111027
+ disable_thinking: true
111028
+ }
111029
+ };
111030
+ outcome = await attemptDispatch(dispatchedBody);
111031
+ }
111032
+ if (!outcome.ok) throw outcome.error;
111033
+ trace.completeSuccess(outcome.payload.providerStatusCode ?? null);
111034
+ return { ...outcome.payload, internalDispatchAttempts };
110735
111035
  } catch (error48) {
110736
111036
  const sanitizedError = attachProviderDispatchFailure(error48, dispatchMarker, response);
111037
+ sanitizedError.runtimeInternalDispatchAttempts = internalDispatchAttempts;
110737
111038
  trace.completeError(toProviderNetworkDebugError(sanitizedError), response?.status ?? null);
110738
111039
  throw attachProviderFailureTrace(sanitizedError, trace.id);
110739
111040
  }
@@ -110835,7 +111136,7 @@ var init_provider_client = __esm({
110835
111136
  }
110836
111137
  const text = extractOpenAiResponsesText(payload);
110837
111138
  if (!text) {
110838
- throw new Error("OpenAI Responses API did not include any text content.");
111139
+ throw emptyProviderContentError("OpenAI Responses API did not include any text content.");
110839
111140
  }
110840
111141
  trace.completeSuccess(response.status);
110841
111142
  return {
@@ -110982,7 +111283,7 @@ var init_provider_client = __esm({
110982
111283
  }
110983
111284
  const text = extractAnthropicMessageText(payload);
110984
111285
  if (!text) {
110985
- throw new Error("Anthropic response did not include any text content.");
111286
+ throw emptyProviderContentError("Anthropic response did not include any text content.");
110986
111287
  }
110987
111288
  const reasoningContent = extractAnthropicReasoningContent(payload);
110988
111289
  const anthropicUsage = buildAnthropicUsagePayload(payload?.usage);
@@ -111362,7 +111663,7 @@ var init_provider_client = __esm({
111362
111663
  blockedError.runtimeProviderResult = providerResult;
111363
111664
  throw blockedError;
111364
111665
  }
111365
- throw new Error("Google response did not include any text content.");
111666
+ throw emptyProviderContentError("Google response did not include any text content.");
111366
111667
  }
111367
111668
  trace.completeSuccess(response.status);
111368
111669
  return providerResult;
@@ -111670,6 +111971,8 @@ var init_provider_client = __esm({
111670
111971
  });
111671
111972
  const providerKeySlots = resolveProviderSecretKeySlots(provider, secrets);
111672
111973
  let providerKeySlotIndex = Math.max(0, input.providerKeySlotIndex ?? 0);
111974
+ const keySweepStartSlotIndex = input.keySweepStartSlotIndex ?? providerKeySlotIndex;
111975
+ const emptyContentRetryPolicy = resolveEmptyContentRetryPolicy(config2);
111673
111976
  if (input.allowFallback !== false) {
111674
111977
  const eligibleSlot = providerKeySlots.findIndex((_, index) => index >= providerKeySlotIndex && runtimeKeySlotSupportsModel(config2, secrets, provider, index, model));
111675
111978
  if (eligibleSlot >= 0) providerKeySlotIndex = eligibleSlot;
@@ -111756,6 +112059,7 @@ var init_provider_client = __esm({
111756
112059
  requestInputTokens: attempt.requestInputTokens,
111757
112060
  providerDiagnostics: attempt.providerDiagnostics,
111758
112061
  providerRequestId: attempt.providerRequestId,
112062
+ response: attempt.response ?? null,
111759
112063
  retryable: attempt.retryable ?? false,
111760
112064
  fallbackFrom: chain.at(-1) ?? null
111761
112065
  }));
@@ -112033,7 +112337,7 @@ var init_provider_client = __esm({
112033
112337
  registerTraderProviderCallFinished(schedulerResourceKey, schedulerOwnerId, failedAtMs - startedAtMs);
112034
112338
  const detail = getSanitizedRuntimeErrorMessage(error48) || String(error48 || "unknown provider error");
112035
112339
  const nativeFailureKind = error48?.runtimeNativeFailureKind;
112036
- const statusCode = extractRuntimeProviderFailureStatusCode(error48);
112340
+ const statusCode = isEmptyProviderContentFailure(error48) ? null : extractRuntimeProviderFailureStatusCode(error48);
112037
112341
  const rawInternalDispatchAttempts = error48?.runtimeInternalDispatchAttempts;
112038
112342
  const observedInvocationAttempts2 = await withInternalDispatchAttempts(
112039
112343
  rawInternalDispatchAttempts
@@ -112094,7 +112398,12 @@ var init_provider_client = __esm({
112094
112398
  errorDetail: detail,
112095
112399
  statusCode,
112096
112400
  failureCode: nativeFailureKind === "transport" ? "transport_error" : nativeFailureKind === "timeout" ? "timeout" : signal?.aborted || isAbortLikeError(error48) ? "cancelled" : void 0,
112097
- retryable: isRetryableProviderFailureForFallback(detail),
112401
+ retryable: isRetryableProviderAttemptFailure({
112402
+ detail,
112403
+ statusCode,
112404
+ nativeFailureKind,
112405
+ emptyContent: isEmptyProviderContentFailure(error48)
112406
+ }),
112098
112407
  providerCost: failedCostInfo?.costStatus === "unavailable" ? null : failedCostInfo?.cost,
112099
112408
  userCost: failedCostInfo?.costStatus === "unavailable" ? null : failedCostInfo?.costUser,
112100
112409
  costStatus: failedCostInfo?.costStatus ?? "unavailable",
@@ -112132,7 +112441,9 @@ var init_provider_client = __esm({
112132
112441
  });
112133
112442
  }
112134
112443
  }
112135
- if ((!egress || googleEgressHasBudget(egress)) && !signal?.aborted && input.allowFallback !== false && !emittedDelta && (isKeySpecificOrTransientProviderFailure(detail) || isModelSpecificProviderFailure(detail) || retryableRouteFailure)) {
112444
+ const emptyContentFailure = isEmptyProviderContentFailure(error48);
112445
+ const keySpecificOrTransientFailure = isKeySpecificOrTransientProviderFailure(detail) || statusCode === HTTP_STATUS.REQUEST_TIMEOUT || nativeFailureKind === "transport" || emptyContentFailure;
112446
+ if ((!egress || googleEgressHasBudget(egress)) && !signal?.aborted && input.allowFallback !== false && !emittedDelta && (keySpecificOrTransientFailure || isModelSpecificProviderFailure(detail) || retryableRouteFailure)) {
112136
112447
  const nextProviderKeySlotIndex = providerKeySlots.findIndex((_, index) => index > providerKeySlotIndex && runtimeKeySlotSupportsModel(config2, secrets, provider, index, model) && (!isModelSpecificProviderFailure(detail) || resolveNativeProviderCredentialSlots(provider, secrets)[index]?.baseUrl !== resolveNativeProviderCredentialSlots(provider, secrets)[providerKeySlotIndex]?.baseUrl));
112137
112448
  if (provider !== "local" && nextProviderKeySlotIndex >= 0) {
112138
112449
  const diagnostics = normalizeProviderDiagnostics(error48?.runtimeProviderDiagnostics);
@@ -112168,6 +112479,38 @@ var init_provider_client = __esm({
112168
112479
  return await invokeRuntimeProviderAttempt({
112169
112480
  ...input,
112170
112481
  providerKeySlotIndex: nextProviderKeySlotIndex,
112482
+ keySweepStartSlotIndex,
112483
+ googleEgressRoute: void 0,
112484
+ googleEgressTriedRoutes: [],
112485
+ nativeRecoverySafe,
112486
+ invocationAttemptChain: invocationAttempts2
112487
+ });
112488
+ }
112489
+ }
112490
+ if (emptyContentFailure && (!egress || googleEgressHasBudget(egress)) && !signal?.aborted && input.allowFallback !== false && !emittedDelta) {
112491
+ const retryPolicy = emptyContentRetryPolicy;
112492
+ const retryCount = input.emptyContentRetryCount ?? 0;
112493
+ const retryDelayMs = retryPolicy === null ? 0 : (retryPolicy.delay_seconds + retryPolicy.jitter_min_seconds + Math.random() * (retryPolicy.jitter_max_seconds - retryPolicy.jitter_min_seconds)) * MS_PER_SECOND;
112494
+ const remainingMs = input.nativeRequestDeadlineMs === void 0 ? Number.POSITIVE_INFINITY : input.nativeRequestDeadlineMs - Date.now();
112495
+ if (retryPolicy !== null && retryCount < retryPolicy.max_retries && retryDelayMs < remainingMs) {
112496
+ try {
112497
+ await waitForProviderRetry(retryDelayMs, signal);
112498
+ } catch (cancelled) {
112499
+ cancelled.runtimeInvocationAttempts = invocationAttempts2;
112500
+ cancelled.runtimePartialOutput = emittedDelta;
112501
+ cancelled.runtimeNativeRecoverySafe = nativeRecoverySafe;
112502
+ throw cancelled;
112503
+ }
112504
+ appendRuntimeDebugEvent({
112505
+ label: "provider_empty_content_retry",
112506
+ note: `provider=${provider} model=${model} retry=${retryCount + 1}/${retryPolicy.max_retries}`,
112507
+ outcome: "error"
112508
+ });
112509
+ return await invokeRuntimeProviderAttempt({
112510
+ ...input,
112511
+ providerKeySlotIndex: keySweepStartSlotIndex,
112512
+ keySweepStartSlotIndex,
112513
+ emptyContentRetryCount: retryCount + 1,
112171
112514
  googleEgressRoute: void 0,
112172
112515
  googleEgressTriedRoutes: [],
112173
112516
  nativeRecoverySafe,
@@ -113609,7 +113952,6 @@ __export(local_analysis_exports, {
113609
113952
  isClientRuntimeAiScheduleStillActive: () => isClientRuntimeAiScheduleStillActive,
113610
113953
  isServerDispatchAccountStateStale: () => isServerDispatchAccountStateStale,
113611
113954
  perpDexScopeForSymbols: () => perpDexScopeForSymbols,
113612
- profileEquityPerpDexScope: () => profileEquityPerpDexScope,
113613
113955
  resolveEffectivePromptRuntimeProvenance: () => resolveEffectivePromptRuntimeProvenance,
113614
113956
  resolveExternalInferenceRuntimeTimeoutSeconds: () => resolveExternalInferenceRuntimeTimeoutSeconds,
113615
113957
  resolveLocalRuntimeSecretProvider: () => resolveLocalRuntimeSecretProvider,
@@ -113618,7 +113960,7 @@ __export(local_analysis_exports, {
113618
113960
  runLocalRuntimeCycle: () => runLocalRuntimeCycle,
113619
113961
  summarizeReviewFailureExplanation: () => summarizeReviewFailureExplanation
113620
113962
  });
113621
- var CYCLE_TIMEOUT_FLOOR_MS, DECISION_SETTLEMENT_RESERVE_MAX_BUDGET_DIVISOR, MIN_AGENT_INSTRUCTION_RETRY_AFTER_MS, PROMPT_PARITY_ERROR_DETAIL_MAX_CHARS, EXTERNAL_INFERENCE_RUNTIME_POLL_INTERVAL_MS, REVIEW_PROVIDER_SERVER_ERROR_STATUSES, TRUNCATION_ELLIPSIS2, normalizeNativeValues, assertPromptModelController, resolveRuntimeReasoningControlsForModel, modelScopedKey, resolveNativeValuesForModel, observeRuntimeCycle, observeAccountState, aiOrderSlippageFraction, serverBehaviorStateArtifacts, ClientRuntimeAgentInstructionEmpty, isClientRuntimeAgentInstructionEmpty, ClientRuntimeAiSchedulePaused, ClientRuntimeAiScheduleStillActive, isClientRuntimeAiScheduleStillActive, ServerDispatchAccountStateStale, isServerDispatchAccountStateStale, isClientRuntimeAiSchedulePaused, buildClaimedAgentRuntimeCycleResult, resolveRuntimeMarginModePreference, resolveRuntimeLeveragePreference, resolveBooleanSetting2, CLIENT_RUNTIME_LIVE_CONTEXT_UNAVAILABLE_ERRORS, BEHAVIOR_STATE_UNAVAILABLE_ERROR, CriticalBehaviorStateError, clampNumber, resolveExternalInferenceRuntimeTimeoutSeconds, toPositiveFinite3, compactSnippet, hashRuntimeDebugText, EFFECTIVE_INPUT_MANIFEST_SCHEMA_VERSION, PROMPT_ASSEMBLY_DEFINITION_VERSION, RUNTIME_SOURCE_DEFINITION_VERSION, DECISION_INPUT_DEFINITION_VERSION, CONTEXT_ENVELOPE_DEFINITION_VERSION, CLIENT_RUNTIME_SOURCE_VERSION, CLIENT_MAIN_PROMPT_RENDERER, SERVER_MAIN_PROMPT_RENDERER, CLIENT_REVIEW_PROMPT_RENDERER, SERVER_REVIEW_PROMPT_RENDERER, resolveEffectivePromptRuntimeProvenance, canonicalManifestValue, canonicalManifestJson, sha256ManifestHex, effectiveInputComponent, buildEffectiveInputManifest, derivePromptVisibleSections, decodeDecisionTracePayload, extractDecisionSymbolTrace, formatDecisionSymbolTrace, formatActionableDecisionSymbols, normalizePromptSymbols, JSON_MODEL_OUTPUT_FENCE_PATTERN, STRICT_MODEL_OUTPUT_KEYS, currentModelOutputValidationErrors, currentModelOutputMatchesContract, projectCurrentModelDecisionContent, modelOutputValidationError, buildMissingDecisionHold, buildDecisionPlansFromResponse, buildReviewCandidatePlansFromResponse, forceUnavailableSymbolsToHold, extractTemplatePlaceholders, requireReviewPrimaryUserPromptTemplate, containsCompetingBehaviorStateMarkup, containsCompetingMainBehaviorStateMarkup, requireStrategyReviewTemplates, preflightStrategyReviewPromptContract, extractRuntimeReasoningSelection, isAbortError, isRuntimeTimeoutAbortReason, REVIEW_FAILURE_SENSITIVE_DB_TOKENS, REVIEW_FAILURE_SCHEMA_DISCLOSURE_TOKENS, REVIEW_FAILURE_SQL_STATEMENT_PATTERN, REVIEW_FAILURE_TRACEBACK_PATTERN, isSensitiveReviewFailureDetail, summarizeReviewFailureExplanation, buildReviewFailureHoldReason, createAbortError2, settleRuntimeCyclePromise, unwrapRuntimeCycleSettledResult, normalizeDecisionLabel, normalizeRuntimeSymbol, PromptContractFetchError, isLivePromptContextUnavailableError, buildFailClosedHoldResult, buildPromptConstructionFailureResult, buildLivePromptContextUnavailableFailureResult, pickFirstString, normalizeRuntimeStringList, requirePositiveRuntimeLimit, resolveRuntimeTradingScope, normalizeRuntimeProviderAlias, resolveCatalogModelEntry, createClientRuntimeProviderSetupError, createProviderSetupRejectionError, evaluateModelEligibility, extractReviewRuntimeReasoningSelection, isUsableRuntimeSettingsFallback, resolveRuntimeSettings, formatRuntimeDurationMs, normalizeRuntimeTimingNote, appendRuntimeTimingEvent, reportPromptParityTelemetry, resolveLocalRuntimeSecretRequirements, resolveLocalRuntimeSecretProvider, toEpochSeconds, REQUIRED_AI_INDICATOR_KEYS, sortTradingTimeframes, normalizePromptIdentityTimestamp, resolveCompletedCandleBoundary, normalizeAiIndicatorFlags, getPromptLookback, computeSma, computeEma, computeRsi, computeAtr, computeMacd, computeBollingerBands, getIndicatorValue, buildPromptCandlesComponent, buildPromptCandlesPayload, formatUtcTimestampWithWeekday, formatUtcNowWithWeekday, formatPromptPrice, capacityUnitSize, computePromptUnitsUsedForPosition, buildPromptAccountStatusValue, buildPromptPositionsValue, sanitizePromptSymbol, fillTimeMs, fillSize, normalizeFillSide, normalizeFillOrderId, normalizeFillRiskOrderIdentity, fillStartPosition, fillSortValue, sortFillsAscending, sortFillsDescending, inferEntryFromStartPositionChain, inferEntryFromCurrentPositionSize, calculateCurrentPositionState, calculatePositionEntryTimes, countPositionAdds, latestPositionRiskIncreaseTimeMs, latestPositionRiskIncreaseEvidence, compactPromptRiskIncrease, roundPositiveDecimalHalfUp, compactPromptLastTrade, ENTRY_TRADE_FIELDS, PREVIOUS_DECISION_FIELDS, PREVIOUS_CAMPAIGN_FIELDS, hasExactKeys2, isNonnegativeInteger, isFiniteNumber, isExactEnumString, isNonemptyPromptText, isCampaignReasoningText, projectBackendDecisionMemoryItem, requireRenderedStrategyBehaviorState, canonicalFillSideForRiskEvidence, isValidRiskEvidenceFill, isValidCampaignBoundaryFill, normalizeFillHistoryCoverage, resolveFillHistoryCoverageForSymbol, buildPromptBehaviorStateArtifacts, buildPromptBehaviorStateValue, shouldCompareServerPromptParity, buildLocalRuntimePromptArtifacts, createRuntimeId2, asRecord, buildRuntimeConstraintRejectionMessage, hasDeviceProviderSecret, requireNonEmptyStringField, requirePositiveIntegerField, compareContractVersion, parsePromptContractTimestamp, assertPromptContractCompatibility, assertPromptContractTemporalBounds, sleepWithAbort, requireAgentPollRetryAfterMs, materializeClaimedClientRuntimeAgentInstruction, attachClientRuntimeErrorProvenance, isExternalRuntimeProviderResult, invokeClientExternalInference, assertPromptContractBindingTupleEqual, assertPromptContractScopeMatch, fetchBoundPromptContracts, formatTemplateWithNamedVariables, carryReturnedModelCalls, runLocalRuntimeCycle;
113963
+ var CYCLE_TIMEOUT_FLOOR_MS, DECISION_SETTLEMENT_RESERVE_MAX_BUDGET_DIVISOR, MIN_AGENT_INSTRUCTION_RETRY_AFTER_MS, PROMPT_PARITY_ERROR_DETAIL_MAX_CHARS, EXTERNAL_INFERENCE_RUNTIME_POLL_INTERVAL_MS, REVIEW_PROVIDER_SERVER_ERROR_STATUSES, TRUNCATION_ELLIPSIS2, normalizeNativeValues, assertPromptModelController, resolveRuntimeReasoningControlsForModel, modelScopedKey, resolveNativeValuesForModel, observeRuntimeCycle, observeAccountState, aiOrderSlippageFraction, serverBehaviorStateArtifacts, ClientRuntimeAgentInstructionEmpty, isClientRuntimeAgentInstructionEmpty, ClientRuntimeAiSchedulePaused, ClientRuntimeAiScheduleStillActive, isClientRuntimeAiScheduleStillActive, ServerDispatchAccountStateStale, isServerDispatchAccountStateStale, isClientRuntimeAiSchedulePaused, acceptancePositionCaps, accountSnapshotCapturedAt, buildClaimedAgentRuntimeCycleResult, resolveRuntimeMarginModePreference, resolveRuntimeLeveragePreference, resolveBooleanSetting2, CLIENT_RUNTIME_LIVE_CONTEXT_UNAVAILABLE_ERRORS, BEHAVIOR_STATE_UNAVAILABLE_ERROR, CriticalBehaviorStateError, clampNumber, resolveExternalInferenceRuntimeTimeoutSeconds, toPositiveFinite3, compactSnippet, hashRuntimeDebugText, EFFECTIVE_INPUT_MANIFEST_SCHEMA_VERSION, PROMPT_ASSEMBLY_DEFINITION_VERSION, RUNTIME_SOURCE_DEFINITION_VERSION, DECISION_INPUT_DEFINITION_VERSION, CONTEXT_ENVELOPE_DEFINITION_VERSION, CLIENT_RUNTIME_SOURCE_VERSION, CLIENT_MAIN_PROMPT_RENDERER, SERVER_MAIN_PROMPT_RENDERER, CLIENT_REVIEW_PROMPT_RENDERER, SERVER_REVIEW_PROMPT_RENDERER, resolveEffectivePromptRuntimeProvenance, canonicalManifestValue, canonicalManifestJson, sha256ManifestHex, effectiveInputComponent, buildEffectiveInputManifest, derivePromptVisibleSections, decodeDecisionTracePayload, extractDecisionSymbolTrace, formatDecisionSymbolTrace, formatActionableDecisionSymbols, decisionRecordsBySymbol, normalizePromptSymbols, JSON_MODEL_OUTPUT_FENCE_PATTERN, STRICT_MODEL_OUTPUT_KEYS, currentModelOutputValidationErrors, currentModelOutputMatchesContract, projectCurrentModelDecisionContent, modelOutputValidationError, buildMissingDecisionHold, buildDecisionPlansFromResponse, buildReviewCandidatePlansFromResponse, forceUnavailableSymbolsToHold, extractTemplatePlaceholders, requireReviewPrimaryUserPromptTemplate, containsCompetingBehaviorStateMarkup, containsCompetingMainBehaviorStateMarkup, requireStrategyReviewTemplates, preflightStrategyReviewPromptContract, extractRuntimeReasoningSelection, isAbortError, isRuntimeTimeoutAbortReason, REVIEW_FAILURE_SENSITIVE_DB_TOKENS, REVIEW_FAILURE_SCHEMA_DISCLOSURE_TOKENS, REVIEW_FAILURE_SQL_STATEMENT_PATTERN, REVIEW_FAILURE_TRACEBACK_PATTERN, isSensitiveReviewFailureDetail, summarizeReviewFailureExplanation, buildReviewFailureHoldReason, createAbortError2, settleRuntimeCyclePromise, unwrapRuntimeCycleSettledResult, normalizeDecisionLabel, normalizeRuntimeSymbol, PromptContractFetchError, isLivePromptContextUnavailableError, buildFailClosedHoldResult, buildPromptConstructionFailureResult, buildLivePromptContextUnavailableFailureResult, pickFirstString, normalizeRuntimeStringList, requirePositiveRuntimeLimit, resolveRuntimeTradingScope, normalizeRuntimeProviderAlias, resolveCatalogModelEntry, createClientRuntimeProviderSetupError, createProviderSetupRejectionError, evaluateModelEligibility, extractReviewRuntimeReasoningSelection, isUsableRuntimeSettingsFallback, resolveRuntimeSettings, formatRuntimeDurationMs, normalizeRuntimeTimingNote, appendRuntimeTimingEvent, reportPromptParityTelemetry, resolveLocalRuntimeSecretRequirements, resolveLocalRuntimeSecretProvider, toEpochSeconds, REQUIRED_AI_INDICATOR_KEYS, sortTradingTimeframes, normalizePromptIdentityTimestamp, resolveCompletedCandleBoundary, normalizeAiIndicatorFlags, getPromptLookback, computeSma, computeEma, computeRsi, computeAtr, computeMacd, computeBollingerBands, getIndicatorValue, buildPromptCandlesComponent, CANDLE_CLOSE_TICKER_TIMEFRAME, candleCloseTicker, buildPromptCandlesPayload, formatUtcTimestampWithWeekday, formatUtcNowWithWeekday, formatPromptPrice, capacityUnitSize, computePromptUnitsUsedForPosition, buildPromptAccountStatusValue, buildPromptPositionsValue, sanitizePromptSymbol, fillTimeMs, fillSize, normalizeFillSide, normalizeFillOrderId, normalizeFillRiskOrderIdentity, fillStartPosition, fillSortValue, sortFillsAscending, sortFillsDescending, inferEntryFromStartPositionChain, inferEntryFromCurrentPositionSize, calculateCurrentPositionState, calculatePositionEntryTimes, countPositionAdds, latestPositionRiskIncreaseTimeMs, latestPositionRiskIncreaseEvidence, compactPromptRiskIncrease, roundPositiveDecimalHalfUp, compactPromptLastTrade, ENTRY_TRADE_FIELDS, PREVIOUS_DECISION_FIELDS, PREVIOUS_CAMPAIGN_FIELDS, hasExactKeys2, isNonnegativeInteger, isFiniteNumber, isExactEnumString, isNonemptyPromptText, isCampaignReasoningText, projectBackendDecisionMemoryItem, requireRenderedStrategyBehaviorState, canonicalFillSideForRiskEvidence, isValidRiskEvidenceFill, isValidCampaignBoundaryFill, normalizeFillHistoryCoverage, resolveFillHistoryCoverageForSymbol, buildPromptBehaviorStateArtifacts, buildPromptBehaviorStateValue, shouldCompareServerPromptParity, buildLocalRuntimePromptArtifacts, createRuntimeId2, asRecord, buildRuntimeConstraintRejectionMessage, hasDeviceProviderSecret, requireNonEmptyStringField, requirePositiveIntegerField, compareContractVersion, parsePromptContractTimestamp, assertPromptContractCompatibility, assertPromptContractTemporalBounds, sleepWithAbort, requireAgentPollRetryAfterMs, materializeClaimedClientRuntimeAgentInstruction, attachClientRuntimeErrorProvenance, isExternalRuntimeProviderResult, invokeClientExternalInference, assertPromptContractBindingTupleEqual, assertPromptContractScopeMatch, fetchBoundPromptContracts, formatTemplateWithNamedVariables, carryReturnedModelCalls, runLocalRuntimeCycle;
113622
113964
  var init_local_analysis = __esm({
113623
113965
  "lib/runtime/local-analysis.ts"() {
113624
113966
  "use strict";
@@ -113793,6 +114135,10 @@ var init_local_analysis = __esm({
113793
114135
  };
113794
114136
  isServerDispatchAccountStateStale = (value) => value instanceof Error && value.name === "ServerDispatchAccountStateStale";
113795
114137
  isClientRuntimeAiSchedulePaused = (value) => value instanceof ClientRuntimeAiSchedulePaused;
114138
+ acceptancePositionCaps = (executionMode, caps) => executionMode === "server" ? { remaining_global_units: null, remaining_exchange_units: null, remaining_asset_units: null } : caps;
114139
+ accountSnapshotCapturedAt = (executionMode, accountStateFetchedAtMs) => new Date(
114140
+ (executionMode === "server" ? accountStateFetchedAtMs : null) ?? Date.now()
114141
+ ).toISOString();
113796
114142
  buildClaimedAgentRuntimeCycleResult = async (input) => {
113797
114143
  const { config: config2, settings, instruction, runtimeInput, signal } = input;
113798
114144
  const binding = runtimeInput.runtimeContractBinding;
@@ -113989,9 +114335,11 @@ var init_local_analysis = __esm({
113989
114335
  runtime_disabled: settings.main_model_enabled === false,
113990
114336
  kill_switch_active: false,
113991
114337
  max_trades_per_prompt: remainingPromptUnits,
113992
- remaining_exchange_units: Math.max(0, maxTradesPerExchange - (exchangeUnitsUsed.get(getHyperliquidMarketDex(entry.symbol)) ?? 0)),
113993
- remaining_global_units: remainingGlobalUnits,
113994
- remaining_asset_units: remainingAssetUnits,
114338
+ ...acceptancePositionCaps(runtimeInput.executionMode, {
114339
+ remaining_exchange_units: Math.max(0, maxTradesPerExchange - (exchangeUnitsUsed.get(getHyperliquidMarketDex(entry.symbol)) ?? 0)),
114340
+ remaining_global_units: remainingGlobalUnits,
114341
+ remaining_asset_units: remainingAssetUnits
114342
+ }),
113995
114343
  current_symbol_signed_units: currentSignedUnits,
113996
114344
  model_allowed: true,
113997
114345
  provider_allowed: true
@@ -114113,7 +114461,7 @@ var init_local_analysis = __esm({
114113
114461
  clientExchangeSnapshot: buildClientExchangeSnapshot({
114114
114462
  walletAddress,
114115
114463
  symbol: symbol2,
114116
- capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
114464
+ capturedAt: accountSnapshotCapturedAt(runtimeInput.executionMode, accountState.evidence?.fetchedAtMs),
114117
114465
  markPrice: primaryPrice,
114118
114466
  accountSummary: accountState.accountSummary,
114119
114467
  positions: accountState.positions,
@@ -114455,6 +114803,12 @@ var init_local_analysis = __esm({
114455
114803
  };
114456
114804
  formatDecisionSymbolTrace = (symbols) => symbols.length > 0 ? symbols.map((entry) => `${entry.symbol}:${entry.decision}/${entry.units}`).join(",") : "none";
114457
114805
  formatActionableDecisionSymbols = (symbols) => formatDecisionSymbolTrace(symbols.filter((entry) => entry.decision !== "HOLD" && entry.units > 0));
114806
+ decisionRecordsBySymbol = (plans) => Object.fromEntries(plans.map((plan) => [plan.symbol, {
114807
+ decision: plan.decision,
114808
+ reasoning: plan.reasoning,
114809
+ units: plan.units,
114810
+ tradability: plan.tradability
114811
+ }]));
114458
114812
  normalizePromptSymbols = (symbols) => {
114459
114813
  const seen = /* @__PURE__ */ new Set();
114460
114814
  const normalized = [];
@@ -115689,10 +116043,19 @@ ${reviewOutputContract}`;
115689
116043
  });
115690
116044
  return { c: summarized };
115691
116045
  };
116046
+ CANDLE_CLOSE_TICKER_TIMEFRAME = "5m";
116047
+ candleCloseTicker = (symbol2, candlesByTimeframe) => {
116048
+ const preferred = candlesByTimeframe[CANDLE_CLOSE_TICKER_TIMEFRAME] ?? [];
116049
+ const reference = preferred.length > 0 ? preferred : Object.values(candlesByTimeframe).find((rows) => rows.length > 0) ?? [];
116050
+ const latest = reference.reduce((current, candle) => current === null || toEpochSeconds(candle.timestamp) > toEpochSeconds(current.timestamp) ? candle : current, null);
116051
+ const close = toPositiveFinite3(latest?.close);
116052
+ return close === null ? null : { symbol: symbol2, price: close, timestamp: "", source: "recent_candle_close" };
116053
+ };
115692
116054
  buildPromptCandlesPayload = (input) => {
115693
116055
  const payload = {};
115694
116056
  for (const symbol2 of input.symbols) {
115695
- const asOfTimestamp = toEpochSeconds(input.tickersBySymbol[symbol2]?.timestamp) || Math.floor(Date.now() / MS_PER_SECOND);
116057
+ const symbolTicker = input.tickersBySymbol[symbol2];
116058
+ const asOfTimestamp = (symbolTicker?.is_fresh === true ? toEpochSeconds(symbolTicker.timestamp) : 0) || Math.floor(Date.now() / MS_PER_SECOND);
115696
116059
  const symbolData = {
115697
116060
  data: {}
115698
116061
  };
@@ -117637,10 +118000,6 @@ ${behaviorJson}
117637
118000
  );
117638
118001
  }
117639
118002
  let requestTimeoutSeconds = clampNumber(settings.timeout_seconds, config2.default_timeout_seconds);
117640
- let requestTimeoutMs = Math.max(CYCLE_TIMEOUT_FLOOR_MS, Math.round(requestTimeoutSeconds * MS_PER_SECOND));
117641
- if (requestTimeoutMs !== defaultTimeoutMs) {
117642
- armCycleDeadline(requestTimeoutMs, "Runtime request timeout reached.");
117643
- }
117644
118003
  const {
117645
118004
  symbols,
117646
118005
  timeframes,
@@ -117890,8 +118249,13 @@ ${behaviorJson}
117890
118249
  const marketDataStartedAtMs = Date.now();
117891
118250
  const candlesTickerPromise = Promise.all(
117892
118251
  symbols.map(async (marketSymbol) => {
118252
+ let tickerError = null;
117893
118253
  const [loadedTicker, loadedCandles] = await Promise.all([
117894
- getLiveTicker(marketSymbol, "hyperliquid", timeoutController.signal),
118254
+ getLiveTicker(marketSymbol, "hyperliquid", timeoutController.signal).catch((error48) => {
118255
+ if (timeoutController.signal.aborted || isAbortLikeError(error48)) throw error48;
118256
+ tickerError = error48;
118257
+ return null;
118258
+ }),
117895
118259
  Promise.all(
117896
118260
  sortedTimeframes.map(async (marketTimeframe) => [
117897
118261
  marketTimeframe,
@@ -117912,11 +118276,17 @@ ${behaviorJson}
117912
118276
  ])
117913
118277
  )
117914
118278
  ]);
117915
- return {
117916
- symbol: marketSymbol,
117917
- ticker: loadedTicker,
117918
- candles: Object.fromEntries(loadedCandles)
117919
- };
118279
+ const candles = Object.fromEntries(loadedCandles);
118280
+ const ticker2 = loadedTicker?.is_fresh === true && toPositiveFinite3(loadedTicker.price) !== null ? loadedTicker : candleCloseTicker(marketSymbol, candles) ?? loadedTicker;
118281
+ if (ticker2 === null) throw tickerError;
118282
+ if (loadedTicker === null) {
118283
+ appendRuntimeDebugEvent({
118284
+ label: "live_ticker_unavailable",
118285
+ note: `symbol=${marketSymbol} price_source=recent_candle_close detail=${tickerError instanceof Error ? tickerError.message : String(tickerError)}`,
118286
+ outcome: "error"
118287
+ });
118288
+ }
118289
+ return { symbol: marketSymbol, ticker: ticker2, candles };
117920
118290
  })
117921
118291
  ).then((result) => {
117922
118292
  const primaryTicker = result.find((entry) => entry.symbol === localFallbackSymbol)?.ticker ?? result[0]?.ticker;
@@ -118049,7 +118419,7 @@ ${behaviorJson}
118049
118419
  const clientExchangeSnapshot = buildClientExchangeSnapshot({
118050
118420
  walletAddress,
118051
118421
  symbol: symbol2,
118052
- capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
118422
+ capturedAt: accountSnapshotCapturedAt(input.executionMode, browserAccountState.evidence?.fetchedAtMs),
118053
118423
  markPrice: toPositiveFinite3(availableToTrade.mark_price) ?? toPositiveFinite3(ticker.price),
118054
118424
  accountSummary,
118055
118425
  positions,
@@ -118083,8 +118453,8 @@ ${behaviorJson}
118083
118453
  const maxTradesPerExchange = Math.round(clampNumber(promptKnobs.max_trades_per_exchange, maxTradesGlobal));
118084
118454
  const metadataTradeSize = clampNumber(promptKnobs.trade_size, config2.default_ai_trade_amount);
118085
118455
  const metadataLeverage = clampNumber(promptKnobs.leverage, config2.default_leverage);
118086
- const metricsWindowHours = Math.round(clampNumber(promptKnobs.metrics_window_hours, 0));
118087
- const metricsSecondaryWindowHours = Math.round(clampNumber(promptKnobs.metrics_secondary_window_hours, 0));
118456
+ const metricsWindowHours = clampNumber(promptKnobs.metrics_window_hours, 0);
118457
+ const metricsSecondaryWindowHours = clampNumber(promptKnobs.metrics_secondary_window_hours, 0);
118088
118458
  const promptSymbols = Array.isArray(promptKnobs.active_symbols) && promptKnobs.active_symbols.length > 0 ? promptKnobs.active_symbols.map((item) => String(item || "").trim()).filter(Boolean) : symbols;
118089
118459
  const promptTimeframes = Array.isArray(promptKnobs.active_timeframes) && promptKnobs.active_timeframes.length > 0 ? sortTradingTimeframes(promptKnobs.active_timeframes.map((item) => String(item || "").trim()).filter(Boolean)) : sortedTimeframes;
118090
118460
  const executionFreshnessMaxAgeSeconds = requirePositiveIntegerField(
@@ -118261,7 +118631,7 @@ ${behaviorJson}
118261
118631
  throw new Error(message);
118262
118632
  }
118263
118633
  } catch (error48) {
118264
- if (!(error48 instanceof Error) || !serverProviderNotConfigured || !deviceProviderModelEligible || normalizeModelFallbacks(settings.model_fallbacks).main.length === 0) throw error48;
118634
+ if (!(error48 instanceof Error) || normalizeModelFallbacks(settings.model_fallbacks).main.length === 0) throw error48;
118265
118635
  primaryAvailabilityError = Object.assign(error48, { modelFallbackSafe: true });
118266
118636
  }
118267
118637
  const localAcceptanceConstraints = {
@@ -118733,8 +119103,10 @@ ${stringifyPromptJson(candlesPayload)}
118733
119103
  config2,
118734
119104
  requestTimeoutSeconds
118735
119105
  );
118736
- requestTimeoutMs = Math.max(CYCLE_TIMEOUT_FLOOR_MS, Math.round(requestTimeoutSeconds * MS_PER_SECOND));
118737
- armCycleDeadline(requestTimeoutMs, "Runtime request timeout reached.");
119106
+ armCycleDeadline(
119107
+ Math.max(CYCLE_TIMEOUT_FLOOR_MS, Math.round(requestTimeoutSeconds * MS_PER_SECOND)),
119108
+ "Runtime request timeout reached."
119109
+ );
118738
119110
  appendRuntimeDebugEvent({
118739
119111
  label: "external_inference_timeout_extended",
118740
119112
  note: `lane=main seconds=${requestTimeoutSeconds}`
@@ -118824,7 +119196,12 @@ ${stringifyPromptJson(candlesPayload)}
118824
119196
  systemPrompt,
118825
119197
  userPrompt,
118826
119198
  temperature: entryParameters?.temperature ?? temperature,
118827
- maxTokens: entryParameters?.max_tokens ?? maxTokens,
119199
+ // Every Main model gets at least the configured output budget, as in
119200
+ // the Server loop (ai_trading_service.py _execute_llm_request).
119201
+ maxTokens: Math.max(
119202
+ entryParameters?.max_tokens ?? maxTokens,
119203
+ requirePositiveIntegerField(config2.max_tokens_min, "max_tokens_min")
119204
+ ),
118828
119205
  reasoningPayload: modelIndex === 0 ? reasoningPayload : buildRuntimeReasoningPayload(controls, extractRuntimeReasoningSelection({ runtime_reasoning: entryParameters?.runtime_reasoning }, controls.control_type, controls.control_type === "toggle" ? controls.toggle_behavior : "disable_reasoning")),
118829
119206
  nativeRequestParameters: entryConfig?.native_request_parameters,
118830
119207
  nativeRequestParameterValues: modelIndex === 0 ? nativeRequestParameterValues : filterNativeRequestParameterValues(entryConfig?.native_request_parameters, entryParameters?.native_request_parameter_values),
@@ -118966,6 +119343,7 @@ ${stringifyPromptJson(candlesPayload)}
118966
119343
  let finalTradability = selectedPrimaryPlan?.tradability ?? parsed.tradability;
118967
119344
  let reviewTradability = null;
118968
119345
  let finalAnalysis = primaryDecisionContent;
119346
+ let reviewedCycle = null;
118969
119347
  let finalModel = primaryDisplayModel;
118970
119348
  let finalProvider = providerResponse.provider;
118971
119349
  let finalSystemPrompt = systemPrompt;
@@ -119272,7 +119650,11 @@ ${reviewOutputContract}`;
119272
119650
  finalReasoning = selectedReviewedPlan?.reasoning ?? reviewed.reasoning;
119273
119651
  reviewTradability = selectedReviewedPlan?.tradability ?? reviewed.tradability;
119274
119652
  finalTradability = reviewTradability;
119275
- finalAnalysis = reviewDecisionContent;
119653
+ finalAnalysis = finalDecisionPlans.length > 1 ? JSON.stringify(decisionRecordsBySymbol(finalDecisionPlans)) : reviewDecisionContent;
119654
+ reviewedCycle = {
119655
+ originalModel: primaryDisplayModel,
119656
+ originalDecisions: decisionRecordsBySymbol(primaryDecisionPlans)
119657
+ };
119276
119658
  const reviewDisplayModel = isExternalRuntimeProviderResult(reviewResponse) ? String(reviewResponse.model || reviewModel).trim() || reviewModel : projectInvocationStageModelLabel({
119277
119659
  requestedModel: requestedReviewModel,
119278
119660
  displayModel: String(reviewResponse.model || reviewModel).trim() || reviewModel,
@@ -119324,6 +119706,7 @@ ${reviewOutputContract}`;
119324
119706
  ...entry,
119325
119707
  ...reviewedSymbolKeys.has(normalizeRuntimeSymbol(entry.symbol)) ? { decision: "HOLD", units: 0, reasoning: finalReasoning } : {}
119326
119708
  }));
119709
+ if (finalDecisionPlans.length > 1) finalAnalysis = JSON.stringify(decisionRecordsBySymbol(finalDecisionPlans));
119327
119710
  const failedSelectedPlan = finalDecisionPlans.find((entry) => normalizeRuntimeSymbol(entry.symbol) === normalizeRuntimeSymbol(symbol2)) ?? finalDecisionPlans[0];
119328
119711
  finalDecision = failedSelectedPlan?.decision ?? "HOLD";
119329
119712
  finalUnits = failedSelectedPlan?.units ?? 0;
@@ -119380,7 +119763,7 @@ ${reviewOutputContract}`;
119380
119763
  Math.round(Number(settings.tradability_increase_minimum ?? config2.default_tradability_increase_minimum))
119381
119764
  )
119382
119765
  );
119383
- const acceptedExecutionPlans = finalDecisionPlans.map((entry) => {
119766
+ const acceptExecutionPlan = (entry) => {
119384
119767
  const planSymbol = normalizeRuntimeSymbol(entry.symbol);
119385
119768
  const isPrimaryPlanSymbol = planSymbol === normalizeRuntimeSymbol(symbol2);
119386
119769
  const planSignedUnits = computePlanSignedUnits(entry.symbol);
@@ -119421,9 +119804,11 @@ ${reviewOutputContract}`;
119421
119804
  const planConstraints = {
119422
119805
  ...localAcceptanceConstraints,
119423
119806
  max_trades_per_prompt: remainingPromptUnits,
119424
- remaining_global_units: remainingGlobalUnits,
119425
- remaining_exchange_units: Math.max(0, maxTradesPerExchange - (exchangeUnitsUsed.get(getHyperliquidMarketDex(entry.symbol)) ?? 0)),
119426
- remaining_asset_units: remainingAssetUnits,
119807
+ ...acceptancePositionCaps(input.executionMode, {
119808
+ remaining_global_units: remainingGlobalUnits,
119809
+ remaining_exchange_units: Math.max(0, maxTradesPerExchange - (exchangeUnitsUsed.get(getHyperliquidMarketDex(entry.symbol)) ?? 0)),
119810
+ remaining_asset_units: remainingAssetUnits
119811
+ }),
119427
119812
  current_symbol_signed_units: planSignedUnits
119428
119813
  };
119429
119814
  const planAcceptance = evaluateRuntimeDecisionAcceptance({
@@ -119496,7 +119881,16 @@ ${reviewOutputContract}`;
119496
119881
  reasoning: entry.reasoning,
119497
119882
  executionContext: buildExecutionContextForSymbol(entry.symbol)
119498
119883
  };
119499
- });
119884
+ };
119885
+ const acceptedBySlot = /* @__PURE__ */ new Map();
119886
+ for (const slot of reductionFirstOrder(finalDecisionPlans.map((entry) => ({
119887
+ decision: entry.decision,
119888
+ units: entry.units,
119889
+ signedUnits: computePlanSignedUnits(entry.symbol)
119890
+ })))) {
119891
+ acceptedBySlot.set(slot, acceptExecutionPlan(finalDecisionPlans[slot]));
119892
+ }
119893
+ const acceptedExecutionPlans = finalDecisionPlans.map((_, slot) => acceptedBySlot.get(slot));
119500
119894
  const selectedAcceptedPlan = acceptedExecutionPlans.find((entry) => normalizeRuntimeSymbol(entry.symbol) === normalizeRuntimeSymbol(symbol2)) ?? acceptedExecutionPlans[0];
119501
119895
  const acceptance = {
119502
119896
  accepted: true,
@@ -119658,6 +120052,7 @@ ${reviewOutputContract}`;
119658
120052
  completedAt: (/* @__PURE__ */ new Date()).toISOString(),
119659
120053
  settingsFallbackUsed,
119660
120054
  settingsSnapshot: settingsSnapshotWithContext,
120055
+ reviewedCycle,
119661
120056
  clientExchangeSnapshot,
119662
120057
  executionContext: selectedAcceptedPlan?.executionContext ?? buildExecutionContextForSymbol(symbol2),
119663
120058
  executionPlans: acceptedExecutionPlans
@@ -119759,6 +120154,7 @@ var init_engine = __esm({
119759
120154
  init_hyperliquid_account_state_adapter();
119760
120155
  init_hyperliquid_market_symbol();
119761
120156
  init_client_killswitch();
120157
+ init_perp_dex_scope();
119762
120158
  init_api2();
119763
120159
  init_history_evidence();
119764
120160
  init_portfolio_evidence();
@@ -120153,24 +120549,16 @@ var init_engine = __esm({
120153
120549
  withServerPositionEvents = (result) => result.executionReports.map((report) => {
120154
120550
  const action = String(report.action ?? "").toUpperCase();
120155
120551
  if (report.status !== "executed" || !["BUY", "SELL", "FLIP_OPEN"].includes(action)) return report;
120156
- const bySide = (side) => side === "BUY" ? "LONG" : "SHORT";
120157
- let event = null;
120158
- let direction = null;
120159
- if (result.intent === "open" || result.intent === "add") {
120160
- event = result.intent;
120161
- direction = bySide(action);
120162
- } else if (result.intent === "reduce") {
120163
- event = "reduce";
120164
- direction = action === "BUY" ? "SHORT" : "LONG";
120165
- } else if (result.intent === "close") {
120166
- event = "close";
120167
- direction = action === "SELL" ? "LONG" : "SHORT";
120168
- } else if (result.intent === "flip" && (result.side === "buy" || result.side === "sell")) {
120169
- const [closeLeg, entryLeg] = flipExecutionLegs(result.side, "executed");
120170
- const leg = report.execution_metadata?.decision_leg === "entry" || action === "FLIP_OPEN" ? entryLeg : closeLeg;
120171
- event = leg.positionEvent;
120172
- direction = leg.positionDirection;
120173
- }
120552
+ const side = result.intent === "flip" || action === "FLIP_OPEN" ? result.side : action === "BUY" ? "buy" : "sell";
120553
+ if (side !== "buy" && side !== "sell") return report;
120554
+ const leg = report.execution_metadata?.decision_leg === "entry" || action === "FLIP_OPEN" ? "entry" : "flip_close";
120555
+ const { positionEvent: intentEvent, positionDirection: direction } = executedOrderPositionEvent(
120556
+ String(result.intent ?? ""),
120557
+ side,
120558
+ leg
120559
+ );
120560
+ const beganFlat = report.execution_metadata?.entry_began_flat;
120561
+ const event = (result.intent === "open" || result.intent === "add") && typeof beganFlat === "boolean" ? beganFlat ? "open" : "add" : result.intent === "close" && result.reasonCode === "close_fill_unresolved" ? "reduce" : intentEvent;
120174
120562
  if (!event || !direction) return report;
120175
120563
  return { ...report, execution_metadata: { ...report.execution_metadata, position_event: event, position_direction: direction } };
120176
120564
  });
@@ -120457,6 +120845,8 @@ var init_engine = __esm({
120457
120845
  this._settleUnreportedModelCalls = null;
120458
120846
  // How many of an error's model calls its last error report carried.
120459
120847
  this._lastErrorReportCalls = null;
120848
+ // The retry wait the API returned for this runtime's latest error report.
120849
+ this._reportedProviderRetryAfterSeconds = null;
120460
120850
  this._activeRuntimeContractIdentity = null;
120461
120851
  this._contractRebindInFlight = false;
120462
120852
  this._contractRebindExhausted = false;
@@ -120645,6 +121035,7 @@ var init_engine = __esm({
120645
121035
  await this._trailingMaintenancePromise;
120646
121036
  await this._pendingProtectionRecoveryPromise;
120647
121037
  await waitForBrowserExchangeMutationSettlement(profileId);
121038
+ const stopCloseVenues = profileEquityVenues(paused.settings.trading_symbols, paused.config.default_trading_symbols);
120648
121039
  const { positions } = await fetchBrowserAccountState2({
120649
121040
  publicRequestPriority: "trading_reduce",
120650
121041
  config: paused.config,
@@ -120653,6 +121044,8 @@ var init_engine = __esm({
120653
121044
  tickerPrice: 0,
120654
121045
  leverage: 1,
120655
121046
  aggregatePerpDexs: true,
121047
+ // Only the bot's exchanges: positions elsewhere are not the bot's to close.
121048
+ perpDexScope: stopCloseVenues?.filter(Boolean),
120656
121049
  forceRefresh: true,
120657
121050
  sessionId: this._sessionId ?? void 0
120658
121051
  });
@@ -120665,7 +121058,8 @@ var init_engine = __esm({
120665
121058
  positions,
120666
121059
  config: paused.config,
120667
121060
  signingKey,
120668
- timeoutSeconds
121061
+ timeoutSeconds,
121062
+ venues: stopCloseVenues
120669
121063
  });
120670
121064
  if (summary.positionCloseFailures > 0) {
120671
121065
  throw new Error(`${summary.positionCloseFailures} position(s) could not be closed`);
@@ -123321,7 +123715,17 @@ var init_engine = __esm({
123321
123715
  // A Server bot's row records what started its cycle, as the
123322
123716
  // Python Server loop's does (a Client row never has, and the key
123323
123717
  // is part of a row's Insights settings epoch).
123324
- settingsSnapshot: this._expectedExecutionMode === "server" ? { ...result.settingsSnapshot, analysis_trigger_origin: ignoreAiSchedule ? "manual" : "scheduled" } : result.settingsSnapshot,
123718
+ settingsSnapshot: {
123719
+ ...result.settingsSnapshot,
123720
+ ...this._expectedExecutionMode === "server" ? { analysis_trigger_origin: ignoreAiSchedule ? "manual" : "scheduled" } : {},
123721
+ // A cycle Review changed keeps the Main model and its own
123722
+ // decisions, as the Server loop's row does; the decision route
123723
+ // also records them as per-symbol rows.
123724
+ ...result.reviewedCycle ? {
123725
+ original_model: result.reviewedCycle.originalModel,
123726
+ original_decisions: result.reviewedCycle.originalDecisions
123727
+ } : {}
123728
+ },
123325
123729
  clientExchangeSnapshot: result.clientExchangeSnapshot ?? null,
123326
123730
  // The server refuses a report with more attempts than one cycle can make.
123327
123731
  invocations: boundRuntimeReportAttempts(
@@ -123429,7 +123833,7 @@ var init_engine = __esm({
123429
123833
  symbol: plan.executionContext.symbol,
123430
123834
  decision,
123431
123835
  units: Math.trunc(Number(plan.units))
123432
- })));
123836
+ })), capacityPlans[0]?.plan.executionContext.decisionSnapshotCapturedAt);
123433
123837
  capacityPlans.forEach(({ planIndex }, index) => serverCapacityByPlan.set(planIndex, allocations[index]));
123434
123838
  }
123435
123839
  const runPlan = async (plan, planIndex) => {
@@ -123633,23 +124037,43 @@ var init_engine = __esm({
123633
124037
  }
123634
124038
  };
123635
124039
  const cycleSupersededWithoutExecution = () => !this._executionFinalizationRequired && (analysisAbortController.signal.aborted || this._isStopping || this._analysisRequestId !== requestId);
123636
- for (let planIndex = 0; planIndex < executionPlans.length; planIndex += 1) {
123637
- if (planIndex > 0 && this._windowHandoffRequested) {
124040
+ const advisorySignedUnits = (context) => {
124041
+ try {
124042
+ return signedUnitsFromEntryPosition(
124043
+ context.currentPositionSize,
124044
+ context.currentPositionEntryPrice,
124045
+ context.unitSizeUsdc
124046
+ );
124047
+ } catch {
124048
+ return 0;
124049
+ }
124050
+ };
124051
+ const dispatchOrder = reductionFirstOrder(executionPlans.map((plan) => ({
124052
+ decision: plan.decision,
124053
+ units: plan.units,
124054
+ signedUnits: advisorySignedUnits(plan.executionContext)
124055
+ })));
124056
+ const dispatchedPlanIndexes = [];
124057
+ for (const [dispatched, planIndex] of dispatchOrder.entries()) {
124058
+ if (dispatched > 0 && this._windowHandoffRequested) {
123638
124059
  break;
123639
124060
  }
123640
124061
  const outcome = await runPlan(executionPlans[planIndex], planIndex);
123641
124062
  if (outcome.control === "return") {
123642
124063
  return;
123643
124064
  }
124065
+ if (outcome.result) {
124066
+ recordPlanResult(outcome.result);
124067
+ dispatchedPlanIndexes.push(planIndex);
124068
+ }
123644
124069
  if (outcome.control === "break") {
123645
- if (outcome.result) recordPlanResult(outcome.result);
123646
124070
  break;
123647
124071
  }
123648
- recordPlanResult(outcome.result);
123649
124072
  if (cycleSupersededWithoutExecution()) {
123650
124073
  return;
123651
124074
  }
123652
124075
  }
124076
+ executionResults.splice(0, executionResults.length, ...executionResults.map((executionResult, position) => ({ executionResult, planIndex: dispatchedPlanIndexes[position] })).sort((left, right) => left.planIndex - right.planIndex).map(({ executionResult }) => executionResult));
123653
124077
  const executionReports = executionResults.flatMap((executionResult) => Array.isArray(executionResult.executionReports) ? this._expectedExecutionMode === "server" ? withServerPositionEvents(executionResult) : executionResult.executionReports : []);
123654
124078
  const executedOrderReports = executionReports.filter((report) => report.status === "executed" && String(report.order_id || "").trim().length > 0);
123655
124079
  const handoffCleanups = executionResults.flatMap((executionResult) => executionResult.handoffCleanup ? [executionResult.handoffCleanup] : []);
@@ -123948,9 +124372,8 @@ var init_engine = __esm({
123948
124372
  });
123949
124373
  return;
123950
124374
  }
123951
- if (hasEventBoundProviderFailureEvidence(error48) && this._expectedExecutionMode === "server") {
123952
- const backoffSeconds = Number((await this.getExecutionConfig(profileId).catch(() => null))?.provider_failure_backoff_seconds);
123953
- if (Number.isFinite(backoffSeconds) && backoffSeconds > 0) providerRetryDelayMs = backoffSeconds * MS_PER_SECOND;
124375
+ if (this._expectedExecutionMode === "server" && this._reportedProviderRetryAfterSeconds !== null) {
124376
+ providerRetryDelayMs = this._reportedProviderRetryAfterSeconds * MS_PER_SECOND;
123954
124377
  }
123955
124378
  if (hasEventBoundProviderFailureEvidence(error48)) {
123956
124379
  this.scheduleProviderFailureDiagnosticsTelemetry({
@@ -124044,7 +124467,7 @@ var init_engine = __esm({
124044
124467
  primary_analysis_disabled: this._primaryAnalysisDisabled,
124045
124468
  agent_poll_retry_ms: agentPollDelayMs
124046
124469
  });
124047
- const providerRetryWake = providerRetryDelayMs !== null && aiSchedulePauseMs === null && agentPollDelayMs === null && (this._nextRunAtMs == null || this._nextRunAtMs > Date.now() + providerRetryDelayMs) ? providerRetryDelayMs : null;
124470
+ const providerRetryWake = providerRetryDelayMs !== null && aiSchedulePauseMs === null && agentPollDelayMs === null ? providerRetryDelayMs : null;
124048
124471
  if (providerRetryWake !== null) this._nextRunAtMs = Date.now() + providerRetryWake;
124049
124472
  const windowEndsAtMs = this._aiScheduleWindowEndsAtMs;
124050
124473
  const nextWorkAtMs = this._primaryAnalysisDisabled && this._loopIntervalMs != null ? Date.now() + this._loopIntervalMs : this._nextRunAtMs;
@@ -124271,6 +124694,7 @@ var init_engine = __esm({
124271
124694
  }
124272
124695
  }
124273
124696
  async reportError(reason, options) {
124697
+ this._reportedProviderRetryAfterSeconds = null;
124274
124698
  if (this._isStopping) {
124275
124699
  this._lastError = null;
124276
124700
  return null;
@@ -124349,6 +124773,8 @@ var init_engine = __esm({
124349
124773
  }
124350
124774
  );
124351
124775
  const accepted = this._setRuntimeStatus(response.runtime, "error_report");
124776
+ const retryAfterSeconds = Number(response.provider_retry_after_seconds);
124777
+ this._reportedProviderRetryAfterSeconds = accepted && response.provider_retry_after_seconds != null && Number.isFinite(retryAfterSeconds) && retryAfterSeconds >= 0 ? retryAfterSeconds : null;
124352
124778
  this._lastError = persistedError;
124353
124779
  this._notifyListeners();
124354
124780
  return accepted ? response.runtime ?? null : null;
@@ -124888,7 +125314,7 @@ var init_engine = __esm({
124888
125314
  positionCloseFailures: 0
124889
125315
  };
124890
125316
  if (context.close_positions) {
124891
- const stalePositions = evaluation.accountState?.positions ?? [];
125317
+ const stalePositions = positionsOnVenues(evaluation.accountState?.positions ?? [], evaluation.equityVenues);
124892
125318
  try {
124893
125319
  const signingKey = String(
124894
125320
  this._deviceSecrets?.hyperliquidSigningKey || ""
@@ -124917,6 +125343,8 @@ var init_engine = __esm({
124917
125343
  tickerPrice: 0,
124918
125344
  leverage: 1,
124919
125345
  aggregatePerpDexs: true,
125346
+ // The exchanges the check read: positions elsewhere are not the bot's to close.
125347
+ perpDexScope: evaluation.equityVenues?.filter(Boolean),
124920
125348
  forceRefresh: true,
124921
125349
  sessionId: this._sessionId ?? void 0,
124922
125350
  signal: refreshController.signal
@@ -124939,7 +125367,8 @@ var init_engine = __esm({
124939
125367
  positions: freshPositions,
124940
125368
  config: config2,
124941
125369
  signingKey,
124942
- timeoutSeconds: closeTimeoutSeconds
125370
+ timeoutSeconds: closeTimeoutSeconds,
125371
+ venues: evaluation.equityVenues
124943
125372
  });
124944
125373
  } else {
124945
125374
  closeSummary = {