@vtxmacro/cli 2026.10.45 → 2026.10.47
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/exo-harness.ts +74 -4
- package/bin/vtx-mcp.js +20 -3
- package/bin/vtx-service-bootstrap.js +20 -3
- package/bin/vtx-service-launcher.js +19 -2
- package/bin/vtx.js +1327 -668
- package/package.json +1 -1
package/bin/vtx.js
CHANGED
|
@@ -122,7 +122,7 @@ var init_routing = __esm({
|
|
|
122
122
|
var agent_cli_release_default;
|
|
123
123
|
var init_agent_cli_release = __esm({
|
|
124
124
|
"agent-cli-release.json"() {
|
|
125
|
-
agent_cli_release_default = { package_name: "@vtxmacro/cli", package_version: "2026.10.
|
|
125
|
+
agent_cli_release_default = { package_name: "@vtxmacro/cli", package_version: "2026.10.47", 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" } } };
|
|
126
126
|
}
|
|
127
127
|
});
|
|
128
128
|
|
|
@@ -929,6 +929,10 @@ var init_runtime_policy_generated = __esm({
|
|
|
929
929
|
auto_resume_failure_detail_chars: 500,
|
|
930
930
|
vault_migration_error_chars: 200
|
|
931
931
|
},
|
|
932
|
+
event_batch: {
|
|
933
|
+
window_milliseconds: 1e3,
|
|
934
|
+
max_events: 32
|
|
935
|
+
},
|
|
932
936
|
request_retry: {
|
|
933
937
|
max_attempts: 3,
|
|
934
938
|
base_delay_milliseconds: 300,
|
|
@@ -1378,13 +1382,22 @@ var init_runtime_policy_generated = __esm({
|
|
|
1378
1382
|
page_start_wait_seconds: 45,
|
|
1379
1383
|
page_start_poll_seconds: 1,
|
|
1380
1384
|
profiles_read_timeout_seconds: 30,
|
|
1381
|
-
command_notice_reconnect_max_seconds: 60
|
|
1385
|
+
command_notice_reconnect_max_seconds: 60,
|
|
1386
|
+
sleep_quiet_milliseconds: 3e3,
|
|
1387
|
+
sleep_max_seconds: 60,
|
|
1388
|
+
sleep_min_seconds: 10,
|
|
1389
|
+
sleep_alarm_grace_seconds: 15,
|
|
1390
|
+
sleep_elastic_below_milliseconds: 1e3,
|
|
1391
|
+
sleep_request_wait_milliseconds: 4e3,
|
|
1392
|
+
sleep_defer_seconds: 30
|
|
1382
1393
|
}
|
|
1383
1394
|
},
|
|
1384
1395
|
websocket: {
|
|
1385
1396
|
client_connection: {
|
|
1386
1397
|
reconnect_delay_ms: 3e3,
|
|
1387
1398
|
ping_interval_ms: 3e4,
|
|
1399
|
+
pong_timeout_ms: 5e3,
|
|
1400
|
+
max_unanswered_pings: 2,
|
|
1388
1401
|
message_flush_interval_ms: 16,
|
|
1389
1402
|
price_change_highlight_ms: 1e3,
|
|
1390
1403
|
debug_recent_channel_limit: 24
|
|
@@ -1403,6 +1416,9 @@ var init_runtime_policy_generated = __esm({
|
|
|
1403
1416
|
min_length: 3,
|
|
1404
1417
|
max_length: 20,
|
|
1405
1418
|
update_confirmation_ms: 3e3
|
|
1419
|
+
},
|
|
1420
|
+
passkey_names: {
|
|
1421
|
+
max_length: 100
|
|
1406
1422
|
}
|
|
1407
1423
|
},
|
|
1408
1424
|
profiles: {
|
|
@@ -1466,7 +1482,8 @@ var init_runtime_policy_generated = __esm({
|
|
|
1466
1482
|
full_history_default_limit: 20,
|
|
1467
1483
|
default_page_size: 50,
|
|
1468
1484
|
trade_lookup_max_order_ids: 200,
|
|
1469
|
-
decision_batch_default_limit: 50
|
|
1485
|
+
decision_batch_default_limit: 50,
|
|
1486
|
+
non_admin_lookback_days: 30
|
|
1470
1487
|
},
|
|
1471
1488
|
updates: {
|
|
1472
1489
|
posts: {
|
|
@@ -1497,7 +1514,7 @@ var init_runtime_policy_generated = __esm({
|
|
|
1497
1514
|
});
|
|
1498
1515
|
|
|
1499
1516
|
// lib/constants.ts
|
|
1500
|
-
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, PROMPT_RESCUE_ASKS_PER_CYCLE_BUILD, USD_DISPLAY_DECIMALS, 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, NATIVE_PROTECTION_RECORD_WITH_LOTS_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, AGENT_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, CLAUDE_CODE_POLICY_MAX_MODELS, CLAUDE_CODE_POLICY_MODEL_NAME_MAX_CHARS, CLAUDE_CODE_POLICY_MAX_TURNS, ANTHROPIC_SCHEMA_PROPERTY_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_RELATIVE_VOLUME_DIGITS, BINARY_RADIX, 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_PUBLIC_READ_WINDOWS_KEPT, CLIENT_RUNTIME_NOTE_GAP_MAX_LOOPS, 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;
|
|
1517
|
+
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, PROMPT_RESCUE_ASKS_PER_CYCLE_BUILD, USD_DISPLAY_DECIMALS, 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, NATIVE_PROTECTION_RECORD_WITH_LOTS_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, AGENT_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, CLAUDE_CODE_POLICY_MAX_MODELS, CLAUDE_CODE_POLICY_MODEL_NAME_MAX_CHARS, CLAUDE_CODE_POLICY_MAX_TURNS, ANTHROPIC_SCHEMA_PROPERTY_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_RELATIVE_VOLUME_DIGITS, BINARY_RADIX, 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_PUBLIC_READ_WINDOWS_KEPT, CLIENT_RUNTIME_NOTE_GAP_MAX_LOOPS, 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, CLIENT_PROTECTION_CAPABILITY_VERSION, BYOK_PROVIDER_DISPLAY_ORDER_STEP, TOKENS_PER_MILLION, RENDER_DEBUG_ID_RANDOM_CHARS;
|
|
1501
1518
|
var init_constants = __esm({
|
|
1502
1519
|
"lib/constants.ts"() {
|
|
1503
1520
|
"use strict";
|
|
@@ -2046,6 +2063,7 @@ var init_constants = __esm({
|
|
|
2046
2063
|
AGENT_CLI_TAKEOVER_REQUIRED_EXIT_CODE = 2;
|
|
2047
2064
|
EXIT_CODE_INTERRUPTED = 130;
|
|
2048
2065
|
EXIT_CODE_SIGNAL_BASE = 128;
|
|
2066
|
+
CLIENT_PROTECTION_CAPABILITY_VERSION = 2;
|
|
2049
2067
|
BYOK_PROVIDER_DISPLAY_ORDER_STEP = 10;
|
|
2050
2068
|
TOKENS_PER_MILLION = 1e6;
|
|
2051
2069
|
RENDER_DEBUG_ID_RANDOM_CHARS = 6;
|
|
@@ -21036,6 +21054,10 @@ var init_runtime_policy_generated2 = __esm({
|
|
|
21036
21054
|
auto_resume_failure_detail_chars: 500,
|
|
21037
21055
|
vault_migration_error_chars: 200
|
|
21038
21056
|
},
|
|
21057
|
+
event_batch: {
|
|
21058
|
+
window_milliseconds: 1e3,
|
|
21059
|
+
max_events: 32
|
|
21060
|
+
},
|
|
21039
21061
|
request_retry: {
|
|
21040
21062
|
max_attempts: 3,
|
|
21041
21063
|
base_delay_milliseconds: 300,
|
|
@@ -21485,13 +21507,22 @@ var init_runtime_policy_generated2 = __esm({
|
|
|
21485
21507
|
page_start_wait_seconds: 45,
|
|
21486
21508
|
page_start_poll_seconds: 1,
|
|
21487
21509
|
profiles_read_timeout_seconds: 30,
|
|
21488
|
-
command_notice_reconnect_max_seconds: 60
|
|
21510
|
+
command_notice_reconnect_max_seconds: 60,
|
|
21511
|
+
sleep_quiet_milliseconds: 3e3,
|
|
21512
|
+
sleep_max_seconds: 60,
|
|
21513
|
+
sleep_min_seconds: 10,
|
|
21514
|
+
sleep_alarm_grace_seconds: 15,
|
|
21515
|
+
sleep_elastic_below_milliseconds: 1e3,
|
|
21516
|
+
sleep_request_wait_milliseconds: 4e3,
|
|
21517
|
+
sleep_defer_seconds: 30
|
|
21489
21518
|
}
|
|
21490
21519
|
},
|
|
21491
21520
|
websocket: {
|
|
21492
21521
|
client_connection: {
|
|
21493
21522
|
reconnect_delay_ms: 3e3,
|
|
21494
21523
|
ping_interval_ms: 3e4,
|
|
21524
|
+
pong_timeout_ms: 5e3,
|
|
21525
|
+
max_unanswered_pings: 2,
|
|
21495
21526
|
message_flush_interval_ms: 16,
|
|
21496
21527
|
price_change_highlight_ms: 1e3,
|
|
21497
21528
|
debug_recent_channel_limit: 24
|
|
@@ -21510,6 +21541,9 @@ var init_runtime_policy_generated2 = __esm({
|
|
|
21510
21541
|
min_length: 3,
|
|
21511
21542
|
max_length: 20,
|
|
21512
21543
|
update_confirmation_ms: 3e3
|
|
21544
|
+
},
|
|
21545
|
+
passkey_names: {
|
|
21546
|
+
max_length: 100
|
|
21513
21547
|
}
|
|
21514
21548
|
},
|
|
21515
21549
|
profiles: {
|
|
@@ -21573,7 +21607,8 @@ var init_runtime_policy_generated2 = __esm({
|
|
|
21573
21607
|
full_history_default_limit: 20,
|
|
21574
21608
|
default_page_size: 50,
|
|
21575
21609
|
trade_lookup_max_order_ids: 200,
|
|
21576
|
-
decision_batch_default_limit: 50
|
|
21610
|
+
decision_batch_default_limit: 50,
|
|
21611
|
+
non_admin_lookback_days: 30
|
|
21577
21612
|
},
|
|
21578
21613
|
updates: {
|
|
21579
21614
|
posts: {
|
|
@@ -25625,16 +25660,16 @@ var init_mcp_client = __esm({
|
|
|
25625
25660
|
MAX_REJECTION_REASON_CHARS = runtime_policy_generated_default2.external_inference.host_core.mcp_rejection_reason_max_chars;
|
|
25626
25661
|
CONTROL_CHARACTERS = /[\u0000-\u001f\u007f]/gu;
|
|
25627
25662
|
publicRejectionReason = (text) => {
|
|
25628
|
-
const
|
|
25629
|
-
const [firstLine = ""] = (
|
|
25663
|
+
const marker2 = text.indexOf(PUBLIC_TOOL_ERROR_PREFIX);
|
|
25664
|
+
const [firstLine = ""] = (marker2 < 0 ? text : text.slice(0, marker2)).split("\n");
|
|
25630
25665
|
const reason = sanitizeRuntimeDiagnosticValue(firstLine.replace(CONTROL_CHARACTERS, " ")).trim();
|
|
25631
25666
|
if (!reason) return null;
|
|
25632
25667
|
return reason.length > MAX_REJECTION_REASON_CHARS ? `${reason.slice(0, MAX_REJECTION_REASON_CHARS)}\u2026` : reason;
|
|
25633
25668
|
};
|
|
25634
25669
|
parsePublicToolError = (text) => {
|
|
25635
|
-
const
|
|
25636
|
-
if (
|
|
25637
|
-
const raw = text.slice(
|
|
25670
|
+
const marker2 = text.lastIndexOf(PUBLIC_TOOL_ERROR_PREFIX);
|
|
25671
|
+
if (marker2 < 0) return null;
|
|
25672
|
+
const raw = text.slice(marker2 + PUBLIC_TOOL_ERROR_PREFIX.length).trim();
|
|
25638
25673
|
try {
|
|
25639
25674
|
const parsed = publicToolErrorSchema.safeParse(JSON.parse(raw));
|
|
25640
25675
|
return parsed.success ? parsed.data : null;
|
|
@@ -25977,7 +26012,7 @@ var init_mcp_client = __esm({
|
|
|
25977
26012
|
parseSseDocuments = (body) => {
|
|
25978
26013
|
const documents = [];
|
|
25979
26014
|
let dataLines = [];
|
|
25980
|
-
const
|
|
26015
|
+
const flush2 = () => {
|
|
25981
26016
|
if (dataLines.length === 0) return;
|
|
25982
26017
|
const data4 = dataLines.join("\n");
|
|
25983
26018
|
dataLines = [];
|
|
@@ -25985,7 +26020,7 @@ var init_mcp_client = __esm({
|
|
|
25985
26020
|
};
|
|
25986
26021
|
for (const rawLine of body.replace(/\r\n/g, "\n").split("\n")) {
|
|
25987
26022
|
if (!rawLine) {
|
|
25988
|
-
|
|
26023
|
+
flush2();
|
|
25989
26024
|
continue;
|
|
25990
26025
|
}
|
|
25991
26026
|
if (rawLine.startsWith(":")) continue;
|
|
@@ -25997,7 +26032,7 @@ var init_mcp_client = __esm({
|
|
|
25997
26032
|
dataLines.push(rawLine.slice(SSE_DATA_FIELD_PREFIX.length).replace(/^ /, ""));
|
|
25998
26033
|
}
|
|
25999
26034
|
}
|
|
26000
|
-
|
|
26035
|
+
flush2();
|
|
26001
26036
|
if (documents.length === 0) {
|
|
26002
26037
|
throw new ExternalInferenceMcpError(
|
|
26003
26038
|
"invalid_response",
|
|
@@ -35998,6 +36033,68 @@ var init_agent_state = __esm({
|
|
|
35998
36033
|
}
|
|
35999
36034
|
});
|
|
36000
36035
|
|
|
36036
|
+
// lib/inference-host/agent-answer.ts
|
|
36037
|
+
var CODE_FENCE, OBJECT_ON_OWN_LINE, closingJsonFenceDocument, scanObject, closingJsonObjectDocument, agentAnswerJsonDocument;
|
|
36038
|
+
var init_agent_answer = __esm({
|
|
36039
|
+
"lib/inference-host/agent-answer.ts"() {
|
|
36040
|
+
"use strict";
|
|
36041
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
36042
|
+
init_define_VTX_EXO_POLICY();
|
|
36043
|
+
init_define_VTX_GROK_POLICY();
|
|
36044
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
36045
|
+
CODE_FENCE = "```";
|
|
36046
|
+
OBJECT_ON_OWN_LINE = /(?:^|\n)[ \t]*(?=\{)/gu;
|
|
36047
|
+
closingJsonFenceDocument = (text) => {
|
|
36048
|
+
const trimmed = text.trim();
|
|
36049
|
+
const open4 = trimmed.indexOf(CODE_FENCE);
|
|
36050
|
+
const close = trimmed.lastIndexOf(CODE_FENCE);
|
|
36051
|
+
if (open4 < 0 || close === open4 || trimmed.indexOf(CODE_FENCE, open4 + CODE_FENCE.length) !== close) return null;
|
|
36052
|
+
const match = /```json[ \t]*\r?\n([\s\S]*?)\r?\n?```$/iu.exec(trimmed);
|
|
36053
|
+
return match ? match[1] : null;
|
|
36054
|
+
};
|
|
36055
|
+
scanObject = (text, start) => {
|
|
36056
|
+
let depth = 0;
|
|
36057
|
+
let inString = false;
|
|
36058
|
+
for (let index = start; index < text.length; index += 1) {
|
|
36059
|
+
const char = text[index];
|
|
36060
|
+
if (inString) {
|
|
36061
|
+
if (char === "\\") index += 1;
|
|
36062
|
+
else if (char === '"') inString = false;
|
|
36063
|
+
else if (char === "\n") return { close: null, stop: index };
|
|
36064
|
+
} else if (char === '"') inString = true;
|
|
36065
|
+
else if (char === "{" || char === "[") depth += 1;
|
|
36066
|
+
else if (char === "}" || char === "]") {
|
|
36067
|
+
depth -= 1;
|
|
36068
|
+
if (depth === 0) return { close: char === "}" ? index : null, stop: index };
|
|
36069
|
+
}
|
|
36070
|
+
}
|
|
36071
|
+
return { close: null, stop: text.length };
|
|
36072
|
+
};
|
|
36073
|
+
closingJsonObjectDocument = (text) => {
|
|
36074
|
+
const trimmed = text.trim();
|
|
36075
|
+
if (!trimmed.endsWith("}") || trimmed.includes(CODE_FENCE)) return null;
|
|
36076
|
+
const objects = [];
|
|
36077
|
+
let resumeAt = 0;
|
|
36078
|
+
for (const match of trimmed.matchAll(OBJECT_ON_OWN_LINE)) {
|
|
36079
|
+
const start = match.index + match[0].length;
|
|
36080
|
+
if (start < resumeAt) continue;
|
|
36081
|
+
const { close, stop } = scanObject(trimmed, start);
|
|
36082
|
+
resumeAt = stop + 1;
|
|
36083
|
+
if (close === null) continue;
|
|
36084
|
+
try {
|
|
36085
|
+
JSON.parse(trimmed.slice(start, close + 1));
|
|
36086
|
+
} catch {
|
|
36087
|
+
continue;
|
|
36088
|
+
}
|
|
36089
|
+
objects.push({ start, close });
|
|
36090
|
+
}
|
|
36091
|
+
if (objects.length !== 1 || objects[0].close !== trimmed.length - 1) return null;
|
|
36092
|
+
return trimmed.slice(objects[0].start);
|
|
36093
|
+
};
|
|
36094
|
+
agentAnswerJsonDocument = (text) => closingJsonFenceDocument(text) ?? closingJsonObjectDocument(text);
|
|
36095
|
+
}
|
|
36096
|
+
});
|
|
36097
|
+
|
|
36001
36098
|
// lib/inference-host/runner.ts
|
|
36002
36099
|
import { createHash as createHash5, randomUUID as randomUUID2 } from "node:crypto";
|
|
36003
36100
|
function createDefaultInferenceHostRunnerDependencies(options) {
|
|
@@ -36053,6 +36150,7 @@ var init_runner = __esm({
|
|
|
36053
36150
|
init_agent_state();
|
|
36054
36151
|
init_crypto();
|
|
36055
36152
|
init_mcp_client();
|
|
36153
|
+
init_agent_answer();
|
|
36056
36154
|
init_config2();
|
|
36057
36155
|
init_oauth();
|
|
36058
36156
|
providerHttpStatus = (error48) => {
|
|
@@ -38386,7 +38484,8 @@ var init_runner = __esm({
|
|
|
38386
38484
|
0,
|
|
38387
38485
|
claimCallRoundTripMs - (serverProcessingMs ?? 0)
|
|
38388
38486
|
);
|
|
38389
|
-
const
|
|
38487
|
+
const serverDeadlineClockOffsetMs = claim.schema_version === "external_inference_job_claim_result_v4" ? claimCallStartedAtMs + claim.server_processing_ms - Date.parse(claim.server_time_at) : 0;
|
|
38488
|
+
const serverReportClockOffsetMs = claim.schema_version === "external_inference_job_claim_result_v4" ? claimResponseReceivedAtMs - Date.parse(claim.server_time_at) : 0;
|
|
38390
38489
|
emitDiagnostic("claim_batch_received", {
|
|
38391
38490
|
claim_request_id: request.claim_request_id,
|
|
38392
38491
|
jobs: claim.claims.map((item) => ({
|
|
@@ -38399,7 +38498,8 @@ var init_runner = __esm({
|
|
|
38399
38498
|
claim_count: claim.claims.length,
|
|
38400
38499
|
round_trip_ms: claimCallRoundTripMs,
|
|
38401
38500
|
server_processing_ms: serverProcessingMs,
|
|
38402
|
-
server_clock_offset_ms:
|
|
38501
|
+
server_clock_offset_ms: serverDeadlineClockOffsetMs,
|
|
38502
|
+
server_report_clock_offset_ms: serverReportClockOffsetMs,
|
|
38403
38503
|
transport_residual_ms: claimTransportResidualMs,
|
|
38404
38504
|
minimum_freshness_remaining_ms: claim.claims.length ? Math.min(...claim.claims.map((item) => item.provider_dispatch_freshness_remaining_ms)) : null,
|
|
38405
38505
|
active_attempts: active.size
|
|
@@ -38489,7 +38589,8 @@ var init_runner = __esm({
|
|
|
38489
38589
|
roundTripMs: claimTransportResidualMs,
|
|
38490
38590
|
claimResponseReceivedAtMs,
|
|
38491
38591
|
receiptDurability: batchReceiptDurability,
|
|
38492
|
-
|
|
38592
|
+
serverDeadlineClockOffsetMs,
|
|
38593
|
+
serverReportClockOffsetMs
|
|
38493
38594
|
});
|
|
38494
38595
|
}
|
|
38495
38596
|
if (this.options.once) requestDrain("once_complete");
|
|
@@ -38634,9 +38735,10 @@ var init_runner = __esm({
|
|
|
38634
38735
|
signal,
|
|
38635
38736
|
now
|
|
38636
38737
|
} = options;
|
|
38637
|
-
const
|
|
38638
|
-
const hostClockMs = (serverTimestamp) => Date.parse(serverTimestamp) +
|
|
38639
|
-
const
|
|
38738
|
+
const serverDeadlineClockOffsetMs = options.prestarted?.serverDeadlineClockOffsetMs ?? 0;
|
|
38739
|
+
const hostClockMs = (serverTimestamp) => Date.parse(serverTimestamp) + serverDeadlineClockOffsetMs;
|
|
38740
|
+
const serverReportClockOffsetMs = options.prestarted?.serverReportClockOffsetMs ?? 0;
|
|
38741
|
+
const serverIsoAt = (hostMs) => isoAt(hostMs - serverReportClockOffsetMs);
|
|
38640
38742
|
const adapterId = this.options.adapterId ?? "codex";
|
|
38641
38743
|
const usageSource = this.options.usageSource ?? (adapterId === "codex" ? "codex_app_server" : adapterId);
|
|
38642
38744
|
const sameAttemptRecovery = this.options.sameAttemptRecovery ?? adapterId === "codex";
|
|
@@ -39635,10 +39737,16 @@ var init_runner = __esm({
|
|
|
39635
39737
|
try {
|
|
39636
39738
|
value = JSON.parse(text);
|
|
39637
39739
|
} catch {
|
|
39638
|
-
|
|
39639
|
-
|
|
39640
|
-
|
|
39641
|
-
|
|
39740
|
+
const fenced = agentAnswerJsonDocument(text);
|
|
39741
|
+
try {
|
|
39742
|
+
if (fenced === null) throw new Error("unfenced");
|
|
39743
|
+
value = JSON.parse(fenced);
|
|
39744
|
+
} catch {
|
|
39745
|
+
throw new InferenceHostRunnerError(
|
|
39746
|
+
"invalid_agent_wake",
|
|
39747
|
+
"Inference Agent returned invalid wake JSON."
|
|
39748
|
+
);
|
|
39749
|
+
}
|
|
39642
39750
|
}
|
|
39643
39751
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
39644
39752
|
throw new InferenceHostRunnerError("invalid_agent_wake", "Inference Agent wake is invalid.");
|
|
@@ -44544,10 +44652,10 @@ var init_pi_transport = __esm({
|
|
|
44544
44652
|
}
|
|
44545
44653
|
}
|
|
44546
44654
|
};
|
|
44547
|
-
const consume = (
|
|
44655
|
+
const consume = (flush2 = false) => {
|
|
44548
44656
|
if (pending3.length > HOST_RUNTIME_POLICY6.pi_receipt_event_max_chars) throw new Error("pi_receipt_event_too_large");
|
|
44549
44657
|
const events = pending3.split(/\r?\n\r?\n/u);
|
|
44550
|
-
pending3 =
|
|
44658
|
+
pending3 = flush2 ? "" : events.pop();
|
|
44551
44659
|
for (const event of events) {
|
|
44552
44660
|
const data4 = event.split(/\r?\n/u).filter((line) => line.startsWith(SSE_DATA_PREFIX2)).map((line) => line.slice(SSE_DATA_PREFIX2.length).trimStart()).join("\n");
|
|
44553
44661
|
if (data4) inspect3(data4);
|
|
@@ -46217,23 +46325,23 @@ var init_grok_state = __esm({
|
|
|
46217
46325
|
throw error48;
|
|
46218
46326
|
}
|
|
46219
46327
|
const encoded = encodedCwd(value.workspace);
|
|
46220
|
-
let
|
|
46221
|
-
if (encoded.length <= GROK_NATIVE_SESSION_GROUP_NAME_MAX_CHARS)
|
|
46328
|
+
let groups2;
|
|
46329
|
+
if (encoded.length <= GROK_NATIVE_SESSION_GROUP_NAME_MAX_CHARS) groups2 = [join12(sessions, encoded)];
|
|
46222
46330
|
else {
|
|
46223
|
-
|
|
46331
|
+
groups2 = [];
|
|
46224
46332
|
for (const entry of await readdir6(sessions, { withFileTypes: true })) {
|
|
46225
46333
|
if (!entry.isDirectory() || entry.isSymbolicLink()) continue;
|
|
46226
46334
|
const group = join12(sessions, entry.name);
|
|
46227
46335
|
if (await realpath7(group) !== resolve7(group)) throw invalid();
|
|
46228
46336
|
try {
|
|
46229
|
-
if ((await nativeFile(join12(group, ".cwd"), HOST_RUNTIME_POLICY9.grok_cwd_marker_max_bytes)).trim() === value.workspace)
|
|
46337
|
+
if ((await nativeFile(join12(group, ".cwd"), HOST_RUNTIME_POLICY9.grok_cwd_marker_max_bytes)).trim() === value.workspace) groups2.push(group);
|
|
46230
46338
|
} catch (error48) {
|
|
46231
46339
|
if (!missing(error48)) throw error48;
|
|
46232
46340
|
}
|
|
46233
46341
|
}
|
|
46234
|
-
if (
|
|
46342
|
+
if (groups2.length > 1) throw invalid();
|
|
46235
46343
|
}
|
|
46236
|
-
for (const group of
|
|
46344
|
+
for (const group of groups2) {
|
|
46237
46345
|
const session = join12(group, value.sessionId);
|
|
46238
46346
|
try {
|
|
46239
46347
|
await nativeDirectory(group);
|
|
@@ -47280,14 +47388,14 @@ var init_claude_code_runtime = __esm({
|
|
|
47280
47388
|
SESSION_ID = /^[0-9a-f-]{36}$/u;
|
|
47281
47389
|
claudeCodeSessionTranscriptExists = async (configDir, sessionId) => {
|
|
47282
47390
|
if (!SESSION_ID.test(sessionId)) return false;
|
|
47283
|
-
let
|
|
47391
|
+
let groups2;
|
|
47284
47392
|
try {
|
|
47285
|
-
|
|
47393
|
+
groups2 = await readdir7(join14(configDir, "projects"));
|
|
47286
47394
|
} catch (error48) {
|
|
47287
47395
|
if (error48.code === "ENOENT") return false;
|
|
47288
47396
|
throw error48;
|
|
47289
47397
|
}
|
|
47290
|
-
for (const group of
|
|
47398
|
+
for (const group of groups2) {
|
|
47291
47399
|
try {
|
|
47292
47400
|
if ((await lstat9(join14(configDir, "projects", group, `${sessionId}.jsonl`))).isFile()) return true;
|
|
47293
47401
|
} catch (error48) {
|
|
@@ -47299,14 +47407,14 @@ var init_claude_code_runtime = __esm({
|
|
|
47299
47407
|
removeClaudeCodeSessionTranscript = async (configDir, sessionId) => {
|
|
47300
47408
|
if (!SESSION_ID.test(sessionId)) return;
|
|
47301
47409
|
const projects = join14(configDir, "projects");
|
|
47302
|
-
let
|
|
47410
|
+
let groups2;
|
|
47303
47411
|
try {
|
|
47304
|
-
|
|
47412
|
+
groups2 = await readdir7(projects);
|
|
47305
47413
|
} catch (error48) {
|
|
47306
47414
|
if (error48.code === "ENOENT") return;
|
|
47307
47415
|
throw error48;
|
|
47308
47416
|
}
|
|
47309
|
-
for (const group of
|
|
47417
|
+
for (const group of groups2) {
|
|
47310
47418
|
await rm12(join14(projects, group, `${sessionId}.jsonl`), { force: true });
|
|
47311
47419
|
}
|
|
47312
47420
|
};
|
|
@@ -50367,12 +50475,12 @@ ${result.stderr}`)) {
|
|
|
50367
50475
|
let cooperativeStopTimedOut = false;
|
|
50368
50476
|
let cooperativeStopTimer = null;
|
|
50369
50477
|
const pending3 = { stdout: "", stderr: "" };
|
|
50370
|
-
const writeTaggedOutput = (stream, text,
|
|
50478
|
+
const writeTaggedOutput = (stream, text, flush2 = false) => {
|
|
50371
50479
|
const lines = `${pending3[stream]}${text}`.split(/\r?\n/u);
|
|
50372
50480
|
const remainder = lines.pop() ?? "";
|
|
50373
|
-
pending3[stream] =
|
|
50374
|
-
if (
|
|
50375
|
-
if (
|
|
50481
|
+
pending3[stream] = flush2 ? "" : remainder;
|
|
50482
|
+
if (flush2 && remainder) lines.push(remainder);
|
|
50483
|
+
if (flush2 && lines.at(-1) === "") lines.pop();
|
|
50376
50484
|
for (const line of lines) {
|
|
50377
50485
|
if (!line) continue;
|
|
50378
50486
|
try {
|
|
@@ -54826,7 +54934,7 @@ var init_protection_storage = __esm({
|
|
|
54826
54934
|
});
|
|
54827
54935
|
|
|
54828
54936
|
// lib/android-app.ts
|
|
54829
|
-
var ANDROID_APP_PACKAGES, ANDROID_APP_REFERRER_SCHEME, ANDROID_APP_LAUNCH_STORAGE_KEY, ANDROID_APP_HOST_FRAGMENT_PARAM, knownLaunch, storedLaunch, referrerPackage, HOST_FRAGMENT_PAIR_PREFIX, fragmentParts, hostFragment, freshNavigation, remember, followAppReopens, androidAppLaunch, isAndroidAppPage;
|
|
54937
|
+
var ANDROID_APP_PACKAGES, ANDROID_APP_REFERRER_SCHEME, ANDROID_APP_LAUNCH_STORAGE_KEY, ANDROID_APP_HOST_FRAGMENT_PARAM, knownLaunch, storedLaunch, referrerPackage, HOST_FRAGMENT_PAIR_PREFIX, fragmentParts, hostFragment, freshNavigation, remember, hostNamedListeners, followAppReopens, androidAppLaunch, isAndroidAppPage;
|
|
54830
54938
|
var init_android_app = __esm({
|
|
54831
54939
|
"lib/android-app.ts"() {
|
|
54832
54940
|
"use strict";
|
|
@@ -54882,11 +54990,13 @@ var init_android_app = __esm({
|
|
|
54882
54990
|
}
|
|
54883
54991
|
return launch;
|
|
54884
54992
|
};
|
|
54993
|
+
hostNamedListeners = /* @__PURE__ */ new Set();
|
|
54885
54994
|
followAppReopens = () => {
|
|
54886
54995
|
window.addEventListener("hashchange", () => {
|
|
54887
54996
|
if (!knownLaunch) return;
|
|
54888
54997
|
const named = knownLaunch.hostDeviceId ? null : hostFragment();
|
|
54889
54998
|
remember(named ? { ...knownLaunch, hostDeviceId: named } : knownLaunch);
|
|
54999
|
+
if (named) hostNamedListeners.forEach((listener) => listener());
|
|
54890
55000
|
});
|
|
54891
55001
|
};
|
|
54892
55002
|
androidAppLaunch = () => {
|
|
@@ -56295,7 +56405,7 @@ var init_esm = __esm({
|
|
|
56295
56405
|
strm.flush(ev.data[1]);
|
|
56296
56406
|
};
|
|
56297
56407
|
};
|
|
56298
|
-
astrmify = function(fns, strm, opts, init2, id2,
|
|
56408
|
+
astrmify = function(fns, strm, opts, init2, id2, flush2, ext) {
|
|
56299
56409
|
var t;
|
|
56300
56410
|
var w = wrkr(fns, init2, id2, function(err2, dat) {
|
|
56301
56411
|
if (err2)
|
|
@@ -56325,7 +56435,7 @@ var init_esm = __esm({
|
|
|
56325
56435
|
strm.terminate = function() {
|
|
56326
56436
|
w.terminate();
|
|
56327
56437
|
};
|
|
56328
|
-
if (
|
|
56438
|
+
if (flush2) {
|
|
56329
56439
|
strm.flush = function(sync) {
|
|
56330
56440
|
w.postMessage([0, sync]);
|
|
56331
56441
|
};
|
|
@@ -57389,7 +57499,7 @@ function getProfileHeaders(baseHeaders = {}, explicitProfileId) {
|
|
|
57389
57499
|
if (profileId) headers["x-profile-id"] = profileId.toString();
|
|
57390
57500
|
return headers;
|
|
57391
57501
|
}
|
|
57392
|
-
var configuredApiTransport, getApiUrl, sendApiRequest, apiFetch, sleep, DEVICE_CLOCK_HEADER, deviceClockHeader, inFlightClientGetRequests, recentClientGetResponses, clientGetRequestGenerations, initializedClientGetRequestKeys, CLIENT_GET_DEDUPE_TTL_MS, CLIENT_RUNTIME_STATUSES_DEDUPE_TTL_MS, CLIENT_LLM_CONFIG_PRIME_TTL_MS, AUTH_BOOTSTRAP_GET_MAX_ATTEMPTS, AUTH_BOOTSTRAP_RETRY_JITTER_MS, canUseClientGetRequestCache, invalidateClientGetRequestCache, raceWithAbortSignal, shareClientGetRequest, clientGetRequestKey, clientPreferencesRequestKey, invalidateClientPreferencesCache, parseRetryAfterMs2, resolveAuthBootstrapRetryDelayMs, fetchAuthBootstrapGetWithRetry, annotateMarketDataRequestError, buildMarketDataFetchError, buildMarketDataNetworkError, buildMarketDataResponseBodyError, isTransientNetworkFetchError, createIdempotencyKey, getErrorMessage, getErrorPayloadOrEmpty, getErrorPayloadOrFallbackDetail, getErrorMessageFromResponse, throwUnauthorizedIfNeeded, activeProfileId, PROFILE_STORAGE_KEY;
|
|
57502
|
+
var configuredApiTransport, getApiUrl, sendApiRequest, apiFetch, sleep, DEVICE_CLOCK_HEADER, deviceClockHeader, inFlightClientGetRequests, recentClientGetResponses, clientGetRequestGenerations, initializedClientGetRequestKeys, CLIENT_GET_DEDUPE_TTL_MS, CLIENT_RUNTIME_STATUSES_DEDUPE_TTL_MS, CLIENT_LLM_CONFIG_PRIME_TTL_MS, AUTH_BOOTSTRAP_GET_MAX_ATTEMPTS, AUTH_BOOTSTRAP_RETRY_JITTER_MS, singleUserHostCache, canUseClientGetRequestCache, clientGetRequestCacheActive, invalidateClientGetRequestCache, raceWithAbortSignal, shareClientGetRequest, clientGetRequestKey, clientPreferencesRequestKey, invalidateClientPreferencesCache, parseRetryAfterMs2, resolveAuthBootstrapRetryDelayMs, fetchAuthBootstrapGetWithRetry, annotateMarketDataRequestError, buildMarketDataFetchError, buildMarketDataNetworkError, buildMarketDataResponseBodyError, isTransientNetworkFetchError, createIdempotencyKey, getErrorMessage, getErrorPayloadOrEmpty, getErrorPayloadOrFallbackDetail, getErrorMessageFromResponse, throwUnauthorizedIfNeeded, activeProfileId, PROFILE_STORAGE_KEY;
|
|
57393
57503
|
var init_shared = __esm({
|
|
57394
57504
|
"lib/api/shared.ts"() {
|
|
57395
57505
|
"use strict";
|
|
@@ -57449,7 +57559,9 @@ var init_shared = __esm({
|
|
|
57449
57559
|
CLIENT_LLM_CONFIG_PRIME_TTL_MS = runtime_policy_generated_default2.ui.api_client.llm_config_prime_ttl_ms;
|
|
57450
57560
|
AUTH_BOOTSTRAP_GET_MAX_ATTEMPTS = runtime_policy_generated_default2.ui.auth_bootstrap_retry.max_attempts;
|
|
57451
57561
|
AUTH_BOOTSTRAP_RETRY_JITTER_MS = runtime_policy_generated_default2.ui.auth_bootstrap_retry.jitter_milliseconds;
|
|
57452
|
-
|
|
57562
|
+
singleUserHostCache = false;
|
|
57563
|
+
canUseClientGetRequestCache = (cookie) => (typeof window !== "undefined" || singleUserHostCache) && !cookie;
|
|
57564
|
+
clientGetRequestCacheActive = () => canUseClientGetRequestCache();
|
|
57453
57565
|
invalidateClientGetRequestCache = (key) => {
|
|
57454
57566
|
initializedClientGetRequestKeys.add(key);
|
|
57455
57567
|
clientGetRequestGenerations.set(key, (clientGetRequestGenerations.get(key) ?? 0) + 1);
|
|
@@ -57499,7 +57611,7 @@ var init_shared = __esm({
|
|
|
57499
57611
|
clientGetRequestKey = (name, profileId) => `${name}:${profileId ?? "none"}`;
|
|
57500
57612
|
clientPreferencesRequestKey = (profileId, includeTradeLayouts) => `${clientGetRequestKey("preferences", profileId)}:trade-layouts:${includeTradeLayouts ? "full" : "lite"}`;
|
|
57501
57613
|
invalidateClientPreferencesCache = (profileId) => {
|
|
57502
|
-
if (
|
|
57614
|
+
if (!clientGetRequestCacheActive()) return;
|
|
57503
57615
|
for (const includeTradeLayouts of [false, true]) {
|
|
57504
57616
|
const baseKey = clientPreferencesRequestKey(profileId, includeTradeLayouts);
|
|
57505
57617
|
invalidateClientGetRequestCache(baseKey);
|
|
@@ -57576,7 +57688,7 @@ var init_shared = __esm({
|
|
|
57576
57688
|
isTransientNetworkFetchError = (error48) => {
|
|
57577
57689
|
const message = error48 instanceof Error ? error48.message : String(error48 || "");
|
|
57578
57690
|
const normalized = message.toLowerCase();
|
|
57579
|
-
return message === "Failed to fetch" || message === "TypeError: Failed to fetch" || normalized.includes("network error") || normalized.includes("failed to fetch");
|
|
57691
|
+
return message === "Failed to fetch" || message === "TypeError: Failed to fetch" || normalized.includes("network error") || normalized.includes("failed to fetch") || normalized === "fetch failed";
|
|
57580
57692
|
};
|
|
57581
57693
|
createIdempotencyKey = (action) => {
|
|
57582
57694
|
const suffix = typeof crypto !== "undefined" && typeof crypto.randomUUID === "function" ? crypto.randomUUID() : `${Date.now()}-${Math.random().toString(HEX_RADIX).slice(RANDOM_FRACTION_PREFIX_LENGTH)}`;
|
|
@@ -58623,6 +58735,413 @@ var init_network_debug = __esm({
|
|
|
58623
58735
|
}
|
|
58624
58736
|
});
|
|
58625
58737
|
|
|
58738
|
+
// lib/runtime/runtime-error-reason-rules.json
|
|
58739
|
+
var runtime_error_reason_rules_default;
|
|
58740
|
+
var init_runtime_error_reason_rules = __esm({
|
|
58741
|
+
"lib/runtime/runtime-error-reason-rules.json"() {
|
|
58742
|
+
runtime_error_reason_rules_default = {
|
|
58743
|
+
about: "The one owner of runtime error reason codes, loaded by the web runtime (runtime-error-reason-rules.ts) and the API (runtime_error_reason_rules.py). Rules are tried in order on the normalized message without its warning prefix or its AI panel history wrapper (Analysis unavailable:), lowercased, so a stored row and the bare message get the same code; the first match names the code. A condition is equals, starts_with, contains, all, any, or a named predicate each runtime implements. reason_codes classifies every code: transient codes clear on their own; WARN codes record a skipped cycle, not a failure. A code not listed is ERROR and needs the owner's attention.",
|
|
58744
|
+
unclassified_messages: [
|
|
58745
|
+
"unknown runtime error.",
|
|
58746
|
+
"vtx did not receive error details for this runtime failure."
|
|
58747
|
+
],
|
|
58748
|
+
rules: [
|
|
58749
|
+
{ reason_code: "ai_service_rate_limit", when: { predicate: "provider_attempt_summary_http_429" } },
|
|
58750
|
+
{ reason_code: "ai_service_unavailable", when: { predicate: "provider_attempt_summary_unavailable" } },
|
|
58751
|
+
{ reason_code: "hyperliquid_request_capacity", when: { starts_with: "vtx could not obtain hyperliquid request capacity" } },
|
|
58752
|
+
{ reason_code: "http_request_capacity", when: { starts_with: "vtx could not obtain http request capacity" } },
|
|
58753
|
+
{ reason_code: "live_market_stats_unavailable", when: { equals: "live market stats unavailable for client runtime contract" } },
|
|
58754
|
+
{ reason_code: "live_performance_unavailable", when: { equals: "live performance context unavailable for client runtime contract" } },
|
|
58755
|
+
{ reason_code: "live_market_regime_unavailable", when: { equals: "live market regime context unavailable for client runtime contract" } },
|
|
58756
|
+
{ reason_code: "live_calendar_unavailable", when: { equals: "live calendar context unavailable for client runtime contract" } },
|
|
58757
|
+
{ reason_code: "live_derived_context_timeout", when: { equals: "timed out while building live derived context for client runtime contract" } },
|
|
58758
|
+
{ reason_code: "live_derived_context_build_failed", when: { equals: "failed to build live derived context for client runtime contract" } },
|
|
58759
|
+
{ reason_code: "internal_data_error", when: { any: [
|
|
58760
|
+
{ equals: "internal data error. please try again." },
|
|
58761
|
+
{ equals: "vtx could not read the required app data. please try again." }
|
|
58762
|
+
] } },
|
|
58763
|
+
{ reason_code: "private_node_stale", when: { all: [
|
|
58764
|
+
{ contains: "order was not sent" },
|
|
58765
|
+
{ any: [
|
|
58766
|
+
{ contains: "too stale to validate the signing key" },
|
|
58767
|
+
{ contains: "required hyperliquid account data was stale" }
|
|
58768
|
+
] }
|
|
58769
|
+
] } },
|
|
58770
|
+
{ reason_code: "signer_validation_unavailable", when: { all: [
|
|
58771
|
+
{ contains: "order was not sent" },
|
|
58772
|
+
{ any: [
|
|
58773
|
+
{ contains: "private account service could not validate the signing key" },
|
|
58774
|
+
{ contains: "required hyperliquid account data was temporarily unavailable" }
|
|
58775
|
+
] }
|
|
58776
|
+
] } },
|
|
58777
|
+
{ reason_code: "wallet_not_authorized", when: { all: [
|
|
58778
|
+
{ contains: "order was not sent" },
|
|
58779
|
+
{ any: [
|
|
58780
|
+
{ contains: "signing key is not authorized for the configured wallet" },
|
|
58781
|
+
{ contains: "hyperliquid confirmed that the signing key is not authorized" },
|
|
58782
|
+
{ contains: "hyperliquid has not approved this key for this profile's wallet" }
|
|
58783
|
+
] }
|
|
58784
|
+
] } },
|
|
58785
|
+
{ reason_code: "credentials_missing", when: { all: [
|
|
58786
|
+
{ contains: "order was not sent" },
|
|
58787
|
+
{ contains: "authorized signing key are required for trading" }
|
|
58788
|
+
] } },
|
|
58789
|
+
{ reason_code: "local_safety_block", when: { contains: "order was not sent before exchange dispatch" } },
|
|
58790
|
+
{ reason_code: "redis_unavailable", when: { contains: "order was not sent because execution coordination was unavailable" } },
|
|
58791
|
+
{ reason_code: "exchange_rejected", when: { all: [
|
|
58792
|
+
{ starts_with: "hyperliquid rejected the " },
|
|
58793
|
+
{ contains: " order:" }
|
|
58794
|
+
] } },
|
|
58795
|
+
{ reason_code: "outcome_unknown", when: { all: [
|
|
58796
|
+
{ contains: "vtx could not confirm whether the " },
|
|
58797
|
+
{ contains: " order was applied" }
|
|
58798
|
+
] } },
|
|
58799
|
+
{ reason_code: "internal_execution_error", when: { all: [
|
|
58800
|
+
{ starts_with: "vtx could not complete the " },
|
|
58801
|
+
{ contains: " order:" }
|
|
58802
|
+
] } },
|
|
58803
|
+
{ reason_code: "hyperliquid_rate_limit", when: { any: [
|
|
58804
|
+
{ contains: "hyperliquid returned 429" },
|
|
58805
|
+
{ contains: "hyperliquid returned http 429" },
|
|
58806
|
+
{ contains: "public reads are waiting for a rate-limit cooldown" },
|
|
58807
|
+
{ contains: "public reads are waiting after a hyperliquid rate limit" },
|
|
58808
|
+
{ contains: "recovery queue before its deadline" },
|
|
58809
|
+
{ contains: "hyperliquid info endpoint returned 429" },
|
|
58810
|
+
{ contains: "hyperliquid rate limit (429)" },
|
|
58811
|
+
{ contains: "hyperliquid public api returned http 429" },
|
|
58812
|
+
{ contains: "hyperliquid public info cooldown is active" },
|
|
58813
|
+
{ contains: "hyperliquid public request cooldown is active" },
|
|
58814
|
+
{ contains: "hyperliquid public recovery is waiting after an observed http 429" },
|
|
58815
|
+
{ contains: "hyperliquid provider recovery could not dispatch before the request deadline" }
|
|
58816
|
+
] } },
|
|
58817
|
+
{ reason_code: "hyperliquid_read_budget_exhausted", when: { any: [
|
|
58818
|
+
{ all: [
|
|
58819
|
+
{ contains: "fresh hyperliquid data" },
|
|
58820
|
+
{ contains: "current read budget" }
|
|
58821
|
+
] },
|
|
58822
|
+
{ contains: "server's public-read budget is full" },
|
|
58823
|
+
{ contains: "app's shared public-read budget is also full" },
|
|
58824
|
+
{ all: [
|
|
58825
|
+
{ contains: "hyperliquid" },
|
|
58826
|
+
{ contains: "budget exhausted" }
|
|
58827
|
+
] },
|
|
58828
|
+
{ contains: "hyperliquid execution preflight is waiting for its fair public-read turn" },
|
|
58829
|
+
{ contains: "hyperliquid local public request allowance is exhausted" }
|
|
58830
|
+
] } },
|
|
58831
|
+
{ reason_code: "hyperliquid_data_unavailable", when: { any: [
|
|
58832
|
+
{ contains: "fresh private hyperliquid data is unavailable" },
|
|
58833
|
+
{ contains: "private hyperliquid node is stale" },
|
|
58834
|
+
{ contains: "private hyperliquid info circuit is open" },
|
|
58835
|
+
{ contains: "private hyperliquid freshness probe failed" },
|
|
58836
|
+
{ contains: "hyperliquid info endpoint is stale for" },
|
|
58837
|
+
{ contains: "hyperliquid fresh public read returned non-json" },
|
|
58838
|
+
{ contains: "hyperliquid public freshness bracket moved backwards" }
|
|
58839
|
+
] } },
|
|
58840
|
+
{ reason_code: "behavior_state_unavailable", when: { any: [
|
|
58841
|
+
{ all: [
|
|
58842
|
+
{ contains: "your prompt on the ai page contains something vtx can't use" },
|
|
58843
|
+
{ contains: "next scheduled cycle" }
|
|
58844
|
+
] },
|
|
58845
|
+
{ all: [
|
|
58846
|
+
{ contains: "critical behavior context could not be constructed" },
|
|
58847
|
+
{ contains: "next scheduled cycle" }
|
|
58848
|
+
] }
|
|
58849
|
+
] } },
|
|
58850
|
+
{ reason_code: "hyperliquid_wallet_not_authorized", when: { any: [
|
|
58851
|
+
{ contains: "hyperliquid api wallet is not authorized" },
|
|
58852
|
+
{ contains: "hyperliquid signing key is not authorized for this wallet" },
|
|
58853
|
+
{ contains: "hyperliquid has not approved this key for this profile's wallet" }
|
|
58854
|
+
] } },
|
|
58855
|
+
{ reason_code: "ai_service_rate_limit", when: { any: [
|
|
58856
|
+
{ all: [
|
|
58857
|
+
{ contains: "exhausted fallback chain" },
|
|
58858
|
+
{ contains: "(429)" }
|
|
58859
|
+
] },
|
|
58860
|
+
{ contains: "ai provider returned 429" },
|
|
58861
|
+
{ contains: "ai provider and fallback model returned 429" },
|
|
58862
|
+
{ contains: "ai service rate limit (429)" },
|
|
58863
|
+
{ contains: "external ai account has reached its current usage limit" }
|
|
58864
|
+
] } },
|
|
58865
|
+
{ reason_code: "ai_service_unavailable", when: { any: [
|
|
58866
|
+
{ contains: "ai provider returned 503" },
|
|
58867
|
+
{ contains: "ai provider returned 500" },
|
|
58868
|
+
{ contains: "ai provider returned 502" },
|
|
58869
|
+
{ contains: "ai provider returned 504" },
|
|
58870
|
+
{ contains: "ai provider and fallback model returned 503" },
|
|
58871
|
+
{ contains: "service unavailable" },
|
|
58872
|
+
{ contains: "ai service unavailable (503)" },
|
|
58873
|
+
{ contains: "ai provider is temporarily unavailable" },
|
|
58874
|
+
{ contains: "codex reported server overload" },
|
|
58875
|
+
{ contains: "external inference host heartbeat is stale" },
|
|
58876
|
+
{ contains: "external inference host is finishing or recovering outstanding work" },
|
|
58877
|
+
{ contains: "external ai membership is currently available. at least one is cooling down" },
|
|
58878
|
+
{ contains: "external inference current advertisement is stale" },
|
|
58879
|
+
{ predicate: "provider_retry_status" }
|
|
58880
|
+
] } },
|
|
58881
|
+
{ reason_code: "app_bootstrap_unavailable", when: { any: [
|
|
58882
|
+
{ contains: "vtx could not load this profile's runtime settings" },
|
|
58883
|
+
{ contains: "vtx runtime settings temporarily unavailable due to server load" }
|
|
58884
|
+
] } },
|
|
58885
|
+
{ reason_code: "runtime_config_missing", when: { contains: "vtx is missing required runtime configuration" } },
|
|
58886
|
+
{ reason_code: "provider_not_configured", when: { any: [
|
|
58887
|
+
{ contains: "client runtime provider setup error" },
|
|
58888
|
+
{ contains: "is not configured for this profile" },
|
|
58889
|
+
{ contains: "is not account-synced for this profile" }
|
|
58890
|
+
] } },
|
|
58891
|
+
{ reason_code: "provider_unavailable", when: { contains: "client runtime provider error" } },
|
|
58892
|
+
{ reason_code: "browser_cors_failure", when: { any: [
|
|
58893
|
+
{ contains: "the browser blocked the ai provider request" },
|
|
58894
|
+
{ contains: "request was blocked" },
|
|
58895
|
+
{ contains: "failed in browser (network/cors)" }
|
|
58896
|
+
] } },
|
|
58897
|
+
{ reason_code: "market_data_browser_failure", when: { any: [
|
|
58898
|
+
{ contains: "market data did not load" },
|
|
58899
|
+
{ contains: "market data request failed in browser" }
|
|
58900
|
+
] } },
|
|
58901
|
+
{ reason_code: "browser_network_failure", when: { any: [
|
|
58902
|
+
{ contains: "browser could not complete a vtx runtime request" },
|
|
58903
|
+
{ contains: "hyperliquid public request network failure" },
|
|
58904
|
+
{ contains: "a browser network request failed" },
|
|
58905
|
+
{ contains: "browser could not reach the ai provider" },
|
|
58906
|
+
{ contains: "failed in browser (network request failed)" }
|
|
58907
|
+
] } },
|
|
58908
|
+
{ reason_code: "provider_network_failure", when: { contains: "vtx could not reach the ai provider" } },
|
|
58909
|
+
{ reason_code: "runtime_timeout", when: { any: [
|
|
58910
|
+
{ contains: "ai run took too long" },
|
|
58911
|
+
{ contains: "cycle deadline was reached" },
|
|
58912
|
+
{ contains: "this analysis timed out" },
|
|
58913
|
+
{ contains: "hyperliquid request exceeded its total read deadline" }
|
|
58914
|
+
] } },
|
|
58915
|
+
{ reason_code: "snapshot_stale", when: { any: [
|
|
58916
|
+
{ contains: "decision skipped: account data was" },
|
|
58917
|
+
{ contains: "couldn't refresh this bot's hyperliquid account data in time" },
|
|
58918
|
+
{ contains: "server account context could not be rebuilt inside the dispatch freshness window" }
|
|
58919
|
+
] } },
|
|
58920
|
+
{ reason_code: "model_output_schema_invalid", when: { any: [
|
|
58921
|
+
{ starts_with: "model_output_schema_invalid:" },
|
|
58922
|
+
{ contains: "model's reply could not be read" },
|
|
58923
|
+
{ contains: "the agent's instruction could not be read" }
|
|
58924
|
+
] } },
|
|
58925
|
+
{ reason_code: "ai_service_rate_limit", when: { contains: "provider request failed (http 429)" } },
|
|
58926
|
+
{ reason_code: "external_inference_window_missed", when: { any: [
|
|
58927
|
+
{ contains: "external inference host claimed the server prompt but did not dispatch it" },
|
|
58928
|
+
{ contains: "external inference host did not claim the server prompt inside its account-state freshness window" }
|
|
58929
|
+
] } },
|
|
58930
|
+
{ reason_code: "runtime_timeout", when: { contains: "failure code: runtime_timeout" } },
|
|
58931
|
+
{ reason_code: "account_state_changing", when: { any: [
|
|
58932
|
+
{ contains: "account state is changing while preparing prompt context" },
|
|
58933
|
+
{ contains: "server account state changed" }
|
|
58934
|
+
] } },
|
|
58935
|
+
{ reason_code: "runtime_contract_changed", when: { any: [
|
|
58936
|
+
{ contains: "rejected by contract: contract_identity_mismatch" },
|
|
58937
|
+
{ contains: "rejected by contract: contract_binding_mismatch" }
|
|
58938
|
+
] } },
|
|
58939
|
+
{ reason_code: "decision_persistence_timeout", when: { contains: "could not confirm that its decision was saved before the cycle deadline" } },
|
|
58940
|
+
{ reason_code: "model_unavailable", when: { any: [
|
|
58941
|
+
{ contains: "this model is not available from the selected provider" },
|
|
58942
|
+
{ contains: "model is not available on the selected provider" },
|
|
58943
|
+
{ contains: "client runtime model error" },
|
|
58944
|
+
{ contains: " is not available on " },
|
|
58945
|
+
{ starts_with: "unknown model" }
|
|
58946
|
+
] } },
|
|
58947
|
+
{ reason_code: "runtime_contract_changed", when: { any: [
|
|
58948
|
+
{ contains: "the bot's run changed while this analysis was waiting" },
|
|
58949
|
+
{ equals: "runtime_fence_stale" },
|
|
58950
|
+
{ equals: "settings_superseded" },
|
|
58951
|
+
{ contains: "terminal code: runtime_fence_" },
|
|
58952
|
+
{ contains: "failure code: runtime_fence_" }
|
|
58953
|
+
] } },
|
|
58954
|
+
{ reason_code: "runtime_timeout", when: { any: [
|
|
58955
|
+
{ contains: "terminal code: deadline_exceeded" },
|
|
58956
|
+
{ equals: "the operation was aborted." },
|
|
58957
|
+
{ contains: "encountered timeouterror without additional error details" }
|
|
58958
|
+
] } },
|
|
58959
|
+
{ reason_code: "ai_service_rate_limit", when: { any: [
|
|
58960
|
+
{ contains: "terminal code: codex_rate_limited." },
|
|
58961
|
+
{ contains: "terminal code: provider_rate_limited." }
|
|
58962
|
+
] } },
|
|
58963
|
+
{ reason_code: "ai_service_unavailable", when: { any: [
|
|
58964
|
+
{ contains: "terminal code: codex_server_overloaded." },
|
|
58965
|
+
{ contains: "terminal code: codex_internal_error." },
|
|
58966
|
+
{ contains: "terminal code: codex_http_connection_failed." },
|
|
58967
|
+
{ contains: "terminal code: codex_response_stream_connection_failed." },
|
|
58968
|
+
{ contains: "terminal code: codex_response_stream_disconnected." },
|
|
58969
|
+
{ contains: "terminal code: codex_provider_retry_exhausted." },
|
|
58970
|
+
{ contains: "terminal code: model_unavailable." },
|
|
58971
|
+
{ contains: "terminal code: reasoning_effort_unavailable." }
|
|
58972
|
+
] } },
|
|
58973
|
+
{ reason_code: "external_inference_failed", when: { any: [
|
|
58974
|
+
{ contains: "terminal code: " },
|
|
58975
|
+
{ contains: "external ai recovery checkpoint failed" }
|
|
58976
|
+
] } },
|
|
58977
|
+
{ reason_code: "vtx_api_request_failed", when: { contains: "client runtime inference job read failed" } },
|
|
58978
|
+
{ reason_code: "hyperliquid_data_unavailable", when: { any: [
|
|
58979
|
+
{ starts_with: "hyperliquid didn't answer vtx's request" },
|
|
58980
|
+
{ starts_with: "hyperliquid info request failed (5" }
|
|
58981
|
+
] } },
|
|
58982
|
+
{ reason_code: "hyperliquid_request_rejected", when: { any: [
|
|
58983
|
+
{ starts_with: "hyperliquid refused vtx's request" },
|
|
58984
|
+
{ starts_with: "hyperliquid info request failed (4" }
|
|
58985
|
+
] } },
|
|
58986
|
+
{ reason_code: "hyperliquid_read_budget_exhausted", when: { contains: "hyperliquid public read capacity is in use by higher-priority reads" } },
|
|
58987
|
+
{ reason_code: "cycle_ended_without_decision", when: { any: [
|
|
58988
|
+
{ contains: "this analysis ended before it reached a decision" },
|
|
58989
|
+
{ starts_with: "client_runtime_no_decision_cycle" }
|
|
58990
|
+
] } },
|
|
58991
|
+
{ reason_code: "provider_credentials_refreshing", when: { contains: "client provider credentials changed; account refresh is pending" } },
|
|
58992
|
+
{ reason_code: "browser_network_failure", when: { any: [
|
|
58993
|
+
{ equals: "fetch failed" },
|
|
58994
|
+
{ equals: "terminated" },
|
|
58995
|
+
{ contains: "content-length header of network response exceeds response body" }
|
|
58996
|
+
] } },
|
|
58997
|
+
{ reason_code: "provider_not_configured", when: { any: [
|
|
58998
|
+
{ contains: "no profile api key was provided for source" },
|
|
58999
|
+
{ contains: "no configured external inference host currently supports the selected model" }
|
|
59000
|
+
] } },
|
|
59001
|
+
{ reason_code: "provider_access_denied", when: { any: [
|
|
59002
|
+
{ starts_with: "provider request failed (http 401" },
|
|
59003
|
+
{ starts_with: "provider request failed (http 402" },
|
|
59004
|
+
{ starts_with: "provider request failed (http 403" },
|
|
59005
|
+
{ contains: "user location is not supported for the api use" }
|
|
59006
|
+
] } },
|
|
59007
|
+
{ reason_code: "model_output_schema_invalid", when: { contains: "rejected by constraints: symbol_mismatch" } },
|
|
59008
|
+
{ reason_code: "internal_data_error", when: { any: [
|
|
59009
|
+
{ contains: "external inference delivery identity did not match" },
|
|
59010
|
+
{ contains: "external inference idempotency key conflicts with another job" },
|
|
59011
|
+
{ contains: "external inference advertisement evidence is inconsistent" }
|
|
59012
|
+
] } },
|
|
59013
|
+
{ reason_code: "ai_service_rate_limit", when: { equals: "rate limit (paused)" } },
|
|
59014
|
+
{ reason_code: "profile_wallet_unavailable", when: { equals: "profile_wallet_unavailable" } },
|
|
59015
|
+
{ reason_code: "provider_access_denied", when: { all: [
|
|
59016
|
+
{ starts_with: "ai provider attempts failed:" },
|
|
59017
|
+
{ any: [{ contains: ": http 401" }, { contains: ": http 402" }, { contains: ": http 403" }] }
|
|
59018
|
+
] } },
|
|
59019
|
+
{ reason_code: "runtime_contract_changed", when: { any: [
|
|
59020
|
+
{ contains: "the external agent setting changed while this cycle was starting" },
|
|
59021
|
+
{ contains: "external inference job creation runtime fence is stale" }
|
|
59022
|
+
] } },
|
|
59023
|
+
{ reason_code: "account_state_changing", when: { contains: "server account state reconciliation is pending" } },
|
|
59024
|
+
{ reason_code: "snapshot_stale", when: { contains: "rejected by constraints: snapshot_stale" } },
|
|
59025
|
+
{ reason_code: "provider_not_configured", when: { any: [
|
|
59026
|
+
{ starts_with: "missing device-local api key for" },
|
|
59027
|
+
{ contains: "codex host runtime must be upgraded" }
|
|
59028
|
+
] } },
|
|
59029
|
+
{ reason_code: "model_output_schema_invalid", when: { any: [
|
|
59030
|
+
{ contains: "did not include any message content" },
|
|
59031
|
+
{ contains: "did not include any text content" }
|
|
59032
|
+
] } },
|
|
59033
|
+
{ reason_code: "browser_network_failure", when: { equals: "load failed" } },
|
|
59034
|
+
{ reason_code: "ai_service_unavailable", when: { starts_with: "ai provider recovery cooldown" } },
|
|
59035
|
+
{ reason_code: "hyperliquid_credentials_missing", when: { contains: "has no hyperliquid credentials configured" } },
|
|
59036
|
+
{ reason_code: "external_inference_window_missed", when: { contains: "external inference admission deadline expired while refreshing account context" } }
|
|
59037
|
+
],
|
|
59038
|
+
reason_codes: {
|
|
59039
|
+
account_state_changing: { transient: true, severity: "ERROR" },
|
|
59040
|
+
ai_service_rate_limit: { transient: true, severity: "ERROR" },
|
|
59041
|
+
ai_service_unavailable: { transient: true, severity: "ERROR" },
|
|
59042
|
+
app_bootstrap_unavailable: { transient: true, severity: "ERROR" },
|
|
59043
|
+
behavior_state_unavailable: { transient: true, severity: "WARN" },
|
|
59044
|
+
browser_cors_failure: { transient: true, severity: "ERROR" },
|
|
59045
|
+
browser_network_failure: { transient: true, severity: "ERROR" },
|
|
59046
|
+
credentials_missing: { transient: false, severity: "ERROR" },
|
|
59047
|
+
cycle_ended_without_decision: { transient: true, severity: "ERROR" },
|
|
59048
|
+
decision_persistence_timeout: { transient: true, severity: "ERROR" },
|
|
59049
|
+
device_signing_key_invalid: { transient: false, severity: "ERROR" },
|
|
59050
|
+
device_signing_key_unauthorized: { transient: false, severity: "ERROR" },
|
|
59051
|
+
exchange_rejected: { transient: false, severity: "ERROR" },
|
|
59052
|
+
external_inference_failed: { transient: false, severity: "ERROR" },
|
|
59053
|
+
external_inference_window_missed: { transient: true, severity: "ERROR" },
|
|
59054
|
+
http_request_capacity: { transient: true, severity: "ERROR" },
|
|
59055
|
+
hyperliquid_credentials_missing: { transient: false, severity: "ERROR" },
|
|
59056
|
+
hyperliquid_data_unavailable: { transient: true, severity: "ERROR" },
|
|
59057
|
+
hyperliquid_rate_limit: { transient: true, severity: "ERROR" },
|
|
59058
|
+
hyperliquid_read_budget_exhausted: { transient: true, severity: "WARN" },
|
|
59059
|
+
hyperliquid_request_capacity: { transient: true, severity: "ERROR" },
|
|
59060
|
+
hyperliquid_request_rejected: { transient: false, severity: "ERROR" },
|
|
59061
|
+
hyperliquid_wallet_not_authorized: { transient: false, severity: "ERROR" },
|
|
59062
|
+
internal_data_error: { transient: false, severity: "ERROR" },
|
|
59063
|
+
internal_execution_error: { transient: false, severity: "ERROR" },
|
|
59064
|
+
live_calendar_unavailable: { transient: true, severity: "ERROR" },
|
|
59065
|
+
live_derived_context_build_failed: { transient: true, severity: "ERROR" },
|
|
59066
|
+
live_derived_context_timeout: { transient: true, severity: "ERROR" },
|
|
59067
|
+
live_market_regime_unavailable: { transient: true, severity: "ERROR" },
|
|
59068
|
+
live_market_stats_unavailable: { transient: true, severity: "ERROR" },
|
|
59069
|
+
live_performance_unavailable: { transient: true, severity: "ERROR" },
|
|
59070
|
+
local_safety_block: { transient: false, severity: "ERROR" },
|
|
59071
|
+
market_data_browser_failure: { transient: true, severity: "ERROR" },
|
|
59072
|
+
model_output_schema_invalid: { transient: true, severity: "ERROR" },
|
|
59073
|
+
model_unavailable: { transient: false, severity: "ERROR" },
|
|
59074
|
+
outcome_unknown: { transient: true, severity: "ERROR" },
|
|
59075
|
+
private_node_stale: { transient: true, severity: "ERROR" },
|
|
59076
|
+
profile_wallet_unavailable: { transient: false, severity: "ERROR" },
|
|
59077
|
+
protective_order_not_placed: { transient: false, severity: "WARN" },
|
|
59078
|
+
protective_order_unmanaged: { transient: false, severity: "WARN" },
|
|
59079
|
+
provider_access_denied: { transient: false, severity: "ERROR" },
|
|
59080
|
+
provider_credentials_refreshing: { transient: true, severity: "ERROR" },
|
|
59081
|
+
provider_network_failure: { transient: true, severity: "ERROR" },
|
|
59082
|
+
provider_not_configured: { transient: false, severity: "ERROR" },
|
|
59083
|
+
provider_unavailable: { transient: true, severity: "ERROR" },
|
|
59084
|
+
redis_unavailable: { transient: true, severity: "ERROR" },
|
|
59085
|
+
runtime_config_missing: { transient: false, severity: "ERROR" },
|
|
59086
|
+
runtime_contract_changed: { transient: true, severity: "ERROR" },
|
|
59087
|
+
runtime_timeout: { transient: true, severity: "ERROR" },
|
|
59088
|
+
signer_validation_unavailable: { transient: false, severity: "ERROR" },
|
|
59089
|
+
snapshot_stale: { transient: true, severity: "ERROR" },
|
|
59090
|
+
vtx_api_request_failed: { transient: true, severity: "ERROR" },
|
|
59091
|
+
wallet_not_authorized: { transient: false, severity: "ERROR" }
|
|
59092
|
+
}
|
|
59093
|
+
};
|
|
59094
|
+
}
|
|
59095
|
+
});
|
|
59096
|
+
|
|
59097
|
+
// lib/runtime/runtime-error-reason-rules.ts
|
|
59098
|
+
var RuntimeReasonError, runtimeRequestFailure, raisedRuntimeErrorReasonCode, HISTORY_WRAPPER, runtimeErrorReasonSubject, RULES, matches, matchRuntimeErrorReasonCode;
|
|
59099
|
+
var init_runtime_error_reason_rules2 = __esm({
|
|
59100
|
+
"lib/runtime/runtime-error-reason-rules.ts"() {
|
|
59101
|
+
"use strict";
|
|
59102
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
59103
|
+
init_define_VTX_EXO_POLICY();
|
|
59104
|
+
init_define_VTX_GROK_POLICY();
|
|
59105
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
59106
|
+
init_runtime_error_reason_rules();
|
|
59107
|
+
init_constants();
|
|
59108
|
+
RuntimeReasonError = class extends Error {
|
|
59109
|
+
constructor(message, runtimeReasonCode, options) {
|
|
59110
|
+
super(message, options);
|
|
59111
|
+
this.name = "RuntimeReasonError";
|
|
59112
|
+
this.runtimeReasonCode = runtimeReasonCode;
|
|
59113
|
+
}
|
|
59114
|
+
};
|
|
59115
|
+
runtimeRequestFailure = (message, status, unexplained) => unexplained && (status >= HTTP_SERVER_ERROR_MIN || status === HTTP_STATUS.TOO_MANY_REQUESTS) ? new RuntimeReasonError(message, "vtx_api_request_failed") : new Error(message);
|
|
59116
|
+
raisedRuntimeErrorReasonCode = (error48) => error48 instanceof RuntimeReasonError ? error48.runtimeReasonCode : null;
|
|
59117
|
+
HISTORY_WRAPPER = /^analysis unavailable:\s*(?:\u26a0\ufe0f?\s*)?/iu;
|
|
59118
|
+
runtimeErrorReasonSubject = (normalizedWithoutWarning) => normalizedWithoutWarning.replace(HISTORY_WRAPPER, "").trim();
|
|
59119
|
+
RULES = runtime_error_reason_rules_default;
|
|
59120
|
+
matches = (condition, lowered, texts, predicates) => {
|
|
59121
|
+
if ("equals" in condition) return lowered === condition.equals;
|
|
59122
|
+
if ("starts_with" in condition) return lowered.startsWith(condition.starts_with);
|
|
59123
|
+
if ("contains" in condition) return lowered.includes(condition.contains);
|
|
59124
|
+
if ("all" in condition) return condition.all.every((item) => matches(item, lowered, texts, predicates));
|
|
59125
|
+
if ("any" in condition) return condition.any.some((item) => matches(item, lowered, texts, predicates));
|
|
59126
|
+
return predicates[condition.predicate](...texts);
|
|
59127
|
+
};
|
|
59128
|
+
matchRuntimeErrorReasonCode = (normalized, normalizedWithoutWarning, predicates) => {
|
|
59129
|
+
const subject = runtimeErrorReasonSubject(normalizedWithoutWarning);
|
|
59130
|
+
const lowered = subject.toLowerCase();
|
|
59131
|
+
if (!normalized || RULES.unclassified_messages.includes(lowered)) {
|
|
59132
|
+
return null;
|
|
59133
|
+
}
|
|
59134
|
+
const texts = [normalized, subject];
|
|
59135
|
+
for (const rule of RULES.rules) {
|
|
59136
|
+
if (matches(rule.when, lowered, texts, predicates)) {
|
|
59137
|
+
return rule.reason_code;
|
|
59138
|
+
}
|
|
59139
|
+
}
|
|
59140
|
+
return null;
|
|
59141
|
+
};
|
|
59142
|
+
}
|
|
59143
|
+
});
|
|
59144
|
+
|
|
58626
59145
|
// lib/runtime/monotonic-clock.ts
|
|
58627
59146
|
var monotonicNowMs, monotonicAgeMs;
|
|
58628
59147
|
var init_monotonic_clock = __esm({
|
|
@@ -58954,27 +59473,35 @@ var init_local_breadcrumbs = __esm({
|
|
|
58954
59473
|
if (pending3.length === 0) {
|
|
58955
59474
|
return 0;
|
|
58956
59475
|
}
|
|
59476
|
+
const report = (entry) => options.reporter(normalizedProfileId, {
|
|
59477
|
+
// Authenticate delivery with the current owner after recovery/reload.
|
|
59478
|
+
// Historical ownership remains unchanged inside the breadcrumb.
|
|
59479
|
+
sessionId: sanitizeOptionalString(options.sessionId) ?? sanitizeOptionalString(entry.sessionId),
|
|
59480
|
+
deviceId: sanitizeOptionalString(options.deviceId) ?? sanitizeOptionalString(entry.deviceId),
|
|
59481
|
+
mode: entry.mode ?? (options.mode === "assistant" ? "assistant" : options.mode === "trader" ? "trader" : null),
|
|
59482
|
+
lastRunAt: sanitizeOptionalString(entry.lastRunAt) ?? sanitizeOptionalString(options.lastRunAt),
|
|
59483
|
+
eventType: "client_recovered_local_breadcrumb",
|
|
59484
|
+
detail: `Recovered local runtime breadcrumb: ${entry.kind}`,
|
|
59485
|
+
payload: {
|
|
59486
|
+
flush_reason: flushReason,
|
|
59487
|
+
recovered_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
59488
|
+
breadcrumb: entry
|
|
59489
|
+
}
|
|
59490
|
+
});
|
|
58957
59491
|
const flushedIds = [];
|
|
58958
|
-
|
|
58959
|
-
|
|
58960
|
-
|
|
58961
|
-
|
|
58962
|
-
|
|
58963
|
-
|
|
58964
|
-
|
|
58965
|
-
|
|
58966
|
-
|
|
58967
|
-
|
|
58968
|
-
|
|
58969
|
-
|
|
58970
|
-
|
|
58971
|
-
recovered_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
58972
|
-
breadcrumb: entry
|
|
58973
|
-
}
|
|
58974
|
-
});
|
|
58975
|
-
flushedIds.push(entry.id);
|
|
58976
|
-
} catch {
|
|
58977
|
-
break;
|
|
59492
|
+
if (options.together) {
|
|
59493
|
+
const settled2 = await Promise.allSettled(pending3.map((entry) => Promise.resolve().then(() => report(entry))));
|
|
59494
|
+
pending3.forEach((entry, index) => {
|
|
59495
|
+
if (settled2[index].status === "fulfilled") flushedIds.push(entry.id);
|
|
59496
|
+
});
|
|
59497
|
+
} else {
|
|
59498
|
+
for (const entry of pending3) {
|
|
59499
|
+
try {
|
|
59500
|
+
await report(entry);
|
|
59501
|
+
flushedIds.push(entry.id);
|
|
59502
|
+
} catch {
|
|
59503
|
+
break;
|
|
59504
|
+
}
|
|
58978
59505
|
}
|
|
58979
59506
|
}
|
|
58980
59507
|
if (flushedIds.length > 0) {
|
|
@@ -59212,16 +59739,18 @@ async function getExecutionAssetMetadata(exchange, symbol2, options) {
|
|
|
59212
59739
|
});
|
|
59213
59740
|
if (!response.ok) {
|
|
59214
59741
|
const summary = `Failed to fetch execution asset metadata: ${response.status} ${response.statusText}`;
|
|
59742
|
+
const code = await response.clone().json().then((body) => typeof body?.detail?.code === "string" ? body.detail.code : null).catch(() => null);
|
|
59215
59743
|
const detail = await getErrorMessageFromResponse(response, summary);
|
|
59216
59744
|
throw new ExecutionAssetMetadataRequestError(
|
|
59217
59745
|
detail === summary ? summary : `${summary}: ${detail}`,
|
|
59218
59746
|
response.status,
|
|
59219
|
-
parseRetryAfterMs2(response.headers.get("Retry-After"))
|
|
59747
|
+
parseRetryAfterMs2(response.headers.get("Retry-After")),
|
|
59748
|
+
code
|
|
59220
59749
|
);
|
|
59221
59750
|
}
|
|
59222
59751
|
return response.json();
|
|
59223
59752
|
}
|
|
59224
|
-
var ExecutionAssetMetadataRequestError;
|
|
59753
|
+
var ExecutionAssetMetadataRequestError, CLIENT_EXECUTION_METADATA_DEVICE_READ, executionMetadataNeedsDeviceRead;
|
|
59225
59754
|
var init_market_data = __esm({
|
|
59226
59755
|
"lib/api/market-data.ts"() {
|
|
59227
59756
|
"use strict";
|
|
@@ -59235,13 +59764,16 @@ var init_market_data = __esm({
|
|
|
59235
59764
|
init_shared();
|
|
59236
59765
|
init_constants();
|
|
59237
59766
|
ExecutionAssetMetadataRequestError = class extends Error {
|
|
59238
|
-
constructor(message, status, retryAfterMs) {
|
|
59767
|
+
constructor(message, status, retryAfterMs, code = null) {
|
|
59239
59768
|
super(message);
|
|
59240
59769
|
this.status = status;
|
|
59241
59770
|
this.retryAfterMs = retryAfterMs;
|
|
59771
|
+
this.code = code;
|
|
59242
59772
|
this.name = "ExecutionAssetMetadataRequestError";
|
|
59243
59773
|
}
|
|
59244
59774
|
};
|
|
59775
|
+
CLIENT_EXECUTION_METADATA_DEVICE_READ = "client_execution_metadata_device_read";
|
|
59776
|
+
executionMetadataNeedsDeviceRead = (error48) => error48 instanceof ExecutionAssetMetadataRequestError && error48.code === CLIENT_EXECUTION_METADATA_DEVICE_READ;
|
|
59245
59777
|
}
|
|
59246
59778
|
});
|
|
59247
59779
|
|
|
@@ -59557,6 +60089,109 @@ var init_llm_config = __esm({
|
|
|
59557
60089
|
}
|
|
59558
60090
|
});
|
|
59559
60091
|
|
|
60092
|
+
// lib/api/runtime-event-batch.ts
|
|
60093
|
+
var EVENT_BATCH, groups, batchRouteMissing, statusOf, sendSingly, flush, queueRuntimeEvent, eventBody, reportRuntimeEvent;
|
|
60094
|
+
var init_runtime_event_batch = __esm({
|
|
60095
|
+
"lib/api/runtime-event-batch.ts"() {
|
|
60096
|
+
"use strict";
|
|
60097
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
60098
|
+
init_define_VTX_EXO_POLICY();
|
|
60099
|
+
init_define_VTX_GROK_POLICY();
|
|
60100
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
60101
|
+
init_runtime_policy_generated2();
|
|
60102
|
+
init_constants();
|
|
60103
|
+
EVENT_BATCH = runtime_policy_generated_default2.trading.engine.client_runtime.event_batch;
|
|
60104
|
+
groups = /* @__PURE__ */ new Map();
|
|
60105
|
+
batchRouteMissing = false;
|
|
60106
|
+
statusOf = (error48) => {
|
|
60107
|
+
const value = Number(error48?.status);
|
|
60108
|
+
return Number.isFinite(value) ? value : null;
|
|
60109
|
+
};
|
|
60110
|
+
sendSingly = (events, sendOne) => {
|
|
60111
|
+
for (const event of events) sendOne(event.body).then(event.resolve, event.reject);
|
|
60112
|
+
};
|
|
60113
|
+
flush = (key) => {
|
|
60114
|
+
const group = groups.get(key);
|
|
60115
|
+
if (!group) return;
|
|
60116
|
+
groups.delete(key);
|
|
60117
|
+
if (group.timer) clearTimeout(group.timer);
|
|
60118
|
+
if (batchRouteMissing) {
|
|
60119
|
+
sendSingly(group.events, group.sendOne);
|
|
60120
|
+
return;
|
|
60121
|
+
}
|
|
60122
|
+
for (let start = 0; start < group.events.length; start += EVENT_BATCH.max_events) {
|
|
60123
|
+
const chunk = group.events.slice(start, start + EVENT_BATCH.max_events);
|
|
60124
|
+
group.sendBatch(chunk.map((event) => event.body)).then(
|
|
60125
|
+
(response) => {
|
|
60126
|
+
const results = response?.results;
|
|
60127
|
+
const unrecorded = chunk.filter((event, index) => {
|
|
60128
|
+
if (results?.[index]?.status === "not_recorded") return true;
|
|
60129
|
+
event.resolve({ status: "event_recorded" });
|
|
60130
|
+
return false;
|
|
60131
|
+
});
|
|
60132
|
+
sendSingly(unrecorded, group.sendOne);
|
|
60133
|
+
},
|
|
60134
|
+
(error48) => {
|
|
60135
|
+
const status = statusOf(error48);
|
|
60136
|
+
if (status === HTTP_STATUS.METHOD_NOT_ALLOWED) {
|
|
60137
|
+
batchRouteMissing = true;
|
|
60138
|
+
sendSingly(chunk, group.sendOne);
|
|
60139
|
+
return;
|
|
60140
|
+
}
|
|
60141
|
+
if (status === HTTP_STATUS.UNPROCESSABLE_CONTENT) {
|
|
60142
|
+
sendSingly(chunk, group.sendOne);
|
|
60143
|
+
return;
|
|
60144
|
+
}
|
|
60145
|
+
chunk.forEach((event) => event.reject(error48));
|
|
60146
|
+
}
|
|
60147
|
+
);
|
|
60148
|
+
}
|
|
60149
|
+
};
|
|
60150
|
+
queueRuntimeEvent = (key, body, send) => new Promise((resolve16, reject) => {
|
|
60151
|
+
let group = groups.get(key);
|
|
60152
|
+
if (!group) {
|
|
60153
|
+
group = { events: [], timer: null, sendBatch: send.batch, sendOne: send.one };
|
|
60154
|
+
groups.set(key, group);
|
|
60155
|
+
group.timer = setTimeout(() => flush(key), EVENT_BATCH.window_milliseconds);
|
|
60156
|
+
}
|
|
60157
|
+
group.events.push({ body, resolve: resolve16, reject });
|
|
60158
|
+
if (group.events.length >= EVENT_BATCH.max_events) flush(key);
|
|
60159
|
+
});
|
|
60160
|
+
eventBody = (payload) => ({
|
|
60161
|
+
session_id: payload.sessionId ?? null,
|
|
60162
|
+
device_id: payload.deviceId ?? null,
|
|
60163
|
+
...String(payload.schedulerInstanceId ?? "").trim() ? { scheduler_instance_id: String(payload.schedulerInstanceId).trim() } : {},
|
|
60164
|
+
mode: payload.mode ?? null,
|
|
60165
|
+
last_run_at: payload.lastRunAt ?? null,
|
|
60166
|
+
event_type: payload.eventType,
|
|
60167
|
+
detail: payload.detail ?? null,
|
|
60168
|
+
payload: payload.payload ?? null
|
|
60169
|
+
});
|
|
60170
|
+
reportRuntimeEvent = (profileId, payload, options, post) => {
|
|
60171
|
+
const body = eventBody(payload);
|
|
60172
|
+
const sendOne = (event) => post("/runtime/event", profileId, JSON.stringify(event), options);
|
|
60173
|
+
if (options?.keepalive || options?.signal) return sendOne(body);
|
|
60174
|
+
const context = {
|
|
60175
|
+
session_id: body.session_id ?? null,
|
|
60176
|
+
device_id: body.device_id ?? null,
|
|
60177
|
+
mode: body.mode ?? null,
|
|
60178
|
+
...body.scheduler_instance_id ? { scheduler_instance_id: body.scheduler_instance_id } : {}
|
|
60179
|
+
};
|
|
60180
|
+
const key = [
|
|
60181
|
+
String(profileId).trim(),
|
|
60182
|
+
JSON.stringify(context),
|
|
60183
|
+
options?.runtimeLeaseToken ?? "",
|
|
60184
|
+
options?.omitRuntimeLeaseToken ? "omit" : "",
|
|
60185
|
+
options?.reconcileOnly ? "reconcile" : ""
|
|
60186
|
+
].join("|");
|
|
60187
|
+
return queueRuntimeEvent(key, body, {
|
|
60188
|
+
batch: (events) => post("/runtime/events", profileId, JSON.stringify({ ...context, events }), options),
|
|
60189
|
+
one: sendOne
|
|
60190
|
+
});
|
|
60191
|
+
};
|
|
60192
|
+
}
|
|
60193
|
+
});
|
|
60194
|
+
|
|
59560
60195
|
// lib/api/insights-access-center.ts
|
|
59561
60196
|
var init_insights_access_center = __esm({
|
|
59562
60197
|
"lib/api/insights-access-center.ts"() {
|
|
@@ -59686,6 +60321,17 @@ var init_admin_signups = __esm({
|
|
|
59686
60321
|
}
|
|
59687
60322
|
});
|
|
59688
60323
|
|
|
60324
|
+
// lib/api/client-exchange-reconciliation.ts
|
|
60325
|
+
var init_client_exchange_reconciliation = __esm({
|
|
60326
|
+
"lib/api/client-exchange-reconciliation.ts"() {
|
|
60327
|
+
"use strict";
|
|
60328
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
60329
|
+
init_define_VTX_EXO_POLICY();
|
|
60330
|
+
init_define_VTX_GROK_POLICY();
|
|
60331
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
60332
|
+
}
|
|
60333
|
+
});
|
|
60334
|
+
|
|
59689
60335
|
// lib/runtime/hyperliquid-account-mode-contract.ts
|
|
59690
60336
|
function resolveExactHyperliquidAccountMode(userAbstraction, ...dexEvidence) {
|
|
59691
60337
|
const mode = extractCanonicalHyperliquidAccountMode(userAbstraction);
|
|
@@ -60332,7 +60978,7 @@ var init_hyperliquid_public_capacity = __esm({
|
|
|
60332
60978
|
});
|
|
60333
60979
|
|
|
60334
60980
|
// lib/runtime/hyperliquid-public-read.ts
|
|
60335
|
-
var policy, weights, recoveryPolicy, budgets, unpersistedBudgets, cache, pending2, PREFIX, priorityRank, createHyperliquidPublicPriorityScope, promoteHyperliquidPublicPriority, hostTransport, hyperliquidPrivateInfoHeldOff, abortError2, checkAbort, wait, waitUnlessPromoted, storage, loadBudget, saveBudget, withBudgetLock, HyperliquidPublicReadError, getHyperliquidPublicReadBudget, cooldownError, recoveryWaitError, ranks, mostUrgentRank, lastRank, capacityPolicy, READERS_KEY, memoryReaders, unwrittenReaders, validSchedule, readTradingReaders, noteTradingReader, noteHyperliquidTradingRuntime, noteHyperliquidUnscheduledTradingRead, noteHyperliquidTradingRuntimeAttach, hyperliquidDemandWindowMs, hyperliquidDemandHorizonMs, greatestCommonDivisor, heldDemand, ranTogether, isHeldBack, reservationRank, classBoundaries, everyone, slotOf, windowWeights, foldDemand, demandFor, heldBackDecision, fallbackDelayMs, admit, rowWeightedCharge, settleRowWeightedReservation, cooldown, finishHyperliquidRecoveryRequest, assertHyperliquidRecoveryDispatch, validateHyperliquidRecoveryDispatch, cacheTtlMs, eligibleCache, reserveHyperliquidPublicReads, releaseHyperliquidPublicReadReservation, admitHyperliquidExchangeRequest, recordHyperliquidExchangeResponse, readHyperliquidPublicInfo;
|
|
60981
|
+
var policy, weights, recoveryPolicy, budgets, unpersistedBudgets, cache, pending2, PREFIX, priorityRank, createHyperliquidPublicPriorityScope, promoteHyperliquidPublicPriority, hostTransport, hyperliquidPrivateInfoHeldOff, abortError2, checkAbort, wait, waitUnlessPromoted, storage, loadBudget, saveBudget, withBudgetLock, PUBLIC_READ_REASON_CODES, HyperliquidPublicReadError, getHyperliquidPublicReadBudget, cooldownError, recoveryWaitError, ranks, mostUrgentRank, lastRank, capacityPolicy, READERS_KEY, memoryReaders, unwrittenReaders, validSchedule, readTradingReaders, noteTradingReader, noteHyperliquidTradingRuntime, noteHyperliquidUnscheduledTradingRead, noteHyperliquidTradingRuntimeAttach, hyperliquidDemandWindowMs, hyperliquidDemandHorizonMs, greatestCommonDivisor, heldDemand, ranTogether, isHeldBack, reservationRank, classBoundaries, everyone, slotOf, windowWeights, unscheduledSlot, demandEntryLength, foldDemand, demandFor, heldBackDecision, fallbackDelayMs, admit, rowWeightedCharge, settleRowWeightedReservation, cooldown, finishHyperliquidRecoveryRequest, assertHyperliquidRecoveryDispatch, validateHyperliquidRecoveryDispatch, cacheTtlMs, eligibleCache, reserveHyperliquidPublicReads, releaseHyperliquidPublicReadReservation, admitHyperliquidExchangeRequest, recordHyperliquidExchangeResponse, readHyperliquidPublicInfo;
|
|
60336
60982
|
var init_hyperliquid_public_read = __esm({
|
|
60337
60983
|
"lib/runtime/hyperliquid-public-read.ts"() {
|
|
60338
60984
|
"use strict";
|
|
@@ -60342,6 +60988,7 @@ var init_hyperliquid_public_read = __esm({
|
|
|
60342
60988
|
init_define_VTX_PI_MODEL_POLICY();
|
|
60343
60989
|
init_runtime_redaction();
|
|
60344
60990
|
init_runtime_policy_generated2();
|
|
60991
|
+
init_runtime_error_reason_rules2();
|
|
60345
60992
|
init_constants();
|
|
60346
60993
|
init_hyperliquid_public_capacity();
|
|
60347
60994
|
policy = runtime_policy_generated_default2.exchange.hyperliquid.client_public_read_budget;
|
|
@@ -60353,7 +61000,7 @@ var init_hyperliquid_public_read = __esm({
|
|
|
60353
61000
|
pending2 = /* @__PURE__ */ new Map();
|
|
60354
61001
|
PREFIX = "vtx:hl-public-read-budget:v1:";
|
|
60355
61002
|
priorityRank = (priority) => runtime_policy_generated_default2.exchange.hyperliquid.public_request_priority[priority];
|
|
60356
|
-
createHyperliquidPublicPriorityScope = (priority) => ({ value: priority });
|
|
61003
|
+
createHyperliquidPublicPriorityScope = (priority, unscheduled = false) => ({ value: priority, ...unscheduled ? { unscheduled: true } : {} });
|
|
60357
61004
|
promoteHyperliquidPublicPriority = (scope, priority) => {
|
|
60358
61005
|
if (priorityRank(priority) >= priorityRank(scope.value)) return;
|
|
60359
61006
|
scope.value = priority;
|
|
@@ -60445,9 +61092,17 @@ var init_hyperliquid_public_read = __esm({
|
|
|
60445
61092
|
}
|
|
60446
61093
|
return work();
|
|
60447
61094
|
};
|
|
60448
|
-
|
|
61095
|
+
PUBLIC_READ_REASON_CODES = {
|
|
61096
|
+
public_budget_exhausted: "hyperliquid_read_budget_exhausted",
|
|
61097
|
+
public_recovery_wait: "hyperliquid_rate_limit",
|
|
61098
|
+
public_cooldown_active: "hyperliquid_rate_limit",
|
|
61099
|
+
public_rate_limited: "hyperliquid_rate_limit",
|
|
61100
|
+
public_network_error: "browser_network_failure",
|
|
61101
|
+
public_timeout: "runtime_timeout"
|
|
61102
|
+
};
|
|
61103
|
+
HyperliquidPublicReadError = class extends RuntimeReasonError {
|
|
60449
61104
|
constructor(code, message, requestType, status, retryAfterMs, requiredWeight, usedWeight, maxWeight) {
|
|
60450
|
-
super(message);
|
|
61105
|
+
super(message, PUBLIC_READ_REASON_CODES[code]);
|
|
60451
61106
|
this.code = code;
|
|
60452
61107
|
this.requestType = requestType;
|
|
60453
61108
|
this.status = status;
|
|
@@ -60503,7 +61158,7 @@ var init_hyperliquid_public_read = __esm({
|
|
|
60503
61158
|
let readers = memoryReaders;
|
|
60504
61159
|
try {
|
|
60505
61160
|
const stored = JSON.parse(storage()?.getItem(READERS_KEY) ?? "null");
|
|
60506
|
-
if (Array.isArray(stored) && stored.every((reader) => typeof reader?.id === "string" && Number.isFinite(reader.until) && Number.isFinite(reader.notedAt) && (reader.schedule === void 0 || typeof reader.schedule === "object" && reader.schedule !== null && validSchedule(reader.schedule)))) {
|
|
61161
|
+
if (Array.isArray(stored) && stored.every((reader) => typeof reader?.id === "string" && Number.isFinite(reader.until) && Number.isFinite(reader.notedAt) && (reader.schedule === void 0 || typeof reader.schedule === "object" && reader.schedule !== null && validSchedule(reader.schedule)) && (reader.unscheduled === void 0 || reader.unscheduled === true))) {
|
|
60507
61162
|
readers = stored.filter((reader) => {
|
|
60508
61163
|
const own = unwrittenReaders.get(reader.id);
|
|
60509
61164
|
return own === void 0 || own !== null && reader.notedAt > own.notedAt;
|
|
@@ -60557,16 +61212,20 @@ var init_hyperliquid_public_read = __esm({
|
|
|
60557
61212
|
while (b3 !== 0) [a, b3] = [b3, a % b3];
|
|
60558
61213
|
return a;
|
|
60559
61214
|
};
|
|
60560
|
-
heldDemand = (buckets, now,
|
|
61215
|
+
heldDemand = (buckets, now, allReaders) => {
|
|
61216
|
+
const isMeasured = (reader) => reader.unscheduled === true && !reader.schedule;
|
|
61217
|
+
const measured = allReaders.some(isMeasured);
|
|
61218
|
+
const readers = allReaders.filter((reader) => !isMeasured(reader));
|
|
60561
61219
|
const schedules = readers.flatMap((reader) => reader.schedule ? [reader.schedule] : []);
|
|
60562
|
-
|
|
61220
|
+
const all = { held: buckets, measuredRelease: false };
|
|
61221
|
+
if (schedules.length === 0 || schedules.length < readers.length) return all;
|
|
60563
61222
|
let linedUpMs = schedules[0].loopMs;
|
|
60564
61223
|
for (const { loopMs } of schedules) {
|
|
60565
61224
|
linedUpMs = linedUpMs / greatestCommonDivisor(linedUpMs, loopMs) * loopMs;
|
|
60566
|
-
if (linedUpMs >= capacityPolicy.horizonMs) return
|
|
61225
|
+
if (linedUpMs >= capacityPolicy.horizonMs) return all;
|
|
60567
61226
|
}
|
|
60568
61227
|
const releaseAfterMs = linedUpMs + Math.max(...schedules.map((schedule) => schedule.loopMs)) + Math.max(...schedules.map((schedule) => schedule.cycleMs)) + capacityPolicy.windowMs;
|
|
60569
|
-
if (releaseAfterMs >= capacityPolicy.horizonMs) return
|
|
61228
|
+
if (releaseAfterMs >= capacityPolicy.horizonMs) return all;
|
|
60570
61229
|
const phased = schedules.filter((schedule) => capacityPolicy.windowMs % schedule.loopMs !== 0);
|
|
60571
61230
|
const linesUpAnew = phased.length > 1;
|
|
60572
61231
|
const offCadenceAt = Math.max(
|
|
@@ -60584,12 +61243,13 @@ var init_hyperliquid_public_read = __esm({
|
|
|
60584
61243
|
now - Math.max(...schedules.map((schedule) => schedule.cycleMs)) - capacityPolicy.windowMs,
|
|
60585
61244
|
now
|
|
60586
61245
|
);
|
|
60587
|
-
|
|
61246
|
+
const held = buckets.filter((bucket) => {
|
|
60588
61247
|
const bucketStart = bucket.index * capacityPolicy.bucketMs;
|
|
60589
61248
|
const bucketEnd = bucketStart + capacityPolicy.bucketMs;
|
|
60590
61249
|
const startup = startups.some(({ from, to }) => from < bucketEnd && to > bucketStart - capacityPolicy.windowMs);
|
|
60591
61250
|
return !startup || !seenTogether || now < Math.max(bucketEnd, offCadenceAt) + releaseAfterMs;
|
|
60592
61251
|
});
|
|
61252
|
+
return { held, measuredRelease: measured && held.length < buckets.length };
|
|
60593
61253
|
};
|
|
60594
61254
|
ranTogether = (readers, startupsEnd, latestEnd, now) => {
|
|
60595
61255
|
const windowMs = capacityPolicy.windowMs;
|
|
@@ -60609,16 +61269,23 @@ var init_hyperliquid_public_read = __esm({
|
|
|
60609
61269
|
everyone = lastRank + 1;
|
|
60610
61270
|
slotOf = (boundary) => boundary - mostUrgentRank;
|
|
60611
61271
|
windowWeights = (reservations, endAt) => {
|
|
60612
|
-
const
|
|
61272
|
+
const classes = classBoundaries.length;
|
|
61273
|
+
const weights2 = Array.from({ length: classes + 1 + classes }, () => 0);
|
|
60613
61274
|
for (const entry of reservations) {
|
|
60614
61275
|
if (entry.at <= endAt - capacityPolicy.windowMs || entry.at > endAt) continue;
|
|
60615
61276
|
classBoundaries.forEach((boundary, slot) => {
|
|
60616
|
-
if (reservationRank(entry)
|
|
61277
|
+
if (reservationRank(entry) >= boundary) return;
|
|
61278
|
+
weights2[slot] += entry.weight;
|
|
61279
|
+
if (!entry.unscheduled) weights2[classes + 1 + slot] += entry.weight;
|
|
60617
61280
|
});
|
|
61281
|
+
if (entry.unscheduled) weights2[classes] += entry.weight;
|
|
60618
61282
|
}
|
|
60619
61283
|
return weights2;
|
|
60620
61284
|
};
|
|
61285
|
+
unscheduledSlot = 1 + classBoundaries.length;
|
|
61286
|
+
demandEntryLength = 1 + classBoundaries.length + 1 + classBoundaries.length;
|
|
60621
61287
|
foldDemand = (budget, now) => {
|
|
61288
|
+
if (budget.splitFolded !== void 0 && budget.folded !== budget.splitFolded) budget.olderTabFoldedAt = now;
|
|
60622
61289
|
const foldUpTo = now - capacityPolicy.windowMs;
|
|
60623
61290
|
const foldedUpTo = Math.min(budget.folded ?? 0, foldUpTo);
|
|
60624
61291
|
const oldest = publicDemandBucketIndex(now - capacityPolicy.horizonMs, capacityPolicy.bucketMs);
|
|
@@ -60629,21 +61296,30 @@ var init_hyperliquid_public_read = __esm({
|
|
|
60629
61296
|
if (index < oldest) continue;
|
|
60630
61297
|
let entry = demand.find((item) => item[0] === index);
|
|
60631
61298
|
if (!entry) {
|
|
60632
|
-
entry = [index, ...
|
|
61299
|
+
entry = [index, ...Array.from({ length: demandEntryLength - 1 }, () => 0)];
|
|
60633
61300
|
demand.push(entry);
|
|
60634
61301
|
}
|
|
60635
61302
|
const weights2 = windowWeights(budget.reservations, reservation.at);
|
|
60636
61303
|
const bucketPeaks = entry;
|
|
60637
|
-
|
|
60638
|
-
|
|
60639
|
-
});
|
|
61304
|
+
const slots = bucketPeaks.length >= demandEntryLength ? demandEntryLength - 1 : classBoundaries.length;
|
|
61305
|
+
for (let slot = 0; slot < slots; slot += 1) bucketPeaks[slot + 1] = Math.max(bucketPeaks[slot + 1], weights2[slot]);
|
|
60640
61306
|
}
|
|
60641
61307
|
budget.folded = foldUpTo;
|
|
61308
|
+
budget.splitFolded = foldUpTo;
|
|
60642
61309
|
budget.demand = demand;
|
|
60643
61310
|
budget.reservations = budget.reservations.filter((entry) => entry.at > now - HYPERLIQUID_PUBLIC_READ_WINDOWS_KEPT * capacityPolicy.windowMs);
|
|
60644
61311
|
};
|
|
60645
61312
|
demandFor = (budget, rank, now) => {
|
|
60646
|
-
const of = (entry) =>
|
|
61313
|
+
const of = (entry) => {
|
|
61314
|
+
const split3 = entry.length >= demandEntryLength;
|
|
61315
|
+
return {
|
|
61316
|
+
index: entry[0],
|
|
61317
|
+
higherPeak: entry[slotOf(rank)],
|
|
61318
|
+
totalPeak: entry[slotOf(everyone)],
|
|
61319
|
+
unscheduledPeak: split3 ? entry[unscheduledSlot] : entry[slotOf(rank)],
|
|
61320
|
+
otherHigherPeak: split3 ? entry[unscheduledSlot + slotOf(rank)] : entry[slotOf(rank)]
|
|
61321
|
+
};
|
|
61322
|
+
};
|
|
60647
61323
|
const unfolded = budget.reservations.filter((reservation) => reservation.at > (budget.folded ?? 0)).map((reservation) => [
|
|
60648
61324
|
publicDemandBucketIndex(Math.min(reservation.at, now), capacityPolicy.bucketMs),
|
|
60649
61325
|
...windowWeights(budget.reservations, reservation.at)
|
|
@@ -60659,8 +61335,16 @@ var init_hyperliquid_public_read = __esm({
|
|
|
60659
61335
|
const buckets = demandFor(budget, fromRank, now);
|
|
60660
61336
|
const lastFailureMs = budget.lastFailure ?? 0;
|
|
60661
61337
|
const computed = adaptivePublicCapacity({ nowMs: now, lastFailureMs, buckets, policy: capacityPolicy });
|
|
60662
|
-
const
|
|
60663
|
-
|
|
61338
|
+
const peakOf = (list2) => adaptivePublicCapacity({ nowMs: now, lastFailureMs, buckets: list2, policy: capacityPolicy }).peakHigher;
|
|
61339
|
+
const { held, measuredRelease } = heldDemand(buckets, now, readers);
|
|
61340
|
+
const olderTab = budget.olderTabFoldedAt !== void 0 && now - budget.olderTabFoldedAt < capacityPolicy.horizonMs;
|
|
61341
|
+
let peakHigher = peakOf(olderTab && measuredRelease ? buckets : held);
|
|
61342
|
+
if (measuredRelease && !olderTab) {
|
|
61343
|
+
const others = peakOf(held.map((bucket) => ({ ...bucket, higherPeak: bucket.otherHigherPeak })));
|
|
61344
|
+
const unscheduled = peakOf(buckets.map((bucket) => ({ ...bucket, higherPeak: bucket.unscheduledPeak })));
|
|
61345
|
+
peakHigher = Math.min(computed.peakHigher, Math.max(peakHigher, others + unscheduled));
|
|
61346
|
+
}
|
|
61347
|
+
return { capacity: Math.min(computed.capacity, policy.max_weight), peakHigher };
|
|
60664
61348
|
};
|
|
60665
61349
|
const own = above(rank);
|
|
60666
61350
|
const uiRank = priorityRank("ui");
|
|
@@ -60761,7 +61445,13 @@ var init_hyperliquid_public_read = __esm({
|
|
|
60761
61445
|
recovery.nextAt = now + recoveryPolicy.recovery_min_spacing_ms;
|
|
60762
61446
|
permit = { endpoint: apiUrl, id: ticket, generation: recovery.generation, expiresAt };
|
|
60763
61447
|
}
|
|
60764
|
-
budget.reservations.push({
|
|
61448
|
+
budget.reservations.push({
|
|
61449
|
+
at: now,
|
|
61450
|
+
weight,
|
|
61451
|
+
rank,
|
|
61452
|
+
...reservationId ? { id: reservationId } : {},
|
|
61453
|
+
...priority.unscheduled ? { unscheduled: true } : {}
|
|
61454
|
+
});
|
|
60765
61455
|
foldDemand(budget, now);
|
|
60766
61456
|
saveBudget(key, budget);
|
|
60767
61457
|
return { ready: true, permit, waitMs: 0 };
|
|
@@ -61052,7 +61742,8 @@ var init_hyperliquid_public_read = __esm({
|
|
|
61052
61742
|
}
|
|
61053
61743
|
if (!response.ok) {
|
|
61054
61744
|
const detail = sanitizeRuntimeDiagnosticValue(typeof payload?.response === "string" ? payload.response : typeof payload?.detail === "string" ? payload.detail : "");
|
|
61055
|
-
|
|
61745
|
+
const reasonCode = response.status >= HTTP_SERVER_ERROR_MIN ? "hyperliquid_data_unavailable" : "hyperliquid_request_rejected";
|
|
61746
|
+
throw Object.assign(new RuntimeReasonError(`Hyperliquid info request failed (${response.status}) request_type=${requestType}.${detail ? ` ${detail}` : ""}`, reasonCode), {
|
|
61056
61747
|
status: response.status,
|
|
61057
61748
|
requestType
|
|
61058
61749
|
});
|
|
@@ -61134,6 +61825,92 @@ var init_hyperliquid_exchange_rejections = __esm({
|
|
|
61134
61825
|
}
|
|
61135
61826
|
});
|
|
61136
61827
|
|
|
61828
|
+
// lib/runtime/hyperliquid-market-catalog.ts
|
|
61829
|
+
var DEFAULT_DEX, DEFAULT_DEX_INDEX, ISOLATED_ONLY_MARGIN_MODES, malformed, perpDexIndexes, integer3, marketIdentityRow, listedMarketRows;
|
|
61830
|
+
var init_hyperliquid_market_catalog = __esm({
|
|
61831
|
+
"lib/runtime/hyperliquid-market-catalog.ts"() {
|
|
61832
|
+
"use strict";
|
|
61833
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
61834
|
+
init_define_VTX_EXO_POLICY();
|
|
61835
|
+
init_define_VTX_GROK_POLICY();
|
|
61836
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
61837
|
+
init_constants();
|
|
61838
|
+
init_hyperliquid_market_symbol();
|
|
61839
|
+
init_runtime_error_reason_rules2();
|
|
61840
|
+
DEFAULT_DEX = "";
|
|
61841
|
+
DEFAULT_DEX_INDEX = 0;
|
|
61842
|
+
ISOLATED_ONLY_MARGIN_MODES = /* @__PURE__ */ new Set(["nocross", "strictisolated"]);
|
|
61843
|
+
malformed = (message) => new RuntimeReasonError(message, "hyperliquid_data_unavailable");
|
|
61844
|
+
perpDexIndexes = (perpDexs) => {
|
|
61845
|
+
if (!Array.isArray(perpDexs) || perpDexs.length === 0 || perpDexs.some((item) => item !== null && (!item || typeof item !== "object" || Array.isArray(item) || !String(item.name ?? "").trim()))) {
|
|
61846
|
+
throw malformed("Hyperliquid returned a malformed perpDexs list.");
|
|
61847
|
+
}
|
|
61848
|
+
const indexes = /* @__PURE__ */ new Map([[DEFAULT_DEX, DEFAULT_DEX_INDEX]]);
|
|
61849
|
+
perpDexs.forEach((item, index) => {
|
|
61850
|
+
if (item === null) indexes.set(DEFAULT_DEX, index);
|
|
61851
|
+
else indexes.set(String(item.name).trim().toLowerCase(), index);
|
|
61852
|
+
});
|
|
61853
|
+
return indexes;
|
|
61854
|
+
};
|
|
61855
|
+
integer3 = (value) => {
|
|
61856
|
+
const parsed = typeof value === "number" ? value : typeof value === "string" && value.trim() ? Number(value) : NaN;
|
|
61857
|
+
return Number.isFinite(parsed) ? Math.trunc(parsed) : null;
|
|
61858
|
+
};
|
|
61859
|
+
marketIdentityRow = (input) => {
|
|
61860
|
+
const symbol2 = normalizeHyperliquidMarketSymbol(input.asset.name);
|
|
61861
|
+
if (!symbol2) throw malformed("A Hyperliquid market entry has no name.");
|
|
61862
|
+
const dex = getHyperliquidMarketDex(symbol2);
|
|
61863
|
+
if (dex !== String(input.dex ?? "").trim().toLowerCase()) throw malformed(`Hyperliquid listed ${symbol2} under another DEX.`);
|
|
61864
|
+
const baseSymbol = dex ? symbol2.slice(dex.length + 1) : symbol2;
|
|
61865
|
+
const szDecimals = integer3(input.asset.szDecimals);
|
|
61866
|
+
if (szDecimals === null || szDecimals < 0) throw malformed(`Hyperliquid's entry for ${symbol2} has no size precision.`);
|
|
61867
|
+
const leverage = input.asset.maxLeverage ? integer3(input.asset.maxLeverage) : 1;
|
|
61868
|
+
if (leverage === null) throw malformed(`Hyperliquid's entry for ${symbol2} has an invalid max leverage.`);
|
|
61869
|
+
const rawMarginMode = input.asset.marginMode;
|
|
61870
|
+
const marginMode = rawMarginMode === null || rawMarginMode === void 0 ? null : String(rawMarginMode).trim() || null;
|
|
61871
|
+
const assetId = input.perpDexIndex === DEFAULT_DEX_INDEX ? input.indexInMeta : HYPERLIQUID_EXCHANGE_SPECIFICATION.hip3_asset_id_base + input.perpDexIndex * HYPERLIQUID_EXCHANGE_SPECIFICATION.hip3_asset_id_dex_stride + input.indexInMeta;
|
|
61872
|
+
return {
|
|
61873
|
+
symbol: symbol2,
|
|
61874
|
+
dex,
|
|
61875
|
+
coin: symbol2,
|
|
61876
|
+
base_symbol: baseSymbol,
|
|
61877
|
+
quote_symbol: "USDC",
|
|
61878
|
+
display_symbol: `${baseSymbol}-USDC`,
|
|
61879
|
+
asset_id: assetId,
|
|
61880
|
+
asset_index: assetId,
|
|
61881
|
+
index_in_meta: input.indexInMeta,
|
|
61882
|
+
perp_dex_index: input.perpDexIndex,
|
|
61883
|
+
max_leverage: Math.max(1, leverage),
|
|
61884
|
+
sz_decimals: szDecimals,
|
|
61885
|
+
market_type: "perp",
|
|
61886
|
+
margin_mode: marginMode,
|
|
61887
|
+
only_isolated: input.asset.onlyIsolated === true || ISOLATED_ONLY_MARGIN_MODES.has(String(marginMode ?? "").toLowerCase())
|
|
61888
|
+
};
|
|
61889
|
+
};
|
|
61890
|
+
listedMarketRows = (requested, metas, dexIndexes, caseSensitiveSymbols, options) => {
|
|
61891
|
+
if (Array.isArray(caseSensitiveSymbols)) configureHyperliquidMarketSymbolCasing(caseSensitiveSymbols);
|
|
61892
|
+
const wanted = new Set(requested.map((symbol2) => normalizeHyperliquidMarketSymbol(symbol2)).filter(Boolean));
|
|
61893
|
+
const listed = {};
|
|
61894
|
+
for (const [dex, response] of Object.entries(metas)) {
|
|
61895
|
+
const universe = response && typeof response === "object" ? response.universe : null;
|
|
61896
|
+
if (!Array.isArray(universe) || universe.length === 0 || universe.some((asset) => !asset || typeof asset !== "object" || !String(asset.name ?? "").trim())) {
|
|
61897
|
+
throw malformed(`Hyperliquid returned malformed market metadata for ${dex || "the default DEX"}.`);
|
|
61898
|
+
}
|
|
61899
|
+
const perpDexIndex = dex === DEFAULT_DEX ? DEFAULT_DEX_INDEX : dexIndexes.get(dex);
|
|
61900
|
+
if (perpDexIndex === void 0) throw malformed(`Hyperliquid does not list the perp DEX ${dex}.`);
|
|
61901
|
+
universe.forEach((asset, indexInMeta) => {
|
|
61902
|
+
const symbol2 = normalizeHyperliquidMarketSymbol(asset.name);
|
|
61903
|
+
const delisted = asset.isDelisted === true;
|
|
61904
|
+
if (wanted.has(symbol2) && (options.includeDelisted || !delisted)) {
|
|
61905
|
+
listed[symbol2] = marketIdentityRow({ dex, perpDexIndex, indexInMeta, asset });
|
|
61906
|
+
}
|
|
61907
|
+
});
|
|
61908
|
+
}
|
|
61909
|
+
return listed;
|
|
61910
|
+
};
|
|
61911
|
+
}
|
|
61912
|
+
});
|
|
61913
|
+
|
|
61137
61914
|
// lib/runtime/exchange-mutation-fence.ts
|
|
61138
61915
|
var activeSettlementsByScope, normalizeScope, trackBrowserExchangeMutation, waitForBrowserExchangeMutationSettlement;
|
|
61139
61916
|
var init_exchange_mutation_fence = __esm({
|
|
@@ -61278,290 +62055,6 @@ var init_status_contract = __esm({
|
|
|
61278
62055
|
}
|
|
61279
62056
|
});
|
|
61280
62057
|
|
|
61281
|
-
// lib/runtime/runtime-error-reason-rules.json
|
|
61282
|
-
var runtime_error_reason_rules_default;
|
|
61283
|
-
var init_runtime_error_reason_rules = __esm({
|
|
61284
|
-
"lib/runtime/runtime-error-reason-rules.json"() {
|
|
61285
|
-
runtime_error_reason_rules_default = {
|
|
61286
|
-
about: "The one owner of runtime error reason codes, loaded by the web runtime (runtime-error-reason-rules.ts) and the API (runtime_error_reason_rules.py). Rules are tried in order on the normalized message without its warning prefix or its AI panel history wrapper (Analysis unavailable:), lowercased, so a stored row and the bare message get the same code; the first match names the code. A condition is equals, starts_with, contains, all, any, or a named predicate each runtime implements. reason_codes classifies every code: transient codes clear on their own; WARN codes record a skipped cycle, not a failure. A code not listed is ERROR and needs the owner's attention.",
|
|
61287
|
-
unclassified_messages: [
|
|
61288
|
-
"unknown runtime error.",
|
|
61289
|
-
"vtx did not receive error details for this runtime failure."
|
|
61290
|
-
],
|
|
61291
|
-
rules: [
|
|
61292
|
-
{ reason_code: "ai_service_rate_limit", when: { predicate: "provider_attempt_summary_http_429" } },
|
|
61293
|
-
{ reason_code: "ai_service_unavailable", when: { predicate: "provider_attempt_summary_unavailable" } },
|
|
61294
|
-
{ reason_code: "hyperliquid_request_capacity", when: { starts_with: "vtx could not obtain hyperliquid request capacity" } },
|
|
61295
|
-
{ reason_code: "http_request_capacity", when: { starts_with: "vtx could not obtain http request capacity" } },
|
|
61296
|
-
{ reason_code: "live_market_stats_unavailable", when: { equals: "live market stats unavailable for client runtime contract" } },
|
|
61297
|
-
{ reason_code: "live_performance_unavailable", when: { equals: "live performance context unavailable for client runtime contract" } },
|
|
61298
|
-
{ reason_code: "live_market_regime_unavailable", when: { equals: "live market regime context unavailable for client runtime contract" } },
|
|
61299
|
-
{ reason_code: "live_calendar_unavailable", when: { equals: "live calendar context unavailable for client runtime contract" } },
|
|
61300
|
-
{ reason_code: "live_derived_context_timeout", when: { equals: "timed out while building live derived context for client runtime contract" } },
|
|
61301
|
-
{ reason_code: "live_derived_context_build_failed", when: { equals: "failed to build live derived context for client runtime contract" } },
|
|
61302
|
-
{ reason_code: "internal_data_error", when: { any: [
|
|
61303
|
-
{ equals: "internal data error. please try again." },
|
|
61304
|
-
{ equals: "vtx could not read the required app data. please try again." }
|
|
61305
|
-
] } },
|
|
61306
|
-
{ reason_code: "private_node_stale", when: { all: [
|
|
61307
|
-
{ contains: "order was not sent" },
|
|
61308
|
-
{ any: [
|
|
61309
|
-
{ contains: "too stale to validate the signing key" },
|
|
61310
|
-
{ contains: "required hyperliquid account data was stale" }
|
|
61311
|
-
] }
|
|
61312
|
-
] } },
|
|
61313
|
-
{ reason_code: "signer_validation_unavailable", when: { all: [
|
|
61314
|
-
{ contains: "order was not sent" },
|
|
61315
|
-
{ any: [
|
|
61316
|
-
{ contains: "private account service could not validate the signing key" },
|
|
61317
|
-
{ contains: "required hyperliquid account data was temporarily unavailable" }
|
|
61318
|
-
] }
|
|
61319
|
-
] } },
|
|
61320
|
-
{ reason_code: "wallet_not_authorized", when: { all: [
|
|
61321
|
-
{ contains: "order was not sent" },
|
|
61322
|
-
{ any: [
|
|
61323
|
-
{ contains: "signing key is not authorized for the configured wallet" },
|
|
61324
|
-
{ contains: "hyperliquid confirmed that the signing key is not authorized" },
|
|
61325
|
-
{ contains: "hyperliquid has not approved this key for this profile's wallet" }
|
|
61326
|
-
] }
|
|
61327
|
-
] } },
|
|
61328
|
-
{ reason_code: "credentials_missing", when: { all: [
|
|
61329
|
-
{ contains: "order was not sent" },
|
|
61330
|
-
{ contains: "authorized signing key are required for trading" }
|
|
61331
|
-
] } },
|
|
61332
|
-
{ reason_code: "local_safety_block", when: { contains: "order was not sent before exchange dispatch" } },
|
|
61333
|
-
{ reason_code: "redis_unavailable", when: { contains: "order was not sent because execution coordination was unavailable" } },
|
|
61334
|
-
{ reason_code: "exchange_rejected", when: { all: [
|
|
61335
|
-
{ starts_with: "hyperliquid rejected the " },
|
|
61336
|
-
{ contains: " order:" }
|
|
61337
|
-
] } },
|
|
61338
|
-
{ reason_code: "outcome_unknown", when: { all: [
|
|
61339
|
-
{ contains: "vtx could not confirm whether the " },
|
|
61340
|
-
{ contains: " order was applied" }
|
|
61341
|
-
] } },
|
|
61342
|
-
{ reason_code: "internal_execution_error", when: { all: [
|
|
61343
|
-
{ starts_with: "vtx could not complete the " },
|
|
61344
|
-
{ contains: " order:" }
|
|
61345
|
-
] } },
|
|
61346
|
-
{ reason_code: "hyperliquid_rate_limit", when: { any: [
|
|
61347
|
-
{ contains: "hyperliquid returned 429" },
|
|
61348
|
-
{ contains: "hyperliquid returned http 429" },
|
|
61349
|
-
{ contains: "public reads are waiting for a rate-limit cooldown" },
|
|
61350
|
-
{ contains: "public reads are waiting after a hyperliquid rate limit" },
|
|
61351
|
-
{ contains: "recovery queue before its deadline" },
|
|
61352
|
-
{ contains: "hyperliquid info endpoint returned 429" },
|
|
61353
|
-
{ contains: "hyperliquid rate limit (429)" },
|
|
61354
|
-
{ contains: "hyperliquid public api returned http 429" },
|
|
61355
|
-
{ contains: "hyperliquid public info cooldown is active" },
|
|
61356
|
-
{ contains: "hyperliquid public request cooldown is active" },
|
|
61357
|
-
{ contains: "hyperliquid public recovery is waiting after an observed http 429" },
|
|
61358
|
-
{ contains: "hyperliquid provider recovery could not dispatch before the request deadline" }
|
|
61359
|
-
] } },
|
|
61360
|
-
{ reason_code: "hyperliquid_read_budget_exhausted", when: { any: [
|
|
61361
|
-
{ all: [
|
|
61362
|
-
{ contains: "fresh hyperliquid data" },
|
|
61363
|
-
{ contains: "current read budget" }
|
|
61364
|
-
] },
|
|
61365
|
-
{ contains: "server's public-read budget is full" },
|
|
61366
|
-
{ contains: "app's shared public-read budget is also full" },
|
|
61367
|
-
{ all: [
|
|
61368
|
-
{ contains: "hyperliquid" },
|
|
61369
|
-
{ contains: "budget exhausted" }
|
|
61370
|
-
] },
|
|
61371
|
-
{ contains: "hyperliquid execution preflight is waiting for its fair public-read turn" },
|
|
61372
|
-
{ contains: "hyperliquid local public request allowance is exhausted" }
|
|
61373
|
-
] } },
|
|
61374
|
-
{ reason_code: "hyperliquid_data_unavailable", when: { any: [
|
|
61375
|
-
{ contains: "fresh private hyperliquid data is unavailable" },
|
|
61376
|
-
{ contains: "private hyperliquid node is stale" },
|
|
61377
|
-
{ contains: "private hyperliquid info circuit is open" },
|
|
61378
|
-
{ contains: "private hyperliquid freshness probe failed" },
|
|
61379
|
-
{ contains: "hyperliquid info endpoint is stale for" },
|
|
61380
|
-
{ contains: "hyperliquid fresh public read returned non-json" },
|
|
61381
|
-
{ contains: "hyperliquid public freshness bracket moved backwards" }
|
|
61382
|
-
] } },
|
|
61383
|
-
{ reason_code: "behavior_state_unavailable", when: { any: [
|
|
61384
|
-
{ all: [
|
|
61385
|
-
{ contains: "your prompt on the ai page contains something vtx can't use" },
|
|
61386
|
-
{ contains: "next scheduled cycle" }
|
|
61387
|
-
] },
|
|
61388
|
-
{ all: [
|
|
61389
|
-
{ contains: "critical behavior context could not be constructed" },
|
|
61390
|
-
{ contains: "next scheduled cycle" }
|
|
61391
|
-
] }
|
|
61392
|
-
] } },
|
|
61393
|
-
{ reason_code: "hyperliquid_wallet_not_authorized", when: { any: [
|
|
61394
|
-
{ contains: "hyperliquid api wallet is not authorized" },
|
|
61395
|
-
{ contains: "hyperliquid signing key is not authorized for this wallet" },
|
|
61396
|
-
{ contains: "hyperliquid has not approved this key for this profile's wallet" }
|
|
61397
|
-
] } },
|
|
61398
|
-
{ reason_code: "ai_service_rate_limit", when: { any: [
|
|
61399
|
-
{ all: [
|
|
61400
|
-
{ contains: "exhausted fallback chain" },
|
|
61401
|
-
{ contains: "(429)" }
|
|
61402
|
-
] },
|
|
61403
|
-
{ contains: "ai provider returned 429" },
|
|
61404
|
-
{ contains: "ai provider and fallback model returned 429" },
|
|
61405
|
-
{ contains: "ai service rate limit (429)" },
|
|
61406
|
-
{ contains: "external ai account has reached its current usage limit" }
|
|
61407
|
-
] } },
|
|
61408
|
-
{ reason_code: "ai_service_unavailable", when: { any: [
|
|
61409
|
-
{ contains: "ai provider returned 503" },
|
|
61410
|
-
{ contains: "ai provider returned 500" },
|
|
61411
|
-
{ contains: "ai provider returned 502" },
|
|
61412
|
-
{ contains: "ai provider returned 504" },
|
|
61413
|
-
{ contains: "ai provider and fallback model returned 503" },
|
|
61414
|
-
{ contains: "service unavailable" },
|
|
61415
|
-
{ contains: "ai service unavailable (503)" },
|
|
61416
|
-
{ contains: "ai provider is temporarily unavailable" },
|
|
61417
|
-
{ contains: "codex reported server overload" },
|
|
61418
|
-
{ contains: "external inference host heartbeat is stale" },
|
|
61419
|
-
{ contains: "external inference host is finishing or recovering outstanding work" },
|
|
61420
|
-
{ contains: "external ai membership is currently available. at least one is cooling down" },
|
|
61421
|
-
{ contains: "external inference current advertisement is stale" },
|
|
61422
|
-
{ predicate: "provider_retry_status" }
|
|
61423
|
-
] } },
|
|
61424
|
-
{ reason_code: "app_bootstrap_unavailable", when: { any: [
|
|
61425
|
-
{ contains: "vtx could not load this profile's runtime settings" },
|
|
61426
|
-
{ contains: "vtx runtime settings temporarily unavailable due to server load" }
|
|
61427
|
-
] } },
|
|
61428
|
-
{ reason_code: "runtime_config_missing", when: { contains: "vtx is missing required runtime configuration" } },
|
|
61429
|
-
{ reason_code: "provider_not_configured", when: { any: [
|
|
61430
|
-
{ contains: "client runtime provider setup error" },
|
|
61431
|
-
{ contains: "is not configured for this profile" },
|
|
61432
|
-
{ contains: "is not account-synced for this profile" }
|
|
61433
|
-
] } },
|
|
61434
|
-
{ reason_code: "provider_unavailable", when: { contains: "client runtime provider error" } },
|
|
61435
|
-
{ reason_code: "browser_cors_failure", when: { any: [
|
|
61436
|
-
{ contains: "the browser blocked the ai provider request" },
|
|
61437
|
-
{ contains: "request was blocked" },
|
|
61438
|
-
{ contains: "failed in browser (network/cors)" }
|
|
61439
|
-
] } },
|
|
61440
|
-
{ reason_code: "market_data_browser_failure", when: { any: [
|
|
61441
|
-
{ contains: "market data did not load" },
|
|
61442
|
-
{ contains: "market data request failed in browser" }
|
|
61443
|
-
] } },
|
|
61444
|
-
{ reason_code: "browser_network_failure", when: { any: [
|
|
61445
|
-
{ contains: "browser could not complete a vtx runtime request" },
|
|
61446
|
-
{ contains: "hyperliquid public request network failure" },
|
|
61447
|
-
{ contains: "a browser network request failed" },
|
|
61448
|
-
{ contains: "browser could not reach the ai provider" },
|
|
61449
|
-
{ contains: "failed in browser (network request failed)" }
|
|
61450
|
-
] } },
|
|
61451
|
-
{ reason_code: "provider_network_failure", when: { contains: "vtx could not reach the ai provider" } },
|
|
61452
|
-
{ reason_code: "runtime_timeout", when: { any: [
|
|
61453
|
-
{ contains: "ai run took too long" },
|
|
61454
|
-
{ contains: "cycle deadline was reached" },
|
|
61455
|
-
{ contains: "this analysis timed out" },
|
|
61456
|
-
{ contains: "hyperliquid request exceeded its total read deadline" }
|
|
61457
|
-
] } },
|
|
61458
|
-
{ reason_code: "snapshot_stale", when: { contains: "decision skipped: account data was" } },
|
|
61459
|
-
{ reason_code: "ai_service_rate_limit", when: { contains: "provider request failed (http 429)" } },
|
|
61460
|
-
{ reason_code: "external_inference_window_missed", when: { any: [
|
|
61461
|
-
{ contains: "external inference host claimed the server prompt but did not dispatch it" },
|
|
61462
|
-
{ contains: "external inference host did not claim the server prompt inside its account-state freshness window" }
|
|
61463
|
-
] } },
|
|
61464
|
-
{ reason_code: "runtime_timeout", when: { contains: "failure code: runtime_timeout" } },
|
|
61465
|
-
{ reason_code: "account_state_changing", when: { contains: "account state is changing while preparing prompt context" } },
|
|
61466
|
-
{ reason_code: "runtime_contract_changed", when: { any: [
|
|
61467
|
-
{ contains: "rejected by contract: contract_identity_mismatch" },
|
|
61468
|
-
{ contains: "rejected by contract: contract_binding_mismatch" }
|
|
61469
|
-
] } },
|
|
61470
|
-
{ reason_code: "decision_persistence_timeout", when: { contains: "could not confirm that its decision was saved before the cycle deadline" } },
|
|
61471
|
-
{ reason_code: "model_unavailable", when: { any: [
|
|
61472
|
-
{ contains: "this model is not available from the selected provider" },
|
|
61473
|
-
{ contains: "model is not available on the selected provider" },
|
|
61474
|
-
{ contains: "client runtime model error" },
|
|
61475
|
-
{ contains: " is not available on " },
|
|
61476
|
-
{ starts_with: "unknown model" }
|
|
61477
|
-
] } }
|
|
61478
|
-
],
|
|
61479
|
-
reason_codes: {
|
|
61480
|
-
account_state_changing: { transient: true, severity: "ERROR" },
|
|
61481
|
-
ai_service_rate_limit: { transient: true, severity: "ERROR" },
|
|
61482
|
-
ai_service_unavailable: { transient: true, severity: "ERROR" },
|
|
61483
|
-
app_bootstrap_unavailable: { transient: true, severity: "ERROR" },
|
|
61484
|
-
behavior_state_unavailable: { transient: true, severity: "WARN" },
|
|
61485
|
-
browser_cors_failure: { transient: true, severity: "ERROR" },
|
|
61486
|
-
browser_network_failure: { transient: true, severity: "ERROR" },
|
|
61487
|
-
credentials_missing: { transient: false, severity: "ERROR" },
|
|
61488
|
-
decision_persistence_timeout: { transient: true, severity: "ERROR" },
|
|
61489
|
-
exchange_rejected: { transient: false, severity: "ERROR" },
|
|
61490
|
-
external_inference_window_missed: { transient: true, severity: "ERROR" },
|
|
61491
|
-
http_request_capacity: { transient: true, severity: "ERROR" },
|
|
61492
|
-
hyperliquid_data_unavailable: { transient: true, severity: "ERROR" },
|
|
61493
|
-
hyperliquid_rate_limit: { transient: true, severity: "ERROR" },
|
|
61494
|
-
hyperliquid_read_budget_exhausted: { transient: true, severity: "WARN" },
|
|
61495
|
-
hyperliquid_request_capacity: { transient: true, severity: "ERROR" },
|
|
61496
|
-
hyperliquid_wallet_not_authorized: { transient: false, severity: "ERROR" },
|
|
61497
|
-
internal_data_error: { transient: false, severity: "ERROR" },
|
|
61498
|
-
internal_execution_error: { transient: false, severity: "ERROR" },
|
|
61499
|
-
live_calendar_unavailable: { transient: true, severity: "ERROR" },
|
|
61500
|
-
live_derived_context_build_failed: { transient: true, severity: "ERROR" },
|
|
61501
|
-
live_derived_context_timeout: { transient: true, severity: "ERROR" },
|
|
61502
|
-
live_market_regime_unavailable: { transient: true, severity: "ERROR" },
|
|
61503
|
-
live_market_stats_unavailable: { transient: true, severity: "ERROR" },
|
|
61504
|
-
live_performance_unavailable: { transient: true, severity: "ERROR" },
|
|
61505
|
-
local_safety_block: { transient: false, severity: "ERROR" },
|
|
61506
|
-
market_data_browser_failure: { transient: true, severity: "ERROR" },
|
|
61507
|
-
model_unavailable: { transient: false, severity: "ERROR" },
|
|
61508
|
-
outcome_unknown: { transient: true, severity: "ERROR" },
|
|
61509
|
-
private_node_stale: { transient: true, severity: "ERROR" },
|
|
61510
|
-
protective_order_not_placed: { transient: false, severity: "WARN" },
|
|
61511
|
-
protective_order_unmanaged: { transient: false, severity: "WARN" },
|
|
61512
|
-
provider_network_failure: { transient: true, severity: "ERROR" },
|
|
61513
|
-
provider_not_configured: { transient: false, severity: "ERROR" },
|
|
61514
|
-
provider_unavailable: { transient: true, severity: "ERROR" },
|
|
61515
|
-
redis_unavailable: { transient: true, severity: "ERROR" },
|
|
61516
|
-
runtime_config_missing: { transient: false, severity: "ERROR" },
|
|
61517
|
-
runtime_contract_changed: { transient: true, severity: "ERROR" },
|
|
61518
|
-
runtime_timeout: { transient: true, severity: "ERROR" },
|
|
61519
|
-
signer_validation_unavailable: { transient: false, severity: "ERROR" },
|
|
61520
|
-
snapshot_stale: { transient: true, severity: "ERROR" },
|
|
61521
|
-
wallet_not_authorized: { transient: false, severity: "ERROR" }
|
|
61522
|
-
}
|
|
61523
|
-
};
|
|
61524
|
-
}
|
|
61525
|
-
});
|
|
61526
|
-
|
|
61527
|
-
// lib/runtime/runtime-error-reason-rules.ts
|
|
61528
|
-
var HISTORY_WRAPPER, runtimeErrorReasonSubject, RULES, matches, matchRuntimeErrorReasonCode;
|
|
61529
|
-
var init_runtime_error_reason_rules2 = __esm({
|
|
61530
|
-
"lib/runtime/runtime-error-reason-rules.ts"() {
|
|
61531
|
-
"use strict";
|
|
61532
|
-
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
61533
|
-
init_define_VTX_EXO_POLICY();
|
|
61534
|
-
init_define_VTX_GROK_POLICY();
|
|
61535
|
-
init_define_VTX_PI_MODEL_POLICY();
|
|
61536
|
-
init_runtime_error_reason_rules();
|
|
61537
|
-
HISTORY_WRAPPER = /^analysis unavailable:\s*(?:\u26a0\ufe0f?\s*)?/iu;
|
|
61538
|
-
runtimeErrorReasonSubject = (normalizedWithoutWarning) => normalizedWithoutWarning.replace(HISTORY_WRAPPER, "").trim();
|
|
61539
|
-
RULES = runtime_error_reason_rules_default;
|
|
61540
|
-
matches = (condition, lowered, texts, predicates) => {
|
|
61541
|
-
if ("equals" in condition) return lowered === condition.equals;
|
|
61542
|
-
if ("starts_with" in condition) return lowered.startsWith(condition.starts_with);
|
|
61543
|
-
if ("contains" in condition) return lowered.includes(condition.contains);
|
|
61544
|
-
if ("all" in condition) return condition.all.every((item) => matches(item, lowered, texts, predicates));
|
|
61545
|
-
if ("any" in condition) return condition.any.some((item) => matches(item, lowered, texts, predicates));
|
|
61546
|
-
return predicates[condition.predicate](...texts);
|
|
61547
|
-
};
|
|
61548
|
-
matchRuntimeErrorReasonCode = (normalized, normalizedWithoutWarning, predicates) => {
|
|
61549
|
-
const subject = runtimeErrorReasonSubject(normalizedWithoutWarning);
|
|
61550
|
-
const lowered = subject.toLowerCase();
|
|
61551
|
-
if (!normalized || RULES.unclassified_messages.includes(lowered)) {
|
|
61552
|
-
return null;
|
|
61553
|
-
}
|
|
61554
|
-
const texts = [normalized, subject];
|
|
61555
|
-
for (const rule of RULES.rules) {
|
|
61556
|
-
if (matches(rule.when, lowered, texts, predicates)) {
|
|
61557
|
-
return rule.reason_code;
|
|
61558
|
-
}
|
|
61559
|
-
}
|
|
61560
|
-
return null;
|
|
61561
|
-
};
|
|
61562
|
-
}
|
|
61563
|
-
});
|
|
61564
|
-
|
|
61565
62058
|
// lib/runtime/signing-key-messages.ts
|
|
61566
62059
|
var SIGNING_KEY_NOT_APPROVED, SIGNING_KEY_INVALID, SIGNING_KEY_THEN_START, SIGNING_KEY_NOT_APPROVED_THEN_START;
|
|
61567
62060
|
var init_signing_key_messages = __esm({
|
|
@@ -61579,7 +62072,7 @@ var init_signing_key_messages = __esm({
|
|
|
61579
62072
|
});
|
|
61580
62073
|
|
|
61581
62074
|
// lib/runtime/error-surface-contract.ts
|
|
61582
|
-
var RUNTIME_SERVICE_UNAVAILABLE_TOKENS, RUNTIME_APP_BOOTSTRAP_UNAVAILABLE_TOKENS, RUNTIME_BROWSER_FETCH_FAILURE_TOKENS, SENSITIVE_DB_TOKENS, SCHEMA_DISCLOSURE_TOKENS, SQL_STATEMENT_PATTERN, TRACEBACK_PATTERN, DB_SESSION_STATE_PATTERNS, RUNTIME_MARKET_DATA_FAILURE_TOKENS, RUNTIME_CYCLE_DEADLINE_TOKENS, RUNTIME_TIMEOUT_TOKENS, RUNTIME_GENERIC_TIMEOUT_MESSAGE, LEGACY_RUNTIME_TIMEOUT_PATTERN, RUNTIME_PROVIDER_NETWORK_FAILURE_TOKENS, RUNTIME_EXPLICIT_CORS_TOKENS, RUNTIME_MODEL_UNAVAILABLE_TOKENS, RUNTIME_REASONING_CONTROL_REJECTION_TOKENS, RUNTIME_CANONICAL_PREFIX_TOKENS, RUNTIME_PROVIDER_RETRY_STATUS_PATTERN, RUNTIME_SERVICE_UNAVAILABLE_STATUSES, RUNTIME_MISSING_CONFIG_PATTERN, DEFAULT_RUNTIME_RETRY_SECONDS, normalizeRuntimeRetrySeconds, hasRuntimeRetrySeconds, runtimeRetryPhrase, applyRuntimeRetrySeconds, RUNTIME_PROVIDER_FAILURE_PATTERN, RUNTIME_HYPERLIQUID_RATE_LIMIT_PATTERN, RUNTIME_HYPERLIQUID_INFO_429_PATTERN, RUNTIME_HYPERLIQUID_REQUEST_TYPE_PATTERN, RUNTIME_HYPERLIQUID_WALLET_NOT_AUTHORIZED_PATTERN, runtimePausePrefix, ensureRuntimeWarningPrefix, stripRuntimeWarningPrefix, isRuntimeAppBootstrapUnavailableError, isSensitiveRuntimeErrorDetail, extractRuntimeProviderError, extractHttpStatusCode, formatHyperliquidRateLimitMessage, providerStatusLabel, PROVIDER_ATTEMPT_SUMMARY_ITEM, PROVIDER_ATTEMPT_SUMMARY_PATTERN, PROVIDER_ATTEMPT_STATUS_PATTERN, isCanonicalProviderAttemptSummary, providerAttemptSummaryStatuses, normalizeRuntimeErrorMessage, RUNTIME_ERROR_REASON_PREDICATES, deriveRuntimeErrorReasonCode, EXECUTION_DISPATCH_RISK_RANK, selectPrimaryExecutionFailure, EXECUTION_ERROR_DEFAULTS, isExecutionErrorReasonCode, RuntimeExecutionError, projectExecutionErrorContract, projectRuntimeErrorSurfaceContract;
|
|
62075
|
+
var RUNTIME_SERVICE_UNAVAILABLE_TOKENS, RUNTIME_APP_BOOTSTRAP_UNAVAILABLE_TOKENS, RUNTIME_BROWSER_FETCH_FAILURE_TOKENS, SENSITIVE_DB_TOKENS, SCHEMA_DISCLOSURE_TOKENS, SQL_STATEMENT_PATTERN, TRACEBACK_PATTERN, DB_SESSION_STATE_PATTERNS, RUNTIME_MARKET_DATA_FAILURE_TOKENS, RUNTIME_CYCLE_DEADLINE_TOKENS, RUNTIME_TIMEOUT_TOKENS, RUNTIME_GENERIC_TIMEOUT_MESSAGE, LEGACY_RUNTIME_TIMEOUT_PATTERN, RUNTIME_PROVIDER_NETWORK_FAILURE_TOKENS, RUNTIME_EXPLICIT_CORS_TOKENS, RUNTIME_MODEL_UNAVAILABLE_TOKENS, RUNTIME_REASONING_CONTROL_REJECTION_TOKENS, RUNTIME_CANONICAL_PREFIX_TOKENS, RUNTIME_PROVIDER_RETRY_STATUS_PATTERN, RUNTIME_SERVICE_UNAVAILABLE_STATUSES, RUNTIME_MISSING_CONFIG_PATTERN, DEFAULT_RUNTIME_RETRY_SECONDS, normalizeRuntimeRetrySeconds, hasRuntimeRetrySeconds, runtimeRetryPhrase, applyRuntimeRetrySeconds, RUNTIME_PROVIDER_FAILURE_PATTERN, RUNTIME_HYPERLIQUID_RATE_LIMIT_PATTERN, RUNTIME_HYPERLIQUID_INFO_429_PATTERN, RUNTIME_HYPERLIQUID_INFO_STATUS_PATTERN, formatHyperliquidReadFailureMessage, RUNTIME_HYPERLIQUID_REQUEST_TYPE_PATTERN, RUNTIME_HYPERLIQUID_WALLET_NOT_AUTHORIZED_PATTERN, runtimePausePrefix, ensureRuntimeWarningPrefix, stripRuntimeWarningPrefix, isRuntimeAppBootstrapUnavailableError, isSensitiveRuntimeErrorDetail, extractRuntimeProviderError, extractHttpStatusCode, formatHyperliquidRateLimitMessage, providerStatusLabel, PROVIDER_ATTEMPT_SUMMARY_ITEM, PROVIDER_ATTEMPT_SUMMARY_PATTERN, PROVIDER_ATTEMPT_STATUS_PATTERN, isCanonicalProviderAttemptSummary, providerAttemptSummaryStatuses, normalizeRuntimeErrorMessage, RUNTIME_ERROR_REASON_PREDICATES, deriveRuntimeErrorReasonCode, EXECUTION_DISPATCH_RISK_RANK, selectPrimaryExecutionFailure, EXECUTION_ERROR_DEFAULTS, isExecutionErrorReasonCode, RuntimeExecutionError, projectExecutionErrorContract, projectRuntimeErrorSurfaceContract;
|
|
61583
62076
|
var init_error_surface_contract = __esm({
|
|
61584
62077
|
"lib/runtime/error-surface-contract.ts"() {
|
|
61585
62078
|
"use strict";
|
|
@@ -61704,7 +62197,11 @@ var init_error_surface_contract = __esm({
|
|
|
61704
62197
|
RUNTIME_CANONICAL_PREFIX_TOKENS = [
|
|
61705
62198
|
"**ai trader paused**:",
|
|
61706
62199
|
"**ai assistant paused**:",
|
|
61707
|
-
"**rate limit**:"
|
|
62200
|
+
"**rate limit**:",
|
|
62201
|
+
// Already plain words (formatHyperliquidReadFailureMessage): a stored row read
|
|
62202
|
+
// back must not be reworded by the provider "503" or wallet rules.
|
|
62203
|
+
"hyperliquid didn't answer vtx's request",
|
|
62204
|
+
"hyperliquid refused vtx's request"
|
|
61708
62205
|
];
|
|
61709
62206
|
RUNTIME_PROVIDER_RETRY_STATUS_PATTERN = /^(ai provider temporarily unavailable(?:\s+\(http\s+(\d{3})(?:\s+[a-z_]+)?\))?|codex reported server overload);\s+retrying automatically(?:\s+in\s+(\d+)s)?$/i;
|
|
61710
62207
|
RUNTIME_SERVICE_UNAVAILABLE_STATUSES = /* @__PURE__ */ new Set([
|
|
@@ -61737,6 +62234,14 @@ var init_error_surface_contract = __esm({
|
|
|
61737
62234
|
RUNTIME_PROVIDER_FAILURE_PATTERN = /^provider request failed(?:\s*\(http\s*(\d{3})[^)]*\))?(?::\s*(.*))?$/i;
|
|
61738
62235
|
RUNTIME_HYPERLIQUID_RATE_LIMIT_PATTERN = /hyperliquid(?:\s+rate\s+limit\s*\(\s*429\s*\)|\s+info\s+request\s+failed\s*\(\s*429\s*\))/i;
|
|
61739
62236
|
RUNTIME_HYPERLIQUID_INFO_429_PATTERN = /hyperliquid\s+info\s+request\s+failed\s*\(\s*429\s*\)(.*)$/i;
|
|
62237
|
+
RUNTIME_HYPERLIQUID_INFO_STATUS_PATTERN = /hyperliquid\s+info\s+request\s+failed\s*\(\s*(\d{3})\s*\)\s*(?:request_type=[A-Za-z0-9_.:-]+\.?)?\s*(.*)$/i;
|
|
62238
|
+
formatHyperliquidReadFailureMessage = (status, detail) => {
|
|
62239
|
+
if (status >= HTTP_SERVER_ERROR_MIN) {
|
|
62240
|
+
return `Hyperliquid didn't answer VTX's request (HTTP ${status}). VTX tries again next cycle.`;
|
|
62241
|
+
}
|
|
62242
|
+
const reason = detail.trim().replace(/\.$/, "");
|
|
62243
|
+
return `Hyperliquid refused VTX's request (HTTP ${status})${reason ? `: ${reason}` : ""}. VTX tries again next cycle.`;
|
|
62244
|
+
};
|
|
61740
62245
|
RUNTIME_HYPERLIQUID_REQUEST_TYPE_PATTERN = /\brequest_type=([A-Za-z0-9_.:-]+)/i;
|
|
61741
62246
|
RUNTIME_HYPERLIQUID_WALLET_NOT_AUTHORIZED_PATTERN = /user\s+or\s+api\s+wallet\s+0x[a-f0-9]{40}\s+does\s+not\s+exist/i;
|
|
61742
62247
|
runtimePausePrefix = (isAssistantActive) => isAssistantActive ? "\u26A0\uFE0F **AI Assistant Paused**" : "\u26A0\uFE0F **AI Trader Paused**";
|
|
@@ -61893,6 +62398,13 @@ var init_error_surface_contract = __esm({
|
|
|
61893
62398
|
if (RUNTIME_HYPERLIQUID_RATE_LIMIT_PATTERN.test(message)) {
|
|
61894
62399
|
return formatHyperliquidRateLimitMessage({ message, pausePrefix, retrySeconds });
|
|
61895
62400
|
}
|
|
62401
|
+
const hyperliquidReadFailure = message.match(RUNTIME_HYPERLIQUID_INFO_STATUS_PATTERN);
|
|
62402
|
+
if (hyperliquidReadFailure) {
|
|
62403
|
+
return ensureRuntimeWarningPrefix(formatHyperliquidReadFailureMessage(
|
|
62404
|
+
Number(hyperliquidReadFailure[1]),
|
|
62405
|
+
hyperliquidReadFailure[2] ?? ""
|
|
62406
|
+
));
|
|
62407
|
+
}
|
|
61896
62408
|
if (RUNTIME_HYPERLIQUID_WALLET_NOT_AUTHORIZED_PATTERN.test(message)) {
|
|
61897
62409
|
return `${pausePrefix}: ${SIGNING_KEY_NOT_APPROVED_THEN_START}`;
|
|
61898
62410
|
}
|
|
@@ -62087,7 +62599,8 @@ var init_error_surface_contract = __esm({
|
|
|
62087
62599
|
isActive = true,
|
|
62088
62600
|
isAssistantActive = false,
|
|
62089
62601
|
retrySeconds = null,
|
|
62090
|
-
errorOrigin = null
|
|
62602
|
+
errorOrigin = null,
|
|
62603
|
+
reasonCode = null
|
|
62091
62604
|
}) => {
|
|
62092
62605
|
const errorMessage = normalizeRuntimeErrorMessage({
|
|
62093
62606
|
error: error48,
|
|
@@ -62095,7 +62608,7 @@ var init_error_surface_contract = __esm({
|
|
|
62095
62608
|
retrySeconds,
|
|
62096
62609
|
errorOrigin
|
|
62097
62610
|
});
|
|
62098
|
-
const errorReasonCode = deriveRuntimeErrorReasonCode({
|
|
62611
|
+
const errorReasonCode = reasonCode ?? deriveRuntimeErrorReasonCode({
|
|
62099
62612
|
error: errorMessage,
|
|
62100
62613
|
isAssistantActive
|
|
62101
62614
|
});
|
|
@@ -72421,20 +72934,20 @@ function check_whole(group, unique) {
|
|
|
72421
72934
|
}
|
|
72422
72935
|
}
|
|
72423
72936
|
function determine_group(unique) {
|
|
72424
|
-
let
|
|
72937
|
+
let groups2 = GROUPS;
|
|
72425
72938
|
for (let cp of unique) {
|
|
72426
|
-
let gs =
|
|
72939
|
+
let gs = groups2.filter((g) => group_has_cp(g, cp));
|
|
72427
72940
|
if (!gs.length) {
|
|
72428
72941
|
if (!GROUPS.some((g) => group_has_cp(g, cp))) {
|
|
72429
72942
|
throw error_disallowed(cp);
|
|
72430
72943
|
} else {
|
|
72431
|
-
throw error_group_member(
|
|
72944
|
+
throw error_group_member(groups2[0], cp);
|
|
72432
72945
|
}
|
|
72433
72946
|
}
|
|
72434
|
-
|
|
72947
|
+
groups2 = gs;
|
|
72435
72948
|
if (gs.length == 1) break;
|
|
72436
72949
|
}
|
|
72437
|
-
return
|
|
72950
|
+
return groups2;
|
|
72438
72951
|
}
|
|
72439
72952
|
function flatten(split3) {
|
|
72440
72953
|
return split3.map(({ input, error: error48, output: output3 }) => {
|
|
@@ -92725,7 +93238,7 @@ var init_hyperliquid_signer = __esm({
|
|
|
92725
93238
|
});
|
|
92726
93239
|
|
|
92727
93240
|
// lib/runtime/hyperliquid-client.ts
|
|
92728
|
-
var HyperliquidExchangeRejectionError, durableMutationAuthorityArgs, assertFreshPreparedExecutionContext, normalizeSymbol, HYPERLIQUID_NONCE_STORAGE_KEY, HYPERLIQUID_NONCE_LOCK_NAME, lastGeneratedNonce, readBrowserStoredHyperliquidNonce, writeBrowserStoredHyperliquidNonce, browserNonceCoordinator, allocateHyperliquidNonce, hostNonceAllocator, allocateActionNonce, generateHyperliquidNonce, normalizeDecimalString, HYPERLIQUID_PRICE_SIGNIFICANT_FIGURES, HYPERLIQUID_INTEGER_PRICE_MINIMUM, shortestDecimalParts, formatHyperliquidPerpPriceGrid, formatHyperliquidTriggerPriceWire, hyperliquidOrderPriceRounding, formatHyperliquidOrderPriceWire, countSignificantDigits, countDecimalPlaces, validateHyperliquidPerpPriceWire, validateHyperliquidSizeWire, formatSizeWire, inferApiUrl, inferIsTestnet, postHyperliquidInfoRead, postHyperliquidInfo, fetchBrowserHyperliquidInfoPayload, fetchBrowserHyperliquidInfoRead, fetchBrowserHyperliquidInfoText, coerceMarketMaxLeverage, toFiniteNumber, OPEN_ORDER_NUMERIC_STRING, OPEN_ORDER_ID_STRING, parseCanonicalOpenOrderId, parseOpenOrderFiniteNumber, parseOpenOrderNonNegativeNumber, NATIVE_FIRED_TRIGGER_CONDITION, parseOpenOrderPositiveNumber, parseOpenOrderPresentationNumber, readOpenOrderField, firstFiniteNumber, parseFundingUsdcFromInfoPosition, isExchangeIsolatedOnly, resolveLeverageTarget, computeHip3AssetId, getPerpDexIndexMap, buildAssetInfosFromMetaResponse, requireWalletAddress, assertPositiveInteger, assertPositiveNumber, normalizeOrderSide, normalizeHyperliquidClientOrderId, resolveAssets, findResolvedAsset, normalizeExecutionAssetMetadata, resolveHyperliquidAsset, resolveHyperliquidAssetIndex, decimalUnits, quantizeHyperliquidOrderSizeValue, hyperliquidSignedSizeMatchesRequestedSize, finitePositive, readDevicePrivateExecutionContext, quantizeHyperliquidOrderSize, fetchBrowserAvailableAssets, fetchBrowserAllMids, fetchBrowserSymbolMidPrice, fetchBrowserOpenOrders, parseCanonicalHyperliquidOrderStatusEvidence, fetchBrowserOrderStatusEvidence, fetchBrowserUserRole, fetchBrowserAccountState, fetchBrowserPosition, buildHyperliquidOrderWire, buildHyperliquidTriggerOrderWire, signHyperliquidPayload, signHyperliquidPreparedAction, buildHyperliquidCancelPayload, buildHyperliquidUpdateLeveragePayload, buildHyperliquidMarketOrderPayload, buildHyperliquidLimitOrderPayload, buildHyperliquidTriggerOrderPayload, buildHyperliquidOrderBatchPayload, buildHyperliquidModifyOrderPayload, TRAILING_PCT_PATTERN, buildHyperliquidTrailingStopPayload, extractHyperliquidExchangeError, acknowledgementLookupPacing, lookupUntilListed, resolveHyperliquidTriggerAcknowledgements, readHyperliquidTrailingStopAcknowledgement, resolveHyperliquidModifyAcknowledgement, isDefinitiveHyperliquidExchangeResponse, extractDefinitiveHyperliquidOrderId, CANONICAL_POSITIVE_DECIMAL_PATTERN, extractCanonicalHyperliquidOrderStateAcknowledgement, extractCanonicalHyperliquidOrderStateAcknowledgements, extractCanonicalHyperliquidFilledOrderAcknowledgement, extractDefinitiveHyperliquidOrderMemberResults, buildHyperliquidOrderDiagnostics, loadClientExecutionReferenceEvidence, sha256Hex, extractSignedPayloadClientOrderId, extractSignedPayloadMutationCorrelation, assertDurableMutationMatchesSignedAction, exchangeRejectionReason, exchangeActionPriority, submitHyperliquidExchangePayload;
|
|
93241
|
+
var HyperliquidExchangeRejectionError, durableMutationAuthorityArgs, assertFreshPreparedExecutionContext, normalizeSymbol, normalizeBotMarket, HYPERLIQUID_NONCE_STORAGE_KEY, HYPERLIQUID_NONCE_LOCK_NAME, lastGeneratedNonce, readBrowserStoredHyperliquidNonce, writeBrowserStoredHyperliquidNonce, browserNonceCoordinator, allocateHyperliquidNonce, hostNonceAllocator, allocateActionNonce, generateHyperliquidNonce, normalizeDecimalString, HYPERLIQUID_PRICE_SIGNIFICANT_FIGURES, HYPERLIQUID_INTEGER_PRICE_MINIMUM, shortestDecimalParts, formatHyperliquidPerpPriceGrid, formatHyperliquidTriggerPriceWire, hyperliquidOrderPriceRounding, formatHyperliquidOrderPriceWire, countSignificantDigits, countDecimalPlaces, validateHyperliquidPerpPriceWire, validateHyperliquidSizeWire, formatSizeWire, inferApiUrl, inferIsTestnet, postHyperliquidInfoRead, postHyperliquidInfo, fetchBrowserHyperliquidInfoPayload, fetchBrowserHyperliquidInfoRead, fetchBrowserHyperliquidInfoText, coerceMarketMaxLeverage, toFiniteNumber, OPEN_ORDER_NUMERIC_STRING, OPEN_ORDER_ID_STRING, parseCanonicalOpenOrderId, parseOpenOrderFiniteNumber, parseOpenOrderNonNegativeNumber, NATIVE_FIRED_TRIGGER_CONDITION, parseOpenOrderPositiveNumber, parseOpenOrderPresentationNumber, readOpenOrderField, firstFiniteNumber, parseFundingUsdcFromInfoPosition, isExchangeIsolatedOnly, resolveLeverageTarget, computeHip3AssetId, getPerpDexIndexMap, buildAssetInfosFromMetaResponse, requireWalletAddress, assertPositiveInteger, assertPositiveNumber, normalizeOrderSide, normalizeHyperliquidClientOrderId, resolveAssets, findResolvedAsset, normalizeExecutionAssetMetadata, readDeviceExecutionAssetMetadata, requireBotProfileId, executionAssetMetadataFor, resolveHyperliquidAsset, resolveHyperliquidAssetIndex, decimalUnits, quantizeHyperliquidOrderSizeValue, hyperliquidSignedSizeMatchesRequestedSize, finitePositive, readDevicePrivateExecutionContext, quantizeHyperliquidOrderSize, fetchBrowserAvailableAssets, fetchBrowserAllMids, fetchBrowserSymbolMidPrice, fetchBrowserOpenOrders, parseCanonicalHyperliquidOrderStatusEvidence, fetchBrowserOrderStatusEvidence, fetchBrowserUserRole, fetchBrowserAccountState, fetchBrowserPosition, buildHyperliquidOrderWire, buildHyperliquidTriggerOrderWire, signHyperliquidPayload, signHyperliquidPreparedAction, buildHyperliquidCancelPayload, buildHyperliquidUpdateLeveragePayload, buildHyperliquidMarketOrderPayload, buildHyperliquidLimitOrderPayload, buildHyperliquidTriggerOrderPayload, buildHyperliquidOrderBatchPayload, buildHyperliquidModifyOrderPayload, TRAILING_PCT_PATTERN, buildHyperliquidTrailingStopPayload, extractHyperliquidExchangeError, acknowledgementLookupPacing, lookupUntilListed, resolveHyperliquidTriggerAcknowledgements, readHyperliquidTrailingStopAcknowledgement, resolveHyperliquidModifyAcknowledgement, isDefinitiveHyperliquidExchangeResponse, extractDefinitiveHyperliquidOrderId, CANONICAL_POSITIVE_DECIMAL_PATTERN, extractCanonicalHyperliquidOrderStateAcknowledgement, extractCanonicalHyperliquidOrderStateAcknowledgements, extractCanonicalHyperliquidFilledOrderAcknowledgement, extractDefinitiveHyperliquidOrderMemberResults, buildHyperliquidOrderDiagnostics, loadClientExecutionReferenceEvidence, sha256Hex, extractSignedPayloadClientOrderId, extractSignedPayloadMutationCorrelation, assertDurableMutationMatchesSignedAction, exchangeRejectionReason, exchangeActionPriority, submitHyperliquidExchangePayload;
|
|
92729
93242
|
var init_hyperliquid_client = __esm({
|
|
92730
93243
|
"lib/runtime/hyperliquid-client.ts"() {
|
|
92731
93244
|
"use strict";
|
|
@@ -92744,6 +93257,8 @@ var init_hyperliquid_client = __esm({
|
|
|
92744
93257
|
init_hyperliquid_exchange_rejections();
|
|
92745
93258
|
init_hyperliquid_market_symbol();
|
|
92746
93259
|
init_network_debug();
|
|
93260
|
+
init_hyperliquid_market_catalog();
|
|
93261
|
+
init_runtime_error_reason_rules2();
|
|
92747
93262
|
init_runtime_redaction();
|
|
92748
93263
|
init_exchange_mutation_fence();
|
|
92749
93264
|
init_runtime_handoff();
|
|
@@ -92786,6 +93301,11 @@ var init_hyperliquid_client = __esm({
|
|
|
92786
93301
|
}
|
|
92787
93302
|
};
|
|
92788
93303
|
normalizeSymbol = (value) => normalizeHyperliquidMarketSymbol(value);
|
|
93304
|
+
normalizeBotMarket = (config2, value) => {
|
|
93305
|
+
const caseSensitiveSymbols = config2?.client_runtime_hyperliquid_case_sensitive_symbols;
|
|
93306
|
+
if (Array.isArray(caseSensitiveSymbols)) configureHyperliquidMarketSymbolCasing(caseSensitiveSymbols);
|
|
93307
|
+
return normalizeSymbol(value);
|
|
93308
|
+
};
|
|
92789
93309
|
HYPERLIQUID_NONCE_STORAGE_KEY = "vtx_hyperliquid_exchange_nonce_v1";
|
|
92790
93310
|
HYPERLIQUID_NONCE_LOCK_NAME = "vtx_hyperliquid_exchange_nonce";
|
|
92791
93311
|
lastGeneratedNonce = 0;
|
|
@@ -93263,16 +93783,57 @@ var init_hyperliquid_client = __esm({
|
|
|
93263
93783
|
only_isolated: metadata.only_isolated === true
|
|
93264
93784
|
};
|
|
93265
93785
|
};
|
|
93786
|
+
readDeviceExecutionAssetMetadata = async (input, symbol2) => {
|
|
93787
|
+
const market = normalizeBotMarket(input.config, symbol2);
|
|
93788
|
+
const dex = getHyperliquidMarketDex(market);
|
|
93789
|
+
const notListed = () => new RuntimeReasonError(`Hyperliquid does not list ${market}.`, "internal_data_error");
|
|
93790
|
+
const perpDexConfig = input.config?.client_runtime_hyperliquid_perp_dexs;
|
|
93791
|
+
const enabledDexes = perpDexConfig?.enabled && Array.isArray(perpDexConfig.allowed_dexes) ? perpDexConfig.allowed_dexes.map((value) => String(value ?? "").trim().toLowerCase()) : [];
|
|
93792
|
+
if (dex && !enabledDexes.includes(dex)) throw notListed();
|
|
93793
|
+
let indexes = /* @__PURE__ */ new Map([["", 0]]);
|
|
93794
|
+
if (dex) {
|
|
93795
|
+
indexes = perpDexIndexes(await postHyperliquidInfo(input, { type: "perpDexs" }, "hyperliquid.perpDexs"));
|
|
93796
|
+
if (!indexes.has(dex)) throw notListed();
|
|
93797
|
+
}
|
|
93798
|
+
const meta3 = await postHyperliquidInfo(input, dex ? { type: "meta", dex } : { type: "meta" }, `hyperliquid.meta${dex ? `.${dex}` : ""}`);
|
|
93799
|
+
const row = listedMarketRows(
|
|
93800
|
+
[market],
|
|
93801
|
+
{ [dex]: meta3 },
|
|
93802
|
+
indexes,
|
|
93803
|
+
input.config?.client_runtime_hyperliquid_case_sensitive_symbols,
|
|
93804
|
+
{ includeDelisted: true }
|
|
93805
|
+
)[market];
|
|
93806
|
+
if (!row) throw notListed();
|
|
93807
|
+
return row;
|
|
93808
|
+
};
|
|
93809
|
+
requireBotProfileId = (input, symbol2) => {
|
|
93810
|
+
const profileId = Number(input.profileId);
|
|
93811
|
+
if (!Number.isSafeInteger(profileId) || profileId <= 0) {
|
|
93812
|
+
throw new RuntimeReasonError(`The bot's profile is needed to read ${symbol2}'s execution metadata.`, "internal_data_error");
|
|
93813
|
+
}
|
|
93814
|
+
return profileId;
|
|
93815
|
+
};
|
|
93816
|
+
executionAssetMetadataFor = async (input, symbol2, options = {}) => {
|
|
93817
|
+
const requestOptions = {
|
|
93818
|
+
profileId: requireBotProfileId(input, symbol2),
|
|
93819
|
+
...options.forceCatalogRefresh ? { forceCatalogRefresh: true } : {},
|
|
93820
|
+
...input.publicRequestPriority === "trading_reduce" ? { publicRequestPriority: "trading_reduce" } : {}
|
|
93821
|
+
};
|
|
93822
|
+
try {
|
|
93823
|
+
return await getExecutionAssetMetadata("hyperliquid", symbol2, requestOptions);
|
|
93824
|
+
} catch (error48) {
|
|
93825
|
+
if (!executionMetadataNeedsDeviceRead(error48)) throw error48;
|
|
93826
|
+
options.onDeviceRead?.();
|
|
93827
|
+
return readDeviceExecutionAssetMetadata(input, symbol2);
|
|
93828
|
+
}
|
|
93829
|
+
};
|
|
93266
93830
|
resolveHyperliquidAsset = async (input) => {
|
|
93267
|
-
const symbol2 =
|
|
93831
|
+
const symbol2 = normalizeBotMarket(input.config, input.symbol);
|
|
93268
93832
|
if (!symbol2) {
|
|
93269
93833
|
throw new Error("Missing Hyperliquid symbol.");
|
|
93270
93834
|
}
|
|
93271
93835
|
if (input.refreshCatalog) {
|
|
93272
|
-
return normalizeExecutionAssetMetadata(symbol2, await
|
|
93273
|
-
forceCatalogRefresh: true,
|
|
93274
|
-
...input.publicRequestPriority === "trading_reduce" ? { publicRequestPriority: "trading_reduce" } : {}
|
|
93275
|
-
}));
|
|
93836
|
+
return normalizeExecutionAssetMetadata(symbol2, await executionAssetMetadataFor(input, symbol2, { forceCatalogRefresh: true }));
|
|
93276
93837
|
}
|
|
93277
93838
|
if (Array.isArray(input.assets) && input.assets.length > 0) {
|
|
93278
93839
|
const explicitAsset = findResolvedAsset(symbol2, input.assets);
|
|
@@ -93280,10 +93841,16 @@ var init_hyperliquid_client = __esm({
|
|
|
93280
93841
|
return explicitAsset;
|
|
93281
93842
|
}
|
|
93282
93843
|
}
|
|
93844
|
+
requireBotProfileId(input, symbol2);
|
|
93845
|
+
let readOnDevice = false;
|
|
93283
93846
|
try {
|
|
93284
|
-
|
|
93285
|
-
|
|
93847
|
+
return normalizeExecutionAssetMetadata(symbol2, await executionAssetMetadataFor(input, symbol2, {
|
|
93848
|
+
onDeviceRead: () => {
|
|
93849
|
+
readOnDevice = true;
|
|
93850
|
+
}
|
|
93851
|
+
}));
|
|
93286
93852
|
} catch (executionMetadataError) {
|
|
93853
|
+
if (readOnDevice) throw executionMetadataError;
|
|
93287
93854
|
const assets = await resolveAssets(input);
|
|
93288
93855
|
const fallbackAsset = findResolvedAsset(symbol2, assets);
|
|
93289
93856
|
if (fallbackAsset) {
|
|
@@ -93397,7 +93964,7 @@ var init_hyperliquid_client = __esm({
|
|
|
93397
93964
|
return { executionPositionSize, executionMarkPrice, executionContextAtMs };
|
|
93398
93965
|
};
|
|
93399
93966
|
quantizeHyperliquidOrderSize = async (input) => {
|
|
93400
|
-
const symbol2 =
|
|
93967
|
+
const symbol2 = normalizeBotMarket(input.config, input.symbol);
|
|
93401
93968
|
if (!symbol2) {
|
|
93402
93969
|
throw new Error("Missing Hyperliquid symbol.");
|
|
93403
93970
|
}
|
|
@@ -93408,7 +93975,7 @@ var init_hyperliquid_client = __esm({
|
|
|
93408
93975
|
symbol: symbol2
|
|
93409
93976
|
}) : null;
|
|
93410
93977
|
devicePrivateContext?.catch(() => void 0);
|
|
93411
|
-
const metadata =
|
|
93978
|
+
const metadata = await executionAssetMetadataFor(input, symbol2);
|
|
93412
93979
|
const deviceContext = devicePrivateContext ? await devicePrivateContext : null;
|
|
93413
93980
|
const executionContextReceivedAtMonotonicMs = globalThis.performance.now();
|
|
93414
93981
|
const resolved = normalizeExecutionAssetMetadata(symbol2, metadata);
|
|
@@ -93465,9 +94032,9 @@ var init_hyperliquid_client = __esm({
|
|
|
93465
94032
|
const allowedDexes = Array.isArray(perpDexConfig.allowed_dexes) ? perpDexConfig.allowed_dexes.map((dex) => String(dex || "").trim().toLowerCase()).filter(Boolean) : [];
|
|
93466
94033
|
if (allowedDexes.length > 0) {
|
|
93467
94034
|
const perpDexPayload = await postHyperliquidInfo(input, { type: "perpDexs" }, "hyperliquid.perpDexs");
|
|
93468
|
-
const
|
|
94035
|
+
const perpDexIndexes2 = getPerpDexIndexMap(perpDexPayload);
|
|
93469
94036
|
for (const dex of allowedDexes) {
|
|
93470
|
-
const perpDexIndex =
|
|
94037
|
+
const perpDexIndex = perpDexIndexes2.get(dex);
|
|
93471
94038
|
if (perpDexIndex === void 0) {
|
|
93472
94039
|
throw new Error(`Configured Hyperliquid perp DEX is not available: ${dex}`);
|
|
93473
94040
|
}
|
|
@@ -95251,7 +95818,7 @@ var exchange_mutation_evidence_exports = {};
|
|
|
95251
95818
|
__export(exchange_mutation_evidence_exports, {
|
|
95252
95819
|
readClientExchangeReconciliationEvidence: () => readClientExchangeReconciliationEvidence
|
|
95253
95820
|
});
|
|
95254
|
-
var resolveHyperliquidApiUrl, readClientExchangeReconciliationEvidence;
|
|
95821
|
+
var profileRuntimeConfig, resolveHyperliquidApiUrl, readClientExchangeReconciliationEvidence;
|
|
95255
95822
|
var init_exchange_mutation_evidence = __esm({
|
|
95256
95823
|
"lib/runtime/exchange-mutation-evidence.ts"() {
|
|
95257
95824
|
"use strict";
|
|
@@ -95262,15 +95829,18 @@ var init_exchange_mutation_evidence = __esm({
|
|
|
95262
95829
|
init_api2();
|
|
95263
95830
|
init_hyperliquid_client();
|
|
95264
95831
|
init_monotonic_clock();
|
|
95265
|
-
|
|
95266
|
-
const fromAnswer = String(answered ?? "").trim();
|
|
95267
|
-
if (fromAnswer) return fromAnswer;
|
|
95832
|
+
profileRuntimeConfig = async (profileId, signal) => {
|
|
95268
95833
|
const numericProfileId = Number(profileId);
|
|
95269
|
-
|
|
95834
|
+
return getLLMConfig(
|
|
95270
95835
|
void 0,
|
|
95271
95836
|
Number.isSafeInteger(numericProfileId) && numericProfileId > 0 ? numericProfileId : void 0,
|
|
95272
95837
|
signal
|
|
95273
95838
|
);
|
|
95839
|
+
};
|
|
95840
|
+
resolveHyperliquidApiUrl = async (profileId, answered, signal) => {
|
|
95841
|
+
const fromAnswer = String(answered ?? "").trim();
|
|
95842
|
+
if (fromAnswer) return fromAnswer;
|
|
95843
|
+
const config2 = await profileRuntimeConfig(profileId, signal);
|
|
95274
95844
|
const apiUrl = String(config2?.client_runtime_exchange_endpoints?.hyperliquid_api_url ?? "").trim();
|
|
95275
95845
|
if (!apiUrl) throw new Error("Missing client runtime Hyperliquid API URL.");
|
|
95276
95846
|
return apiUrl;
|
|
@@ -95305,6 +95875,12 @@ var init_exchange_mutation_evidence = __esm({
|
|
|
95305
95875
|
"hyperliquid.frontendOpenOrders"
|
|
95306
95876
|
);
|
|
95307
95877
|
const historicalOrders = input.required.historical_orders === true ? await fetchBrowserHyperliquidInfoPayload(readInput, { type: "historicalOrders", user: wallet }, "hyperliquid.historicalOrders") : void 0;
|
|
95878
|
+
const assetSymbol = String(input.required.execution_asset_symbol ?? "").trim();
|
|
95879
|
+
const executionAsset = assetSymbol ? await readDeviceExecutionAssetMetadata({
|
|
95880
|
+
...readInput,
|
|
95881
|
+
// Which HIP-3 DEXes VTX enables: the caller's runtime config, else the profile's.
|
|
95882
|
+
config: input.config ?? await profileRuntimeConfig(input.profileId, input.signal)
|
|
95883
|
+
}, assetSymbol) : void 0;
|
|
95308
95884
|
return {
|
|
95309
95885
|
evidence: {
|
|
95310
95886
|
wallet_address: wallet,
|
|
@@ -95312,7 +95888,8 @@ var init_exchange_mutation_evidence = __esm({
|
|
|
95312
95888
|
order_statuses: orderStatuses,
|
|
95313
95889
|
active_asset_data: activeAssetData,
|
|
95314
95890
|
...openOrders === void 0 ? {} : { open_orders: openOrders },
|
|
95315
|
-
...historicalOrders === void 0 ? {} : { historical_orders: historicalOrders }
|
|
95891
|
+
...historicalOrders === void 0 ? {} : { historical_orders: historicalOrders },
|
|
95892
|
+
...executionAsset === void 0 ? {} : { execution_asset: executionAsset }
|
|
95316
95893
|
},
|
|
95317
95894
|
startedAtMonotonicMs
|
|
95318
95895
|
};
|
|
@@ -96652,21 +97229,7 @@ async function reportClientRuntimeError(profileId, payload, options) {
|
|
|
96652
97229
|
);
|
|
96653
97230
|
}
|
|
96654
97231
|
async function reportClientRuntimeLifecycleEvent(profileId, payload, options) {
|
|
96655
|
-
return postClientRuntime
|
|
96656
|
-
"/runtime/event",
|
|
96657
|
-
profileId,
|
|
96658
|
-
JSON.stringify({
|
|
96659
|
-
session_id: payload.sessionId ?? null,
|
|
96660
|
-
device_id: payload.deviceId ?? null,
|
|
96661
|
-
...String(payload.schedulerInstanceId ?? "").trim() ? { scheduler_instance_id: String(payload.schedulerInstanceId).trim() } : {},
|
|
96662
|
-
mode: payload.mode ?? null,
|
|
96663
|
-
last_run_at: payload.lastRunAt ?? null,
|
|
96664
|
-
event_type: payload.eventType,
|
|
96665
|
-
detail: payload.detail ?? null,
|
|
96666
|
-
payload: payload.payload ?? null
|
|
96667
|
-
}),
|
|
96668
|
-
options
|
|
96669
|
-
);
|
|
97232
|
+
return reportRuntimeEvent(profileId, payload, options, postClientRuntime);
|
|
96670
97233
|
}
|
|
96671
97234
|
async function reportClientRuntimeTradeSync(profileId, payload, options) {
|
|
96672
97235
|
const extras = {
|
|
@@ -96849,7 +97412,7 @@ async function getClientRuntimeStatuses(profileIds, signal, options) {
|
|
|
96849
97412
|
ttlMs: viewer.requestKey ? 0 : CLIENT_RUNTIME_STATUSES_DEDUPE_TTL_MS
|
|
96850
97413
|
});
|
|
96851
97414
|
}
|
|
96852
|
-
var clientRuntimeSecretHeaders, preferencesWriteQueue, getCopyTradingRuntimeLeaseToken, getCopyTradingSchedulerInstanceId, AI_TRADE_HISTORY_BY_ORDER_IDS_MAX_BATCH, AI_TRADE_HISTORY_BY_ORDER_IDS_MAX_CONCURRENCY, resolveClientRuntimeStatusViewerHeaders, CLIENT_SUPPORTED_PROMPT_CONTRACT_VERSION,
|
|
97415
|
+
var clientRuntimeSecretHeaders, preferencesWriteQueue, getCopyTradingRuntimeLeaseToken, getCopyTradingSchedulerInstanceId, AI_TRADE_HISTORY_BY_ORDER_IDS_MAX_BATCH, AI_TRADE_HISTORY_BY_ORDER_IDS_MAX_CONCURRENCY, resolveClientRuntimeStatusViewerHeaders, CLIENT_SUPPORTED_PROMPT_CONTRACT_VERSION, completedDeferredClientRuntimeStops, rememberCompletedDeferredClientRuntimeStop, consumeCompletedDeferredClientRuntimeStop, toNumericProfileId, buildClientRuntimeBody, shouldAttachRuntimeIdempotencyKey, attachRuntimeLeaseHeader, attachRuntimeSchedulerInstanceHeader, resolveRuntimeLeaseToken, resolveSchedulerBoundRuntimeLeaseToken, persistRuntimeLeaseFromPayload, persistRuntimeLeaseStatusMetadata, shouldClearPersistedRuntimeLeaseOnError, createRuntimeRequestError, parseClientRuntimeRequestContext, recordRuntimeAuthFailureBreadcrumb, classifyRuntimeRequestError, annotateRuntimeRequestError, CLIENT_RUNTIME_RETRYABLE_STATUSES, isRetryableClientRuntimeStatus, shouldRetryClientRuntimeHttpStatus, isRuntimeIdempotencyInProgressError, isRetryableRuntimeConflictError, resolveClientRuntimeRetryDelayMs, reconcilePendingClientExchangeMutation, CLIENT_RUNTIME_CLAIM_EXCHANGE_MUTATION_WAIT_CODES, CLIENT_EXCHANGE_AUTHORITY_DEVICE_KEY, CLIENT_EXCHANGE_AUTHORITY_SESSION_KEY, getOrCreateClientExchangeAuthorityIdentity, resolveClientExchangeMutationAuthority, pinClientExchangeMutationAuthority, CLIENT_EXCHANGE_MUTATION_AUTHORITY_MISMATCH, isClientExchangeMutationAuthorityConflict, handOffClientExchangeMutationToReconciliation, clientExchangeMutationAuthorityBody, isPendingClientExchangeMutationError, isMissingActiveClientExchangeMutationError, clientExchangeMutationReconciliationTimers, ClientExchangeMutationRebuildRequiredError, isTerminalClientExchangeMutation, clientExchangeMutationReconciliationKey, clearScheduledClientExchangeMutationReconciliation, snapshotClientExchangeMutationReconciliationAuthority, completeClientExchangeMutationReconciliation, protectiveBoundClientExchangeMutations, rememberProtectiveBoundClientExchangeMutation, isProtectiveBoundClientExchangeMutation, postClientExchangeMutationReconciliation, scheduleClientExchangeMutationReconciliation;
|
|
96853
97416
|
var init_api2 = __esm({
|
|
96854
97417
|
"lib/api.ts"() {
|
|
96855
97418
|
"use strict";
|
|
@@ -96869,6 +97432,7 @@ var init_api2 = __esm({
|
|
|
96869
97432
|
init_client_runtime_provider_visibility_contract();
|
|
96870
97433
|
init_google_auth_url();
|
|
96871
97434
|
init_network_debug();
|
|
97435
|
+
init_runtime_error_reason_rules2();
|
|
96872
97436
|
init_monotonic_clock();
|
|
96873
97437
|
init_bot_exchanges();
|
|
96874
97438
|
init_local_breadcrumbs();
|
|
@@ -96885,6 +97449,7 @@ var init_api2 = __esm({
|
|
|
96885
97449
|
init_logout();
|
|
96886
97450
|
init_llm_config();
|
|
96887
97451
|
init_llm_config();
|
|
97452
|
+
init_runtime_event_batch();
|
|
96888
97453
|
init_insights_access_center();
|
|
96889
97454
|
init_updates();
|
|
96890
97455
|
init_profile_emoji();
|
|
@@ -96892,6 +97457,7 @@ var init_api2 = __esm({
|
|
|
96892
97457
|
init_account_summary();
|
|
96893
97458
|
init_mobile_notifications();
|
|
96894
97459
|
init_admin_signups();
|
|
97460
|
+
init_client_exchange_reconciliation();
|
|
96895
97461
|
init_server_runtime_lease();
|
|
96896
97462
|
clientRuntimeSecretHeaders = (profileId) => {
|
|
96897
97463
|
const headers = getProfileHeaders({}, profileId);
|
|
@@ -96934,7 +97500,6 @@ var init_api2 = __esm({
|
|
|
96934
97500
|
CLIENT_SUPPORTED_PROMPT_CONTRACT_VERSION = String(
|
|
96935
97501
|
process.env.NEXT_PUBLIC_CLIENT_RUNTIME_PROMPT_CONTRACT_VERSION || "2026-08-24.1"
|
|
96936
97502
|
).trim() || "2026-08-24.1";
|
|
96937
|
-
CLIENT_PROTECTION_CAPABILITY_VERSION = 1;
|
|
96938
97503
|
completedDeferredClientRuntimeStops = /* @__PURE__ */ new Set();
|
|
96939
97504
|
rememberCompletedDeferredClientRuntimeStop = (profileId, result) => {
|
|
96940
97505
|
if (result.runtime_stop_completed === true) {
|
|
@@ -97102,10 +97667,11 @@ var init_api2 = __esm({
|
|
|
97102
97667
|
profile_equity_venues_changed: "The bot's markets moved to another venue during this Client Mode cycle. The next cycle measures the new venue."
|
|
97103
97668
|
}[rawMessage.trim()] : void 0;
|
|
97104
97669
|
const message = walletCohortMessage ?? rawMessage;
|
|
97105
|
-
const error48 =
|
|
97106
|
-
|
|
97107
|
-
|
|
97108
|
-
|
|
97670
|
+
const error48 = Object.assign(runtimeRequestFailure(message, response.status, rawMessage === defaultMessage), {
|
|
97671
|
+
status: response.status,
|
|
97672
|
+
detail: payload.detail,
|
|
97673
|
+
modelFallbackSafe: nestedDetail?.model_fallback_safe === true
|
|
97674
|
+
});
|
|
97109
97675
|
const code = typeof payload.code === "string" ? payload.code.trim() : typeof nestedDetail?.code === "string" ? nestedDetail.code.trim() : "";
|
|
97110
97676
|
if (code) {
|
|
97111
97677
|
error48.code = code;
|
|
@@ -97235,7 +97801,7 @@ var init_api2 = __esm({
|
|
|
97235
97801
|
if (!isRetryableClientRuntimeStatus(status)) {
|
|
97236
97802
|
return false;
|
|
97237
97803
|
}
|
|
97238
|
-
if (path === "/runtime/event" || path === "/runtime/server-prompt-rescue") {
|
|
97804
|
+
if (path === "/runtime/event" || path === "/runtime/events" || path === "/runtime/server-prompt-rescue") {
|
|
97239
97805
|
return false;
|
|
97240
97806
|
}
|
|
97241
97807
|
return true;
|
|
@@ -98181,6 +98747,7 @@ var init_vault = __esm({
|
|
|
98181
98747
|
init_define_VTX_PI_MODEL_POLICY();
|
|
98182
98748
|
init_host_storage();
|
|
98183
98749
|
init_runtime_redaction();
|
|
98750
|
+
init_runtime_error_reason_rules2();
|
|
98184
98751
|
init_api2();
|
|
98185
98752
|
init_client_runtime_secret_contract();
|
|
98186
98753
|
init_client_runtime_provider_contract();
|
|
@@ -98192,9 +98759,9 @@ var init_vault = __esm({
|
|
|
98192
98759
|
init_byokProviderRegistry();
|
|
98193
98760
|
init_constants();
|
|
98194
98761
|
CLIENT_VAULT_CHANGED_EVENT = "vtx-client-vault-changed";
|
|
98195
|
-
ClientRuntimeSecretRefreshPendingError = class extends
|
|
98762
|
+
ClientRuntimeSecretRefreshPendingError = class extends RuntimeReasonError {
|
|
98196
98763
|
constructor(retryAfterSeconds) {
|
|
98197
|
-
super("Client provider credentials changed; account refresh is pending.");
|
|
98764
|
+
super("Client provider credentials changed; account refresh is pending.", "provider_credentials_refreshing");
|
|
98198
98765
|
this.code = "client_runtime_secret_refresh_pending";
|
|
98199
98766
|
this.retryAfterSeconds = retryAfterSeconds;
|
|
98200
98767
|
}
|
|
@@ -98823,6 +99390,7 @@ var init_browser_trading = __esm({
|
|
|
98823
99390
|
const payload = await buildHyperliquidUpdateLeveragePayload({
|
|
98824
99391
|
config: input.config ?? null,
|
|
98825
99392
|
publicRequestPriority: priorityOf(input),
|
|
99393
|
+
profileId: input.profileId,
|
|
98826
99394
|
signingKey,
|
|
98827
99395
|
symbol: input.symbol,
|
|
98828
99396
|
leverage: input.leverage,
|
|
@@ -98862,6 +99430,7 @@ var init_browser_trading = __esm({
|
|
|
98862
99430
|
const payload = await buildHyperliquidMarketOrderPayload({
|
|
98863
99431
|
config: input.config ?? null,
|
|
98864
99432
|
publicRequestPriority: priorityOf(input),
|
|
99433
|
+
profileId: input.profileId,
|
|
98865
99434
|
signingKey,
|
|
98866
99435
|
symbol: input.symbol,
|
|
98867
99436
|
side: input.side,
|
|
@@ -98943,6 +99512,7 @@ var init_browser_trading = __esm({
|
|
|
98943
99512
|
const payload = await buildHyperliquidLimitOrderPayload({
|
|
98944
99513
|
config: input.config ?? null,
|
|
98945
99514
|
publicRequestPriority: priorityOf(input),
|
|
99515
|
+
profileId: input.profileId,
|
|
98946
99516
|
signingKey,
|
|
98947
99517
|
symbol: input.symbol,
|
|
98948
99518
|
side: input.side,
|
|
@@ -98981,6 +99551,7 @@ var init_browser_trading = __esm({
|
|
|
98981
99551
|
const payload = await buildHyperliquidTriggerOrderPayload({
|
|
98982
99552
|
config: input.config ?? null,
|
|
98983
99553
|
publicRequestPriority: priorityOf(input),
|
|
99554
|
+
profileId: input.profileId,
|
|
98984
99555
|
signingKey,
|
|
98985
99556
|
symbol: input.symbol,
|
|
98986
99557
|
side: input.side,
|
|
@@ -99021,6 +99592,7 @@ var init_browser_trading = __esm({
|
|
|
99021
99592
|
const payload = await buildHyperliquidOrderBatchPayload({
|
|
99022
99593
|
config: input.config ?? null,
|
|
99023
99594
|
publicRequestPriority: priorityOf(input),
|
|
99595
|
+
profileId: input.profileId,
|
|
99024
99596
|
signingKey,
|
|
99025
99597
|
symbol: input.symbol,
|
|
99026
99598
|
members: input.members,
|
|
@@ -99057,6 +99629,7 @@ var init_browser_trading = __esm({
|
|
|
99057
99629
|
const payload = await buildHyperliquidModifyOrderPayload({
|
|
99058
99630
|
config: input.config ?? null,
|
|
99059
99631
|
publicRequestPriority: priorityOf(input),
|
|
99632
|
+
profileId: input.profileId,
|
|
99060
99633
|
signingKey,
|
|
99061
99634
|
symbol: input.symbol,
|
|
99062
99635
|
orderId: input.orderId,
|
|
@@ -99104,6 +99677,7 @@ var init_browser_trading = __esm({
|
|
|
99104
99677
|
const payload = await buildHyperliquidCancelPayload({
|
|
99105
99678
|
config: input.config ?? null,
|
|
99106
99679
|
publicRequestPriority: priorityOf(input),
|
|
99680
|
+
profileId: input.profileId,
|
|
99107
99681
|
signingKey,
|
|
99108
99682
|
symbol: input.symbol,
|
|
99109
99683
|
orderId: input.orderId,
|
|
@@ -99137,6 +99711,7 @@ var init_browser_trading = __esm({
|
|
|
99137
99711
|
const payload = await buildHyperliquidTrailingStopPayload({
|
|
99138
99712
|
config: input.config ?? null,
|
|
99139
99713
|
publicRequestPriority: priorityOf(input),
|
|
99714
|
+
profileId: input.profileId,
|
|
99140
99715
|
signingKey,
|
|
99141
99716
|
symbol: input.symbol,
|
|
99142
99717
|
side: input.side,
|
|
@@ -100132,7 +100707,7 @@ var init_hyperliquid_account_state_adapter = __esm({
|
|
|
100132
100707
|
return withAccountStateEvidence(cached2.result, "stale_if_429", cached2.fetchedAtMs, staleIf429MaxAgeMs);
|
|
100133
100708
|
}
|
|
100134
100709
|
const existingFlight = input.forceRefresh ? void 0 : browserAccountStateInFlight.get(cacheKey);
|
|
100135
|
-
const priority = existingFlight?.priority ?? createHyperliquidPublicPriorityScope(input.publicRequestPriority);
|
|
100710
|
+
const priority = existingFlight?.priority ?? createHyperliquidPublicPriorityScope(input.publicRequestPriority, input.unscheduledRead === true);
|
|
100136
100711
|
promoteHyperliquidPublicPriority(priority, input.publicRequestPriority);
|
|
100137
100712
|
input = { ...input, priorityScope: priority };
|
|
100138
100713
|
let inFlight = existingFlight?.promise;
|
|
@@ -100747,6 +101322,9 @@ var init_protective_evidence = __esm({
|
|
|
100747
101322
|
includeMark: request.include_mark === true || existing?.kind === "market" && existing.includeMark,
|
|
100748
101323
|
shareable: request.reason === "leg_active" && (existing?.kind !== "market" || existing.shareable)
|
|
100749
101324
|
});
|
|
101325
|
+
} else if (request.kind === "execution_asset") {
|
|
101326
|
+
const symbol2 = String(request.symbol ?? "").trim();
|
|
101327
|
+
if (symbol2) items.set(`execution_asset:${symbol2}`, { kind: "execution_asset", symbol: symbol2 });
|
|
100750
101328
|
}
|
|
100751
101329
|
}
|
|
100752
101330
|
return [...items.values()];
|
|
@@ -100768,7 +101346,7 @@ var init_protective_evidence = __esm({
|
|
|
100768
101346
|
const observedAt = (/* @__PURE__ */ new Date()).toISOString();
|
|
100769
101347
|
const perDex = /* @__PURE__ */ new Map();
|
|
100770
101348
|
const scope = `${String(input.apiUrl ?? "")}|${wallet.toLowerCase()}`;
|
|
100771
|
-
const shareable = batch.every((item) => item.kind !== "fills" && item.shareable);
|
|
101349
|
+
const shareable = batch.every((item) => item.kind === "execution_asset" || item.kind !== "fills" && item.shareable);
|
|
100772
101350
|
const dexRead = (key, body, label2) => {
|
|
100773
101351
|
let read = perDex.get(key);
|
|
100774
101352
|
if (read) return read;
|
|
@@ -100793,7 +101371,13 @@ var init_protective_evidence = __esm({
|
|
|
100793
101371
|
const orderStatuses = [];
|
|
100794
101372
|
const fills = [];
|
|
100795
101373
|
const markets = [];
|
|
101374
|
+
const assets = [];
|
|
100796
101375
|
await Promise.all(batch.map(async (item) => {
|
|
101376
|
+
if (item.kind === "execution_asset") {
|
|
101377
|
+
const row = await readOrNull(() => readDeviceExecutionAssetMetadata(input, item.symbol));
|
|
101378
|
+
if (row != null) assets.push({ symbol: item.symbol, row });
|
|
101379
|
+
return;
|
|
101380
|
+
}
|
|
100797
101381
|
if (item.kind === "order_status") {
|
|
100798
101382
|
const oid = orderStatusOid(item.orderRef);
|
|
100799
101383
|
const response = await readOrNull(() => fetchBrowserHyperliquidInfoPayload(
|
|
@@ -100833,7 +101417,8 @@ var init_protective_evidence = __esm({
|
|
|
100833
101417
|
if (orderStatuses.length > 0) report.order_statuses = orderStatuses;
|
|
100834
101418
|
if (fills.length > 0) report.fills = fills;
|
|
100835
101419
|
if (markets.length > 0) report.markets = markets;
|
|
100836
|
-
|
|
101420
|
+
if (assets.length > 0) report.assets = assets;
|
|
101421
|
+
const items = orderStatuses.length + fills.length + markets.length + assets.length;
|
|
100837
101422
|
return items > 0 ? { report, items, startedAtMonotonicMs } : null;
|
|
100838
101423
|
};
|
|
100839
101424
|
withEvidenceReporterLock = async (profileId, work, busy) => {
|
|
@@ -102341,9 +102926,9 @@ var init_native_position_protection = __esm({
|
|
|
102341
102926
|
roundDecimalHalfUp = (value, decimals) => {
|
|
102342
102927
|
const text = String(value);
|
|
102343
102928
|
if (text.includes("e")) return "0";
|
|
102344
|
-
const [
|
|
102345
|
-
if (fraction.length <= decimals) return fraction ? `${
|
|
102346
|
-
let units = BigInt(`${
|
|
102929
|
+
const [integer4, fraction = ""] = text.split(".");
|
|
102930
|
+
if (fraction.length <= decimals) return fraction ? `${integer4}.${fraction}`.replace(/\.?0+$/, "") : integer4;
|
|
102931
|
+
let units = BigInt(`${integer4}${fraction.slice(0, decimals)}`);
|
|
102347
102932
|
if (fraction[decimals] >= HALF_UP_DIGIT) units += BigInt(1);
|
|
102348
102933
|
const digits = units.toString().padStart(decimals + 1, "0");
|
|
102349
102934
|
const rounded = `${digits.slice(0, -decimals)}.${digits.slice(-decimals)}`;
|
|
@@ -104088,7 +104673,7 @@ var init_runtime_execution = __esm({
|
|
|
104088
104673
|
let target;
|
|
104089
104674
|
try {
|
|
104090
104675
|
target = resolveLeverageTarget(
|
|
104091
|
-
await resolveHyperliquidAsset({ symbol: symbol2, config: input.config ?? null, publicRequestPriority: "trading_reconcile" }),
|
|
104676
|
+
await resolveHyperliquidAsset({ symbol: symbol2, config: input.config ?? null, publicRequestPriority: "trading_reconcile", profileId: input.profileId }),
|
|
104092
104677
|
context.leverage,
|
|
104093
104678
|
context.marginMode !== "isolated"
|
|
104094
104679
|
);
|
|
@@ -104626,7 +105211,7 @@ var init_runtime_execution = __esm({
|
|
|
104626
105211
|
}
|
|
104627
105212
|
return parsed;
|
|
104628
105213
|
};
|
|
104629
|
-
writeClientProtectiveGroups = (profileId, symbol2,
|
|
105214
|
+
writeClientProtectiveGroups = (profileId, symbol2, groups2) => {
|
|
104630
105215
|
const key = protectiveGroupStorageKey(profileId, symbol2);
|
|
104631
105216
|
const storage3 = resolveClientRuntimeProtectionStorage();
|
|
104632
105217
|
if (!storage3) {
|
|
@@ -104635,7 +105220,7 @@ var init_runtime_execution = __esm({
|
|
|
104635
105220
|
return false;
|
|
104636
105221
|
}
|
|
104637
105222
|
try {
|
|
104638
|
-
if (
|
|
105223
|
+
if (groups2.length === 0) {
|
|
104639
105224
|
storage3.removeItem(key);
|
|
104640
105225
|
const removed = storage3.getItem(key) === null;
|
|
104641
105226
|
if (removed) {
|
|
@@ -104644,11 +105229,11 @@ var init_runtime_execution = __esm({
|
|
|
104644
105229
|
}
|
|
104645
105230
|
return removed;
|
|
104646
105231
|
} else {
|
|
104647
|
-
const serialized = JSON.stringify(
|
|
105232
|
+
const serialized = JSON.stringify(groups2);
|
|
104648
105233
|
storage3.setItem(key, serialized);
|
|
104649
105234
|
const persisted = storage3.getItem(key) === serialized;
|
|
104650
105235
|
if (persisted) {
|
|
104651
|
-
protectiveGroupMemory.set(key,
|
|
105236
|
+
protectiveGroupMemory.set(key, groups2);
|
|
104652
105237
|
protectiveGroupReadFailures.delete(key);
|
|
104653
105238
|
}
|
|
104654
105239
|
return persisted;
|
|
@@ -104692,25 +105277,25 @@ var init_runtime_execution = __esm({
|
|
|
104692
105277
|
}
|
|
104693
105278
|
}
|
|
104694
105279
|
});
|
|
104695
|
-
exactClientProtectiveGroupSetSnapshot = (
|
|
105280
|
+
exactClientProtectiveGroupSetSnapshot = (groups2) => stableProtectionSnapshot(groups2.map((group) => exactClientProtectiveGroupSnapshot(group)));
|
|
104696
105281
|
storableClientProtectiveGroup = (group) => group != null && group.legs.length === 0 && group.pendingEntry == null ? null : group;
|
|
104697
105282
|
replaceExactClientProtectiveGroup = (profileId, symbol2, expected, candidateReplacement) => {
|
|
104698
105283
|
const replacement = storableClientProtectiveGroup(candidateReplacement);
|
|
104699
|
-
const
|
|
105284
|
+
const groups2 = readFreshClientProtectiveGroups(profileId, symbol2);
|
|
104700
105285
|
if (hasClientProtectiveGroupReadFailure(profileId, symbol2)) return false;
|
|
104701
105286
|
const expectedSnapshot = exactClientProtectiveGroupSnapshot(expected);
|
|
104702
105287
|
const matches2 = (candidate) => exactClientProtectiveGroupSnapshot(candidate) === expectedSnapshot;
|
|
104703
|
-
if (
|
|
105288
|
+
if (groups2.filter(matches2).length !== 1) return false;
|
|
104704
105289
|
return writeClientProtectiveGroups(
|
|
104705
105290
|
profileId,
|
|
104706
105291
|
symbol2,
|
|
104707
|
-
|
|
105292
|
+
groups2.flatMap((candidate) => matches2(candidate) ? replacement == null ? [] : [replacement] : [candidate])
|
|
104708
105293
|
);
|
|
104709
105294
|
};
|
|
104710
105295
|
replaceExactClientProtectiveGroupSet = (profileId, symbol2, expected, replacement) => {
|
|
104711
|
-
const
|
|
105296
|
+
const groups2 = readFreshClientProtectiveGroups(profileId, symbol2);
|
|
104712
105297
|
if (hasClientProtectiveGroupReadFailure(profileId, symbol2)) return false;
|
|
104713
|
-
if (exactClientProtectiveGroupSetSnapshot(
|
|
105298
|
+
if (exactClientProtectiveGroupSetSnapshot(groups2) !== exactClientProtectiveGroupSetSnapshot(expected)) return false;
|
|
104714
105299
|
return writeClientProtectiveGroups(profileId, symbol2, replacement);
|
|
104715
105300
|
};
|
|
104716
105301
|
isClientRuntimeLeaseOwnershipError = (error48) => {
|
|
@@ -104741,12 +105326,12 @@ var init_runtime_execution = __esm({
|
|
|
104741
105326
|
if (provisionalSnapshot !== input.provisionalGroupSnapshot || restoredSnapshot !== input.restoredGroupSnapshot || provisionalGroup.profileId !== profileId || restoredGroup.profileId !== profileId || provisionalGroup.symbol !== symbol2.toUpperCase() || restoredGroup.symbol !== symbol2.toUpperCase() || provisionalGroup.entryOrderId !== input.provisionalEntryOrderId || restoredGroup.entryOrderId !== input.pendingEntryOrderId || provisionalGroup.walletAddress !== input.walletAddress || restoredGroup.walletAddress !== input.walletAddress || provisionalGroup.isLong !== input.isLong || restoredGroup.isLong !== input.isLong || !Array.isArray(provisionalGroup.legs) || !Array.isArray(restoredGroup.legs) || stableProtectionSnapshot(provisionalGroup.pendingEntry) !== stableProtectionSnapshot(input.pendingEntry) || stableProtectionSnapshot(restoredGroup.pendingEntry) !== stableProtectionSnapshot(input.pendingEntry) || provisionalGroup.legs.map((leg) => String(leg.orderId)).sort().join(",") !== [...input.provisionalClientOrderIds].sort().join(",")) {
|
|
104742
105327
|
return false;
|
|
104743
105328
|
}
|
|
104744
|
-
const
|
|
105329
|
+
const groups3 = readFreshClientProtectiveGroups(profileId, symbol2);
|
|
104745
105330
|
if (hasClientProtectiveGroupReadFailure(profileId, symbol2)) return false;
|
|
104746
105331
|
const matchesProvisional = (group) => exactClientProtectiveGroupSnapshot(group) === provisionalSnapshot;
|
|
104747
105332
|
const matchesRestored = (group) => exactClientProtectiveGroupSnapshot(group) === restoredSnapshot;
|
|
104748
|
-
const provisionalGroups =
|
|
104749
|
-
const restoredGroups =
|
|
105333
|
+
const provisionalGroups = groups3.filter(matchesProvisional);
|
|
105334
|
+
const restoredGroups = groups3.filter(matchesRestored);
|
|
104750
105335
|
if (provisionalGroups.length === 0 && restoredGroups.length === 1) {
|
|
104751
105336
|
windowHandoffCleanupAttempts.delete(cleanupAttemptKey);
|
|
104752
105337
|
return true;
|
|
@@ -104795,27 +105380,27 @@ var init_runtime_execution = __esm({
|
|
|
104795
105380
|
replacement
|
|
104796
105381
|
});
|
|
104797
105382
|
if (reservedSourceSnapshot !== input.reservedSourceGroupSnapshot || restoredSourceSnapshot !== input.restoredSourceGroupSnapshot || journalSnapshot !== input.journalGroupSnapshot || exactClientProtectiveGroupSnapshot(expectedRestoredGroup) !== restoredSourceSnapshot || exactClientProtectiveGroupSnapshot(expectedJournalGroup) !== journalSnapshot || reservedSourceGroup.profileId !== profileId || restoredSourceGroup.profileId !== profileId || journalGroup.profileId !== profileId || reservedSourceGroup.symbol !== symbol2.toUpperCase() || restoredSourceGroup.symbol !== symbol2.toUpperCase() || journalGroup.symbol !== symbol2.toUpperCase() || replacement.previousOrderId !== input.previousOrderId || replacement.mutationId !== input.mutationId) return false;
|
|
104798
|
-
const
|
|
105383
|
+
const groups3 = readFreshClientProtectiveGroups(profileId, symbol2);
|
|
104799
105384
|
if (hasClientProtectiveGroupReadFailure(profileId, symbol2)) return false;
|
|
104800
|
-
const reservedSourceMatches =
|
|
104801
|
-
const journalEntryMatches =
|
|
105385
|
+
const reservedSourceMatches = groups3.filter((group) => exactClientProtectiveGroupSnapshot(group) === reservedSourceSnapshot);
|
|
105386
|
+
const journalEntryMatches = groups3.filter((group) => group.entryOrderId === journalGroup.entryOrderId);
|
|
104802
105387
|
const exactJournalMatches = journalEntryMatches.filter((group) => exactClientProtectiveGroupSnapshot(group) === journalSnapshot);
|
|
104803
|
-
const conflictingMutationOwners =
|
|
104804
|
-
const sourceEntryMatches =
|
|
105388
|
+
const conflictingMutationOwners = groups3.flatMap((group) => group.legs.filter((leg) => leg.replacement?.mutationId === input.mutationId && exactClientProtectiveGroupSnapshot(group) !== reservedSourceSnapshot));
|
|
105389
|
+
const sourceEntryMatches = groups3.filter((group) => group.entryOrderId === reservedSourceGroup.entryOrderId);
|
|
104805
105390
|
if (reservedSourceMatches.length > 1 || journalEntryMatches.length !== exactJournalMatches.length || exactJournalMatches.length > 1 || conflictingMutationOwners.length > 0 || sourceEntryMatches.length > 1) return false;
|
|
104806
105391
|
if (reservedSourceMatches.length === 0 && exactJournalMatches.length === 0) {
|
|
104807
105392
|
return true;
|
|
104808
105393
|
}
|
|
104809
|
-
const nextGroups =
|
|
105394
|
+
const nextGroups = groups3.flatMap((group) => {
|
|
104810
105395
|
const snapshot = exactClientProtectiveGroupSnapshot(group);
|
|
104811
105396
|
if (snapshot === reservedSourceSnapshot) return [restoredSourceGroup];
|
|
104812
105397
|
if (snapshot === journalSnapshot) return [];
|
|
104813
105398
|
return [group];
|
|
104814
105399
|
});
|
|
104815
|
-
return replaceExactClientProtectiveGroupSet(profileId, symbol2,
|
|
105400
|
+
return replaceExactClientProtectiveGroupSet(profileId, symbol2, groups3, nextGroups);
|
|
104816
105401
|
}
|
|
104817
105402
|
const entryOrderId = String(input.entryOrderId).trim();
|
|
104818
|
-
const
|
|
105403
|
+
const groups2 = readFreshClientProtectiveGroups(profileId, symbol2);
|
|
104819
105404
|
if (hasClientProtectiveGroupReadFailure(profileId, symbol2)) {
|
|
104820
105405
|
return false;
|
|
104821
105406
|
}
|
|
@@ -104830,7 +105415,7 @@ var init_runtime_execution = __esm({
|
|
|
104830
105415
|
return false;
|
|
104831
105416
|
}
|
|
104832
105417
|
const matchingSnapshot = exactClientProtectiveGroupSnapshot(pendingGroup);
|
|
104833
|
-
const exactMatches =
|
|
105418
|
+
const exactMatches = groups2.filter((group) => exactClientProtectiveGroupSnapshot(group) === matchingSnapshot);
|
|
104834
105419
|
if (exactMatches.length === 0) {
|
|
104835
105420
|
windowHandoffCleanupAttempts.delete(cleanupAttemptKey);
|
|
104836
105421
|
return true;
|
|
@@ -104840,15 +105425,15 @@ var init_runtime_execution = __esm({
|
|
|
104840
105425
|
const persisted2 = replaceExactClientProtectiveGroupSet(
|
|
104841
105426
|
profileId,
|
|
104842
105427
|
symbol2,
|
|
104843
|
-
|
|
104844
|
-
|
|
105428
|
+
groups2,
|
|
105429
|
+
groups2.filter((group) => exactClientProtectiveGroupSnapshot(group) !== matchingSnapshot)
|
|
104845
105430
|
);
|
|
104846
105431
|
if (persisted2) {
|
|
104847
105432
|
windowHandoffCleanupAttempts.delete(cleanupAttemptKey);
|
|
104848
105433
|
}
|
|
104849
105434
|
return persisted2;
|
|
104850
105435
|
}
|
|
104851
|
-
const matchingGroups =
|
|
105436
|
+
const matchingGroups = groups2.filter((group) => group.entryOrderId === entryOrderId);
|
|
104852
105437
|
if (matchingGroups.length === 0 && windowHandoffCleanupAttempts.has(cleanupAttemptKey)) {
|
|
104853
105438
|
windowHandoffCleanupAttempts.delete(cleanupAttemptKey);
|
|
104854
105439
|
return true;
|
|
@@ -104911,9 +105496,9 @@ var init_runtime_execution = __esm({
|
|
|
104911
105496
|
);
|
|
104912
105497
|
};
|
|
104913
105498
|
replaceProtectiveLeg = (profileId, symbol2, previousOrderId, replacement) => {
|
|
104914
|
-
const
|
|
105499
|
+
const groups2 = readFreshClientProtectiveGroups(profileId, symbol2);
|
|
104915
105500
|
if (hasClientProtectiveGroupReadFailure(profileId, symbol2)) return false;
|
|
104916
|
-
const matches2 =
|
|
105501
|
+
const matches2 = groups2.flatMap((group2) => group2.legs.some((leg) => leg.orderId === previousOrderId) ? [group2] : []);
|
|
104917
105502
|
if (matches2.length !== 1) return false;
|
|
104918
105503
|
const [group] = matches2;
|
|
104919
105504
|
if (group.legs.filter((leg) => leg.orderId === previousOrderId).length !== 1) return false;
|
|
@@ -104981,25 +105566,25 @@ var init_runtime_execution = __esm({
|
|
|
104981
105566
|
};
|
|
104982
105567
|
};
|
|
104983
105568
|
ensureProtectiveReplacementJournalCompanion = (input) => {
|
|
104984
|
-
const
|
|
105569
|
+
const groups2 = readFreshClientProtectiveGroups(input.profileId, input.symbol);
|
|
104985
105570
|
if (hasClientProtectiveGroupReadFailure(input.profileId, input.symbol)) return null;
|
|
104986
105571
|
const sourceSnapshot = exactClientProtectiveGroupSnapshot(input.sourceGroup);
|
|
104987
|
-
const sourceMatches =
|
|
105572
|
+
const sourceMatches = groups2.filter((group) => exactClientProtectiveGroupSnapshot(group) === sourceSnapshot);
|
|
104988
105573
|
const sourceLegSnapshot = stableProtectionSnapshot(input.sourceLeg);
|
|
104989
|
-
if (sourceMatches.length !== 1 || sourceMatches[0].legs.filter((leg) => stableProtectionSnapshot(leg) === sourceLegSnapshot).length !== 1 || stableProtectionSnapshot(input.sourceLeg.replacement) !== stableProtectionSnapshot(input.replacement) ||
|
|
105574
|
+
if (sourceMatches.length !== 1 || sourceMatches[0].legs.filter((leg) => stableProtectionSnapshot(leg) === sourceLegSnapshot).length !== 1 || stableProtectionSnapshot(input.sourceLeg.replacement) !== stableProtectionSnapshot(input.replacement) || groups2.flatMap((group) => group.legs.filter((leg) => leg.replacement?.mutationId === input.replacement.mutationId)).length !== 1) return null;
|
|
104990
105575
|
const journalGroup = buildProtectiveReplacementJournalGroup({
|
|
104991
105576
|
sourceGroup: input.sourceGroup,
|
|
104992
105577
|
sourceLeg: { ...input.sourceLeg, replacement: void 0 },
|
|
104993
105578
|
replacement: input.replacement
|
|
104994
105579
|
});
|
|
104995
105580
|
const journalSnapshot = exactClientProtectiveGroupSnapshot(journalGroup);
|
|
104996
|
-
const journalEntryMatches =
|
|
105581
|
+
const journalEntryMatches = groups2.filter((group) => group.entryOrderId === journalGroup.entryOrderId);
|
|
104997
105582
|
if (journalEntryMatches.length > 1 || journalEntryMatches.length === 1 && exactClientProtectiveGroupSnapshot(journalEntryMatches[0]) !== journalSnapshot) return null;
|
|
104998
|
-
const nextGroups = journalEntryMatches.length === 1 ?
|
|
105583
|
+
const nextGroups = journalEntryMatches.length === 1 ? groups2 : [...groups2, journalGroup];
|
|
104999
105584
|
if (!replaceExactClientProtectiveGroupSet(
|
|
105000
105585
|
input.profileId,
|
|
105001
105586
|
input.symbol,
|
|
105002
|
-
|
|
105587
|
+
groups2,
|
|
105003
105588
|
nextGroups
|
|
105004
105589
|
)) return null;
|
|
105005
105590
|
return {
|
|
@@ -105034,12 +105619,12 @@ var init_runtime_execution = __esm({
|
|
|
105034
105619
|
input.reservation.groups
|
|
105035
105620
|
);
|
|
105036
105621
|
transitionProtectiveReplacementAcknowledgement = (input) => {
|
|
105037
|
-
const
|
|
105622
|
+
const groups2 = readFreshClientProtectiveGroups(input.profileId, input.symbol);
|
|
105038
105623
|
if (hasClientProtectiveGroupReadFailure(input.profileId, input.symbol)) return null;
|
|
105039
105624
|
const sourceSnapshot = exactClientProtectiveGroupSnapshot(input.reservation.sourceGroup);
|
|
105040
105625
|
const journalSnapshot = exactClientProtectiveGroupSnapshot(input.reservation.journalGroup);
|
|
105041
|
-
const sourceMatches =
|
|
105042
|
-
const journalMatches =
|
|
105626
|
+
const sourceMatches = groups2.filter((group) => exactClientProtectiveGroupSnapshot(group) === sourceSnapshot);
|
|
105627
|
+
const journalMatches = groups2.filter((group) => exactClientProtectiveGroupSnapshot(group) === journalSnapshot);
|
|
105043
105628
|
if (journalMatches.length !== 1) return null;
|
|
105044
105629
|
const canonicalLeg = {
|
|
105045
105630
|
...input.replacementLeg ?? input.reservation.sourceLeg,
|
|
@@ -105054,7 +105639,7 @@ var init_runtime_execution = __esm({
|
|
|
105054
105639
|
...input.state === "fulfilled" ? { cleanupRequired: true } : {},
|
|
105055
105640
|
legs: input.reservation.sourceGroup.legs.map((leg) => stableProtectionSnapshot(leg) === stableProtectionSnapshot(input.reservation.sourceLeg) ? canonicalLeg : leg)
|
|
105056
105641
|
};
|
|
105057
|
-
const nextGroups2 =
|
|
105642
|
+
const nextGroups2 = groups2.flatMap((group) => {
|
|
105058
105643
|
const snapshot = exactClientProtectiveGroupSnapshot(group);
|
|
105059
105644
|
if (snapshot === sourceSnapshot) return [sourceGroup];
|
|
105060
105645
|
if (snapshot === journalSnapshot) return [];
|
|
@@ -105063,7 +105648,7 @@ var init_runtime_execution = __esm({
|
|
|
105063
105648
|
return replaceExactClientProtectiveGroupSet(
|
|
105064
105649
|
input.profileId,
|
|
105065
105650
|
input.symbol,
|
|
105066
|
-
|
|
105651
|
+
groups2,
|
|
105067
105652
|
nextGroups2
|
|
105068
105653
|
) ? { kind: "source_bound", groups: nextGroups2 } : null;
|
|
105069
105654
|
}
|
|
@@ -105071,27 +105656,27 @@ var init_runtime_execution = __esm({
|
|
|
105071
105656
|
...input.reservation.journalGroup,
|
|
105072
105657
|
legs: [canonicalLeg]
|
|
105073
105658
|
};
|
|
105074
|
-
const nextGroups =
|
|
105659
|
+
const nextGroups = groups2.map((group) => exactClientProtectiveGroupSnapshot(group) === journalSnapshot ? cleanupJournal : group);
|
|
105075
105660
|
return replaceExactClientProtectiveGroupSet(
|
|
105076
105661
|
input.profileId,
|
|
105077
105662
|
input.symbol,
|
|
105078
|
-
|
|
105663
|
+
groups2,
|
|
105079
105664
|
nextGroups
|
|
105080
105665
|
) ? { kind: "cleanup_retained", groups: nextGroups } : null;
|
|
105081
105666
|
};
|
|
105082
105667
|
transitionTerminalProtectiveReplacement = (input) => {
|
|
105083
|
-
const
|
|
105668
|
+
const groups2 = readFreshClientProtectiveGroups(input.profileId, input.symbol);
|
|
105084
105669
|
if (hasClientProtectiveGroupReadFailure(input.profileId, input.symbol)) return false;
|
|
105085
105670
|
const sourceSnapshot = exactClientProtectiveGroupSnapshot(input.sourceGroup);
|
|
105086
105671
|
const journalSnapshot = input.journalGroup == null ? null : exactClientProtectiveGroupSnapshot(input.journalGroup);
|
|
105087
|
-
if (
|
|
105088
|
-
if (journalSnapshot != null &&
|
|
105672
|
+
if (groups2.filter((group) => exactClientProtectiveGroupSnapshot(group) === sourceSnapshot).length !== 1) return false;
|
|
105673
|
+
if (journalSnapshot != null && groups2.filter((group) => exactClientProtectiveGroupSnapshot(group) === journalSnapshot).length !== 1) return false;
|
|
105089
105674
|
const clearedLeg = { ...input.sourceLeg, replacement: void 0 };
|
|
105090
105675
|
const clearedGroup = {
|
|
105091
105676
|
...input.sourceGroup,
|
|
105092
105677
|
legs: input.sourceGroup.legs.map((leg) => stableProtectionSnapshot(leg) === stableProtectionSnapshot(input.sourceLeg) ? clearedLeg : leg)
|
|
105093
105678
|
};
|
|
105094
|
-
const nextGroups =
|
|
105679
|
+
const nextGroups = groups2.flatMap((group) => {
|
|
105095
105680
|
const snapshot = exactClientProtectiveGroupSnapshot(group);
|
|
105096
105681
|
if (snapshot === sourceSnapshot) return [clearedGroup];
|
|
105097
105682
|
if (journalSnapshot != null && snapshot === journalSnapshot) return [];
|
|
@@ -105100,7 +105685,7 @@ var init_runtime_execution = __esm({
|
|
|
105100
105685
|
return replaceExactClientProtectiveGroupSet(
|
|
105101
105686
|
input.profileId,
|
|
105102
105687
|
input.symbol,
|
|
105103
|
-
|
|
105688
|
+
groups2,
|
|
105104
105689
|
nextGroups
|
|
105105
105690
|
);
|
|
105106
105691
|
};
|
|
@@ -105162,12 +105747,12 @@ var init_runtime_execution = __esm({
|
|
|
105162
105747
|
const symbol2 = request.executionContext.symbol;
|
|
105163
105748
|
try {
|
|
105164
105749
|
const profileId = String(request.profileId).trim();
|
|
105165
|
-
const
|
|
105750
|
+
const groups2 = readFreshClientProtectiveGroups(profileId, symbol2);
|
|
105166
105751
|
if (hasClientProtectiveGroupReadFailure(profileId, symbol2)) {
|
|
105167
105752
|
throw new Error("Protective cleanup authority could not be read durably.");
|
|
105168
105753
|
}
|
|
105169
|
-
const exactOwnerGroups =
|
|
105170
|
-
const acknowledgedOwnerMatches = exactOwnerGroups.length === 0 && acknowledgedAuthority != null ?
|
|
105754
|
+
const exactOwnerGroups = groups2.filter((group) => group.isLong === isLong && group.legs.some((candidate) => String(candidate.orderId) === String(leg.orderId)));
|
|
105755
|
+
const acknowledgedOwnerMatches = exactOwnerGroups.length === 0 && acknowledgedAuthority != null ? groups2.flatMap((group) => group.isLong === isLong ? group.legs.flatMap((candidate, legIndex) => {
|
|
105171
105756
|
if (String(candidate.orderId) !== String(acknowledgedAuthority.persistedOrderId)) {
|
|
105172
105757
|
return [];
|
|
105173
105758
|
}
|
|
@@ -105190,7 +105775,7 @@ var init_runtime_execution = __esm({
|
|
|
105190
105775
|
throw new Error("Acknowledged protective cleanup authority could not be bound durably.");
|
|
105191
105776
|
}
|
|
105192
105777
|
}
|
|
105193
|
-
const journalOwnerGroups = exactOwnerGroups.length === 0 && acknowledgedOwnerGroup == null ?
|
|
105778
|
+
const journalOwnerGroups = exactOwnerGroups.length === 0 && acknowledgedOwnerGroup == null ? groups2.filter((group) => group.isLong === isLong && group.cleanupRequired === true && group.attachmentJournal != null && group.legs.some((candidate) => candidate.kind === leg.kind && candidate.size === leg.size && candidate.triggerPrice === leg.triggerPrice && candidate.positionTpsl === true === (leg.positionTpsl === true))) : [];
|
|
105194
105779
|
const ownerGroups = exactOwnerGroups.length > 0 ? exactOwnerGroups : acknowledgedOwnerGroup != null ? [acknowledgedOwnerGroup] : journalOwnerGroups;
|
|
105195
105780
|
if (ownerGroups.length !== 1) {
|
|
105196
105781
|
throw new Error("Protective cleanup authority is not exact.");
|
|
@@ -105351,8 +105936,8 @@ var init_runtime_execution = __esm({
|
|
|
105351
105936
|
return { group, cleanup, persistedGroupSet: persistenceFailed ? null : nextGroups };
|
|
105352
105937
|
};
|
|
105353
105938
|
attachmentMemberNeverLanded = (group, leg) => group.attachmentJournal?.members.some((member) => member.clientOrderId === leg.orderId && member.neverLandedAtMs != null) === true;
|
|
105354
|
-
storedClientProtectiveCover = async (request, entryIsLong,
|
|
105355
|
-
const storedLegs =
|
|
105939
|
+
storedClientProtectiveCover = async (request, entryIsLong, groups2) => {
|
|
105940
|
+
const storedLegs = groups2.filter((group) => group.isLong === entryIsLong).flatMap((group) => group.legs.map((leg) => ({
|
|
105356
105941
|
isLong: group.isLong,
|
|
105357
105942
|
kind: leg.kind,
|
|
105358
105943
|
size: leg.size,
|
|
@@ -105568,7 +106153,8 @@ var init_runtime_execution = __esm({
|
|
|
105568
106153
|
const { sz_decimals: assetSizeDecimals } = await resolveHyperliquidAsset({
|
|
105569
106154
|
symbol: symbol2,
|
|
105570
106155
|
config: request.config,
|
|
105571
|
-
publicRequestPriority: "trading_reduce"
|
|
106156
|
+
publicRequestPriority: "trading_reduce",
|
|
106157
|
+
profileId
|
|
105572
106158
|
});
|
|
105573
106159
|
const candidates = allocatedCandidates.map((candidate) => ({
|
|
105574
106160
|
...candidate,
|
|
@@ -107041,11 +107627,11 @@ var init_runtime_execution = __esm({
|
|
|
107041
107627
|
}
|
|
107042
107628
|
return reports;
|
|
107043
107629
|
};
|
|
107044
|
-
recoverPendingProtectiveReplacements = async (request,
|
|
107630
|
+
recoverPendingProtectiveReplacements = async (request, groups2) => {
|
|
107045
107631
|
const reports = [];
|
|
107046
107632
|
const profileId = String(request.profileId).trim();
|
|
107047
107633
|
const symbol2 = request.executionContext.symbol;
|
|
107048
|
-
for (const group of
|
|
107634
|
+
for (const group of groups2) {
|
|
107049
107635
|
for (const leg of group.legs) {
|
|
107050
107636
|
const replacement = leg.replacement;
|
|
107051
107637
|
if (!replacement) continue;
|
|
@@ -107444,7 +108030,7 @@ var init_runtime_execution = __esm({
|
|
|
107444
108030
|
}
|
|
107445
108031
|
}
|
|
107446
108032
|
}
|
|
107447
|
-
for (const journalGroup of
|
|
108033
|
+
for (const journalGroup of groups2.filter(isProtectiveReplacementJournalGroup)) {
|
|
107448
108034
|
const mutationId = journalGroup.entryOrderId.slice("replacement-journal:".length);
|
|
107449
108035
|
const currentGroups = readFreshClientProtectiveGroups(profileId, symbol2);
|
|
107450
108036
|
if (hasClientProtectiveGroupReadFailure(profileId, symbol2)) {
|
|
@@ -107864,8 +108450,8 @@ var init_runtime_execution = __esm({
|
|
|
107864
108450
|
expectedGroupSet = expectedGroupSet.flatMap((candidate) => exactClientProtectiveGroupSnapshot(candidate) === expectedSnapshot ? replacement == null ? [] : [replacement] : [candidate]);
|
|
107865
108451
|
return true;
|
|
107866
108452
|
};
|
|
107867
|
-
const
|
|
107868
|
-
if (
|
|
108453
|
+
const groups2 = reconciliationGroupSet.filter((group) => group.pendingEntry == null && group.legs.length > 0 && !isProtectiveReplacementJournalGroup(group));
|
|
108454
|
+
if (groups2.length === 0) {
|
|
107869
108455
|
return reports;
|
|
107870
108456
|
}
|
|
107871
108457
|
let livePositionSize = Number(knownPositionSize);
|
|
@@ -107880,7 +108466,7 @@ var init_runtime_execution = __esm({
|
|
|
107880
108466
|
);
|
|
107881
108467
|
livePositionSize = Number(snapshot.size);
|
|
107882
108468
|
} catch (error48) {
|
|
107883
|
-
return
|
|
108469
|
+
return groups2.flatMap((group) => group.legs.map((leg) => ({
|
|
107884
108470
|
order_id: String(leg.orderId),
|
|
107885
108471
|
symbol: symbol2,
|
|
107886
108472
|
action: protectiveAction(leg),
|
|
@@ -107903,7 +108489,7 @@ var init_runtime_execution = __esm({
|
|
|
107903
108489
|
}
|
|
107904
108490
|
liveOrders = fetchedOrders;
|
|
107905
108491
|
} catch (error48) {
|
|
107906
|
-
return
|
|
108492
|
+
return groups2.flatMap((group) => group.legs.map((leg) => ({
|
|
107907
108493
|
order_id: String(leg.orderId),
|
|
107908
108494
|
symbol: symbol2,
|
|
107909
108495
|
action: protectiveAction(leg),
|
|
@@ -107964,7 +108550,7 @@ var init_runtime_execution = __esm({
|
|
|
107964
108550
|
};
|
|
107965
108551
|
const inspectedGroups = [];
|
|
107966
108552
|
const legsLiveSinceMs = protectiveReadStampMs();
|
|
107967
|
-
for (const observedGroup of
|
|
108553
|
+
for (const observedGroup of groups2) {
|
|
107968
108554
|
let group = observedGroup;
|
|
107969
108555
|
const standaloneGroup = observedStandaloneProtectiveGroup(group, liveOrders, symbol2);
|
|
107970
108556
|
if (standaloneGroup != null) {
|
|
@@ -108943,7 +109529,7 @@ var init_runtime_execution = __esm({
|
|
|
108943
109529
|
cancelAllClientProtectiveGroups = async (request, reasonCode) => {
|
|
108944
109530
|
const profileId = String(request.profileId).trim();
|
|
108945
109531
|
const symbol2 = request.executionContext.symbol;
|
|
108946
|
-
const
|
|
109532
|
+
const groups2 = readFreshClientProtectiveGroups(profileId, symbol2);
|
|
108947
109533
|
const reports = [];
|
|
108948
109534
|
if (hasClientProtectiveGroupReadFailure(profileId, symbol2)) {
|
|
108949
109535
|
return [{
|
|
@@ -108956,9 +109542,9 @@ var init_runtime_execution = __esm({
|
|
|
108956
109542
|
}
|
|
108957
109543
|
}];
|
|
108958
109544
|
}
|
|
108959
|
-
let expectedGroups =
|
|
109545
|
+
let expectedGroups = groups2;
|
|
108960
109546
|
const retainedGroups = [];
|
|
108961
|
-
for (const group of
|
|
109547
|
+
for (const group of groups2) {
|
|
108962
109548
|
if (group.pendingEntry != null || group.attachmentJournal != null || isProtectiveReplacementJournalGroup(group)) {
|
|
108963
109549
|
retainedGroups.push(group);
|
|
108964
109550
|
reports.push({
|
|
@@ -109090,7 +109676,8 @@ var init_runtime_execution = __esm({
|
|
|
109090
109676
|
const { sz_decimals: assetSizeDecimals } = await resolveHyperliquidAsset({
|
|
109091
109677
|
symbol: symbol2,
|
|
109092
109678
|
config: request.config,
|
|
109093
|
-
publicRequestPriority: "trading_reduce"
|
|
109679
|
+
publicRequestPriority: "trading_reduce",
|
|
109680
|
+
profileId
|
|
109094
109681
|
});
|
|
109095
109682
|
const reports = [];
|
|
109096
109683
|
const updated = [...retained];
|
|
@@ -109393,11 +109980,12 @@ var init_runtime_execution = __esm({
|
|
|
109393
109980
|
});
|
|
109394
109981
|
};
|
|
109395
109982
|
isDefinitiveEntryRejection = (error48, entryMutationId) => error48 instanceof HyperliquidExchangeRejectionError && Boolean(entryMutationId) && String(error48.clientMutationId ?? "").trim().toLowerCase() === String(entryMutationId).trim().toLowerCase();
|
|
109396
|
-
resolveExchangeSizeDecimals = async (symbol2, config2, publicRequestPriority) => {
|
|
109983
|
+
resolveExchangeSizeDecimals = async (symbol2, config2, publicRequestPriority, profileId) => {
|
|
109397
109984
|
const { sz_decimals: sizeDecimals } = await resolveHyperliquidAsset({
|
|
109398
109985
|
symbol: symbol2,
|
|
109399
109986
|
config: config2,
|
|
109400
|
-
publicRequestPriority
|
|
109987
|
+
publicRequestPriority,
|
|
109988
|
+
profileId
|
|
109401
109989
|
});
|
|
109402
109990
|
if (!Number.isInteger(sizeDecimals) || sizeDecimals < 0) {
|
|
109403
109991
|
throw new Error(`Hyperliquid size precision is unavailable for ${symbol2}.`);
|
|
@@ -109437,6 +110025,7 @@ var init_runtime_execution = __esm({
|
|
|
109437
110025
|
const asset = await resolveHyperliquidAsset({
|
|
109438
110026
|
symbol: input.executionContext.symbol,
|
|
109439
110027
|
config: input.config ?? void 0,
|
|
110028
|
+
profileId: input.profileId,
|
|
109440
110029
|
publicRequestPriority: executionReadPriority(input),
|
|
109441
110030
|
refreshCatalog: true
|
|
109442
110031
|
});
|
|
@@ -110000,12 +110589,12 @@ var init_runtime_execution = __esm({
|
|
|
110000
110589
|
const maxAge = Number(context.executionFreshnessMaxAgeSeconds) * MS_PER_SECOND;
|
|
110001
110590
|
const age = Date.now() - capturedAt;
|
|
110002
110591
|
if (!context.tpSlEnabled || context.stopLossEnabled === false || context.stopLossType !== "trailing" || !Number.isFinite(age) || age < 0 || !Number.isFinite(maxAge) || maxAge <= 0 || age > maxAge || !Number.isFinite(context.currentPositionSize) || context.currentPositionSize === 0 || !Number.isFinite(context.lastPrice) || context.lastPrice <= 0) return [];
|
|
110003
|
-
const
|
|
110004
|
-
if (hasClientProtectiveGroupReadFailure(String(request.profileId).trim(), context.symbol) ||
|
|
110005
|
-
if (!
|
|
110006
|
-
const assetSizeDecimals = await resolveExchangeSizeDecimals(context.symbol, request.config ?? void 0, "trading_reduce");
|
|
110592
|
+
const groups2 = readFreshClientProtectiveGroups(String(request.profileId).trim(), context.symbol);
|
|
110593
|
+
if (hasClientProtectiveGroupReadFailure(String(request.profileId).trim(), context.symbol) || groups2.some((group) => group.walletAddress !== String(context.walletAddress ?? "").trim().toLowerCase() || group.pendingEntry || group.attachmentJournal || group.cleanupRequired || group.legs.some((leg) => leg.replacement))) return [];
|
|
110594
|
+
if (!groups2.some((group) => group.legs.some((leg) => leg.isTrailing && typeof leg.orderId === "number"))) return [];
|
|
110595
|
+
const assetSizeDecimals = await resolveExchangeSizeDecimals(context.symbol, request.config ?? void 0, "trading_reduce", request.profileId);
|
|
110007
110596
|
const isLong = context.currentPositionSize > 0;
|
|
110008
|
-
const improves =
|
|
110597
|
+
const improves = groups2.some((group) => group.isLong === isLong && group.legs.some((leg) => {
|
|
110009
110598
|
if (!leg.isTrailing || typeof leg.orderId !== "number") return false;
|
|
110010
110599
|
const size = roundAssetSize(Math.min(leg.size, Math.abs(context.currentPositionSize)), assetSizeDecimals);
|
|
110011
110600
|
if (!(size > 0)) return false;
|
|
@@ -110069,23 +110658,23 @@ var init_runtime_execution = __esm({
|
|
|
110069
110658
|
}
|
|
110070
110659
|
return [...symbols].sort();
|
|
110071
110660
|
};
|
|
110072
|
-
hasUnresolvedClientProtectiveIdentity = (
|
|
110661
|
+
hasUnresolvedClientProtectiveIdentity = (groups2) => groups2.some((group) => isProtectiveReplacementJournalGroup(group) || group.legs.some((leg) => leg.replacement != null));
|
|
110073
110662
|
resolveClientProtectiveIdentitiesForAdoption = async (input) => {
|
|
110074
110663
|
const profileId = String(input.profileId ?? "").trim();
|
|
110075
110664
|
const walletAddress = String(input.walletAddress ?? "").trim();
|
|
110076
110665
|
const reports = [];
|
|
110077
110666
|
const deferred = [];
|
|
110078
|
-
const ownGroups = (
|
|
110667
|
+
const ownGroups = (groups2) => groups2.filter((group) => group.walletAddress === walletAddress.toLowerCase());
|
|
110079
110668
|
for (const symbol2 of listStoredClientProtectiveSymbols(profileId)) {
|
|
110080
|
-
const
|
|
110669
|
+
const groups2 = ownGroups(readFreshClientProtectiveGroups(profileId, symbol2));
|
|
110081
110670
|
if (hasClientProtectiveGroupReadFailure(profileId, symbol2)) {
|
|
110082
110671
|
deferred.push({ symbol: symbol2, reasonCode: "protective_lifecycle_storage_invalid" });
|
|
110083
110672
|
continue;
|
|
110084
110673
|
}
|
|
110085
|
-
if (!hasUnresolvedClientProtectiveIdentity(
|
|
110674
|
+
if (!hasUnresolvedClientProtectiveIdentity(groups2)) continue;
|
|
110086
110675
|
let symbolReports = [];
|
|
110087
110676
|
try {
|
|
110088
|
-
const sizeDecimals = await resolveExchangeSizeDecimals(symbol2, input.config, "trading_reconcile");
|
|
110677
|
+
const sizeDecimals = await resolveExchangeSizeDecimals(symbol2, input.config, "trading_reconcile", profileId);
|
|
110089
110678
|
const core = {
|
|
110090
110679
|
profileId,
|
|
110091
110680
|
config: input.config,
|
|
@@ -110102,7 +110691,7 @@ var init_runtime_execution = __esm({
|
|
|
110102
110691
|
runtimeDeviceId: authority.runtimeDeviceId,
|
|
110103
110692
|
schedulerInstanceId: authority.schedulerInstanceId
|
|
110104
110693
|
} : { ...core, mutationAuthority: "manual_session" },
|
|
110105
|
-
|
|
110694
|
+
groups2
|
|
110106
110695
|
);
|
|
110107
110696
|
} catch (error48) {
|
|
110108
110697
|
if (isClientRuntimeLeaseOwnershipError(error48)) throw error48;
|
|
@@ -110134,12 +110723,12 @@ var init_runtime_execution = __esm({
|
|
|
110134
110723
|
exportClientProtectiveGroupsForAdoption = (profileId, walletAddress) => {
|
|
110135
110724
|
const normalizedProfileId = String(profileId ?? "").trim();
|
|
110136
110725
|
const normalizedWallet = String(walletAddress ?? "").trim().toLowerCase();
|
|
110137
|
-
const
|
|
110726
|
+
const groups2 = [];
|
|
110138
110727
|
for (const symbol2 of listStoredClientProtectiveSymbols(normalizedProfileId)) {
|
|
110139
110728
|
for (const group of readClientProtectiveGroups(normalizedProfileId, symbol2)) {
|
|
110140
110729
|
if (group.walletAddress !== normalizedWallet) continue;
|
|
110141
110730
|
const journal = group.attachmentJournal;
|
|
110142
|
-
|
|
110731
|
+
groups2.push({
|
|
110143
110732
|
entry_mutation_id: group.pendingEntry?.entryMutationId ?? null,
|
|
110144
110733
|
symbol: group.symbol,
|
|
110145
110734
|
is_long: group.isLong,
|
|
@@ -110176,10 +110765,10 @@ var init_runtime_execution = __esm({
|
|
|
110176
110765
|
});
|
|
110177
110766
|
}
|
|
110178
110767
|
}
|
|
110179
|
-
return
|
|
110768
|
+
return groups2;
|
|
110180
110769
|
};
|
|
110181
110770
|
adoptionGroupKey = (group) => `${group.symbol}|${group.entry_order_id ?? ""}|${group.entry_mutation_id ?? ""}`;
|
|
110182
|
-
applyClientProtectiveAdoptionOutcomes = (profileId, walletAddress,
|
|
110771
|
+
applyClientProtectiveAdoptionOutcomes = (profileId, walletAddress, groups2, legOutcomes) => {
|
|
110183
110772
|
const normalizedProfileId = String(profileId ?? "").trim();
|
|
110184
110773
|
const normalizedWallet = String(walletAddress ?? "").trim().toLowerCase();
|
|
110185
110774
|
const application = {
|
|
@@ -110197,7 +110786,7 @@ var init_runtime_execution = __esm({
|
|
|
110197
110786
|
}
|
|
110198
110787
|
const dispositions = /* @__PURE__ */ new Map();
|
|
110199
110788
|
const exportedDroppedOrderIds = /* @__PURE__ */ new Set();
|
|
110200
|
-
|
|
110789
|
+
groups2.forEach((group, groupIndex) => {
|
|
110201
110790
|
const dropped = droppedLegIndexes.get(groupIndex) ?? /* @__PURE__ */ new Set();
|
|
110202
110791
|
const disposition = { retainedKinds: /* @__PURE__ */ new Set(), droppedKinds: /* @__PURE__ */ new Set() };
|
|
110203
110792
|
group.legs.forEach((leg, legIndex) => {
|
|
@@ -110288,8 +110877,8 @@ var init_runtime_execution = __esm({
|
|
|
110288
110877
|
const normalizedWallet = String(walletAddress ?? "").trim().toLowerCase();
|
|
110289
110878
|
if (!normalizedWallet) return false;
|
|
110290
110879
|
return listStoredClientProtectiveSymbols(normalizedProfileId).some((symbol2) => {
|
|
110291
|
-
const
|
|
110292
|
-
return hasClientProtectiveGroupReadFailure(normalizedProfileId, symbol2) ||
|
|
110880
|
+
const groups2 = readClientProtectiveGroups(normalizedProfileId, symbol2);
|
|
110881
|
+
return hasClientProtectiveGroupReadFailure(normalizedProfileId, symbol2) || groups2.some((group) => group.walletAddress === normalizedWallet);
|
|
110293
110882
|
});
|
|
110294
110883
|
};
|
|
110295
110884
|
hasPendingClientProtectiveGroups = (profileId) => listPendingClientProtectiveSymbols(String(profileId ?? "").trim()).length > 0;
|
|
@@ -110302,7 +110891,7 @@ var init_runtime_execution = __esm({
|
|
|
110302
110891
|
throwIfAborted2(input.signal);
|
|
110303
110892
|
const retired = [];
|
|
110304
110893
|
const reports = await withClientProtectivePlanSetMutation({ profileId, signal: input.signal }, symbol2, async () => {
|
|
110305
|
-
const
|
|
110894
|
+
const groups2 = readFreshClientProtectiveGroups(profileId, symbol2);
|
|
110306
110895
|
if (hasClientProtectiveGroupReadFailure(profileId, symbol2)) {
|
|
110307
110896
|
return [{
|
|
110308
110897
|
order_id: null,
|
|
@@ -110312,10 +110901,10 @@ var init_runtime_execution = __esm({
|
|
|
110312
110901
|
execution_metadata: { reason_code: "protective_lifecycle_storage_invalid" }
|
|
110313
110902
|
}];
|
|
110314
110903
|
}
|
|
110315
|
-
const ownGroups =
|
|
110904
|
+
const ownGroups = groups2.filter((group) => group.pendingEntry != null && group.walletAddress === walletAddress.toLowerCase());
|
|
110316
110905
|
if (ownGroups.length === 0) return [];
|
|
110317
110906
|
input.beforeRead?.();
|
|
110318
|
-
const sizeDecimals = await resolveExchangeSizeDecimals(symbol2, input.config, "trading_reconcile");
|
|
110907
|
+
const sizeDecimals = await resolveExchangeSizeDecimals(symbol2, input.config, "trading_reconcile", profileId);
|
|
110319
110908
|
const request = {
|
|
110320
110909
|
mutationAuthority: "manual_session",
|
|
110321
110910
|
profileId,
|
|
@@ -110458,7 +111047,8 @@ var init_runtime_execution = __esm({
|
|
|
110458
111047
|
sizeDecimals: await resolveExchangeSizeDecimals(
|
|
110459
111048
|
unsizedInput.executionContext.symbol,
|
|
110460
111049
|
unsizedInput.config ?? void 0,
|
|
110461
|
-
unsizedInput.decision === "HOLD" || requestedUnits <= 0 ? "trading_reconcile" : executionReadPriority(unsizedInput)
|
|
111050
|
+
unsizedInput.decision === "HOLD" || requestedUnits <= 0 ? "trading_reconcile" : executionReadPriority(unsizedInput),
|
|
111051
|
+
unsizedInput.profileId
|
|
110462
111052
|
)
|
|
110463
111053
|
}
|
|
110464
111054
|
};
|
|
@@ -111678,7 +112268,8 @@ var init_runtime_execution = __esm({
|
|
|
111678
112268
|
const { sz_decimals: assetSizeDecimals } = await resolveHyperliquidAsset({
|
|
111679
112269
|
symbol: input.executionContext.symbol,
|
|
111680
112270
|
config: input.config,
|
|
111681
|
-
publicRequestPriority: "trading_reduce"
|
|
112271
|
+
publicRequestPriority: "trading_reduce",
|
|
112272
|
+
profileId: input.profileId
|
|
111682
112273
|
});
|
|
111683
112274
|
const provisionalLeg = {
|
|
111684
112275
|
kind,
|
|
@@ -112052,9 +112643,12 @@ var init_runtime_execution = __esm({
|
|
|
112052
112643
|
roundingMode: "nearest",
|
|
112053
112644
|
includePrivateContext: desiredPosition != null && Number.isFinite(desiredPosition),
|
|
112054
112645
|
// The device reads its own position and mark; the server never reads
|
|
112055
|
-
// a Client wallet.
|
|
112646
|
+
// a Client wallet. The bot's own profile and runtime config name the
|
|
112647
|
+
// market's execution row (a market VTX's cached list lacks is read here).
|
|
112056
112648
|
walletAddress: input.walletAddress,
|
|
112057
|
-
signal: input.signal
|
|
112649
|
+
signal: input.signal,
|
|
112650
|
+
profileId: input.profileId,
|
|
112651
|
+
config: input.config ?? null
|
|
112058
112652
|
});
|
|
112059
112653
|
if (desiredPosition != null && Number.isFinite(desiredPosition)) {
|
|
112060
112654
|
const preparedContextMaxAgeMs = Number(
|
|
@@ -112553,12 +113147,12 @@ var init_protective_cutover = __esm({
|
|
|
112553
113147
|
}
|
|
112554
113148
|
}
|
|
112555
113149
|
};
|
|
112556
|
-
adoptionLegOutcomes = (
|
|
113150
|
+
adoptionLegOutcomes = (groups2, adoption) => {
|
|
112557
113151
|
if (Array.isArray(adoption.leg_outcomes)) return adoption.leg_outcomes;
|
|
112558
113152
|
const groupOutcomes = new Map(
|
|
112559
113153
|
(adoption.group_outcomes ?? []).map((item) => [item.group_index, item.outcome])
|
|
112560
113154
|
);
|
|
112561
|
-
return
|
|
113155
|
+
return groups2.flatMap((group, groupIndex) => group.legs.map((leg, legIndex) => ({
|
|
112562
113156
|
group_index: groupIndex,
|
|
112563
113157
|
leg_index: legIndex,
|
|
112564
113158
|
leg_kind: leg.kind === "sl" ? "stop_loss" : leg.kind === "tp" ? "take_profit" : null,
|
|
@@ -112622,9 +113216,9 @@ var init_protective_cutover = __esm({
|
|
|
112622
113216
|
});
|
|
112623
113217
|
return null;
|
|
112624
113218
|
}
|
|
112625
|
-
const
|
|
113219
|
+
const groups2 = exportClientProtectiveGroupsForAdoption(input.profileId, input.walletAddress);
|
|
112626
113220
|
const reportedProtectiveOrderIds = [
|
|
112627
|
-
...new Set(
|
|
113221
|
+
...new Set(groups2.flatMap((group) => group.legs.map((leg) => String(leg.order_id ?? "").trim()).filter(Boolean)))
|
|
112628
113222
|
];
|
|
112629
113223
|
let openOrders;
|
|
112630
113224
|
try {
|
|
@@ -112635,7 +113229,7 @@ var init_protective_cutover = __esm({
|
|
|
112635
113229
|
signal: input.signal,
|
|
112636
113230
|
hyperliquidApiUrl: listedEvidence.hyperliquidApiUrl
|
|
112637
113231
|
},
|
|
112638
|
-
|
|
113232
|
+
groups2.map((group) => getHyperliquidMarketDex(normalizeHyperliquidMarketSymbol(group.symbol)))
|
|
112639
113233
|
);
|
|
112640
113234
|
} catch {
|
|
112641
113235
|
appendRuntimeDebugEvent({
|
|
@@ -112651,7 +113245,7 @@ var init_protective_cutover = __esm({
|
|
|
112651
113245
|
answer = await adoptWithinTimeout(
|
|
112652
113246
|
input.profileId,
|
|
112653
113247
|
{
|
|
112654
|
-
groups,
|
|
113248
|
+
groups: groups2,
|
|
112655
113249
|
reportedProtectiveOrderIds,
|
|
112656
113250
|
walletAddress: input.walletAddress,
|
|
112657
113251
|
openOrders: openOrdersEvidenceForUpload(openOrders)
|
|
@@ -112673,8 +113267,8 @@ var init_protective_cutover = __esm({
|
|
|
112673
113267
|
const { retainedLegs } = applyClientProtectiveAdoptionOutcomes(
|
|
112674
113268
|
input.profileId,
|
|
112675
113269
|
input.walletAddress,
|
|
112676
|
-
|
|
112677
|
-
adoptionLegOutcomes(
|
|
113270
|
+
groups2,
|
|
113271
|
+
adoptionLegOutcomes(groups2, answer)
|
|
112678
113272
|
);
|
|
112679
113273
|
if (retainedLegs > 0) {
|
|
112680
113274
|
adoptionRetryAt.set(
|
|
@@ -112833,8 +113427,8 @@ var init_provider_observability = __esm({
|
|
|
112833
113427
|
const characters = Array.from(value);
|
|
112834
113428
|
if (characters.length <= PROVIDER_DIAGNOSTIC_LIMITS.MAX_ERROR_MESSAGE_CHARS) return value;
|
|
112835
113429
|
let cut = characters.slice(0, PROVIDER_DIAGNOSTIC_LIMITS.MAX_ERROR_MESSAGE_CHARS).join("");
|
|
112836
|
-
const
|
|
112837
|
-
if (
|
|
113430
|
+
const marker2 = cut.lastIndexOf(REDACTED_MARKER_START);
|
|
113431
|
+
if (marker2 !== -1 && value.indexOf("]", marker2) >= cut.length) cut = cut.slice(0, marker2);
|
|
112838
113432
|
return cut.replace(/ +$/, "");
|
|
112839
113433
|
};
|
|
112840
113434
|
normalizeProviderError = (value) => {
|
|
@@ -116024,33 +116618,33 @@ var init_history_evidence = __esm({
|
|
|
116024
116618
|
isDecimalText = (value) => typeof value === "string" && DECIMAL_TEXT.test(value.trim());
|
|
116025
116619
|
isRecord4 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
116026
116620
|
parseHistoryPage = (stream, body, startMs, endMs) => {
|
|
116027
|
-
const
|
|
116621
|
+
const malformed2 = (detail) => new HistoryPageError(`The ${stream} page is not a valid Hyperliquid response: ${detail}`);
|
|
116028
116622
|
if (!STREAMS.has(stream)) throw new HistoryPageError(`Unknown history stream ${stream}.`);
|
|
116029
|
-
if (!isInt(startMs) || !isInt(endMs) || startMs < 0 || endMs < startMs) throw
|
|
116030
|
-
if (typeof body !== "string") throw
|
|
116623
|
+
if (!isInt(startMs) || !isInt(endMs) || startMs < 0 || endMs < startMs) throw malformed2("the window is invalid");
|
|
116624
|
+
if (typeof body !== "string") throw malformed2("the body must be the raw response text");
|
|
116031
116625
|
let rows;
|
|
116032
116626
|
try {
|
|
116033
116627
|
rows = JSON.parse(body);
|
|
116034
116628
|
} catch {
|
|
116035
|
-
throw
|
|
116629
|
+
throw malformed2("the body is not JSON");
|
|
116036
116630
|
}
|
|
116037
|
-
if (!Array.isArray(rows)) throw
|
|
116631
|
+
if (!Array.isArray(rows)) throw malformed2("the body is not a list");
|
|
116038
116632
|
for (const row of rows) {
|
|
116039
|
-
if (!isRecord4(row)) throw
|
|
116633
|
+
if (!isRecord4(row)) throw malformed2("a row is not an object");
|
|
116040
116634
|
const time3 = row.time;
|
|
116041
|
-
if (!isInt(time3)) throw
|
|
116042
|
-
if (time3 < startMs || time3 > endMs) throw
|
|
116043
|
-
if (!isText(row.hash)) throw
|
|
116635
|
+
if (!isInt(time3)) throw malformed2("a row has no millisecond time");
|
|
116636
|
+
if (time3 < startMs || time3 > endMs) throw malformed2("a row lies outside the requested window");
|
|
116637
|
+
if (!isText(row.hash)) throw malformed2("a row has no hash");
|
|
116044
116638
|
if (stream === "fills") {
|
|
116045
116639
|
if (!(isText(row.coin) && isInt(row.oid) && (row.side === "A" || row.side === "B") && isDecimalText(row.px) && isDecimalText(row.sz))) {
|
|
116046
|
-
throw
|
|
116640
|
+
throw malformed2("a fill lacks coin, oid, side, px or sz");
|
|
116047
116641
|
}
|
|
116048
116642
|
continue;
|
|
116049
116643
|
}
|
|
116050
116644
|
const delta = row.delta;
|
|
116051
|
-
if (!isRecord4(delta) || !isText(delta.type)) throw
|
|
116645
|
+
if (!isRecord4(delta) || !isText(delta.type)) throw malformed2("a row has no typed delta");
|
|
116052
116646
|
if (stream === "funding" && !(delta.type === "funding" && isText(delta.coin) && isDecimalText(delta.usdc))) {
|
|
116053
|
-
throw
|
|
116647
|
+
throw malformed2("a funding row lacks coin or usdc");
|
|
116054
116648
|
}
|
|
116055
116649
|
}
|
|
116056
116650
|
return rows;
|
|
@@ -116210,6 +116804,27 @@ var init_portfolio_evidence = __esm({
|
|
|
116210
116804
|
}
|
|
116211
116805
|
});
|
|
116212
116806
|
|
|
116807
|
+
// lib/runtime/host-wake-schedule.ts
|
|
116808
|
+
var marker, markBatchableTimer, markDeferrableTimer;
|
|
116809
|
+
var init_host_wake_schedule = __esm({
|
|
116810
|
+
"lib/runtime/host-wake-schedule.ts"() {
|
|
116811
|
+
"use strict";
|
|
116812
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
116813
|
+
init_define_VTX_EXO_POLICY();
|
|
116814
|
+
init_define_VTX_GROK_POLICY();
|
|
116815
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
116816
|
+
marker = null;
|
|
116817
|
+
markBatchableTimer = (handle, options) => {
|
|
116818
|
+
marker?.(handle, "batchable", options);
|
|
116819
|
+
return handle;
|
|
116820
|
+
};
|
|
116821
|
+
markDeferrableTimer = (handle, options) => {
|
|
116822
|
+
marker?.(handle, "deferrable", options);
|
|
116823
|
+
return handle;
|
|
116824
|
+
};
|
|
116825
|
+
}
|
|
116826
|
+
});
|
|
116827
|
+
|
|
116213
116828
|
// lib/runtime/sl-tp-execution-settings.ts
|
|
116214
116829
|
var hasOwn, defaultConfigKey, resolveSetting, resolveBooleanSetting, resolveFiniteNumberSetting, resolveEnumSetting, RISK_MODES, STOP_LOSS_TYPES, buildRuntimeSlTpExecutionSettings;
|
|
116215
116830
|
var init_sl_tp_execution_settings = __esm({
|
|
@@ -116466,9 +117081,9 @@ var init_prompt_variable_validation_contract = __esm({
|
|
|
116466
117081
|
const addedLengths = [];
|
|
116467
117082
|
let added = 0;
|
|
116468
117083
|
for (const pair of template.matchAll(ESCAPED_BRACE_PAIR_PATTERN)) {
|
|
116469
|
-
const
|
|
117084
|
+
const marker2 = pair[0] === "{{" ? ESCAPED_OPEN_BRACE : ESCAPED_CLOSE_BRACE;
|
|
116470
117085
|
markerStarts.push(pair.index + added);
|
|
116471
|
-
added +=
|
|
117086
|
+
added += marker2.length - pair[0].length;
|
|
116472
117087
|
markerEnds.push(pair.index + pair[0].length + added);
|
|
116473
117088
|
addedLengths.push(added);
|
|
116474
117089
|
}
|
|
@@ -118280,7 +118895,7 @@ var init_native_request_parameters = __esm({
|
|
|
118280
118895
|
});
|
|
118281
118896
|
|
|
118282
118897
|
// lib/runtime/provider-client.ts
|
|
118283
|
-
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, isAqGoogleKey, googleKeySurfaces, googleKeySurfaceProbes, probeGoogleKeySurface, resolveGoogleKeySurface, forgetGoogleKeySurfaceAfterAuthorizationFailure, 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, invokeRuntimeProvider;
|
|
118898
|
+
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, isAqGoogleKey, googleKeySurfaces, googleKeySurfaceProbes, probeGoogleKeySurface, resolveGoogleKeySurface, forgetGoogleKeySurfaceAfterAuthorizationFailure, googlePublicModelIdRegexes, shouldUseGooglePublicEndpointForModel, normalizeGoogleModelId, shouldRetryGoogleVertexRequestPublicly, GOOGLE_VERTEX_PUBLIC_RETRY_NOTE, buildGoogleRequest, GOOGLE_JSON_MODE_REFUSAL_PHRASES, googleTradeResponseMimeType, providerRequestFailure, isGoogleJsonModeRefusal, isGoogleReasoningPart, extractGoogleMessageText, extractGoogleReasoningContent, extractGoogleSafetyMetadata, GOOGLE_BLOCKED_FINISH_REASONS, googleProviderBlockReason, callGoogle, resolveRuntimeProvider, defaultInvocationContext, defaultProviderTransport, invocationFailureCode, buildBrowserInvocation, resolveProviderSecretKey, resolveNativeProviderCredentialSlots, resolveProviderSecretKeySlots, requireOpenAiCompatibleRuntimeBaseUrl, runtimeSubscriptionPlan, runtimeKeySlotSupportsModel, invokeRuntimeProviderAttempt, invokeRuntimeProvider;
|
|
118284
118899
|
var init_provider_client = __esm({
|
|
118285
118900
|
"lib/runtime/provider-client.ts"() {
|
|
118286
118901
|
"use strict";
|
|
@@ -118401,27 +119016,27 @@ var init_provider_client = __esm({
|
|
|
118401
119016
|
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
118402
119017
|
startedAtMs: providerDispatchClockMs()
|
|
118403
119018
|
});
|
|
118404
|
-
providerDispatchLatencyMs = (
|
|
118405
|
-
attachProviderDispatchFailure = (error48,
|
|
119019
|
+
providerDispatchLatencyMs = (marker2) => Math.max(0, providerDispatchClockMs() - marker2.startedAtMs);
|
|
119020
|
+
attachProviderDispatchFailure = (error48, marker2, response = null) => {
|
|
118406
119021
|
const sanitizedError = toSanitizedRuntimeError(error48);
|
|
118407
119022
|
if (error48 instanceof NativeModelTimeoutError) {
|
|
118408
119023
|
sanitizedError.runtimeNativeFailureKind = "timeout";
|
|
118409
|
-
} else if (
|
|
119024
|
+
} else if (marker2 && error48 instanceof TypeError && /failed to fetch|fetch failed|networkerror|load failed/i.test(error48.message)) {
|
|
118410
119025
|
sanitizedError.runtimeNativeFailureKind = "transport";
|
|
118411
119026
|
}
|
|
118412
119027
|
sanitizedError.runtimeProviderStatusCode = response?.status ?? null;
|
|
118413
119028
|
sanitizedError.runtimeProviderRequestId = providerRequestId(response);
|
|
118414
119029
|
sanitizedError.runtimeProviderDiagnostics = {
|
|
118415
|
-
...
|
|
119030
|
+
...marker2?.providerDiagnostics ?? {},
|
|
118416
119031
|
...error48 instanceof NativeModelTimeoutError && error48.attemptCapExpired ? { timeout_bound: "attempt_cap" } : {}
|
|
118417
119032
|
};
|
|
118418
|
-
if (
|
|
118419
|
-
sanitizedError.runtimeRequestInputTokens =
|
|
118420
|
-
if (
|
|
118421
|
-
sanitizedError.runtimeSentReasoningParameters =
|
|
118422
|
-
sanitizedError.runtimeEffectiveReasoningParameters =
|
|
118423
|
-
sanitizedError.runtimeDispatchStartedAt =
|
|
118424
|
-
sanitizedError.runtimeDispatchLatencyMs = providerDispatchLatencyMs(
|
|
119033
|
+
if (marker2?.googleQuotaFailure) sanitizedError.runtimeGoogleQuotaFailure = true;
|
|
119034
|
+
sanitizedError.runtimeRequestInputTokens = marker2?.requestInputTokens ?? null;
|
|
119035
|
+
if (marker2) {
|
|
119036
|
+
sanitizedError.runtimeSentReasoningParameters = marker2.sentReasoningParameters;
|
|
119037
|
+
sanitizedError.runtimeEffectiveReasoningParameters = marker2.effectiveReasoningParameters;
|
|
119038
|
+
sanitizedError.runtimeDispatchStartedAt = marker2.startedAt;
|
|
119039
|
+
sanitizedError.runtimeDispatchLatencyMs = providerDispatchLatencyMs(marker2);
|
|
118425
119040
|
}
|
|
118426
119041
|
return sanitizedError;
|
|
118427
119042
|
};
|
|
@@ -119508,8 +120123,8 @@ var init_provider_client = __esm({
|
|
|
119508
120123
|
const dispatch = async (body) => {
|
|
119509
120124
|
if (body !== finalRequestBody) trace.attachRequest({ url: requestUrl2, method: "POST", headers: requestHeaders, body });
|
|
119510
120125
|
response = null;
|
|
119511
|
-
const
|
|
119512
|
-
dispatchMarker =
|
|
120126
|
+
const marker2 = beginProviderDispatch(body);
|
|
120127
|
+
dispatchMarker = marker2;
|
|
119513
120128
|
const dispatched = useRelay ? await relayNativeProviderRequest(provider, String(apiKey || "").trim(), body, {
|
|
119514
120129
|
profileId: profileId == null ? void 0 : Number(profileId),
|
|
119515
120130
|
signal,
|
|
@@ -119523,7 +120138,7 @@ var init_provider_client = __esm({
|
|
|
119523
120138
|
});
|
|
119524
120139
|
response = dispatched;
|
|
119525
120140
|
const payload = typeof onDelta === "function" ? await readOpenAiCompatibleTextStream(dispatched, runtimeMode, onDelta, (rawPayload) => {
|
|
119526
|
-
Object.assign(
|
|
120141
|
+
Object.assign(marker2.effectiveReasoningParameters, extractProviderReasoningParameters(rawPayload));
|
|
119527
120142
|
}).then(({ payload: streamPayload, rawText }) => {
|
|
119528
120143
|
trace.attachResponse({
|
|
119529
120144
|
status: dispatched.status,
|
|
@@ -119533,7 +120148,7 @@ var init_provider_client = __esm({
|
|
|
119533
120148
|
});
|
|
119534
120149
|
return streamPayload;
|
|
119535
120150
|
}) : await extractOpenAiCompatibleText(dispatched, runtimeMode, (payloadJson, rawText) => {
|
|
119536
|
-
|
|
120151
|
+
marker2.effectiveReasoningParameters = extractProviderReasoningParameters(payloadJson);
|
|
119537
120152
|
trace.attachResponse({
|
|
119538
120153
|
status: dispatched.status,
|
|
119539
120154
|
statusText: dispatched.statusText ?? "",
|
|
@@ -119543,13 +120158,13 @@ var init_provider_client = __esm({
|
|
|
119543
120158
|
});
|
|
119544
120159
|
return {
|
|
119545
120160
|
...payload,
|
|
119546
|
-
sentReasoningParameters:
|
|
119547
|
-
effectiveReasoningParameters:
|
|
119548
|
-
requestInputTokens:
|
|
119549
|
-
providerDiagnostics:
|
|
120161
|
+
sentReasoningParameters: marker2.sentReasoningParameters,
|
|
120162
|
+
effectiveReasoningParameters: marker2.effectiveReasoningParameters,
|
|
120163
|
+
requestInputTokens: marker2.requestInputTokens,
|
|
120164
|
+
providerDiagnostics: marker2.providerDiagnostics,
|
|
119550
120165
|
providerStatusCode: dispatched.status,
|
|
119551
|
-
dispatchStartedAt:
|
|
119552
|
-
dispatchLatencyMs: providerDispatchLatencyMs(
|
|
120166
|
+
dispatchStartedAt: marker2.startedAt,
|
|
120167
|
+
dispatchLatencyMs: providerDispatchLatencyMs(marker2)
|
|
119553
120168
|
};
|
|
119554
120169
|
};
|
|
119555
120170
|
const attemptDispatch = async (body) => {
|
|
@@ -119727,7 +120342,7 @@ var init_provider_client = __esm({
|
|
|
119727
120342
|
});
|
|
119728
120343
|
if (!response.ok) {
|
|
119729
120344
|
const detail = extractProviderErrorDetail(payload, rawText) || "OpenAI Responses request failed";
|
|
119730
|
-
throw
|
|
120345
|
+
throw providerRequestFailure({ response, detail, runtimeMode });
|
|
119731
120346
|
}
|
|
119732
120347
|
const text = extractOpenAiResponsesText(payload);
|
|
119733
120348
|
if (!text) {
|
|
@@ -119874,7 +120489,7 @@ var init_provider_client = __esm({
|
|
|
119874
120489
|
});
|
|
119875
120490
|
if (!response.ok) {
|
|
119876
120491
|
const detail = extractProviderErrorDetail(payload, rawText) || "Anthropic request failed";
|
|
119877
|
-
throw
|
|
120492
|
+
throw providerRequestFailure({ response, detail, runtimeMode });
|
|
119878
120493
|
}
|
|
119879
120494
|
const text = extractAnthropicMessageText(payload);
|
|
119880
120495
|
if (!text) {
|
|
@@ -119987,7 +120602,7 @@ var init_provider_client = __esm({
|
|
|
119987
120602
|
return detail.includes("publisher model") || detail.includes("was not found") || detail.includes("does not have access");
|
|
119988
120603
|
};
|
|
119989
120604
|
GOOGLE_VERTEX_PUBLIC_RETRY_NOTE = "Google Vertex Express could not access this publisher model, so VTX retried the request through the public Gemini endpoint.";
|
|
119990
|
-
buildGoogleRequest = (apiKey, config2, model, systemPrompt, userPrompt, extraMessages, temperature, maxTokens, vertexExpress) => {
|
|
120605
|
+
buildGoogleRequest = (apiKey, config2, model, systemPrompt, userPrompt, extraMessages, temperature, maxTokens, vertexExpress, responseMimeType) => {
|
|
119991
120606
|
const modelId = normalizeGoogleModelId(model, vertexExpress);
|
|
119992
120607
|
const template = vertexExpress ? requireProviderEndpoint(config2, "google_vertex_express_generate_content_url_template") : requireProviderEndpoint(config2, "google_public_generate_content_url_template");
|
|
119993
120608
|
const url2 = template.replace("{model_id}", modelId);
|
|
@@ -119998,6 +120613,9 @@ var init_provider_client = __esm({
|
|
|
119998
120613
|
if (resolvedMaxTokens !== null) {
|
|
119999
120614
|
generationConfig.maxOutputTokens = resolvedMaxTokens;
|
|
120000
120615
|
}
|
|
120616
|
+
if (responseMimeType) {
|
|
120617
|
+
generationConfig.responseMimeType = responseMimeType;
|
|
120618
|
+
}
|
|
120001
120619
|
const payload = vertexExpress ? {
|
|
120002
120620
|
systemInstruction: { parts: [{ text: systemPrompt }] },
|
|
120003
120621
|
contents: [
|
|
@@ -120021,6 +120639,18 @@ var init_provider_client = __esm({
|
|
|
120021
120639
|
};
|
|
120022
120640
|
return { requestUrl: requestUrl2, payload };
|
|
120023
120641
|
};
|
|
120642
|
+
GOOGLE_JSON_MODE_REFUSAL_PHRASES = ["json mode", "response_mime_type", "responsemimetype", "response mime type"];
|
|
120643
|
+
googleTradeResponseMimeType = (config2, model, context) => {
|
|
120644
|
+
const contract = config2.google_trade_request_contract;
|
|
120645
|
+
if (!contract || context.use_case !== "trader") return null;
|
|
120646
|
+
const modelId = model.trim().replace(/^models\//, "");
|
|
120647
|
+
return contract.json_mode_model_id_regexes.some((pattern) => new RegExp(pattern).test(modelId)) ? contract.response_mime_type : null;
|
|
120648
|
+
};
|
|
120649
|
+
providerRequestFailure = (input) => new Error(buildCanonicalProviderFailureMessage(input));
|
|
120650
|
+
isGoogleJsonModeRefusal = (status, detail) => {
|
|
120651
|
+
const lowered = detail.toLowerCase();
|
|
120652
|
+
return status === HTTP_STATUS.BAD_REQUEST && GOOGLE_JSON_MODE_REFUSAL_PHRASES.some((phrase) => lowered.includes(phrase));
|
|
120653
|
+
};
|
|
120024
120654
|
isGoogleReasoningPart = (part) => {
|
|
120025
120655
|
const partType = typeof part.type === "string" ? part.type.trim().toLowerCase() : "";
|
|
120026
120656
|
if (partType === "thinking" || partType === "thought" || partType === "reasoning" || partType === "reasoning_content") {
|
|
@@ -120111,38 +120741,44 @@ var init_provider_client = __esm({
|
|
|
120111
120741
|
const finishReason = typeof payload?.candidates?.[0]?.finishReason === "string" ? payload.candidates[0].finishReason.trim() : "";
|
|
120112
120742
|
return GOOGLE_BLOCKED_FINISH_REASONS.has(finishReason.toLowerCase()) ? finishReason : null;
|
|
120113
120743
|
};
|
|
120114
|
-
callGoogle = async (apiKey, config2, model, systemPrompt, userPrompt, extraMessages, temperature, maxTokens, reasoningPayload, runtimeRequestContract, runtimeMode, signal, nativeRequestParameters, nativeRequestParameterValues, egress) => {
|
|
120744
|
+
callGoogle = async (apiKey, config2, model, systemPrompt, userPrompt, extraMessages, temperature, maxTokens, reasoningPayload, runtimeRequestContract, runtimeMode, signal, nativeRequestParameters, nativeRequestParameterValues, egress, responseMimeType = null) => {
|
|
120115
120745
|
const vertexExpress = !shouldUseGooglePublicEndpointForModel(config2, model) && await resolveGoogleKeySurface(apiKey, config2, signal) === "vertex";
|
|
120116
120746
|
const reasoningParams = resolveProviderReasoningParameters("google", reasoningPayload);
|
|
120117
|
-
|
|
120118
|
-
|
|
120119
|
-
|
|
120120
|
-
|
|
120121
|
-
|
|
120122
|
-
|
|
120123
|
-
|
|
120124
|
-
|
|
120125
|
-
|
|
120126
|
-
|
|
120127
|
-
|
|
120128
|
-
|
|
120129
|
-
|
|
120130
|
-
|
|
120131
|
-
|
|
120132
|
-
|
|
120133
|
-
|
|
120134
|
-
|
|
120135
|
-
|
|
120136
|
-
|
|
120747
|
+
const buildPayload = (onVertex, mimeType) => {
|
|
120748
|
+
const built = buildGoogleRequest(
|
|
120749
|
+
apiKey,
|
|
120750
|
+
config2,
|
|
120751
|
+
model,
|
|
120752
|
+
systemPrompt,
|
|
120753
|
+
userPrompt,
|
|
120754
|
+
extraMessages,
|
|
120755
|
+
temperature,
|
|
120756
|
+
maxTokens,
|
|
120757
|
+
onVertex,
|
|
120758
|
+
mimeType
|
|
120759
|
+
);
|
|
120760
|
+
const generationConfig = built.payload.generationConfig;
|
|
120761
|
+
if (Number.isFinite(Number(reasoningParams.thinkingBudget))) {
|
|
120762
|
+
generationConfig.thinkingConfig = { thinkingBudget: Math.trunc(Number(reasoningParams.thinkingBudget)) };
|
|
120763
|
+
}
|
|
120764
|
+
if (typeof reasoningParams.thinkingLevel === "string" && reasoningParams.thinkingLevel.trim()) {
|
|
120765
|
+
generationConfig.thinkingConfig = {
|
|
120766
|
+
...generationConfig.thinkingConfig || {},
|
|
120767
|
+
thinkingLevel: reasoningParams.thinkingLevel.trim().toLowerCase()
|
|
120768
|
+
};
|
|
120769
|
+
}
|
|
120770
|
+
return {
|
|
120771
|
+
requestUrl: built.requestUrl,
|
|
120772
|
+
payload: applyNativeRequestParameters(
|
|
120773
|
+
built.payload,
|
|
120774
|
+
nativeRequestParameters,
|
|
120775
|
+
nativeRequestParameterValues,
|
|
120776
|
+
"gemini_generate_content",
|
|
120777
|
+
{ includeAppManaged: true }
|
|
120778
|
+
)
|
|
120137
120779
|
};
|
|
120138
|
-
}
|
|
120139
|
-
payload =
|
|
120140
|
-
payload,
|
|
120141
|
-
nativeRequestParameters,
|
|
120142
|
-
nativeRequestParameterValues,
|
|
120143
|
-
"gemini_generate_content",
|
|
120144
|
-
{ includeAppManaged: true }
|
|
120145
|
-
);
|
|
120780
|
+
};
|
|
120781
|
+
let { requestUrl: requestUrl2, payload } = buildPayload(vertexExpress, responseMimeType);
|
|
120146
120782
|
const trace = startRuntimeNetworkDebugTrace({
|
|
120147
120783
|
kind: "provider",
|
|
120148
120784
|
label: "google",
|
|
@@ -120187,52 +120823,27 @@ var init_provider_client = __esm({
|
|
|
120187
120823
|
dispatchMarker.providerDiagnostics = credentialDiagnostics;
|
|
120188
120824
|
response = await dispatch();
|
|
120189
120825
|
let { payload: payloadJson, rawText } = await readProviderPayload(response);
|
|
120190
|
-
|
|
120191
|
-
retriedPublicGeminiEndpoint = true;
|
|
120192
|
-
const firstErrorDetail = extractProviderErrorDetail(payloadJson, rawText) || `Google request failed with HTTP ${response.status}`;
|
|
120826
|
+
const recordRetriedDispatch = async (marker2, answered, errorDetail) => {
|
|
120193
120827
|
internalDispatchAttempts.push({
|
|
120194
|
-
sentReasoningParameters:
|
|
120828
|
+
sentReasoningParameters: marker2.sentReasoningParameters,
|
|
120195
120829
|
effectiveReasoningParameters: extractProviderReasoningParameters(payloadJson),
|
|
120196
|
-
startedAt:
|
|
120197
|
-
latencyMs: providerDispatchLatencyMs(
|
|
120830
|
+
startedAt: marker2.startedAt,
|
|
120831
|
+
latencyMs: providerDispatchLatencyMs(marker2),
|
|
120198
120832
|
transport: "google_generate_content_rest",
|
|
120199
|
-
requestInputTokens:
|
|
120200
|
-
providerDiagnostics: { ...credentialDiagnostics, ...await extractProviderDiagnostics(payloadJson,
|
|
120201
|
-
providerRequestId: providerRequestId(
|
|
120202
|
-
errorDetail
|
|
120203
|
-
statusCode:
|
|
120833
|
+
requestInputTokens: marker2.requestInputTokens,
|
|
120834
|
+
providerDiagnostics: { ...credentialDiagnostics, ...await extractProviderDiagnostics(payloadJson, answered) },
|
|
120835
|
+
providerRequestId: providerRequestId(answered),
|
|
120836
|
+
errorDetail,
|
|
120837
|
+
statusCode: answered.status,
|
|
120204
120838
|
retryable: false
|
|
120205
120839
|
});
|
|
120840
|
+
};
|
|
120841
|
+
if (vertexExpress && shouldRetryGoogleVertexRequestPublicly(response, payloadJson, rawText)) {
|
|
120842
|
+
retriedPublicGeminiEndpoint = true;
|
|
120843
|
+
const firstErrorDetail = extractProviderErrorDetail(payloadJson, rawText) || `Google request failed with HTTP ${response.status}`;
|
|
120844
|
+
await recordRetriedDispatch(dispatchMarker, response, firstErrorDetail);
|
|
120206
120845
|
dispatchMarker = null;
|
|
120207
|
-
({ requestUrl: requestUrl2, payload } =
|
|
120208
|
-
apiKey,
|
|
120209
|
-
config2,
|
|
120210
|
-
model,
|
|
120211
|
-
systemPrompt,
|
|
120212
|
-
userPrompt,
|
|
120213
|
-
extraMessages,
|
|
120214
|
-
temperature,
|
|
120215
|
-
maxTokens,
|
|
120216
|
-
false
|
|
120217
|
-
));
|
|
120218
|
-
if (Number.isFinite(Number(reasoningParams.thinkingBudget))) {
|
|
120219
|
-
payload.generationConfig.thinkingConfig = {
|
|
120220
|
-
thinkingBudget: Math.trunc(Number(reasoningParams.thinkingBudget))
|
|
120221
|
-
};
|
|
120222
|
-
}
|
|
120223
|
-
if (typeof reasoningParams.thinkingLevel === "string" && reasoningParams.thinkingLevel.trim()) {
|
|
120224
|
-
payload.generationConfig.thinkingConfig = {
|
|
120225
|
-
...payload.generationConfig.thinkingConfig || {},
|
|
120226
|
-
thinkingLevel: reasoningParams.thinkingLevel.trim().toLowerCase()
|
|
120227
|
-
};
|
|
120228
|
-
}
|
|
120229
|
-
payload = applyNativeRequestParameters(
|
|
120230
|
-
payload,
|
|
120231
|
-
nativeRequestParameters,
|
|
120232
|
-
nativeRequestParameterValues,
|
|
120233
|
-
"gemini_generate_content",
|
|
120234
|
-
{ includeAppManaged: true }
|
|
120235
|
-
);
|
|
120846
|
+
({ requestUrl: requestUrl2, payload } = buildPayload(false, responseMimeType));
|
|
120236
120847
|
appendRuntimeDebugEvent({
|
|
120237
120848
|
label: "google_vertex_public_retry",
|
|
120238
120849
|
note: GOOGLE_VERTEX_PUBLIC_RETRY_NOTE
|
|
@@ -120250,6 +120861,19 @@ var init_provider_client = __esm({
|
|
|
120250
120861
|
response = await dispatch();
|
|
120251
120862
|
({ payload: payloadJson, rawText } = await readProviderPayload(response));
|
|
120252
120863
|
}
|
|
120864
|
+
const refusalDetail = !response.ok && responseMimeType ? extractProviderErrorDetail(payloadJson, rawText) || "" : "";
|
|
120865
|
+
if (refusalDetail && dispatchMarker && isGoogleJsonModeRefusal(response.status, refusalDetail)) {
|
|
120866
|
+
await recordRetriedDispatch(dispatchMarker, response, refusalDetail);
|
|
120867
|
+
dispatchMarker = null;
|
|
120868
|
+
({ requestUrl: requestUrl2, payload } = buildPayload(vertexExpress && !retriedPublicGeminiEndpoint, null));
|
|
120869
|
+
appendRuntimeDebugEvent({ label: "google_json_mode_refused", note: `model=${model}` });
|
|
120870
|
+
trace.attachRequest({ url: requestUrl2.toString(), method: "POST", headers: requestHeaders, body: payload });
|
|
120871
|
+
response = null;
|
|
120872
|
+
dispatchMarker = beginProviderDispatch(payload);
|
|
120873
|
+
dispatchMarker.providerDiagnostics = credentialDiagnostics;
|
|
120874
|
+
response = await dispatch();
|
|
120875
|
+
({ payload: payloadJson, rawText } = await readProviderPayload(response));
|
|
120876
|
+
}
|
|
120253
120877
|
if (dispatchMarker) {
|
|
120254
120878
|
dispatchMarker.googleQuotaFailure = Array.isArray(payloadJson?.error?.details) && payloadJson.error.details.some((detail) => detail !== null && typeof detail === "object" && detail["@type"] === "type.googleapis.com/google.rpc.QuotaFailure");
|
|
120255
120879
|
dispatchMarker.effectiveReasoningParameters = extractProviderReasoningParameters(payloadJson);
|
|
@@ -120265,7 +120889,7 @@ var init_provider_client = __esm({
|
|
|
120265
120889
|
forgetGoogleKeySurfaceAfterAuthorizationFailure(apiKey, response.status);
|
|
120266
120890
|
const providerDetail = extractProviderErrorDetail(payloadJson, rawText) || "Google request failed";
|
|
120267
120891
|
const detail = retriedPublicGeminiEndpoint ? `${GOOGLE_VERTEX_PUBLIC_RETRY_NOTE} The Gemini retry also failed: ${providerDetail}` : providerDetail;
|
|
120268
|
-
throw
|
|
120892
|
+
throw providerRequestFailure({ response, detail, runtimeMode });
|
|
120269
120893
|
}
|
|
120270
120894
|
const reasoningContent = extractGoogleReasoningContent(payloadJson);
|
|
120271
120895
|
const finishReason = typeof payloadJson?.candidates?.[0]?.finishReason === "string" ? payloadJson.candidates[0].finishReason : null;
|
|
@@ -120754,7 +121378,8 @@ var init_provider_client = __esm({
|
|
|
120754
121378
|
attemptController?.signal ?? signal,
|
|
120755
121379
|
nativeRequestParameters,
|
|
120756
121380
|
nativeRequestParameterValues,
|
|
120757
|
-
egress ? { route: googleRoute, budget: egress, profileId: Number(profileId), timeoutSeconds: timeoutMs / MS_PER_SECOND } : void 0
|
|
121381
|
+
egress ? { route: googleRoute, budget: egress, profileId: Number(profileId), timeoutSeconds: timeoutMs / MS_PER_SECOND } : void 0,
|
|
121382
|
+
googleTradeResponseMimeType(config2, model, invocationContext)
|
|
120758
121383
|
);
|
|
120759
121384
|
} finally {
|
|
120760
121385
|
if (attemptTimer !== void 0) clearTimeout(attemptTimer);
|
|
@@ -122565,6 +123190,7 @@ __export(local_analysis_exports, {
|
|
|
122565
123190
|
buildPromptBehaviorStateValue: () => buildPromptBehaviorStateValue,
|
|
122566
123191
|
buildPromptCandleTimeframeComponent: () => buildPromptCandleTimeframeComponent,
|
|
122567
123192
|
capacityUnitSize: () => capacityUnitSize,
|
|
123193
|
+
currentModelOutputJsonText: () => currentModelOutputJsonText,
|
|
122568
123194
|
derivePromptVisibleSections: () => derivePromptVisibleSections,
|
|
122569
123195
|
isClientRuntimeAgentInstructionEmpty: () => isClientRuntimeAgentInstructionEmpty,
|
|
122570
123196
|
isClientRuntimeAiSchedulePaused: () => isClientRuntimeAiSchedulePaused,
|
|
@@ -122579,7 +123205,7 @@ __export(local_analysis_exports, {
|
|
|
122579
123205
|
runLocalRuntimeCycle: () => runLocalRuntimeCycle,
|
|
122580
123206
|
summarizeReviewFailureExplanation: () => summarizeReviewFailureExplanation
|
|
122581
123207
|
});
|
|
122582
|
-
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, EXTERNAL_INFERENCE_RESULT_WAIT_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, BEHAVIOR_MEMORY_UNAVAILABLE_ERROR, BehaviorMemoryUnavailableError, 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, MANIFEST_COMPONENT_NAME, derivePromptVisibleSections, decodeDecisionTracePayload, extractDecisionSymbolTrace, formatDecisionSymbolTrace, formatActionableDecisionSymbols, decisionRecordsBySymbol, normalizePromptSymbols, JSON_MODEL_OUTPUT_FENCE_PATTERN, STRICT_MODEL_OUTPUT_KEYS, currentModelOutputValidationErrors, currentModelOutputMatchesContract, projectCurrentModelDecisionContent, modelOutputValidationError, SERVER_UNREADABLE_REPLY_HOLD_REASONING, 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, AI_INDICATOR_KEYS_NEWER_THAN_SOME_SERVERS, sortTradingTimeframes, normalizePromptIdentityTimestamp, resolveCompletedCandleBoundary, normalizeAiIndicatorFlags, getPromptLookback, computeSma, computeEma, computeRsi, computeAtr, computeMacd, computeBollingerBands, getIndicatorValue, buildPromptCandlesComponent, buildPromptCandleTimeframeComponent, resolvePromptRelativeVolumeContext, promptRelativeVolumeBaseline, 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, carryReturnedModelCalls, runLocalRuntimeCycle;
|
|
123208
|
+
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, EXTERNAL_INFERENCE_RESULT_WAIT_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, BEHAVIOR_MEMORY_UNAVAILABLE_ERROR, BehaviorMemoryUnavailableError, 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, MANIFEST_COMPONENT_NAME, derivePromptVisibleSections, decodeDecisionTracePayload, extractDecisionSymbolTrace, formatDecisionSymbolTrace, formatActionableDecisionSymbols, decisionRecordsBySymbol, normalizePromptSymbols, JSON_MODEL_OUTPUT_FENCE_PATTERN, currentModelOutputJsonText, STRICT_MODEL_OUTPUT_KEYS, currentModelOutputValidationErrors, currentModelOutputMatchesContract, projectCurrentModelDecisionContent, modelOutputValidationError, SERVER_UNREADABLE_REPLY_HOLD_REASONING, 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, AI_INDICATOR_KEYS_NEWER_THAN_SOME_SERVERS, sortTradingTimeframes, normalizePromptIdentityTimestamp, resolveCompletedCandleBoundary, normalizeAiIndicatorFlags, getPromptLookback, computeSma, computeEma, computeRsi, computeAtr, computeMacd, computeBollingerBands, getIndicatorValue, buildPromptCandlesComponent, buildPromptCandleTimeframeComponent, resolvePromptRelativeVolumeContext, promptRelativeVolumeBaseline, 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, carryReturnedModelCalls, runLocalRuntimeCycle;
|
|
122583
123209
|
var init_local_analysis = __esm({
|
|
122584
123210
|
"lib/runtime/local-analysis.ts"() {
|
|
122585
123211
|
"use strict";
|
|
@@ -122588,6 +123214,7 @@ var init_local_analysis = __esm({
|
|
|
122588
123214
|
init_define_VTX_GROK_POLICY();
|
|
122589
123215
|
init_define_VTX_PI_MODEL_POLICY();
|
|
122590
123216
|
init_sl_tp_execution_settings();
|
|
123217
|
+
init_runtime_error_reason_rules2();
|
|
122591
123218
|
init_retired_model_source();
|
|
122592
123219
|
init_profile_model_cascade();
|
|
122593
123220
|
init_profile_model_fallbacks();
|
|
@@ -122774,9 +123401,9 @@ var init_local_analysis = __esm({
|
|
|
122774
123401
|
const symbols = normalizePromptSymbols(scope.symbols);
|
|
122775
123402
|
const symbol2 = requireNonEmptyStringField(symbols[0], "trading_symbols[0]");
|
|
122776
123403
|
const timeframe = requireNonEmptyStringField(scope.primaryTimeframe, "trading_timeframes[0]");
|
|
122777
|
-
const content = stringifyPromptJson(instruction.candidate);
|
|
123404
|
+
const content = currentModelOutputJsonText(stringifyPromptJson(instruction.candidate));
|
|
122778
123405
|
if (!currentModelOutputMatchesContract(content, symbols)) {
|
|
122779
|
-
throw new
|
|
123406
|
+
throw new RuntimeReasonError("The agent's instruction could not be read.", "model_output_schema_invalid");
|
|
122780
123407
|
}
|
|
122781
123408
|
const tradeSize = clampNumber(
|
|
122782
123409
|
settings.size,
|
|
@@ -123453,6 +124080,19 @@ var init_local_analysis = __esm({
|
|
|
123453
124080
|
return normalized;
|
|
123454
124081
|
};
|
|
123455
124082
|
JSON_MODEL_OUTPUT_FENCE_PATTERN = /^```(?:json)?\s*\n?([\s\S]*?)\n?```$/i;
|
|
124083
|
+
currentModelOutputJsonText = (rawText) => {
|
|
124084
|
+
const trimmed = String(rawText ?? "").trim();
|
|
124085
|
+
const content = String(trimmed.match(JSON_MODEL_OUTPUT_FENCE_PATTERN)?.[1] ?? trimmed).trim();
|
|
124086
|
+
if (!content.startsWith("[")) return content;
|
|
124087
|
+
try {
|
|
124088
|
+
const parsed = JSON.parse(content);
|
|
124089
|
+
if (Array.isArray(parsed) && parsed.length === 1 && parsed[0] && typeof parsed[0] === "object" && !Array.isArray(parsed[0])) {
|
|
124090
|
+
return JSON.stringify(parsed[0]);
|
|
124091
|
+
}
|
|
124092
|
+
} catch {
|
|
124093
|
+
}
|
|
124094
|
+
return content;
|
|
124095
|
+
};
|
|
123456
124096
|
STRICT_MODEL_OUTPUT_KEYS = /* @__PURE__ */ new Set([
|
|
123457
124097
|
"decision",
|
|
123458
124098
|
"units",
|
|
@@ -123466,9 +124106,7 @@ var init_local_analysis = __esm({
|
|
|
123466
124106
|
if (expectedSymbols.length === 0) {
|
|
123467
124107
|
return ["expected_symbols_empty"];
|
|
123468
124108
|
}
|
|
123469
|
-
const
|
|
123470
|
-
const fencedMatch = rawContent.match(JSON_MODEL_OUTPUT_FENCE_PATTERN);
|
|
123471
|
-
const content = String(fencedMatch?.[1] ?? rawContent).trim();
|
|
124109
|
+
const content = currentModelOutputJsonText(rawText);
|
|
123472
124110
|
if (!content.startsWith("{") || !content.endsWith("}")) {
|
|
123473
124111
|
return ["json_object_required"];
|
|
123474
124112
|
}
|
|
@@ -123522,10 +124160,10 @@ var init_local_analysis = __esm({
|
|
|
123522
124160
|
currentModelOutputMatchesContract = (rawText, allowedSymbols) => currentModelOutputValidationErrors(rawText, allowedSymbols).length === 0;
|
|
123523
124161
|
projectCurrentModelDecisionContent = (rawText) => {
|
|
123524
124162
|
const trimmed = rawText.trim();
|
|
123525
|
-
const content =
|
|
124163
|
+
const content = currentModelOutputJsonText(rawText);
|
|
123526
124164
|
const payload = JSON.parse(content);
|
|
123527
124165
|
if (Object.values(payload).every((entry) => Object.keys(entry).length === STRICT_MODEL_OUTPUT_KEYS.size)) {
|
|
123528
|
-
return rawText;
|
|
124166
|
+
return content === String(trimmed.match(JSON_MODEL_OUTPUT_FENCE_PATTERN)?.[1] ?? trimmed).trim() ? rawText : content;
|
|
123529
124167
|
}
|
|
123530
124168
|
return JSON.stringify(Object.fromEntries(Object.entries(payload).map(([symbol2, entry]) => [
|
|
123531
124169
|
symbol2,
|
|
@@ -123541,7 +124179,7 @@ var init_local_analysis = __esm({
|
|
|
123541
124179
|
});
|
|
123542
124180
|
const rejectedIndex = attempts.findLastIndex((item) => item.role === role && item.status === "succeeded");
|
|
123543
124181
|
return Object.assign(
|
|
123544
|
-
new
|
|
124182
|
+
new RuntimeReasonError(`The ${lane} Model's reply could not be read.`, "model_output_schema_invalid"),
|
|
123545
124183
|
{
|
|
123546
124184
|
// Preserve the completed call and its expected symbol scope. The normal
|
|
123547
124185
|
// error reporter / Review safety-HOLD path owns persistence.
|
|
@@ -125991,7 +126629,7 @@ ${behaviorJson}
|
|
|
125991
126629
|
}
|
|
125992
126630
|
}
|
|
125993
126631
|
if (delivered.lane !== input.lane || delivered.job_id !== jobId) {
|
|
125994
|
-
throw new
|
|
126632
|
+
throw new RuntimeReasonError("External inference delivery identity did not match the requested lane.", "internal_data_error");
|
|
125995
126633
|
}
|
|
125996
126634
|
const attemptId = requireNonEmptyStringField(
|
|
125997
126635
|
delivered.attempt_id,
|
|
@@ -126006,7 +126644,7 @@ ${behaviorJson}
|
|
|
126006
126644
|
"external_inference.response_mode"
|
|
126007
126645
|
);
|
|
126008
126646
|
if (responseMode !== "provider_response" && responseMode !== "decision_candidate") {
|
|
126009
|
-
throw new
|
|
126647
|
+
throw new RuntimeReasonError("External inference response mode is invalid.", "internal_data_error");
|
|
126010
126648
|
}
|
|
126011
126649
|
const outputSchemaVersion = requireNonEmptyStringField(
|
|
126012
126650
|
delivered.output_schema_version,
|
|
@@ -126019,7 +126657,7 @@ ${behaviorJson}
|
|
|
126019
126657
|
const authoritative = delivered.authoritative;
|
|
126020
126658
|
const invocation = normalizeAiInvocationTelemetry(authoritative.invocation);
|
|
126021
126659
|
if (invocation.provider !== "external_agent" || invocation.role !== (input.lane === "main" ? "primary" : "review")) {
|
|
126022
|
-
throw new
|
|
126660
|
+
throw new RuntimeReasonError("External inference invocation evidence is invalid.", "internal_data_error");
|
|
126023
126661
|
}
|
|
126024
126662
|
const candidateContent = JSON.stringify(delivered.candidate);
|
|
126025
126663
|
const promptTokens = invocation.usage.input_tokens;
|
|
@@ -127951,7 +128589,7 @@ ${stringifyPromptJson(candlesPayload)}
|
|
|
127951
128589
|
// The loop records this one code for a reply its strict parser rejects.
|
|
127952
128590
|
validationErrorCodes: ["model_output_schema_invalid"],
|
|
127953
128591
|
discardedFields: []
|
|
127954
|
-
} : classifyDecisionParseOutcome(providerResponse.content, symbol2, promptSymbols);
|
|
128592
|
+
} : classifyDecisionParseOutcome(currentModelOutputJsonText(providerResponse.content), symbol2, promptSymbols);
|
|
127955
128593
|
invocationAttempts = applyInvocationParseOutcome(
|
|
127956
128594
|
providerResponse.invocations,
|
|
127957
128595
|
{
|
|
@@ -128276,7 +128914,7 @@ ${reviewOutputContract}`;
|
|
|
128276
128914
|
reviewDecisionContent = projectCurrentModelDecisionContent(reviewResponse.content);
|
|
128277
128915
|
}
|
|
128278
128916
|
const reviewParseOutcome = classifyDecisionParseOutcome(
|
|
128279
|
-
reviewResponse.content,
|
|
128917
|
+
currentModelOutputJsonText(reviewResponse.content),
|
|
128280
128918
|
reviewSymbols[0] ?? symbol2,
|
|
128281
128919
|
reviewSymbols
|
|
128282
128920
|
);
|
|
@@ -128806,7 +129444,7 @@ ${reviewOutputContract}`;
|
|
|
128806
129444
|
});
|
|
128807
129445
|
|
|
128808
129446
|
// lib/runtime/engine.ts
|
|
128809
|
-
var DEVICE_DIAGNOSTICS3, FALLBACK_ERROR_MAX_CHARS, localAnalysis, getExchangeFailureDiagnostics, getRuntimeFallbackAttempts, sentInvocationAttemptCount, boundRuntimeFallbackAttempts, isProviderFailureDiagnosticsCandidate, getEventBoundProviderLabel, getEventBoundProviderTraceId, CLIENT_RUNTIME_POLICY, getRecentProviderFailureDiagnostics, getClientRuntimeErrorProvenance, getRuntimeProviderSetupDiagnostics, buildProviderSetupErrorDiagnosticFields, buildClientRuntimeErrorProvenanceDiagnosticFields, buildRuntimeRequestErrorDiagnosticFields, getCycleErrorModelCalls, isReturnedModelCall, hasEventBoundProviderFailureEvidence, endsWithNeverSentAttempt, classifyRuntimeErrorStage, buildHyperliquidPublicReadDiagnosticFields, buildRuntimeErrorDiagnostics, positiveNumber, resolveRuntimeEngineOptions, withServerPositionEvents, CLIENT_KILLSWITCH_BLOCK_STORAGE_PREFIX, getClientKillswitchBlockStorageKey, isClientRuntimeKillswitchBlocked, persistClientRuntimeKillswitchBlock, clearClientRuntimeKillswitchBlock, hashRuntimeDebugText2, createRuntimeUuid2, getRuntimeContractIdentityToken, getRuntimeStatusContractIdentityToken, getRuntimeContractBindingTokenFromCycleResult, getRuntimeContractBindingTupleToken, getRuntimeStatusContractBindingTupleToken, isTransientRuntimeConflictError, createRuntimeStartCancelledError, isRuntimeContractMismatchError, isClientExecutionModeMismatchError, isClientRuntimeSessionStoppedError, isClientRuntimeLeaseAuthError, isClientRuntimeReleasedError, deriveFailedStartCleanupOwnershipLossReason, isRuntimeAbortError, isExplicitClientExecutionMode, createStopAbortError, isRuntimeContractIdentityAdvancedAbort, CLIENT_RUNTIME_NO_DECISION_RECOVERY_REASON, sanitizeSettingsSnapshotForFallback, preflightClientRuntime, onCadenceGridPoint, ClientExecutionEngine, createStoppedRuntimeSnapshot, ClientRuntimeRegistry, botEngine;
|
|
129447
|
+
var DEVICE_DIAGNOSTICS3, FALLBACK_ERROR_MAX_CHARS, localAnalysis, getExchangeFailureDiagnostics, getRuntimeFallbackAttempts, sentInvocationAttemptCount, boundRuntimeFallbackAttempts, isProviderFailureDiagnosticsCandidate, getEventBoundProviderLabel, getEventBoundProviderTraceId, CLIENT_RUNTIME_POLICY, getRecentProviderFailureDiagnostics, getClientRuntimeErrorProvenance, getRuntimeProviderSetupDiagnostics, buildProviderSetupErrorDiagnosticFields, buildClientRuntimeErrorProvenanceDiagnosticFields, buildRuntimeRequestErrorDiagnosticFields, getCycleErrorModelCalls, isReturnedModelCall, hasEventBoundProviderFailureEvidence, endsWithNeverSentAttempt, classifyRuntimeErrorStage, buildHyperliquidPublicReadDiagnosticFields, buildRuntimeErrorDiagnostics, positiveNumber, resolveRuntimeEngineOptions, withServerPositionEvents, CLIENT_KILLSWITCH_BLOCK_STORAGE_PREFIX, getClientKillswitchBlockStorageKey, isClientRuntimeKillswitchBlocked, persistClientRuntimeKillswitchBlock, clearClientRuntimeKillswitchBlock, hashRuntimeDebugText2, createRuntimeUuid2, getRuntimeContractIdentityToken, getRuntimeStatusContractIdentityToken, getRuntimeContractBindingTokenFromCycleResult, getRuntimeContractBindingTupleToken, getRuntimeStatusContractBindingTupleToken, isTransientRuntimeConflictError, createRuntimeStartCancelledError, isRuntimeContractMismatchError, isClientExecutionModeMismatchError, isClientRuntimeSessionStoppedError, isClientRuntimeLeaseAuthError, isClientRuntimeReleasedError, deriveFailedStartCleanupOwnershipLossReason, isRuntimeAbortError, isExplicitClientExecutionMode, createStopAbortError, isRuntimeContractIdentityAdvancedAbort, CLIENT_RUNTIME_NO_DECISION_RECOVERY_REASON, CLIENT_RUNTIME_NO_DECISION_MESSAGE, sanitizeSettingsSnapshotForFallback, preflightClientRuntime, onCadenceGridPoint, ClientExecutionEngine, createStoppedRuntimeSnapshot, ClientRuntimeRegistry, botEngine;
|
|
128810
129448
|
var init_engine = __esm({
|
|
128811
129449
|
"lib/runtime/engine.ts"() {
|
|
128812
129450
|
"use strict";
|
|
@@ -128852,6 +129490,8 @@ var init_engine = __esm({
|
|
|
128852
129490
|
init_history_evidence();
|
|
128853
129491
|
init_portfolio_evidence();
|
|
128854
129492
|
init_signing_key_messages();
|
|
129493
|
+
init_runtime_error_reason_rules2();
|
|
129494
|
+
init_host_wake_schedule();
|
|
128855
129495
|
init_copy_trading_evidence();
|
|
128856
129496
|
DEVICE_DIAGNOSTICS3 = runtime_policy_generated_default2.trading.engine.client_runtime.device_diagnostics;
|
|
128857
129497
|
FALLBACK_ERROR_MAX_CHARS = runtime_policy_generated_default2.trading.engine.client_runtime.request_bounds.max_fallback_error_length;
|
|
@@ -129197,6 +129837,7 @@ var init_engine = __esm({
|
|
|
129197
129837
|
runtime_error_name: reason instanceof Error && reason.name ? sanitizeRuntimeDiagnosticValue(reason.name) : null,
|
|
129198
129838
|
runtime_error_message: sanitizeRuntimeDiagnosticValue(getSanitizedRuntimeErrorMessage(reason) || "Unknown runtime error."),
|
|
129199
129839
|
fallback_attempt_count: getRuntimeFallbackAttempts(reason)?.length ?? 0,
|
|
129840
|
+
runtime_reason_code: raisedRuntimeErrorReasonCode(reason),
|
|
129200
129841
|
...buildRuntimeRequestErrorDiagnosticFields(reason),
|
|
129201
129842
|
...buildProviderSetupErrorDiagnosticFields(reason),
|
|
129202
129843
|
...buildClientRuntimeErrorProvenanceDiagnosticFields(reason),
|
|
@@ -129211,6 +129852,8 @@ var init_engine = __esm({
|
|
|
129211
129852
|
runtime_error_name: reason instanceof Error && reason.name ? sanitizeRuntimeDiagnosticValue(reason.name) : null,
|
|
129212
129853
|
runtime_error_message: sanitizeRuntimeDiagnosticValue(getSanitizedRuntimeErrorMessage(reason) || "Unknown runtime error."),
|
|
129213
129854
|
fallback_attempt_count: getRuntimeFallbackAttempts(reason)?.length ?? 0,
|
|
129855
|
+
// The code the error was raised with; the server stores it when listed.
|
|
129856
|
+
runtime_reason_code: raisedRuntimeErrorReasonCode(reason),
|
|
129214
129857
|
browser: getRuntimeBrowserDiagnosticsSnapshot(),
|
|
129215
129858
|
...buildRuntimeRequestErrorDiagnosticFields(reason),
|
|
129216
129859
|
...buildProviderSetupErrorDiagnosticFields(reason),
|
|
@@ -129382,6 +130025,7 @@ var init_engine = __esm({
|
|
|
129382
130025
|
return `${recordedReason || ""} ${reasonMessage} ${errorMessage}`.toLowerCase().includes("runtime_contract_identity_advanced");
|
|
129383
130026
|
};
|
|
129384
130027
|
CLIENT_RUNTIME_NO_DECISION_RECOVERY_REASON = "client_runtime_no_decision_cycle";
|
|
130028
|
+
CLIENT_RUNTIME_NO_DECISION_MESSAGE = "This analysis ended before it reached a decision. VTX picks the bot up again automatically.";
|
|
129385
130029
|
sanitizeSettingsSnapshotForFallback = (settingsSnapshot) => {
|
|
129386
130030
|
const { context_snapshots: _contextSnapshots, ...safeSettingsSnapshot } = settingsSnapshot;
|
|
129387
130031
|
return safeSettingsSnapshot;
|
|
@@ -129726,8 +130370,7 @@ var init_engine = __esm({
|
|
|
129726
130370
|
}
|
|
129727
130371
|
/**
|
|
129728
130372
|
* Close on Stop: a Trader's schedule window ended with the option on, so
|
|
129729
|
-
* its open positions close
|
|
129730
|
-
* _handle_schedule_stop does. A failure is reported as a runtime error and
|
|
130373
|
+
* its open positions close. A failure is reported as a runtime error and
|
|
129731
130374
|
* the bot stays paused.
|
|
129732
130375
|
*/
|
|
129733
130376
|
async _closePositionsAtScheduleEnd(profileId, paused, cancelled) {
|
|
@@ -130075,7 +130718,7 @@ var init_engine = __esm({
|
|
|
130075
130718
|
}
|
|
130076
130719
|
}
|
|
130077
130720
|
);
|
|
130078
|
-
await this.reportError(
|
|
130721
|
+
await this.reportError(new RuntimeReasonError(CLIENT_RUNTIME_NO_DECISION_MESSAGE, "cycle_ended_without_decision"), { fatal: false });
|
|
130079
130722
|
this._scheduleRecoverableSuspendAfterExecutionLoop({
|
|
130080
130723
|
reason: CLIENT_RUNTIME_NO_DECISION_RECOVERY_REASON
|
|
130081
130724
|
});
|
|
@@ -130699,6 +131342,14 @@ var init_engine = __esm({
|
|
|
130699
131342
|
get schedulerInstanceId() {
|
|
130700
131343
|
return this._instanceId;
|
|
130701
131344
|
}
|
|
131345
|
+
/** Its own trader lease authority while it runs the profile as a trader, or null (as a CLI host's sweep signs). */
|
|
131346
|
+
get traderLeaseAuthority() {
|
|
131347
|
+
const { _profileId: profileId, _sessionId: sessionId, _deviceId: deviceId } = this;
|
|
131348
|
+
if (this._state !== "running" || this._mode !== "trader" || !profileId || !sessionId || !deviceId) return null;
|
|
131349
|
+
const lease = getPersistedClientRuntimeServerLease(profileId);
|
|
131350
|
+
if (lease?.runtimeSessionId !== sessionId || lease.deviceId !== deviceId || lease.mode !== "trader" || !lease.runtimeLeaseToken) return null;
|
|
131351
|
+
return { runtimeSessionId: sessionId, runtimeLeaseToken: lease.runtimeLeaseToken, runtimeDeviceId: deviceId, schedulerInstanceId: this._instanceId };
|
|
131352
|
+
}
|
|
130702
131353
|
/** Whether this engine runs, starts, or stops a runtime (never claim it again). */
|
|
130703
131354
|
/**
|
|
130704
131355
|
* Resolves once no cycle is in flight, or after the timeout: a Node runtime
|
|
@@ -130904,7 +131555,7 @@ var init_engine = __esm({
|
|
|
130904
131555
|
void this.sendHeartbeat({ confirmGrant: true });
|
|
130905
131556
|
await this._reportAuthoritativeRuntimePresence(profileId);
|
|
130906
131557
|
this._attachLifecycleListeners();
|
|
130907
|
-
this._heartbeatIntervalId = setInterval(() => void this.sendHeartbeat(), this._heartbeatIntervalMs);
|
|
131558
|
+
this._heartbeatIntervalId = markDeferrableTimer(setInterval(() => void this.sendHeartbeat(), this._heartbeatIntervalMs));
|
|
130908
131559
|
await this._startClientKillswitchMonitor(startController);
|
|
130909
131560
|
if (this._state !== "running" || this._killswitchLatched) {
|
|
130910
131561
|
return;
|
|
@@ -133600,6 +134251,7 @@ var init_engine = __esm({
|
|
|
133600
134251
|
}) : null;
|
|
133601
134252
|
const projected = projectRuntimeErrorSurfaceContract({
|
|
133602
134253
|
error: sanitizeRuntimeDiagnosticValue(sanitizedReason),
|
|
134254
|
+
reasonCode: raisedRuntimeErrorReasonCode(reason),
|
|
133603
134255
|
runtimeLiveStatus: this._runtimeStatus?.runtime_live_status ?? "active",
|
|
133604
134256
|
runtimeStopReason: this._runtimeStatus?.runtime_stop_reason ?? null,
|
|
133605
134257
|
isActive: this._mode !== "assistant",
|
|
@@ -133798,7 +134450,7 @@ var init_engine = __esm({
|
|
|
133798
134450
|
// its start.
|
|
133799
134451
|
analyzingObservedAtMs: heartbeatObservedAtMs
|
|
133800
134452
|
});
|
|
133801
|
-
if (Number(response.protective_actions_pending ?? 0) > 0) {
|
|
134453
|
+
if (Number(response.protective_actions_pending ?? 0) > 0 || response.protective_evidence_due === true) {
|
|
133802
134454
|
notifyClientProtectiveActionsPending(heartbeatProfileId);
|
|
133803
134455
|
}
|
|
133804
134456
|
if (this._isStopping || this._state === "stopped" || this._profileId !== heartbeatProfileId || this._sessionId !== heartbeatSessionId || this._deviceId !== heartbeatDeviceId || this._mode !== heartbeatMode || this._lifecycleGeneration !== heartbeatLifecycleGeneration) {
|
|
@@ -133962,6 +134614,8 @@ var init_engine = __esm({
|
|
|
133962
134614
|
mode: this._mode,
|
|
133963
134615
|
lastRunAt: this._lastRunAt,
|
|
133964
134616
|
flushReason: reason,
|
|
134617
|
+
// Its telemetry goes out together, in one request.
|
|
134618
|
+
together: true,
|
|
133965
134619
|
reporter: (profileId, payload) => reportClientRuntimeLifecycleEvent(
|
|
133966
134620
|
profileId,
|
|
133967
134621
|
{ ...payload, schedulerInstanceId: this._instanceId }
|
|
@@ -134012,10 +134666,10 @@ var init_engine = __esm({
|
|
|
134012
134666
|
if (this._state !== "running" || this._mode !== "trader" || this._killswitchLatched) {
|
|
134013
134667
|
return;
|
|
134014
134668
|
}
|
|
134015
|
-
this._killswitchIntervalId = setInterval(
|
|
134669
|
+
this._killswitchIntervalId = markBatchableTimer(setInterval(
|
|
134016
134670
|
() => void this._runClientKillswitchCheck(),
|
|
134017
134671
|
Math.max(CLIENT_RUNTIME_POLICY.killswitch_timer_floor_milliseconds, Math.round(pollIntervalSeconds * MS_PER_SECOND))
|
|
134018
|
-
);
|
|
134672
|
+
));
|
|
134019
134673
|
}
|
|
134020
134674
|
async _runClientKillswitchCheck() {
|
|
134021
134675
|
if (!this._ownsKillswitch() || this._state !== "running" || this._mode !== "trader" || this._killswitchLatched || this._killswitchCheckInFlight || !this._profileId || !this._sessionId || !this._deviceId) {
|
|
@@ -134936,6 +135590,11 @@ var init_engine = __esm({
|
|
|
134936
135590
|
if (!normalized) throw new Error("Missing profile id for client runtime claim.");
|
|
134937
135591
|
return this._getEngine(normalized).schedulerInstanceId;
|
|
134938
135592
|
}
|
|
135593
|
+
/** The local engine's own trader lease authority for this profile, or null. */
|
|
135594
|
+
traderLeaseAuthority(profileId) {
|
|
135595
|
+
const normalized = this._normalizeProfileId(profileId);
|
|
135596
|
+
return normalized ? this._getEngine(normalized, false)?.traderLeaseAuthority ?? null : null;
|
|
135597
|
+
}
|
|
134939
135598
|
/** Whether a local engine runs, starts, or stops this profile. */
|
|
134940
135599
|
isProfileActive(profileId) {
|
|
134941
135600
|
const normalized = this._normalizeProfileId(profileId);
|