@vtxmacro/cli 2026.10.19 → 2026.10.21
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 +7 -3
- package/bin/vtx-mcp.js +8 -4
- package/bin/vtx-service-bootstrap.js +8 -4
- package/bin/vtx-service-launcher.js +7 -3
- package/bin/vtx.js +963 -403
- package/package.json +1 -1
package/bin/vtx.js
CHANGED
|
@@ -113,7 +113,7 @@ var init_routing = __esm({
|
|
|
113
113
|
var agent_cli_release_default;
|
|
114
114
|
var init_agent_cli_release = __esm({
|
|
115
115
|
"agent-cli-release.json"() {
|
|
116
|
-
agent_cli_release_default = { package_name: "@vtxmacro/cli", package_version: "2026.10.
|
|
116
|
+
agent_cli_release_default = { package_name: "@vtxmacro/cli", package_version: "2026.10.21", codex_package_name: "@openai/codex", codex_version: "0.155.0", copilot_sdk_package_name: "@github/copilot-sdk", copilot_sdk_version: "1.0.0-beta.8", copilot_cli_package_name: "@github/copilot", copilot_cli_version: "1.0.80", deepseek_harness_version: "0.1.1-rc.2", deepseek_harness_packages: ["@deepseek-ai/dsh-agent", "@deepseek-ai/dsh-agent-instructions", "@deepseek-ai/dsh-agent-loop", "@deepseek-ai/dsh-agent-spine-demo", "@deepseek-ai/dsh-anonymous-user-id", "@deepseek-ai/dsh-atomic-write", "@deepseek-ai/dsh-attachment", "@deepseek-ai/dsh-brand", "@deepseek-ai/dsh-code-runtime", "@deepseek-ai/dsh-credentials", "@deepseek-ai/dsh-fs", "@deepseek-ai/dsh-goal", "@deepseek-ai/dsh-goal-round-driver", "@deepseek-ai/dsh-home-paths", "@deepseek-ai/dsh-invariants", "@deepseek-ai/dsh-jobs", "@deepseek-ai/dsh-jobs-local", "@deepseek-ai/dsh-launch-environment", "@deepseek-ai/dsh-llm", "@deepseek-ai/dsh-llm-deepseek", "@deepseek-ai/dsh-llm-retry", "@deepseek-ai/dsh-output-retention", "@deepseek-ai/dsh-sandbox", "@deepseek-ai/dsh-sandbox-policy", "@deepseek-ai/dsh-scope", "@deepseek-ai/dsh-session", "@deepseek-ai/dsh-session-checkpoint-policy", "@deepseek-ai/dsh-session-persistence", "@deepseek-ai/dsh-session-persistence-jsonl", "@deepseek-ai/dsh-session-projection", "@deepseek-ai/dsh-session-title", "@deepseek-ai/dsh-settings", "@deepseek-ai/dsh-shell", "@deepseek-ai/dsh-shell-env", "@deepseek-ai/dsh-skill", "@deepseek-ai/dsh-skill-filesystem", "@deepseek-ai/dsh-subprocess", "@deepseek-ai/dsh-system-prompt", "@deepseek-ai/dsh-timeout", "@deepseek-ai/dsh-tool-bash", "@deepseek-ai/dsh-tool-goal", "@deepseek-ai/dsh-tool-jobs", "@deepseek-ai/dsh-tool-skill", "@deepseek-ai/dsh-tools", "@deepseek-ai/dsh-typert-protocol", "@deepseek-ai/dsh-user-approval"], deepseek_cordis_package_name: "@deepseek-ai/cordis", deepseek_cordis_version: "4.0.1", deepseek_support_packages: { "@deepseek-ai/cordis-plugin-timer": "1.1.3" }, platforms: { "linux-x64": { package_name: "@openai/codex-linux-x64", target: "x86_64-unknown-linux-musl", binary_name: "codex", sha256: "660e159a49e823ac8e5986cb238f73158ce4b957d40d9292f8de90862644b501" }, "win32-x64": { package_name: "@openai/codex-win32-x64", target: "x86_64-pc-windows-msvc", binary_name: "codex.exe", sha256: "e4c11374bd9de8ad5c3b7617fd4654bb7839901edb0863f9930666863c7a021b" } }, pi_coding_agent_package_name: "@earendil-works/pi-coding-agent", pi_ai_package_name: "@earendil-works/pi-ai", pi_version: "0.85.1", pi_support_packages: ["@earendil-works/pi-agent-core", "@earendil-works/pi-telemetry", "@earendil-works/pi-tui", "@earendil-works/chord"], grok_version: "1.0.30", grok_platforms: { "linux-x64": { package_name: "@xai-official/grok-linux-x64", binary_name: "grok", sha256: "504dd6546ab991b75d36698242875ce461489cd1f8cd84285873cb55bd5c7d54" }, "win32-x64": { package_name: "@xai-official/grok-win32-x64", binary_name: "grok.exe", sha256: "48736d1a4342a801ea26d0ecde4c516b653f791399065adaa55973f83abd8867" } } };
|
|
117
117
|
}
|
|
118
118
|
});
|
|
119
119
|
|
|
@@ -514,7 +514,6 @@ var init_runtime_policy_generated = __esm({
|
|
|
514
514
|
hidden_ticker_update_interval_ms: 16,
|
|
515
515
|
client_close_fill_sync_attempts: 3,
|
|
516
516
|
client_close_fill_sync_retry_step_ms: 300,
|
|
517
|
-
leverage_update_debounce_ms: 250,
|
|
518
517
|
post_leverage_update_order_delay_ms: 250,
|
|
519
518
|
takeover_telemetry_error_chars: 500,
|
|
520
519
|
takeover_telemetry_error_name_chars: 120,
|
|
@@ -658,7 +657,8 @@ var init_runtime_policy_generated = __esm({
|
|
|
658
657
|
debug_event_lines: 120
|
|
659
658
|
},
|
|
660
659
|
help_page: {
|
|
661
|
-
hash_scroll_settle_ms: 250
|
|
660
|
+
hash_scroll_settle_ms: 250,
|
|
661
|
+
app_docs_retry_seconds: 3
|
|
662
662
|
},
|
|
663
663
|
history_page: {
|
|
664
664
|
preferences_save_debounce_ms: 500,
|
|
@@ -1297,6 +1297,9 @@ var init_runtime_policy_generated = __esm({
|
|
|
1297
1297
|
websocket: {
|
|
1298
1298
|
ping_interval_seconds: 20,
|
|
1299
1299
|
account_open_timeout_seconds: 10
|
|
1300
|
+
},
|
|
1301
|
+
perp_dexs: {
|
|
1302
|
+
default_dex_label: "Hyperliquid"
|
|
1300
1303
|
}
|
|
1301
1304
|
},
|
|
1302
1305
|
cache: {
|
|
@@ -1337,7 +1340,8 @@ var init_runtime_policy_generated = __esm({
|
|
|
1337
1340
|
app_host: {
|
|
1338
1341
|
profiles_refresh_interval_seconds: 60,
|
|
1339
1342
|
running_report_interval_seconds: 5,
|
|
1340
|
-
|
|
1343
|
+
page_start_wait_seconds: 45,
|
|
1344
|
+
page_start_poll_seconds: 1,
|
|
1341
1345
|
profiles_read_timeout_seconds: 30
|
|
1342
1346
|
}
|
|
1343
1347
|
},
|
|
@@ -1462,7 +1466,7 @@ var init_runtime_policy_generated = __esm({
|
|
|
1462
1466
|
});
|
|
1463
1467
|
|
|
1464
1468
|
// lib/constants.ts
|
|
1465
|
-
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, 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, INFERENCE_HOST_RECLAIM_GUARD_CREATE_PASSES, LINUX_PROC_STAT_COMM_TERMINATOR_CHARS, INFERENCE_HOST_RANDOM_BYTES, INFERENCE_OAUTH_TOKEN_MAX_LENGTH, INFERENCE_CREDENTIAL_WINDOWS_NOT_FOUND_EXIT_CODE, MACOS_SECURITY_ITEM_NOT_FOUND_EXIT_CODE, INFERENCE_CREDENTIAL_LABEL_ACCOUNT_KEY_CHARS, INFERENCE_HOST_STABLE_OPERATION_ID_HASH_CHARS, INFERENCE_HOST_DRAIN_PRIORITY, INFERENCE_JOB_CLAIM_SCHEMA_VERSION, INFERENCE_HOST_WINDOWS_TASK_IDENTITY_MAX_CHARS, INFERENCE_HOST_OWNER_ONLY_EXECUTABLE_MODE, WINDOWS_TASKKILL_PROCESS_NOT_FOUND_EXIT_CODE, INFERENCE_HOST_CLI_MAX_SERVICE_POSITIONALS, INFERENCE_HOST_CLI_MAX_COMMAND_POSITIONALS, INFERENCE_HOST_DISPLAY_NAME_MAX_CHARS, INFERENCE_HOST_REVOCATION_CHECKPOINT_MAX_CHARS, INFERENCE_HOST_MODEL_ID_MAX_CHARS, CODEX_RECOVERY_RECEIPT_MAX_CHARS, CODEX_HOSTED_ATTEMPT_PATH_SEGMENTS, CODEX_GUARDIAN_PROCESS_TOKEN_BYTES, CODEX_RATE_LIMIT_EXHAUSTED_PERCENT, INFERENCE_HOST_PROXY_TOKEN_BYTES, GROK_TOOL_SERVER_TOKEN_BYTES, GROK_NATIVE_SESSION_GROUP_NAME_MAX_CHARS, GROK_POLICY_TRANSPORT_MAX_BYTES, EXO_POLICY_MAX_TOOL_ROUNDS, EXO_POLICY_MAX_MODELS, EXO_POLICY_MODEL_NAME_MAX_CHARS, EXO_RUNTIME_VERSION_COMMIT_CHARS, PI_QUALIFIED_MODEL_ID_MAX_CHARS, PI_STRUCTURED_OUTPUT_MAX_DEPTH, PI_STRUCTURED_OUTPUT_MAX_PROPERTIES, INFERENCE_HOST_API_KEY_MIN_CHARS, INFERENCE_HOST_API_KEY_MAX_BYTES, INFERENCE_HOST_API_KEY_IDENTITY_HEX_CHARS, DEEPSEEK_HARNESS_NODE_LTS_MAJOR, DEEPSEEK_HARNESS_NODE_LTS_MIN_MINOR, DEEPSEEK_HARNESS_NODE_CURRENT_MAJOR, PROMPT_FIXED_DIGITS, PROMPT_SIGNIFICANT_DIGITS, PROMPT_NUMBER_MAX_DIGITS, PROMPT_PRICE_INTEGER_THRESHOLD, PROMPT_MARGIN_UTILIZATION_DECIMALS, PROMPT_SYMBOL_MAX_CHARS, PROMPT_PARTIAL_UNIT_ROUND_UP_FRACTION, HALF_UP_ROUNDING_OFFSET, PROMPT_ENTRY_PRICE_MATCH_ABS_TOLERANCE, PROMPT_ENTRY_PRICE_MATCH_REL_TOLERANCE, DECISION_OUTPUT_EXAMPLE_TRADABILITY, INDICATOR_RSI_PERIOD, INDICATOR_ATR_PERIOD, INDICATOR_MACD_FAST_PERIOD, INDICATOR_MACD_SLOW_PERIOD, INDICATOR_MACD_SIGNAL_PERIOD, INDICATOR_BOLLINGER_PERIOD, INDICATOR_BOLLINGER_STD_DEV, INDICATOR_OSCILLATOR_MAX, EMA_SMOOTHING_NUMERATOR, PROMPT_EMA_PERIODS, JSON_UNICODE_ESCAPE_PREFIX_LENGTH, JSON_UNICODE_ESCAPE_HEX_DIGITS, JSON_CONTROL_CHARACTER_MAX, RUNTIME_DEBUG_SNIPPET_CHARS, RUNTIME_DEBUG_PROMPT_SNIPPET_CHARS, RUNTIME_DEBUG_TOKEN_PREFIX_CHARS, RUNTIME_DEBUG_USD_DECIMALS, REVIEW_FAILURE_DETAIL_MAX_CHARS, RUNTIME_LATENCY_SECONDS_DECIMALS, AI_SCHEDULE_CLOCK_PARTS, ESTIMATED_CHARS_PER_TOKEN, PROVIDER_ERROR_RAW_TEXT_MAX_CHARS, AI_CALL_COST_DECIMALS, PROVIDER_DIAGNOSTIC_LIMITS, AI_INVOCATION_CONTRACT_VERSION, AI_INVOCATION_TELEMETRY_LIMITS, PROVIDER_USAGE_DETAIL_LIMITS, HYPERLIQUID_EXCHANGE_SPECIFICATION, HYPERLIQUID_TPSL_BATCH_MIN_ORDERS, HYPERLIQUID_USER_FILLS_PROVIDER_PAGE_CAP, HYPERLIQUID_ROW_WEIGHTED_INFO_REQUESTS, HYPERLIQUID_INFO_ROWS_PER_EXTRA_WEIGHT, HYPERLIQUID_META_AND_ASSET_CTXS_PARTS, HYPERLIQUID_SIDE_PAIR_LENGTH, HYPERLIQUID_SIGNED_SIZE_MATCH_EXTRA_DECIMALS, HYPERLIQUID_OPEN_ORDERS_MAX_NESTING_DEPTH, ACCOUNT_PAYLOAD_MODE_SEARCH_MAX_DEPTH, HYPERLIQUID_ACCOUNT_ROUNDING_DECIMALS, HYPERLIQUID_UNREALIZED_PNL_ZERO_TOLERANCE, HYPERLIQUID_MAX_DEPLOYER_FEE_SCALE, HYPERLIQUID_DEPLOYER_FEE_SCALE_MULTIPLIER, HYPERLIQUID_GROWTH_MODE_FEE_FACTOR, HYPERLIQUID_ALIGNED_QUOTE_NON_DEPLOYER_FEE_FACTOR, HYPERLIQUID_CLOSE_SIZE_RELATIVE_TOLERANCE, HYPERLIQUID_POSITION_SIZE_MATCH_ABS_TOLERANCE, HYPERLIQUID_POSITION_SIZE_MATCH_RELATIVE_TOLERANCE, HYPERLIQUID_LOT_FLOOR_NOISE_DECIMALS, HYPERLIQUID_RECOVERY_BACKOFF_MAX_EXPONENT, HYPERLIQUID_RECOVERY_CONCURRENCY_GROWTH_FACTOR, UUID_BYTES, UUID_HEX_GROUP_ENDS, MSGPACK, CLIENT_RUNTIME_DEFAULT_RETRY_SECONDS, CLIENT_RUNTIME_PROVIDER_ATTEMPT_SUMMARY_MAX_CHARS, CLIENT_RUNTIME_HL_REQUEST_TYPE_MAX_CHARS, CLIENT_RUNTIME_DRAWDOWN_DEBUG_DECIMALS, CLIENT_PROTECTIVE_GROUP_VERSION, CLIENT_PROTECTIVE_TPSL_PAIR_LEGS, CLIENT_PROTECTIVE_FILL_MATCH_ABS_TOLERANCE, CLIENT_PROTECTIVE_FILL_MATCH_REL_TOLERANCE, CLIENT_CLOSE_FILL_EPSILON_ULPS, COPY_TRADING_SIZE_EPSILON, COPY_TRADING_RELATIVE_SIZE_TOLERANCE, COPY_TRADING_NOTIONAL_CAP_TOLERANCE_USD, CLIENT_ACCOUNT_PNL_NONZERO_MIN_USD, RUNTIME_PORTFOLIO_PERIOD_ENTRY_LENGTH, CLIENT_EXCHANGE_RECONCILIATION_MAX_DELAY_MS, RFC1918_172_BLOCK_SECOND_OCTET, AGENT_CLI_TAKEOVER_REQUIRED_EXIT_CODE, EXIT_CODE_INTERRUPTED, EXIT_CODE_SIGNAL_BASE, BYOK_PROVIDER_DISPLAY_ORDER_STEP, TOKENS_PER_MILLION, RENDER_DEBUG_ID_RANDOM_CHARS;
|
|
1469
|
+
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, INFERENCE_HOST_RECLAIM_GUARD_CREATE_PASSES, LINUX_PROC_STAT_COMM_TERMINATOR_CHARS, INFERENCE_HOST_RANDOM_BYTES, INFERENCE_OAUTH_TOKEN_MAX_LENGTH, INFERENCE_CREDENTIAL_WINDOWS_NOT_FOUND_EXIT_CODE, MACOS_SECURITY_ITEM_NOT_FOUND_EXIT_CODE, INFERENCE_CREDENTIAL_LABEL_ACCOUNT_KEY_CHARS, INFERENCE_HOST_STABLE_OPERATION_ID_HASH_CHARS, INFERENCE_HOST_DRAIN_PRIORITY, INFERENCE_JOB_CLAIM_SCHEMA_VERSION, INFERENCE_HOST_WINDOWS_TASK_IDENTITY_MAX_CHARS, INFERENCE_HOST_OWNER_ONLY_EXECUTABLE_MODE, WINDOWS_TASKKILL_PROCESS_NOT_FOUND_EXIT_CODE, INFERENCE_HOST_CLI_MAX_SERVICE_POSITIONALS, INFERENCE_HOST_CLI_MAX_COMMAND_POSITIONALS, INFERENCE_HOST_DISPLAY_NAME_MAX_CHARS, INFERENCE_HOST_REVOCATION_CHECKPOINT_MAX_CHARS, INFERENCE_HOST_MODEL_ID_MAX_CHARS, CODEX_RECOVERY_RECEIPT_MAX_CHARS, CODEX_HOSTED_ATTEMPT_PATH_SEGMENTS, CODEX_GUARDIAN_PROCESS_TOKEN_BYTES, CODEX_RATE_LIMIT_EXHAUSTED_PERCENT, INFERENCE_HOST_PROXY_TOKEN_BYTES, GROK_TOOL_SERVER_TOKEN_BYTES, GROK_NATIVE_SESSION_GROUP_NAME_MAX_CHARS, GROK_POLICY_TRANSPORT_MAX_BYTES, EXO_POLICY_MAX_TOOL_ROUNDS, EXO_POLICY_MAX_MODELS, EXO_POLICY_MODEL_NAME_MAX_CHARS, EXO_RUNTIME_VERSION_COMMIT_CHARS, PI_QUALIFIED_MODEL_ID_MAX_CHARS, PI_STRUCTURED_OUTPUT_MAX_DEPTH, PI_STRUCTURED_OUTPUT_MAX_PROPERTIES, INFERENCE_HOST_API_KEY_MIN_CHARS, INFERENCE_HOST_API_KEY_MAX_BYTES, INFERENCE_HOST_API_KEY_IDENTITY_HEX_CHARS, DEEPSEEK_HARNESS_NODE_LTS_MAJOR, DEEPSEEK_HARNESS_NODE_LTS_MIN_MINOR, DEEPSEEK_HARNESS_NODE_CURRENT_MAJOR, PROMPT_FIXED_DIGITS, PROMPT_SIGNIFICANT_DIGITS, PROMPT_NUMBER_MAX_DIGITS, PROMPT_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_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;
|
|
1466
1470
|
var init_constants = __esm({
|
|
1467
1471
|
"lib/constants.ts"() {
|
|
1468
1472
|
"use strict";
|
|
@@ -1555,6 +1559,7 @@ var init_constants = __esm({
|
|
|
1555
1559
|
HTTP_STATUS_MAX = 599;
|
|
1556
1560
|
HTTP_CLIENT_ERROR_MIN = 400;
|
|
1557
1561
|
HTTP_SERVER_ERROR_MIN = 500;
|
|
1562
|
+
PROMPT_RESCUE_ASKS_PER_CYCLE_BUILD = 2;
|
|
1558
1563
|
USD_DISPLAY_DECIMALS = 2;
|
|
1559
1564
|
AI_COST_ESTIMATE_PERIOD_DAYS = 30;
|
|
1560
1565
|
SECONDS_PER_AI_COST_ESTIMATE_PERIOD = SECONDS_PER_DAY * AI_COST_ESTIMATE_PERIOD_DAYS;
|
|
@@ -1827,6 +1832,8 @@ var init_constants = __esm({
|
|
|
1827
1832
|
PROMPT_FIXED_DIGITS = 2;
|
|
1828
1833
|
PROMPT_SIGNIFICANT_DIGITS = 5;
|
|
1829
1834
|
PROMPT_NUMBER_MAX_DIGITS = 100;
|
|
1835
|
+
PROMPT_RELATIVE_VOLUME_DIGITS = 2;
|
|
1836
|
+
BINARY_RADIX = 2;
|
|
1830
1837
|
PROMPT_PRICE_INTEGER_THRESHOLD = 1e5;
|
|
1831
1838
|
PROMPT_MARGIN_UTILIZATION_DECIMALS = 1;
|
|
1832
1839
|
PROMPT_SYMBOL_MAX_CHARS = 100;
|
|
@@ -20325,7 +20332,6 @@ var init_runtime_policy_generated2 = __esm({
|
|
|
20325
20332
|
hidden_ticker_update_interval_ms: 16,
|
|
20326
20333
|
client_close_fill_sync_attempts: 3,
|
|
20327
20334
|
client_close_fill_sync_retry_step_ms: 300,
|
|
20328
|
-
leverage_update_debounce_ms: 250,
|
|
20329
20335
|
post_leverage_update_order_delay_ms: 250,
|
|
20330
20336
|
takeover_telemetry_error_chars: 500,
|
|
20331
20337
|
takeover_telemetry_error_name_chars: 120,
|
|
@@ -20469,7 +20475,8 @@ var init_runtime_policy_generated2 = __esm({
|
|
|
20469
20475
|
debug_event_lines: 120
|
|
20470
20476
|
},
|
|
20471
20477
|
help_page: {
|
|
20472
|
-
hash_scroll_settle_ms: 250
|
|
20478
|
+
hash_scroll_settle_ms: 250,
|
|
20479
|
+
app_docs_retry_seconds: 3
|
|
20473
20480
|
},
|
|
20474
20481
|
history_page: {
|
|
20475
20482
|
preferences_save_debounce_ms: 500,
|
|
@@ -21108,6 +21115,9 @@ var init_runtime_policy_generated2 = __esm({
|
|
|
21108
21115
|
websocket: {
|
|
21109
21116
|
ping_interval_seconds: 20,
|
|
21110
21117
|
account_open_timeout_seconds: 10
|
|
21118
|
+
},
|
|
21119
|
+
perp_dexs: {
|
|
21120
|
+
default_dex_label: "Hyperliquid"
|
|
21111
21121
|
}
|
|
21112
21122
|
},
|
|
21113
21123
|
cache: {
|
|
@@ -21148,7 +21158,8 @@ var init_runtime_policy_generated2 = __esm({
|
|
|
21148
21158
|
app_host: {
|
|
21149
21159
|
profiles_refresh_interval_seconds: 60,
|
|
21150
21160
|
running_report_interval_seconds: 5,
|
|
21151
|
-
|
|
21161
|
+
page_start_wait_seconds: 45,
|
|
21162
|
+
page_start_poll_seconds: 1,
|
|
21152
21163
|
profiles_read_timeout_seconds: 30
|
|
21153
21164
|
}
|
|
21154
21165
|
},
|
|
@@ -52880,6 +52891,66 @@ var init_protection_storage = __esm({
|
|
|
52880
52891
|
}
|
|
52881
52892
|
});
|
|
52882
52893
|
|
|
52894
|
+
// lib/android-app.ts
|
|
52895
|
+
var ANDROID_APP_PACKAGES, ANDROID_APP_REFERRER_SCHEME, ANDROID_APP_LAUNCH_STORAGE_KEY, ANDROID_APP_HOST_FRAGMENT_PARAM, knownLaunch, storedLaunch, referrerPackage, hostFragment, remember, androidAppLaunch, isAndroidAppPage;
|
|
52896
|
+
var init_android_app = __esm({
|
|
52897
|
+
"lib/android-app.ts"() {
|
|
52898
|
+
"use strict";
|
|
52899
|
+
init_define_VTX_EXO_POLICY();
|
|
52900
|
+
init_define_VTX_GROK_POLICY();
|
|
52901
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
52902
|
+
ANDROID_APP_PACKAGES = ["com.vtxmacro.android", "com.vtxmacro.android.debug"];
|
|
52903
|
+
ANDROID_APP_REFERRER_SCHEME = "android-app://";
|
|
52904
|
+
ANDROID_APP_LAUNCH_STORAGE_KEY = "vtx_android_app_launch";
|
|
52905
|
+
ANDROID_APP_HOST_FRAGMENT_PARAM = "vtx_app_host";
|
|
52906
|
+
storedLaunch = () => {
|
|
52907
|
+
try {
|
|
52908
|
+
const parsed = JSON.parse(window.sessionStorage.getItem(ANDROID_APP_LAUNCH_STORAGE_KEY) || "null");
|
|
52909
|
+
if (!parsed || !ANDROID_APP_PACKAGES.includes(parsed.packageName)) return null;
|
|
52910
|
+
return { packageName: parsed.packageName, hostDeviceId: typeof parsed.hostDeviceId === "string" ? parsed.hostDeviceId : null };
|
|
52911
|
+
} catch {
|
|
52912
|
+
return null;
|
|
52913
|
+
}
|
|
52914
|
+
};
|
|
52915
|
+
referrerPackage = () => {
|
|
52916
|
+
const referrer = document.referrer;
|
|
52917
|
+
if (!referrer.startsWith(ANDROID_APP_REFERRER_SCHEME)) return null;
|
|
52918
|
+
const packageName = referrer.slice(ANDROID_APP_REFERRER_SCHEME.length).replace(/\/$/, "");
|
|
52919
|
+
return ANDROID_APP_PACKAGES.includes(packageName) ? packageName : null;
|
|
52920
|
+
};
|
|
52921
|
+
hostFragment = () => new URLSearchParams(window.location.hash.replace(/^#/, "")).get(ANDROID_APP_HOST_FRAGMENT_PARAM);
|
|
52922
|
+
remember = (launch) => {
|
|
52923
|
+
knownLaunch = launch;
|
|
52924
|
+
try {
|
|
52925
|
+
window.sessionStorage.setItem(ANDROID_APP_LAUNCH_STORAGE_KEY, JSON.stringify(launch));
|
|
52926
|
+
} catch {
|
|
52927
|
+
}
|
|
52928
|
+
const fragment = new URLSearchParams(window.location.hash.replace(/^#/, ""));
|
|
52929
|
+
if (fragment.has(ANDROID_APP_HOST_FRAGMENT_PARAM)) {
|
|
52930
|
+
fragment.delete(ANDROID_APP_HOST_FRAGMENT_PARAM);
|
|
52931
|
+
const rest = fragment.toString();
|
|
52932
|
+
window.history.replaceState(window.history.state, "", `${window.location.pathname}${window.location.search}${rest ? `#${rest}` : ""}`);
|
|
52933
|
+
}
|
|
52934
|
+
return launch;
|
|
52935
|
+
};
|
|
52936
|
+
androidAppLaunch = () => {
|
|
52937
|
+
if (typeof window === "undefined") return null;
|
|
52938
|
+
if (knownLaunch !== void 0) {
|
|
52939
|
+
const named = knownLaunch && !knownLaunch.hostDeviceId ? hostFragment() : null;
|
|
52940
|
+
return named && knownLaunch ? remember({ ...knownLaunch, hostDeviceId: named }) : knownLaunch;
|
|
52941
|
+
}
|
|
52942
|
+
const stored = storedLaunch();
|
|
52943
|
+
const packageName = referrerPackage();
|
|
52944
|
+
if (!packageName) {
|
|
52945
|
+
knownLaunch = stored;
|
|
52946
|
+
return knownLaunch;
|
|
52947
|
+
}
|
|
52948
|
+
return remember({ packageName, hostDeviceId: hostFragment() || stored?.hostDeviceId || null });
|
|
52949
|
+
};
|
|
52950
|
+
isAndroidAppPage = () => androidAppLaunch() !== null;
|
|
52951
|
+
}
|
|
52952
|
+
});
|
|
52953
|
+
|
|
52883
52954
|
// lib/api/browser-api-url.ts
|
|
52884
52955
|
function resolveBrowserApiUrl(hostname3, protocol, publicApiUrl, development, privateSecondOctets) {
|
|
52885
52956
|
if (development) {
|
|
@@ -53000,6 +53071,7 @@ var init_shared = __esm({
|
|
|
53000
53071
|
init_define_VTX_EXO_POLICY();
|
|
53001
53072
|
init_define_VTX_GROK_POLICY();
|
|
53002
53073
|
init_define_VTX_PI_MODEL_POLICY();
|
|
53074
|
+
init_android_app();
|
|
53003
53075
|
init_browser_api_url();
|
|
53004
53076
|
init_runtime_policy_generated2();
|
|
53005
53077
|
init_constants();
|
|
@@ -53175,6 +53247,7 @@ var init_shared = __esm({
|
|
|
53175
53247
|
return `web-${action}-${suffix}`;
|
|
53176
53248
|
};
|
|
53177
53249
|
getErrorMessage = (error48, defaultMessage) => {
|
|
53250
|
+
if (typeof error48?.detail_in_android_app === "string" && isAndroidAppPage()) return error48.detail_in_android_app;
|
|
53178
53251
|
const extractRateLimitMessage = (raw) => {
|
|
53179
53252
|
if (!/rate\s*limit|429|cooling\s*down/i.test(raw)) return null;
|
|
53180
53253
|
const match = raw.match(/cooling\s*down\s*for\s*([0-9]+(?:\.[0-9]+)?)s/i);
|
|
@@ -54793,7 +54866,6 @@ async function getLiveTicker(symbol2 = "PI_XBTUSD", exchange = "kraken", signal)
|
|
|
54793
54866
|
}
|
|
54794
54867
|
async function getExecutionAssetMetadata(exchange, symbol2, options) {
|
|
54795
54868
|
const params = new URLSearchParams();
|
|
54796
|
-
if (options?.includePrivateContext) params.set("include_private_context", "true");
|
|
54797
54869
|
if (options?.forceCatalogRefresh) params.set("force_catalog_refresh", "true");
|
|
54798
54870
|
if (options?.publicRequestPriority) params.set("public_request_priority", options.publicRequestPriority);
|
|
54799
54871
|
const query = params.size > 0 ? `?${params.toString()}` : "";
|
|
@@ -54859,40 +54931,6 @@ var init_client_host_commands = __esm({
|
|
|
54859
54931
|
}
|
|
54860
54932
|
});
|
|
54861
54933
|
|
|
54862
|
-
// lib/api/insights-access-center.ts
|
|
54863
|
-
var init_insights_access_center = __esm({
|
|
54864
|
-
"lib/api/insights-access-center.ts"() {
|
|
54865
|
-
"use strict";
|
|
54866
|
-
init_define_VTX_EXO_POLICY();
|
|
54867
|
-
init_define_VTX_GROK_POLICY();
|
|
54868
|
-
init_define_VTX_PI_MODEL_POLICY();
|
|
54869
|
-
init_shared();
|
|
54870
|
-
}
|
|
54871
|
-
});
|
|
54872
|
-
|
|
54873
|
-
// lib/api/updates.ts
|
|
54874
|
-
var init_updates = __esm({
|
|
54875
|
-
"lib/api/updates.ts"() {
|
|
54876
|
-
"use strict";
|
|
54877
|
-
init_define_VTX_EXO_POLICY();
|
|
54878
|
-
init_define_VTX_GROK_POLICY();
|
|
54879
|
-
init_define_VTX_PI_MODEL_POLICY();
|
|
54880
|
-
init_shared();
|
|
54881
|
-
init_constants();
|
|
54882
|
-
}
|
|
54883
|
-
});
|
|
54884
|
-
|
|
54885
|
-
// lib/api/profile-emoji.ts
|
|
54886
|
-
var init_profile_emoji = __esm({
|
|
54887
|
-
"lib/api/profile-emoji.ts"() {
|
|
54888
|
-
"use strict";
|
|
54889
|
-
init_define_VTX_EXO_POLICY();
|
|
54890
|
-
init_define_VTX_GROK_POLICY();
|
|
54891
|
-
init_define_VTX_PI_MODEL_POLICY();
|
|
54892
|
-
init_shared();
|
|
54893
|
-
}
|
|
54894
|
-
});
|
|
54895
|
-
|
|
54896
54934
|
// lib/runtime/host-storage.ts
|
|
54897
54935
|
function configureRuntimeHostStorage(storage3) {
|
|
54898
54936
|
configuredStorage = storage3;
|
|
@@ -55139,6 +55177,107 @@ var init_server_runtime_lease = __esm({
|
|
|
55139
55177
|
}
|
|
55140
55178
|
});
|
|
55141
55179
|
|
|
55180
|
+
// lib/api/logout.ts
|
|
55181
|
+
var init_logout = __esm({
|
|
55182
|
+
"lib/api/logout.ts"() {
|
|
55183
|
+
"use strict";
|
|
55184
|
+
init_define_VTX_EXO_POLICY();
|
|
55185
|
+
init_define_VTX_GROK_POLICY();
|
|
55186
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
55187
|
+
init_android_app();
|
|
55188
|
+
init_server_runtime_lease();
|
|
55189
|
+
init_shared();
|
|
55190
|
+
}
|
|
55191
|
+
});
|
|
55192
|
+
|
|
55193
|
+
// lib/api/insights-access-center.ts
|
|
55194
|
+
var init_insights_access_center = __esm({
|
|
55195
|
+
"lib/api/insights-access-center.ts"() {
|
|
55196
|
+
"use strict";
|
|
55197
|
+
init_define_VTX_EXO_POLICY();
|
|
55198
|
+
init_define_VTX_GROK_POLICY();
|
|
55199
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
55200
|
+
init_shared();
|
|
55201
|
+
}
|
|
55202
|
+
});
|
|
55203
|
+
|
|
55204
|
+
// lib/api/updates.ts
|
|
55205
|
+
var init_updates = __esm({
|
|
55206
|
+
"lib/api/updates.ts"() {
|
|
55207
|
+
"use strict";
|
|
55208
|
+
init_define_VTX_EXO_POLICY();
|
|
55209
|
+
init_define_VTX_GROK_POLICY();
|
|
55210
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
55211
|
+
init_shared();
|
|
55212
|
+
init_constants();
|
|
55213
|
+
}
|
|
55214
|
+
});
|
|
55215
|
+
|
|
55216
|
+
// lib/api/profile-emoji.ts
|
|
55217
|
+
var init_profile_emoji = __esm({
|
|
55218
|
+
"lib/api/profile-emoji.ts"() {
|
|
55219
|
+
"use strict";
|
|
55220
|
+
init_define_VTX_EXO_POLICY();
|
|
55221
|
+
init_define_VTX_GROK_POLICY();
|
|
55222
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
55223
|
+
init_shared();
|
|
55224
|
+
}
|
|
55225
|
+
});
|
|
55226
|
+
|
|
55227
|
+
// app/(app)/trade/tradeRefreshPolicy.ts
|
|
55228
|
+
function parseTradeRefreshPolicy(raw) {
|
|
55229
|
+
const source = raw && typeof raw === "object" ? raw : {};
|
|
55230
|
+
const parsed = {};
|
|
55231
|
+
for (const key of TRADE_REFRESH_POLICY_KEYS) {
|
|
55232
|
+
const value = Number(source[key]);
|
|
55233
|
+
if (!Number.isFinite(value) || value <= 0) {
|
|
55234
|
+
throw new Error(`Missing required runtime policy ui.trade_refresh_policy.${key}`);
|
|
55235
|
+
}
|
|
55236
|
+
parsed[key] = value;
|
|
55237
|
+
}
|
|
55238
|
+
if (parsed.account_read_backoff_min_ms > parsed.account_read_backoff_max_ms) {
|
|
55239
|
+
throw new Error("Invalid runtime policy ui.trade_refresh_policy: account_read_backoff_min_ms exceeds account_read_backoff_max_ms");
|
|
55240
|
+
}
|
|
55241
|
+
return parsed;
|
|
55242
|
+
}
|
|
55243
|
+
var TRADE_REFRESH_POLICY_KEYS, TRADE_REFRESH_POLICY;
|
|
55244
|
+
var init_tradeRefreshPolicy = __esm({
|
|
55245
|
+
"app/(app)/trade/tradeRefreshPolicy.ts"() {
|
|
55246
|
+
"use strict";
|
|
55247
|
+
init_define_VTX_EXO_POLICY();
|
|
55248
|
+
init_define_VTX_GROK_POLICY();
|
|
55249
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
55250
|
+
init_constants();
|
|
55251
|
+
init_runtime_policy_generated2();
|
|
55252
|
+
TRADE_REFRESH_POLICY_KEYS = [
|
|
55253
|
+
"server_config_stream_timeout_ms",
|
|
55254
|
+
"config_retry_interval_ms",
|
|
55255
|
+
"copy_trading_status_poll_ms",
|
|
55256
|
+
"post_execution_refresh_delay_ms",
|
|
55257
|
+
"account_read_backoff_min_ms",
|
|
55258
|
+
"account_read_backoff_max_ms",
|
|
55259
|
+
"account_read_backoff_exponent_max",
|
|
55260
|
+
"ai_start_grace_min_ms"
|
|
55261
|
+
];
|
|
55262
|
+
TRADE_REFRESH_POLICY = parseTradeRefreshPolicy(
|
|
55263
|
+
runtime_policy_generated_default2.ui?.trade_refresh_policy
|
|
55264
|
+
);
|
|
55265
|
+
}
|
|
55266
|
+
});
|
|
55267
|
+
|
|
55268
|
+
// lib/api/account-summary.ts
|
|
55269
|
+
var init_account_summary = __esm({
|
|
55270
|
+
"lib/api/account-summary.ts"() {
|
|
55271
|
+
"use strict";
|
|
55272
|
+
init_define_VTX_EXO_POLICY();
|
|
55273
|
+
init_define_VTX_GROK_POLICY();
|
|
55274
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
55275
|
+
init_tradeRefreshPolicy();
|
|
55276
|
+
init_constants();
|
|
55277
|
+
init_shared();
|
|
55278
|
+
}
|
|
55279
|
+
});
|
|
55280
|
+
|
|
55142
55281
|
// lib/runtime/hyperliquid-account-mode-contract.ts
|
|
55143
55282
|
function resolveExactHyperliquidAccountMode(userAbstraction, ...dexEvidence) {
|
|
55144
55283
|
const mode = extractCanonicalHyperliquidAccountMode(userAbstraction);
|
|
@@ -55739,7 +55878,7 @@ var init_hyperliquid_order_status = __esm({
|
|
|
55739
55878
|
});
|
|
55740
55879
|
|
|
55741
55880
|
// lib/runtime/hyperliquid-public-read.ts
|
|
55742
|
-
var policy, weights, recoveryPolicy, budgets, unpersistedBudgets, cache, pending2, PREFIX, priorityRank, createHyperliquidPublicPriorityScope, promoteHyperliquidPublicPriority, hostTransport, abortError2, checkAbort, wait, waitUnlessPromoted, storage, loadBudget, saveBudget, withBudgetLock, HyperliquidPublicReadError, getHyperliquidPublicReadBudget, cooldownError, recoveryWaitError, nonTradingWeightCap, nonTradingWaitMs, fallbackDelayMs, admit, settleRowWeightedReservation, cooldown, finishHyperliquidRecoveryRequest, assertHyperliquidRecoveryDispatch, validateHyperliquidRecoveryDispatch, cacheTtlMs, eligibleCache, reserveHyperliquidPublicReads, releaseHyperliquidPublicReadReservation, admitHyperliquidExchangeRequest, recordHyperliquidExchangeResponse, readHyperliquidPublicInfo;
|
|
55881
|
+
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, nonTradingWeightCap, nonTradingWaitMs, fallbackDelayMs, admit, settleRowWeightedReservation, cooldown, finishHyperliquidRecoveryRequest, assertHyperliquidRecoveryDispatch, validateHyperliquidRecoveryDispatch, cacheTtlMs, eligibleCache, reserveHyperliquidPublicReads, releaseHyperliquidPublicReadReservation, admitHyperliquidExchangeRequest, recordHyperliquidExchangeResponse, readHyperliquidPublicInfo;
|
|
55743
55882
|
var init_hyperliquid_public_read = __esm({
|
|
55744
55883
|
"lib/runtime/hyperliquid-public-read.ts"() {
|
|
55745
55884
|
"use strict";
|
|
@@ -55765,6 +55904,7 @@ var init_hyperliquid_public_read = __esm({
|
|
|
55765
55904
|
scope.followers?.forEach((promote) => promote(priority));
|
|
55766
55905
|
};
|
|
55767
55906
|
hostTransport = null;
|
|
55907
|
+
hyperliquidPrivateInfoHeldOff = async () => await hostTransport?.privateInfoHeldOff?.() === true;
|
|
55768
55908
|
abortError2 = (signal) => getSanitizedRuntimeAbortReason(signal, "Aborted");
|
|
55769
55909
|
checkAbort = (signal) => {
|
|
55770
55910
|
if (signal?.aborted) throw abortError2(signal);
|
|
@@ -56512,7 +56652,8 @@ var init_runtime_error_reason_rules = __esm({
|
|
|
56512
56652
|
{ contains: "order was not sent" },
|
|
56513
56653
|
{ any: [
|
|
56514
56654
|
{ contains: "signing key is not authorized for the configured wallet" },
|
|
56515
|
-
{ contains: "hyperliquid confirmed that the signing key is not authorized" }
|
|
56655
|
+
{ contains: "hyperliquid confirmed that the signing key is not authorized" },
|
|
56656
|
+
{ contains: "hyperliquid has not approved this key for this profile's wallet" }
|
|
56516
56657
|
] }
|
|
56517
56658
|
] } },
|
|
56518
56659
|
{ reason_code: "credentials_missing", when: { all: [
|
|
@@ -56576,7 +56717,8 @@ var init_runtime_error_reason_rules = __esm({
|
|
|
56576
56717
|
] } },
|
|
56577
56718
|
{ reason_code: "hyperliquid_wallet_not_authorized", when: { any: [
|
|
56578
56719
|
{ contains: "hyperliquid api wallet is not authorized" },
|
|
56579
|
-
{ contains: "hyperliquid signing key is not authorized for this wallet" }
|
|
56720
|
+
{ contains: "hyperliquid signing key is not authorized for this wallet" },
|
|
56721
|
+
{ contains: "hyperliquid has not approved this key for this profile's wallet" }
|
|
56580
56722
|
] } },
|
|
56581
56723
|
{ reason_code: "ai_service_rate_limit", when: { any: [
|
|
56582
56724
|
{ all: [
|
|
@@ -56742,6 +56884,21 @@ var init_runtime_error_reason_rules2 = __esm({
|
|
|
56742
56884
|
}
|
|
56743
56885
|
});
|
|
56744
56886
|
|
|
56887
|
+
// lib/runtime/signing-key-messages.ts
|
|
56888
|
+
var SIGNING_KEY_NOT_APPROVED, SIGNING_KEY_INVALID, SIGNING_KEY_THEN_START, SIGNING_KEY_NOT_APPROVED_THEN_START;
|
|
56889
|
+
var init_signing_key_messages = __esm({
|
|
56890
|
+
"lib/runtime/signing-key-messages.ts"() {
|
|
56891
|
+
"use strict";
|
|
56892
|
+
init_define_VTX_EXO_POLICY();
|
|
56893
|
+
init_define_VTX_GROK_POLICY();
|
|
56894
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
56895
|
+
SIGNING_KEY_NOT_APPROVED = "Hyperliquid has not approved this key for this profile's wallet. API wallets expire, so it may have run out. On Hyperliquid, open More > API and authorize an API wallet for this wallet, then paste its private key in System > Hyperliquid Configuration > Private Key (Secret) and save.";
|
|
56896
|
+
SIGNING_KEY_INVALID = "This is not a valid private key. Paste the API wallet's private key from Hyperliquid (0x followed by 64 characters).";
|
|
56897
|
+
SIGNING_KEY_THEN_START = "Then start the bot.";
|
|
56898
|
+
SIGNING_KEY_NOT_APPROVED_THEN_START = `${SIGNING_KEY_NOT_APPROVED} ${SIGNING_KEY_THEN_START}`;
|
|
56899
|
+
}
|
|
56900
|
+
});
|
|
56901
|
+
|
|
56745
56902
|
// lib/runtime/error-surface-contract.ts
|
|
56746
56903
|
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;
|
|
56747
56904
|
var init_error_surface_contract = __esm({
|
|
@@ -56754,6 +56911,7 @@ var init_error_surface_contract = __esm({
|
|
|
56754
56911
|
init_status_contract();
|
|
56755
56912
|
init_runtime_redaction();
|
|
56756
56913
|
init_runtime_error_reason_rules2();
|
|
56914
|
+
init_signing_key_messages();
|
|
56757
56915
|
RUNTIME_SERVICE_UNAVAILABLE_TOKENS = [
|
|
56758
56916
|
"503",
|
|
56759
56917
|
"service unavailable",
|
|
@@ -57053,7 +57211,7 @@ var init_error_surface_contract = __esm({
|
|
|
57053
57211
|
return formatHyperliquidRateLimitMessage({ message, pausePrefix, retrySeconds });
|
|
57054
57212
|
}
|
|
57055
57213
|
if (RUNTIME_HYPERLIQUID_WALLET_NOT_AUTHORIZED_PATTERN.test(message)) {
|
|
57056
|
-
return `${pausePrefix}:
|
|
57214
|
+
return `${pausePrefix}: ${SIGNING_KEY_NOT_APPROVED_THEN_START}`;
|
|
57057
57215
|
}
|
|
57058
57216
|
if (statusCode == null && isRuntimeAppBootstrapUnavailableError(message)) {
|
|
57059
57217
|
return `${pausePrefix}: VTX could not load this profile's runtime settings because the server returned 503. ${runtimeRetryPhrase(retrySeconds)}`;
|
|
@@ -57210,7 +57368,7 @@ var init_error_surface_contract = __esm({
|
|
|
57210
57368
|
} else if (resolvedReason === "signer_validation_unavailable") {
|
|
57211
57369
|
message = `\u26A0\uFE0F The ${orderLabel} was not sent: VTX could not verify this profile's signing-key authorization because required Hyperliquid account data was temporarily unavailable. No order was submitted, and the signing key was not rejected. VTX will try again automatically if the trader is running; no action is required.`;
|
|
57212
57370
|
} else if (resolvedReason === "wallet_not_authorized") {
|
|
57213
|
-
message = `\u26A0\uFE0F The ${orderLabel} was not sent:
|
|
57371
|
+
message = `\u26A0\uFE0F The ${orderLabel} was not sent: ${SIGNING_KEY_NOT_APPROVED}`;
|
|
57214
57372
|
} else if (resolvedReason === "credentials_missing") {
|
|
57215
57373
|
message = `\u26A0\uFE0F The ${orderLabel} was not sent: a wallet address and authorized signing key are required for trading.`;
|
|
57216
57374
|
} else if (resolvedReason === "local_safety_block") {
|
|
@@ -88377,20 +88535,14 @@ var init_hyperliquid_client = __esm({
|
|
|
88377
88535
|
if (!symbol2) {
|
|
88378
88536
|
throw new Error("Missing Hyperliquid symbol.");
|
|
88379
88537
|
}
|
|
88380
|
-
const
|
|
88381
|
-
input.includePrivateContext && String(input.walletAddress ?? "").trim()
|
|
88382
|
-
);
|
|
88383
|
-
const devicePrivateContext = deviceReadsPrivateContext ? readDevicePrivateExecutionContext({
|
|
88538
|
+
const devicePrivateContext = input.includePrivateContext ? readDevicePrivateExecutionContext({
|
|
88384
88539
|
...input,
|
|
88385
|
-
|
|
88540
|
+
// Refused before any request when the wallet is missing.
|
|
88541
|
+
walletAddress: requireWalletAddress(String(input.walletAddress ?? "")),
|
|
88386
88542
|
symbol: symbol2
|
|
88387
88543
|
}) : null;
|
|
88388
88544
|
devicePrivateContext?.catch(() => void 0);
|
|
88389
|
-
const metadata = input.
|
|
88390
|
-
includePrivateContext: true,
|
|
88391
|
-
...input.publicRequestPriority === "trading_reduce" ? { publicRequestPriority: "trading_reduce" } : {},
|
|
88392
|
-
profileId: Number.isFinite(Number(input.profileId)) ? Number(input.profileId) : void 0
|
|
88393
|
-
}) : input.publicRequestPriority === "trading_reduce" ? await getExecutionAssetMetadata("hyperliquid", symbol2, { publicRequestPriority: "trading_reduce" }) : await getExecutionAssetMetadata("hyperliquid", symbol2);
|
|
88545
|
+
const metadata = input.publicRequestPriority === "trading_reduce" ? await getExecutionAssetMetadata("hyperliquid", symbol2, { publicRequestPriority: "trading_reduce" }) : await getExecutionAssetMetadata("hyperliquid", symbol2);
|
|
88394
88546
|
const deviceContext = devicePrivateContext ? await devicePrivateContext : null;
|
|
88395
88547
|
const executionContextReceivedAtMonotonicMs = globalThis.performance.now();
|
|
88396
88548
|
const resolved = normalizeExecutionAssetMetadata(symbol2, metadata);
|
|
@@ -88430,11 +88582,6 @@ var init_hyperliquid_client = __esm({
|
|
|
88430
88582
|
executionPositionSize: deviceContext.executionPositionSize,
|
|
88431
88583
|
executionContextAtMs: deviceContext.executionContextAtMs,
|
|
88432
88584
|
executionContextReceivedAtMonotonicMs
|
|
88433
|
-
} : input.includePrivateContext ? {
|
|
88434
|
-
executionMarkPrice: Number.isFinite(Number(metadata.execution_mark_price)) && Number(metadata.execution_mark_price) > 0 ? Number(metadata.execution_mark_price) : null,
|
|
88435
|
-
executionPositionSize: Number.isFinite(Number(metadata.execution_position_size)) ? Number(metadata.execution_position_size) : null,
|
|
88436
|
-
executionContextAtMs: Number.isFinite(Number(metadata.execution_context_at_ms)) && Number(metadata.execution_context_at_ms) > 0 ? Number(metadata.execution_context_at_ms) : null,
|
|
88437
|
-
executionContextReceivedAtMonotonicMs
|
|
88438
88585
|
} : {}
|
|
88439
88586
|
};
|
|
88440
88587
|
};
|
|
@@ -91691,9 +91838,11 @@ var init_api2 = __esm({
|
|
|
91691
91838
|
init_market_data();
|
|
91692
91839
|
init_screener();
|
|
91693
91840
|
init_client_host_commands();
|
|
91841
|
+
init_logout();
|
|
91694
91842
|
init_insights_access_center();
|
|
91695
91843
|
init_updates();
|
|
91696
91844
|
init_profile_emoji();
|
|
91845
|
+
init_account_summary();
|
|
91697
91846
|
init_server_runtime_lease();
|
|
91698
91847
|
clientRuntimeSecretHeaders = (profileId) => {
|
|
91699
91848
|
const headers = getProfileHeaders({}, profileId);
|
|
@@ -92328,6 +92477,7 @@ var init_hyperliquid_signer_binding = __esm({
|
|
|
92328
92477
|
init_hyperliquid_client();
|
|
92329
92478
|
init_hyperliquid_exchange_rejections();
|
|
92330
92479
|
init_error_surface_contract();
|
|
92480
|
+
init_signing_key_messages();
|
|
92331
92481
|
DeviceSigningKeyError = class extends RuntimeExecutionError {
|
|
92332
92482
|
constructor(message, reasonCode, deviceSigningKeyFailure) {
|
|
92333
92483
|
super(message, reasonCode);
|
|
@@ -92399,7 +92549,7 @@ var init_hyperliquid_signer_binding = __esm({
|
|
|
92399
92549
|
);
|
|
92400
92550
|
} catch {
|
|
92401
92551
|
throw new DeviceSigningKeyError(
|
|
92402
|
-
|
|
92552
|
+
SIGNING_KEY_INVALID,
|
|
92403
92553
|
"credentials_missing",
|
|
92404
92554
|
"device_signing_key_invalid"
|
|
92405
92555
|
);
|
|
@@ -92418,7 +92568,7 @@ var init_hyperliquid_signer_binding = __esm({
|
|
|
92418
92568
|
const cached2 = validatedSignerBindings.get(cacheKey);
|
|
92419
92569
|
if (cached2 && cached2.generation === generation) return cached2.binding;
|
|
92420
92570
|
}
|
|
92421
|
-
const
|
|
92571
|
+
const remember2 = (binding) => {
|
|
92422
92572
|
if (signerBindingCache && generation !== null) validatedSignerBindings.set(cacheKey, { generation, binding });
|
|
92423
92573
|
return binding;
|
|
92424
92574
|
};
|
|
@@ -92439,7 +92589,7 @@ var init_hyperliquid_signer_binding = __esm({
|
|
|
92439
92589
|
}
|
|
92440
92590
|
const signerRole = String(roleResponse.role || "").trim().toLowerCase();
|
|
92441
92591
|
if (signerRole === "user" && signerAddress === walletAddress) {
|
|
92442
|
-
return
|
|
92592
|
+
return remember2({
|
|
92443
92593
|
signerAddress,
|
|
92444
92594
|
walletAddress,
|
|
92445
92595
|
signerRole: "user"
|
|
@@ -92451,7 +92601,7 @@ var init_hyperliquid_signer_binding = __esm({
|
|
|
92451
92601
|
["user"]
|
|
92452
92602
|
);
|
|
92453
92603
|
if (masterWallet === walletAddress) {
|
|
92454
|
-
return
|
|
92604
|
+
return remember2({
|
|
92455
92605
|
signerAddress,
|
|
92456
92606
|
walletAddress,
|
|
92457
92607
|
signerRole: "agent"
|
|
@@ -92459,7 +92609,7 @@ var init_hyperliquid_signer_binding = __esm({
|
|
|
92459
92609
|
}
|
|
92460
92610
|
}
|
|
92461
92611
|
throw new DeviceSigningKeyError(
|
|
92462
|
-
|
|
92612
|
+
SIGNING_KEY_NOT_APPROVED,
|
|
92463
92613
|
"wallet_not_authorized",
|
|
92464
92614
|
"device_signing_key_unauthorized"
|
|
92465
92615
|
);
|
|
@@ -96901,7 +97051,7 @@ function copiedTargetNow(reconciliation, recordedTarget, actualPosition) {
|
|
|
96901
97051
|
);
|
|
96902
97052
|
return { copiedNow, targetNow, kept: copiedTargetBesideOwnPosition(targetNow, copiedNow, actualPosition) };
|
|
96903
97053
|
}
|
|
96904
|
-
var clientProtectiveMutationAuthority, executionReadPriority, serverEntryLeverageAlreadyHeld, fetchClientRuntimeOpenOrders, _extractOrderResponseStates, createRuntimeId, _extractFilledSize, _extractOrderId, _toExecutionMetadata, _extractClientMutationId, _stableMutationIdentity, trailingStopMemory, protectiveGroupMemory, protectiveGroupReadFailures, windowHandoffCleanupAttempts, clientRuntimeProtectionStorage, resolveClientRuntimeProtectionStorage, setClientRuntimeProtectionStorage, trailingStopStorageKey, readTrackedTrailingStops, writeTrackedTrailingStops, rememberTrailingStop, protectiveGroupStorageKey, LOST_LEG_EVIDENCE_MAX_AGE_MS, EPISODE_END_FILL_LOOKBACK_MS, withClientProtectivePlanSetLock, readClientProtectiveGroups, writeClientProtectiveGroups, hasClientProtectiveGroupReadFailure, readFreshClientProtectiveGroups, stableProtectionSnapshot, exactClientProtectiveGroupSnapshot, exactClientProtectiveGroupSetSnapshot, storableClientProtectiveGroup, replaceExactClientProtectiveGroup, replaceExactClientProtectiveGroupSet, isClientRuntimeLeaseOwnershipError, hasClientRuntimeProtectionState, clearClientRuntimeVetoedProtectiveIntent, rethrowWindowHandoffAfterProtectiveReplacementVeto, canPersistClientProtectiveGroups, removeTrackedTrailingStop, replaceTrackedTrailingStop, replaceProtectiveLeg, replacementJournalEntryOrderId, buildProtectiveReplacementJournalGroup, isProtectiveReplacementJournalGroup, reserveProtectiveLegReplacement, ensureProtectiveReplacementJournalCompanion, buildVetoedProtectiveReplacementCleanup, assertExactProtectiveReplacementDispatchAuthority, transitionProtectiveReplacementAcknowledgement, transitionTerminalProtectiveReplacement, pendingProtectiveReplacementReport, isConfiguredProtectionRequested, protectiveAction, executedProtectiveReport, isExactClientPositionTpslPair, deviceOwnsClientProtectiveLegKind, isAdoptionNarrowedPositionTpslLeg, hasAmbiguousClientPositionTpslAuthority, protectiveStableShapeMatches, observedProtectiveGroupingMatches, protectiveLiveShapeMatches, protectiveTerminalShapeMatches, cancelClientProtectiveLeg, buildPendingProtectivePlan, persistPendingClientProtectiveGroup, attachmentMemberNeverLanded, storedClientProtectiveCover, attachClientProtectivePlan, resolveJournaledAttachmentContinuity, protectiveMemberRested, ledgerOrderIdsByClientOrderId, journaledAttachmentNeverLanded, recoverJournaledClientProtectiveAttachments, readClientOrderMutation, readPendingEntryMutation, clientOrderNeverLandsAfterMs, requireClientRuntimeConfigSeconds, replacePendingEntryRecovery, recoverPendingClientProtectiveGroups, recoverPendingProtectiveReplacements, liveProtectiveOrderShape, observedStandaloneProtectiveGroup, migrateTrackedTrailingStopsToStandalone, reconcileClientProtectiveGroups, cancelAllClientProtectiveGroups, tightenClientTrailingStops, throwIfAborted2, sleep2, isDefinitiveEntryRejection, resolveExchangeSizeDecimals, roundAssetSize, resolvePositionSize, readServerOrderMarkPrice, serverOrderMetadataRetry, resolveCurrentPositionSize, buildPositionSnapshot, signedRemainingExposureAfterConfirmedReduction, runtimeProtectionAuthority, runtimeProtectionOwners, resolveRuntimeProtectionOwner, drainServerProtectionForRuntime, drainServerProtectionIfOwned, verifyNoLiveClientProtectiveTriggers, clientExecutionMutations, CLIENT_EXECUTION_QUEUE_TIMEOUT_MESSAGE, withClientExecutionMutation, withClientProtectivePlanSetMutation, allocateServerExecutionCapacity, withClientProtectiveAdoptionMutation, executeClientRuntimeDecisionLocked, unsentDecisionOrderReport, withCapacityTrim, SERVER_AUDIT_RECORDED_ELSEWHERE, serverExecutionAuditOutcome, decisionLegOf, withExecutionAuditId, executeClientRuntimeDecision, waitForFlipCloseFreshness, maintainClientRuntimeTrailingStops, listPendingClientProtectiveSymbols, listStoredClientProtectiveSymbols, hasUnresolvedClientProtectiveIdentity, resolveClientProtectiveIdentitiesForAdoption, exportClientProtectiveGroupsForAdoption, adoptionGroupKey, applyClientProtectiveAdoptionOutcomes, hasStoredClientProtectiveGroupsForWallet, hasPendingClientProtectiveGroups, recoverManualClientProtectiveGroups, clientRuntimeDecisionSizesOrders, COMMITTED_EXECUTION_REPORTS, getCommittedExecutionReports, withCommittedExecutionReports, executeClientRuntimeDecisionUnlocked, executeClientCopyTradingIntent, _copyCancelOrderId, executeClientCopyTradingOrderAction;
|
|
97054
|
+
var clientProtectiveMutationAuthority, executionReadPriority, serverEntryLeverageAlreadyHeld, fetchClientRuntimeOpenOrders, _extractOrderResponseStates, createRuntimeId, _extractFilledSize, _extractOrderId, _toExecutionMetadata, _extractClientMutationId, _stableMutationIdentity, trailingStopMemory, protectiveGroupMemory, protectiveGroupReadFailures, windowHandoffCleanupAttempts, clientRuntimeProtectionStorage, resolveClientRuntimeProtectionStorage, setClientRuntimeProtectionStorage, trailingStopStorageKey, readTrackedTrailingStops, writeTrackedTrailingStops, rememberTrailingStop, protectiveGroupStorageKey, LOST_LEG_EVIDENCE_MAX_AGE_MS, EPISODE_END_FILL_LOOKBACK_MS, withClientProtectivePlanSetLock, readClientProtectiveGroups, writeClientProtectiveGroups, hasClientProtectiveGroupReadFailure, readFreshClientProtectiveGroups, stableProtectionSnapshot, exactClientProtectiveGroupSnapshot, exactClientProtectiveGroupSetSnapshot, storableClientProtectiveGroup, replaceExactClientProtectiveGroup, replaceExactClientProtectiveGroupSet, isClientRuntimeLeaseOwnershipError, hasClientRuntimeProtectionState, clearClientRuntimeVetoedProtectiveIntent, rethrowWindowHandoffAfterProtectiveReplacementVeto, canPersistClientProtectiveGroups, removeTrackedTrailingStop, replaceTrackedTrailingStop, replaceProtectiveLeg, replacementJournalEntryOrderId, buildProtectiveReplacementJournalGroup, isProtectiveReplacementJournalGroup, reserveProtectiveLegReplacement, ensureProtectiveReplacementJournalCompanion, buildVetoedProtectiveReplacementCleanup, assertExactProtectiveReplacementDispatchAuthority, transitionProtectiveReplacementAcknowledgement, transitionTerminalProtectiveReplacement, pendingProtectiveReplacementReport, isConfiguredProtectionRequested, protectiveAction, executedProtectiveReport, isExactClientPositionTpslPair, deviceOwnsClientProtectiveLegKind, isAdoptionNarrowedPositionTpslLeg, hasAmbiguousClientPositionTpslAuthority, protectiveStableShapeMatches, observedProtectiveGroupingMatches, protectiveLiveShapeMatches, protectiveTerminalShapeMatches, cancelClientProtectiveLeg, buildPendingProtectivePlan, persistPendingClientProtectiveGroup, attachmentMemberNeverLanded, storedClientProtectiveCover, attachClientProtectivePlan, resolveJournaledAttachmentContinuity, protectiveMemberRested, ledgerOrderIdsByClientOrderId, journaledAttachmentNeverLanded, recoverJournaledClientProtectiveAttachments, readClientOrderMutation, readPendingEntryMutation, clientOrderNeverLandsAfterMs, requireClientRuntimeConfigSeconds, replacePendingEntryRecovery, recoverPendingClientProtectiveGroups, recoverPendingProtectiveReplacements, liveProtectiveOrderShape, observedStandaloneProtectiveGroup, migrateTrackedTrailingStopsToStandalone, reconcileClientProtectiveGroups, cancelAllClientProtectiveGroups, tightenClientTrailingStops, throwIfAborted2, sleep2, isDefinitiveEntryRejection, resolveExchangeSizeDecimals, roundAssetSize, resolvePositionSize, readServerOrderMarkPrice, serverOrderMetadataRetry, resolveCurrentPositionSize, buildPositionSnapshot, signedRemainingExposureAfterConfirmedReduction, runtimeProtectionAuthority, runtimeProtectionOwners, resolveRuntimeProtectionOwner, drainServerProtectionForRuntime, drainServerProtectionIfOwned, verifyNoLiveClientProtectiveTriggers, clientExecutionMutations, CLIENT_EXECUTION_QUEUE_TIMEOUT_MESSAGE, withClientExecutionMutation, withClientProtectivePlanSetMutation, allocateServerExecutionCapacity, withClientProtectiveAdoptionMutation, executeClientRuntimeDecisionLocked, unsentDecisionOrderReport, withCapacityTrim, SERVER_AUDIT_RECORDED_ELSEWHERE, serverExecutionAuditOutcome, decisionLegOf, withExecutionAuditId, executeClientRuntimeDecision, waitForFlipCloseFreshness, maintainClientRuntimeTrailingStops, listPendingClientProtectiveSymbols, listStoredClientProtectiveSymbols, hasUnresolvedClientProtectiveIdentity, resolveClientProtectiveIdentitiesForAdoption, exportClientProtectiveGroupsForAdoption, adoptionGroupKey, applyClientProtectiveAdoptionOutcomes, hasStoredClientProtectiveGroupsForWallet, hasPendingClientProtectiveGroups, recoverManualClientProtectiveGroups, clientRuntimeDecisionSizesOrders, COMMITTED_EXECUTION_REPORTS, COMMITTED_DECISION_ORDER, getCommittedExecutionReports, getCommittedDecisionOrder, withCommittedExecutionReports, executeClientRuntimeDecisionUnlocked, executeClientCopyTradingIntent, _copyCancelOrderId, executeClientCopyTradingOrderAction;
|
|
96905
97055
|
var init_runtime_execution = __esm({
|
|
96906
97056
|
"lib/runtime/runtime-execution.ts"() {
|
|
96907
97057
|
"use strict";
|
|
@@ -102376,7 +102526,7 @@ var init_runtime_execution = __esm({
|
|
|
102376
102526
|
try {
|
|
102377
102527
|
return await executeClientRuntimeDecisionUnlocked(input, progress);
|
|
102378
102528
|
} catch (error48) {
|
|
102379
|
-
throw withCommittedExecutionReports(error48, progress.committedReports);
|
|
102529
|
+
throw withCommittedExecutionReports(error48, progress.committedReports, progress.committedOrder ?? null);
|
|
102380
102530
|
}
|
|
102381
102531
|
});
|
|
102382
102532
|
unsentDecisionOrderReport = (input, reasonCode, metadata = {}) => ({
|
|
@@ -102433,6 +102583,7 @@ var init_runtime_execution = __esm({
|
|
|
102433
102583
|
if (input.executionMode !== "server") return executeClientRuntimeDecisionLocked(input);
|
|
102434
102584
|
const audit = input.serverExecutionAudit ?? { auditId: null };
|
|
102435
102585
|
let entryDispatched = false;
|
|
102586
|
+
let exitDispatched = false;
|
|
102436
102587
|
const recordAudit = async (auditId2, fields, signal = input.signal) => {
|
|
102437
102588
|
try {
|
|
102438
102589
|
const recorded = await recordServerHostExecutionAudit(
|
|
@@ -102469,13 +102620,15 @@ var init_runtime_execution = __esm({
|
|
|
102469
102620
|
onExchangeOrderDispatched: (kind) => {
|
|
102470
102621
|
input.onExchangeOrderDispatched?.(kind);
|
|
102471
102622
|
if (kind === "entry") entryDispatched = true;
|
|
102623
|
+
if (kind === "exit") exitDispatched = true;
|
|
102472
102624
|
}
|
|
102473
102625
|
});
|
|
102474
102626
|
} catch (error48) {
|
|
102475
102627
|
const committedClose = getCommittedExecutionReports(error48).find((report) => report.status === "executed" && decisionLegOf(report) === "flip_close");
|
|
102476
102628
|
if (audit.auditId !== null && (!input.signal?.aborted || committedClose) && (input.decision === "BUY" || input.decision === "SELL")) {
|
|
102477
102629
|
const reason = String(error48?.reasonCode ?? "");
|
|
102478
|
-
const
|
|
102630
|
+
const orderMayHaveGoneOut = entryDispatched || exitDispatched && !committedClose;
|
|
102631
|
+
const [status2, reasonCode2] = reason === "outcome_unknown" || !reason && orderMayHaveGoneOut ? ["outcome_unknown", "outcome_unknown"] : ["error", reason === "exchange_rejected" ? "exchange_rejected" : "execution_error"];
|
|
102479
102632
|
const side = input.decision === "BUY" ? "buy" : "sell";
|
|
102480
102633
|
if (committedClose) {
|
|
102481
102634
|
await recordAudit(audit.auditId, {
|
|
@@ -102952,12 +103105,18 @@ var init_runtime_execution = __esm({
|
|
|
102952
103105
|
return !input.skipTrailingMaintenance && context.tpSlEnabled === true && context.stopLossEnabled !== false && context.stopLossType === "trailing" && positionSize !== 0;
|
|
102953
103106
|
};
|
|
102954
103107
|
COMMITTED_EXECUTION_REPORTS = /* @__PURE__ */ Symbol("committedExecutionReports");
|
|
103108
|
+
COMMITTED_DECISION_ORDER = /* @__PURE__ */ Symbol("committedDecisionOrder");
|
|
102955
103109
|
getCommittedExecutionReports = (error48) => {
|
|
102956
103110
|
if (!error48 || typeof error48 !== "object") return [];
|
|
102957
103111
|
const reports = error48[COMMITTED_EXECUTION_REPORTS];
|
|
102958
103112
|
return Array.isArray(reports) ? reports : [];
|
|
102959
103113
|
};
|
|
102960
|
-
|
|
103114
|
+
getCommittedDecisionOrder = (error48) => {
|
|
103115
|
+
if (!error48 || typeof error48 !== "object") return null;
|
|
103116
|
+
const order = error48[COMMITTED_DECISION_ORDER];
|
|
103117
|
+
return order && typeof order === "object" ? order : null;
|
|
103118
|
+
};
|
|
103119
|
+
withCommittedExecutionReports = (error48, reports, order = null) => {
|
|
102961
103120
|
if (!reports || !reports.some((report) => report.status === "executed")) return error48;
|
|
102962
103121
|
const carrier = error48 && typeof error48 === "object" ? error48 : new Error(String(error48 ?? "Unknown runtime execution error."), { cause: error48 });
|
|
102963
103122
|
Object.defineProperty(carrier, COMMITTED_EXECUTION_REPORTS, {
|
|
@@ -102965,6 +103124,11 @@ var init_runtime_execution = __esm({
|
|
|
102965
103124
|
enumerable: false,
|
|
102966
103125
|
configurable: true
|
|
102967
103126
|
});
|
|
103127
|
+
Object.defineProperty(carrier, COMMITTED_DECISION_ORDER, {
|
|
103128
|
+
value: order,
|
|
103129
|
+
enumerable: false,
|
|
103130
|
+
configurable: true
|
|
103131
|
+
});
|
|
102968
103132
|
return carrier;
|
|
102969
103133
|
};
|
|
102970
103134
|
executeClientRuntimeDecisionUnlocked = async (unsizedInput, progress = { committedReports: null }) => {
|
|
@@ -103361,7 +103525,7 @@ var init_runtime_execution = __esm({
|
|
|
103361
103525
|
config: input.config ?? null,
|
|
103362
103526
|
signal: input.signal,
|
|
103363
103527
|
signingKey: input.signingKey,
|
|
103364
|
-
onExchangeOrderDispatched: () => input.onExchangeOrderDispatched?.("
|
|
103528
|
+
onExchangeOrderDispatched: () => input.onExchangeOrderDispatched?.("exit"),
|
|
103365
103529
|
symbol: input.executionContext.symbol,
|
|
103366
103530
|
position: currentPosition,
|
|
103367
103531
|
estimatedPrice,
|
|
@@ -103373,8 +103537,30 @@ var init_runtime_execution = __esm({
|
|
|
103373
103537
|
const expectedCloseSize = Math.abs(currentPositionSize);
|
|
103374
103538
|
const closeTolerance = Math.max(expectedCloseSize, 1) * Number.EPSILON * CLIENT_CLOSE_FILL_EPSILON_ULPS;
|
|
103375
103539
|
const closeFillConfirmed = confirmedClose != null && Math.abs(confirmedClose.filledSize - expectedCloseSize) <= closeTolerance;
|
|
103540
|
+
const closeReport = {
|
|
103541
|
+
order_id: _extractOrderId(closeResponse),
|
|
103542
|
+
client_mutation_id: _extractClientMutationId(closeResponse),
|
|
103543
|
+
symbol: input.executionContext.symbol,
|
|
103544
|
+
action: classified.side.toUpperCase(),
|
|
103545
|
+
status: "executed",
|
|
103546
|
+
execution_metadata: _toExecutionMetadata(closeResponse)
|
|
103547
|
+
};
|
|
103548
|
+
const committedCloseReports = [...reconciliationReports, closeReport];
|
|
103549
|
+
progress.committedReports = committedCloseReports;
|
|
103550
|
+
const recordPostCloseReports = (reports) => {
|
|
103551
|
+
reconciliationReports.push(...reports);
|
|
103552
|
+
committedCloseReports.push(...reports);
|
|
103553
|
+
};
|
|
103554
|
+
progress.committedOrder = {
|
|
103555
|
+
intent: classified.intent,
|
|
103556
|
+
side: classified.side,
|
|
103557
|
+
reduceOnly: classified.reduceOnly,
|
|
103558
|
+
requestedUnits: classified.requestedUnits,
|
|
103559
|
+
targetSignedUnits: classified.targetSignedUnits,
|
|
103560
|
+
executedSizeAsset: confirmedClose?.filledSize ?? 0
|
|
103561
|
+
};
|
|
103376
103562
|
if (closeFillConfirmed) {
|
|
103377
|
-
|
|
103563
|
+
recordPostCloseReports(await cancelAllClientProtectiveGroups(
|
|
103378
103564
|
input,
|
|
103379
103565
|
"position_closed"
|
|
103380
103566
|
));
|
|
@@ -103385,7 +103571,7 @@ var init_runtime_execution = __esm({
|
|
|
103385
103571
|
[]
|
|
103386
103572
|
);
|
|
103387
103573
|
} else if (hasTrackedProtection) {
|
|
103388
|
-
|
|
103574
|
+
recordPostCloseReports(await reconcileClientProtectiveGroups(
|
|
103389
103575
|
input,
|
|
103390
103576
|
confirmedClose == null ? void 0 : signedRemainingExposureAfterConfirmedReduction(
|
|
103391
103577
|
currentPositionSize,
|
|
@@ -103401,17 +103587,7 @@ var init_runtime_execution = __esm({
|
|
|
103401
103587
|
requestedUnits: classified.requestedUnits,
|
|
103402
103588
|
targetSignedUnits: classified.targetSignedUnits,
|
|
103403
103589
|
executedSizeAsset: confirmedClose?.filledSize ?? 0,
|
|
103404
|
-
executionReports: [
|
|
103405
|
-
...reconciliationReports,
|
|
103406
|
-
{
|
|
103407
|
-
order_id: _extractOrderId(closeResponse),
|
|
103408
|
-
client_mutation_id: _extractClientMutationId(closeResponse),
|
|
103409
|
-
symbol: input.executionContext.symbol,
|
|
103410
|
-
action: classified.side.toUpperCase(),
|
|
103411
|
-
status: "executed",
|
|
103412
|
-
execution_metadata: _toExecutionMetadata(closeResponse)
|
|
103413
|
-
}
|
|
103414
|
-
],
|
|
103590
|
+
executionReports: [...reconciliationReports, closeReport],
|
|
103415
103591
|
message: closeFillConfirmed ? "Closed position" : "The close order did not confirm the full position size; retained trailing protection for any remaining exposure.",
|
|
103416
103592
|
...closeFillConfirmed ? {} : { reasonCode: "close_fill_unresolved" },
|
|
103417
103593
|
executionSnapshotId,
|
|
@@ -103437,7 +103613,7 @@ var init_runtime_execution = __esm({
|
|
|
103437
103613
|
config: input.config ?? null,
|
|
103438
103614
|
signal: input.signal,
|
|
103439
103615
|
signingKey: input.signingKey,
|
|
103440
|
-
onExchangeOrderDispatched: () => input.onExchangeOrderDispatched?.("
|
|
103616
|
+
onExchangeOrderDispatched: () => input.onExchangeOrderDispatched?.("exit"),
|
|
103441
103617
|
symbol: input.executionContext.symbol,
|
|
103442
103618
|
position: currentPosition,
|
|
103443
103619
|
estimatedPrice,
|
|
@@ -103765,7 +103941,7 @@ var init_runtime_execution = __esm({
|
|
|
103765
103941
|
);
|
|
103766
103942
|
}
|
|
103767
103943
|
input.onExchangeOrderDispatched?.(
|
|
103768
|
-
classified.intent === "open" || classified.intent === "add" || classified.intent === "flip" ? "entry" : "
|
|
103944
|
+
classified.intent === "open" || classified.intent === "add" || classified.intent === "flip" ? "entry" : "exit"
|
|
103769
103945
|
);
|
|
103770
103946
|
entryDispatchBoundaryPassed = true;
|
|
103771
103947
|
},
|
|
@@ -103862,6 +104038,15 @@ var init_runtime_execution = __esm({
|
|
|
103862
104038
|
status: "executed",
|
|
103863
104039
|
execution_metadata: classified.intent === "flip" ? { ..._toExecutionMetadata(marketOrderResponse), decision_leg: "entry" } : { ..._toExecutionMetadata(marketOrderResponse), entry_began_flat: livePositionDirection === 0 }
|
|
103864
104040
|
});
|
|
104041
|
+
progress.committedReports = executionReports;
|
|
104042
|
+
progress.committedOrder = {
|
|
104043
|
+
intent: classified.intent,
|
|
104044
|
+
side: classified.side,
|
|
104045
|
+
reduceOnly: classified.reduceOnly,
|
|
104046
|
+
requestedUnits: classified.requestedUnits,
|
|
104047
|
+
targetSignedUnits: classified.targetSignedUnits,
|
|
104048
|
+
executedSizeAsset: confirmedMarketFill == null ? 0 : confirmedMarketFill.filledSize
|
|
104049
|
+
};
|
|
103865
104050
|
const appendPostEntryProtectionFailure = (error48) => {
|
|
103866
104051
|
const projection = projectExecutionErrorContract({
|
|
103867
104052
|
error: error48,
|
|
@@ -104426,7 +104611,6 @@ var init_runtime_execution = __esm({
|
|
|
104426
104611
|
size: destinationSize,
|
|
104427
104612
|
roundingMode: "nearest",
|
|
104428
104613
|
includePrivateContext: desiredPosition != null && Number.isFinite(desiredPosition),
|
|
104429
|
-
profileId: input.profileId,
|
|
104430
104614
|
// The device reads its own position and mark; the server never reads
|
|
104431
104615
|
// a Client wallet.
|
|
104432
104616
|
walletAddress: input.walletAddress,
|
|
@@ -108704,6 +108888,183 @@ var init_profile_model_cascade = __esm({
|
|
|
108704
108888
|
}
|
|
108705
108889
|
});
|
|
108706
108890
|
|
|
108891
|
+
// lib/runtime/prompt-variable-validation-contract.ts
|
|
108892
|
+
var ESCAPED_OPEN_BRACE, ESCAPED_CLOSE_BRACE, PROMPT_PLACEHOLDER_PATTERN, ESCAPED_BRACE_PAIR_PATTERN, readPromptTemplate, restoreEscapedBraces, countAtMost, countBelow, locatePlaceholders, isPromptVariableName, renderPromptTemplate, promptTemplatePlaceholderSpans, promptTemplatePlaceholders, promptTemplateVariables, NEWS_PROMPT_VARIABLES, REFERENCE_CANDLES_PROMPT_VARIABLE, ALLOWED_PROMPT_VARIABLES, OPTIONAL_BLANK_PROMPT_VARIABLES, coercePromptVariableValue, isMissingPromptVariableValue, validatePromptVariables;
|
|
108893
|
+
var init_prompt_variable_validation_contract = __esm({
|
|
108894
|
+
"lib/runtime/prompt-variable-validation-contract.ts"() {
|
|
108895
|
+
"use strict";
|
|
108896
|
+
init_define_VTX_EXO_POLICY();
|
|
108897
|
+
init_define_VTX_GROK_POLICY();
|
|
108898
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
108899
|
+
ESCAPED_OPEN_BRACE = "__VTX_PROMPT_OPEN_BRACE__";
|
|
108900
|
+
ESCAPED_CLOSE_BRACE = "__VTX_PROMPT_CLOSE_BRACE__";
|
|
108901
|
+
PROMPT_PLACEHOLDER_PATTERN = /\{([a-zA-Z0-9_]+)\}/g;
|
|
108902
|
+
ESCAPED_BRACE_PAIR_PATTERN = /\{\{|\}\}/g;
|
|
108903
|
+
readPromptTemplate = (template) => {
|
|
108904
|
+
const prepared = template.replaceAll("{{", ESCAPED_OPEN_BRACE).replaceAll("}}", ESCAPED_CLOSE_BRACE);
|
|
108905
|
+
return {
|
|
108906
|
+
prepared,
|
|
108907
|
+
placeholders: Array.from(prepared.matchAll(PROMPT_PLACEHOLDER_PATTERN), (match) => ({
|
|
108908
|
+
name: match[1],
|
|
108909
|
+
start: match.index,
|
|
108910
|
+
end: match.index + match[0].length
|
|
108911
|
+
}))
|
|
108912
|
+
};
|
|
108913
|
+
};
|
|
108914
|
+
restoreEscapedBraces = (text) => text.replaceAll(ESCAPED_OPEN_BRACE, "{").replaceAll(ESCAPED_CLOSE_BRACE, "}");
|
|
108915
|
+
countAtMost = (ascending, value) => {
|
|
108916
|
+
let low = 0;
|
|
108917
|
+
let high = ascending.length;
|
|
108918
|
+
while (low < high) {
|
|
108919
|
+
const middle = low + high >>> 1;
|
|
108920
|
+
if (ascending[middle] <= value) low = middle + 1;
|
|
108921
|
+
else high = middle;
|
|
108922
|
+
}
|
|
108923
|
+
return low;
|
|
108924
|
+
};
|
|
108925
|
+
countBelow = (ascending, value) => {
|
|
108926
|
+
let low = 0;
|
|
108927
|
+
let high = ascending.length;
|
|
108928
|
+
while (low < high) {
|
|
108929
|
+
const middle = low + high >>> 1;
|
|
108930
|
+
if (ascending[middle] < value) low = middle + 1;
|
|
108931
|
+
else high = middle;
|
|
108932
|
+
}
|
|
108933
|
+
return low;
|
|
108934
|
+
};
|
|
108935
|
+
locatePlaceholders = (template) => {
|
|
108936
|
+
const { prepared, placeholders } = readPromptTemplate(template);
|
|
108937
|
+
const markerStarts = [];
|
|
108938
|
+
const markerEnds = [];
|
|
108939
|
+
const addedLengths = [];
|
|
108940
|
+
let added = 0;
|
|
108941
|
+
for (const pair of template.matchAll(ESCAPED_BRACE_PAIR_PATTERN)) {
|
|
108942
|
+
const marker = pair[0] === "{{" ? ESCAPED_OPEN_BRACE : ESCAPED_CLOSE_BRACE;
|
|
108943
|
+
markerStarts.push(pair.index + added);
|
|
108944
|
+
added += marker.length - pair[0].length;
|
|
108945
|
+
markerEnds.push(pair.index + pair[0].length + added);
|
|
108946
|
+
addedLengths.push(added);
|
|
108947
|
+
}
|
|
108948
|
+
return {
|
|
108949
|
+
prepared,
|
|
108950
|
+
located: placeholders.map((placeholder) => {
|
|
108951
|
+
const markersBefore = countAtMost(markerEnds, placeholder.start);
|
|
108952
|
+
if (countBelow(markerStarts, placeholder.end) !== markersBefore) {
|
|
108953
|
+
return { placeholder, sourceStart: null };
|
|
108954
|
+
}
|
|
108955
|
+
const offset = markersBefore > 0 ? addedLengths[markersBefore - 1] : 0;
|
|
108956
|
+
return { placeholder, sourceStart: placeholder.start - offset };
|
|
108957
|
+
})
|
|
108958
|
+
};
|
|
108959
|
+
};
|
|
108960
|
+
isPromptVariableName = (name) => !/^[0-9]/.test(name);
|
|
108961
|
+
renderPromptTemplate = (template, contextVars) => {
|
|
108962
|
+
if (typeof template !== "string" || !template) {
|
|
108963
|
+
return "";
|
|
108964
|
+
}
|
|
108965
|
+
const safeContext = contextVars && typeof contextVars === "object" ? contextVars : {};
|
|
108966
|
+
const { prepared, placeholders } = readPromptTemplate(template);
|
|
108967
|
+
const rendered = [];
|
|
108968
|
+
let cursor = 0;
|
|
108969
|
+
for (const placeholder of placeholders) {
|
|
108970
|
+
rendered.push(prepared.slice(cursor, placeholder.start));
|
|
108971
|
+
const value = Object.prototype.hasOwnProperty.call(safeContext, placeholder.name) ? safeContext[placeholder.name] : void 0;
|
|
108972
|
+
rendered.push(value === null || value === void 0 ? "" : String(value));
|
|
108973
|
+
cursor = placeholder.end;
|
|
108974
|
+
}
|
|
108975
|
+
rendered.push(prepared.slice(cursor));
|
|
108976
|
+
return restoreEscapedBraces(rendered.join(""));
|
|
108977
|
+
};
|
|
108978
|
+
promptTemplatePlaceholderSpans = (template) => {
|
|
108979
|
+
if (typeof template !== "string" || !template) {
|
|
108980
|
+
return [];
|
|
108981
|
+
}
|
|
108982
|
+
const spans = [];
|
|
108983
|
+
for (const { placeholder, sourceStart } of locatePlaceholders(template).located) {
|
|
108984
|
+
if (sourceStart !== null) {
|
|
108985
|
+
spans.push({
|
|
108986
|
+
name: placeholder.name,
|
|
108987
|
+
start: sourceStart,
|
|
108988
|
+
end: sourceStart + (placeholder.end - placeholder.start)
|
|
108989
|
+
});
|
|
108990
|
+
}
|
|
108991
|
+
}
|
|
108992
|
+
return spans;
|
|
108993
|
+
};
|
|
108994
|
+
promptTemplatePlaceholders = (template) => promptTemplatePlaceholderSpans(template).map((placeholder) => placeholder.name);
|
|
108995
|
+
promptTemplateVariables = (template) => promptTemplatePlaceholders(template).filter(isPromptVariableName);
|
|
108996
|
+
NEWS_PROMPT_VARIABLES = ["news_benzinga", "news_telegram"];
|
|
108997
|
+
REFERENCE_CANDLES_PROMPT_VARIABLE = "reference_candles";
|
|
108998
|
+
ALLOWED_PROMPT_VARIABLES = /* @__PURE__ */ new Set([
|
|
108999
|
+
"current_time",
|
|
109000
|
+
"candles",
|
|
109001
|
+
REFERENCE_CANDLES_PROMPT_VARIABLE,
|
|
109002
|
+
"market_stats",
|
|
109003
|
+
"account_status",
|
|
109004
|
+
"calendar",
|
|
109005
|
+
"behavior_state",
|
|
109006
|
+
"positions",
|
|
109007
|
+
"performance",
|
|
109008
|
+
"market_regime",
|
|
109009
|
+
...NEWS_PROMPT_VARIABLES,
|
|
109010
|
+
"size",
|
|
109011
|
+
"leverage",
|
|
109012
|
+
"interval"
|
|
109013
|
+
]);
|
|
109014
|
+
OPTIONAL_BLANK_PROMPT_VARIABLES = /* @__PURE__ */ new Set([
|
|
109015
|
+
"calendar",
|
|
109016
|
+
REFERENCE_CANDLES_PROMPT_VARIABLE,
|
|
109017
|
+
...NEWS_PROMPT_VARIABLES
|
|
109018
|
+
]);
|
|
109019
|
+
coercePromptVariableValue = (value) => {
|
|
109020
|
+
if (value === null || value === void 0) {
|
|
109021
|
+
return "";
|
|
109022
|
+
}
|
|
109023
|
+
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
|
|
109024
|
+
return value;
|
|
109025
|
+
}
|
|
109026
|
+
if (Array.isArray(value) || typeof value === "object" && value !== null) {
|
|
109027
|
+
return JSON.stringify(value);
|
|
109028
|
+
}
|
|
109029
|
+
return String(value);
|
|
109030
|
+
};
|
|
109031
|
+
isMissingPromptVariableValue = (value) => {
|
|
109032
|
+
if (value === null || value === void 0) {
|
|
109033
|
+
return true;
|
|
109034
|
+
}
|
|
109035
|
+
if (typeof value === "string") {
|
|
109036
|
+
return value.trim().length === 0;
|
|
109037
|
+
}
|
|
109038
|
+
return false;
|
|
109039
|
+
};
|
|
109040
|
+
validatePromptVariables = ({
|
|
109041
|
+
template,
|
|
109042
|
+
contextVars
|
|
109043
|
+
}) => {
|
|
109044
|
+
const normalized = {};
|
|
109045
|
+
for (const [key, value] of Object.entries(contextVars)) {
|
|
109046
|
+
if (!ALLOWED_PROMPT_VARIABLES.has(key)) {
|
|
109047
|
+
throw new Error(`Unknown prompt variable key: ${key}`);
|
|
109048
|
+
}
|
|
109049
|
+
normalized[key] = coercePromptVariableValue(value);
|
|
109050
|
+
}
|
|
109051
|
+
const required2 = new Set(promptTemplateVariables(String(template ?? "")));
|
|
109052
|
+
for (const key of Array.from(required2).sort()) {
|
|
109053
|
+
if (!ALLOWED_PROMPT_VARIABLES.has(key)) {
|
|
109054
|
+
throw new Error(`Unknown prompt variable placeholder in template: ${key}`);
|
|
109055
|
+
}
|
|
109056
|
+
if (!Object.prototype.hasOwnProperty.call(normalized, key)) {
|
|
109057
|
+
throw new Error(`Missing required prompt variable: ${key}`);
|
|
109058
|
+
}
|
|
109059
|
+
if (!OPTIONAL_BLANK_PROMPT_VARIABLES.has(key) && isMissingPromptVariableValue(normalized[key])) {
|
|
109060
|
+
throw new Error(`Missing required prompt variable value: ${key}`);
|
|
109061
|
+
}
|
|
109062
|
+
}
|
|
109063
|
+
return normalized;
|
|
109064
|
+
};
|
|
109065
|
+
}
|
|
109066
|
+
});
|
|
109067
|
+
|
|
108707
109068
|
// lib/ai-settings-helpers.ts
|
|
108708
109069
|
var sortAiSettings;
|
|
108709
109070
|
var init_ai_settings_helpers = __esm({
|
|
@@ -108712,6 +109073,8 @@ var init_ai_settings_helpers = __esm({
|
|
|
108712
109073
|
init_define_VTX_EXO_POLICY();
|
|
108713
109074
|
init_define_VTX_GROK_POLICY();
|
|
108714
109075
|
init_define_VTX_PI_MODEL_POLICY();
|
|
109076
|
+
init_perp_dex_scope();
|
|
109077
|
+
init_prompt_variable_validation_contract();
|
|
108715
109078
|
sortAiSettings = (settings) => {
|
|
108716
109079
|
if (!settings || typeof settings !== "object") return settings;
|
|
108717
109080
|
const normalized = { ...settings };
|
|
@@ -108854,6 +109217,7 @@ var init_ai_settings_helpers = __esm({
|
|
|
108854
109217
|
"trading_timeframes",
|
|
108855
109218
|
"max_trading_timeframes",
|
|
108856
109219
|
"ai_indicators",
|
|
109220
|
+
"reference_candles_settings",
|
|
108857
109221
|
// 3) Trading limits
|
|
108858
109222
|
"trading_interval",
|
|
108859
109223
|
"leverage",
|
|
@@ -109029,7 +109393,7 @@ var init_candle_timeframes = __esm({
|
|
|
109029
109393
|
});
|
|
109030
109394
|
|
|
109031
109395
|
// lib/runtime/candle-prompt-contract.ts
|
|
109032
|
-
var projectCandlePromptComponent;
|
|
109396
|
+
var AI_INDICATOR_ROW_COLUMNS, AI_INDICATOR_KEYS, EMA_INDICATOR_KEYS, CANDLE_BASE_ROW_COLUMNS, candlesRowColumns, projectCandlePromptComponent, readCandleNumber, closedCandleCount, calculateRelativeVolumeSeries;
|
|
109033
109397
|
var init_candle_prompt_contract = __esm({
|
|
109034
109398
|
"lib/runtime/candle-prompt-contract.ts"() {
|
|
109035
109399
|
"use strict";
|
|
@@ -109037,6 +109401,31 @@ var init_candle_prompt_contract = __esm({
|
|
|
109037
109401
|
init_define_VTX_GROK_POLICY();
|
|
109038
109402
|
init_define_VTX_PI_MODEL_POLICY();
|
|
109039
109403
|
init_candle_timeframes();
|
|
109404
|
+
init_constants();
|
|
109405
|
+
AI_INDICATOR_ROW_COLUMNS = {
|
|
109406
|
+
rsi: ["rsi"],
|
|
109407
|
+
macd: ["macd_line", "macd_signal", "macd_hist"],
|
|
109408
|
+
bollinger: ["bb_upper", "bb_lower"],
|
|
109409
|
+
atr: ["atr"],
|
|
109410
|
+
ema_9: ["ema_9"],
|
|
109411
|
+
ema_21: ["ema_21"],
|
|
109412
|
+
ema_50: ["ema_50"],
|
|
109413
|
+
ema_200: ["ema_200"],
|
|
109414
|
+
rv: ["rv"]
|
|
109415
|
+
};
|
|
109416
|
+
AI_INDICATOR_KEYS = Object.keys(AI_INDICATOR_ROW_COLUMNS);
|
|
109417
|
+
EMA_INDICATOR_KEYS = Object.keys(PROMPT_EMA_PERIODS);
|
|
109418
|
+
CANDLE_BASE_ROW_COLUMNS = ["ts", "o", "h", "l", "c", "v"];
|
|
109419
|
+
candlesRowColumns = (activeIndicators) => {
|
|
109420
|
+
const flags = activeIndicators ?? {};
|
|
109421
|
+
const columns = [...CANDLE_BASE_ROW_COLUMNS];
|
|
109422
|
+
for (const key of AI_INDICATOR_KEYS) {
|
|
109423
|
+
if (flags[key]) {
|
|
109424
|
+
columns.push(...AI_INDICATOR_ROW_COLUMNS[key]);
|
|
109425
|
+
}
|
|
109426
|
+
}
|
|
109427
|
+
return columns;
|
|
109428
|
+
};
|
|
109040
109429
|
projectCandlePromptComponent = (input) => {
|
|
109041
109430
|
const intervalSeconds = candleTimeframeSeconds(input.timeframe);
|
|
109042
109431
|
if (intervalSeconds === void 0) {
|
|
@@ -109085,6 +109474,51 @@ var init_candle_prompt_contract = __esm({
|
|
|
109085
109474
|
projected.l = rows[rows.length - 1];
|
|
109086
109475
|
return projected;
|
|
109087
109476
|
};
|
|
109477
|
+
readCandleNumber = (value) => {
|
|
109478
|
+
if (typeof value === "number") {
|
|
109479
|
+
return value;
|
|
109480
|
+
}
|
|
109481
|
+
if (typeof value === "string" && value.trim()) {
|
|
109482
|
+
const numeric2 = Number(value);
|
|
109483
|
+
return Number.isNaN(numeric2) ? void 0 : numeric2;
|
|
109484
|
+
}
|
|
109485
|
+
return void 0;
|
|
109486
|
+
};
|
|
109487
|
+
closedCandleCount = (input) => {
|
|
109488
|
+
const intervalSeconds = candleTimeframeSeconds(input.timeframe);
|
|
109489
|
+
const lastOpenTimestamp = input.openTimestamps.at(-1);
|
|
109490
|
+
if (intervalSeconds === void 0 || lastOpenTimestamp === void 0) {
|
|
109491
|
+
return 0;
|
|
109492
|
+
}
|
|
109493
|
+
const lastIsClosed = lastOpenTimestamp + intervalSeconds <= input.asOfTimestamp;
|
|
109494
|
+
return lastIsClosed ? input.openTimestamps.length : input.openTimestamps.length - 1;
|
|
109495
|
+
};
|
|
109496
|
+
calculateRelativeVolumeSeries = (input) => {
|
|
109497
|
+
const series = Array(input.candles.length).fill(null);
|
|
109498
|
+
const baseline = input.baselineDollarVolume;
|
|
109499
|
+
const recentCandles = input.recentCandles;
|
|
109500
|
+
if (typeof baseline !== "number" || !(baseline > 0) || !Number.isInteger(recentCandles) || recentCandles <= 0) {
|
|
109501
|
+
return series;
|
|
109502
|
+
}
|
|
109503
|
+
const closed = Math.min(Math.max(Math.trunc(Number(input.closedCount)) || 0, 0), input.candles.length);
|
|
109504
|
+
if (closed < recentCandles) {
|
|
109505
|
+
return series;
|
|
109506
|
+
}
|
|
109507
|
+
const dollarVolumes = [];
|
|
109508
|
+
for (const candle of input.candles.slice(0, closed)) {
|
|
109509
|
+
const close = readCandleNumber(candle?.close);
|
|
109510
|
+
const volume = readCandleNumber(candle?.volume);
|
|
109511
|
+
if (close === void 0 || volume === void 0) {
|
|
109512
|
+
return series;
|
|
109513
|
+
}
|
|
109514
|
+
dollarVolumes.push(close * volume);
|
|
109515
|
+
}
|
|
109516
|
+
for (let index = recentCandles - 1; index < closed; index += 1) {
|
|
109517
|
+
const windowDollarVolume = dollarVolumes.slice(index - recentCandles + 1, index + 1).reduce((sum, value) => sum + value, 0);
|
|
109518
|
+
series[index] = Number.isFinite(windowDollarVolume) && windowDollarVolume >= 0 ? windowDollarVolume / baseline : null;
|
|
109519
|
+
}
|
|
109520
|
+
return series;
|
|
109521
|
+
};
|
|
109088
109522
|
}
|
|
109089
109523
|
});
|
|
109090
109524
|
|
|
@@ -109870,6 +110304,7 @@ async function requestServerHostPromptRescue(profileId, payload, options) {
|
|
|
109870
110304
|
options
|
|
109871
110305
|
);
|
|
109872
110306
|
}
|
|
110307
|
+
var SERVER_PROMPT_RESCUE_NODE_OUTAGE_REASON;
|
|
109873
110308
|
var init_server_host_prompt_rescue = __esm({
|
|
109874
110309
|
"lib/api/server-host-prompt-rescue.ts"() {
|
|
109875
110310
|
"use strict";
|
|
@@ -109877,6 +110312,7 @@ var init_server_host_prompt_rescue = __esm({
|
|
|
109877
110312
|
init_define_VTX_GROK_POLICY();
|
|
109878
110313
|
init_define_VTX_PI_MODEL_POLICY();
|
|
109879
110314
|
init_api2();
|
|
110315
|
+
SERVER_PROMPT_RESCUE_NODE_OUTAGE_REASON = "private_node_unavailable";
|
|
109880
110316
|
}
|
|
109881
110317
|
});
|
|
109882
110318
|
|
|
@@ -113227,89 +113663,8 @@ var init_provider_client = __esm({
|
|
|
113227
113663
|
}
|
|
113228
113664
|
});
|
|
113229
113665
|
|
|
113230
|
-
// lib/runtime/prompt-variable-validation-contract.ts
|
|
113231
|
-
var PROMPT_VARIABLE_PATTERN, NEWS_PROMPT_VARIABLES, ALLOWED_PROMPT_VARIABLES, OPTIONAL_BLANK_PROMPT_VARIABLES, coercePromptVariableValue, isMissingPromptVariableValue, validatePromptVariables;
|
|
113232
|
-
var init_prompt_variable_validation_contract = __esm({
|
|
113233
|
-
"lib/runtime/prompt-variable-validation-contract.ts"() {
|
|
113234
|
-
"use strict";
|
|
113235
|
-
init_define_VTX_EXO_POLICY();
|
|
113236
|
-
init_define_VTX_GROK_POLICY();
|
|
113237
|
-
init_define_VTX_PI_MODEL_POLICY();
|
|
113238
|
-
PROMPT_VARIABLE_PATTERN = /(?<!\{)\{([a-zA-Z_][a-zA-Z0-9_]*)\}(?!\})/g;
|
|
113239
|
-
NEWS_PROMPT_VARIABLES = ["news_benzinga", "news_telegram"];
|
|
113240
|
-
ALLOWED_PROMPT_VARIABLES = /* @__PURE__ */ new Set([
|
|
113241
|
-
"current_time",
|
|
113242
|
-
"candles",
|
|
113243
|
-
"market_stats",
|
|
113244
|
-
"account_status",
|
|
113245
|
-
"calendar",
|
|
113246
|
-
"behavior_state",
|
|
113247
|
-
"positions",
|
|
113248
|
-
"performance",
|
|
113249
|
-
"market_regime",
|
|
113250
|
-
...NEWS_PROMPT_VARIABLES,
|
|
113251
|
-
"size",
|
|
113252
|
-
"leverage",
|
|
113253
|
-
"interval"
|
|
113254
|
-
]);
|
|
113255
|
-
OPTIONAL_BLANK_PROMPT_VARIABLES = /* @__PURE__ */ new Set([
|
|
113256
|
-
"calendar",
|
|
113257
|
-
...NEWS_PROMPT_VARIABLES
|
|
113258
|
-
]);
|
|
113259
|
-
coercePromptVariableValue = (value) => {
|
|
113260
|
-
if (value === null || value === void 0) {
|
|
113261
|
-
return "";
|
|
113262
|
-
}
|
|
113263
|
-
if (typeof value === "string" || typeof value === "number" || typeof value === "boolean") {
|
|
113264
|
-
return value;
|
|
113265
|
-
}
|
|
113266
|
-
if (Array.isArray(value) || typeof value === "object" && value !== null) {
|
|
113267
|
-
return JSON.stringify(value);
|
|
113268
|
-
}
|
|
113269
|
-
return String(value);
|
|
113270
|
-
};
|
|
113271
|
-
isMissingPromptVariableValue = (value) => {
|
|
113272
|
-
if (value === null || value === void 0) {
|
|
113273
|
-
return true;
|
|
113274
|
-
}
|
|
113275
|
-
if (typeof value === "string") {
|
|
113276
|
-
return value.trim().length === 0;
|
|
113277
|
-
}
|
|
113278
|
-
return false;
|
|
113279
|
-
};
|
|
113280
|
-
validatePromptVariables = ({
|
|
113281
|
-
template,
|
|
113282
|
-
contextVars
|
|
113283
|
-
}) => {
|
|
113284
|
-
const normalized = {};
|
|
113285
|
-
for (const [key, value] of Object.entries(contextVars)) {
|
|
113286
|
-
if (!ALLOWED_PROMPT_VARIABLES.has(key)) {
|
|
113287
|
-
throw new Error(`Unknown prompt variable key: ${key}`);
|
|
113288
|
-
}
|
|
113289
|
-
normalized[key] = coercePromptVariableValue(value);
|
|
113290
|
-
}
|
|
113291
|
-
const required2 = /* @__PURE__ */ new Set();
|
|
113292
|
-
for (const match of template.matchAll(PROMPT_VARIABLE_PATTERN)) {
|
|
113293
|
-
required2.add(match[1]);
|
|
113294
|
-
}
|
|
113295
|
-
for (const key of required2) {
|
|
113296
|
-
if (!ALLOWED_PROMPT_VARIABLES.has(key)) {
|
|
113297
|
-
throw new Error(`Unknown prompt variable placeholder in template: ${key}`);
|
|
113298
|
-
}
|
|
113299
|
-
if (!Object.prototype.hasOwnProperty.call(normalized, key)) {
|
|
113300
|
-
throw new Error(`Missing required prompt variable: ${key}`);
|
|
113301
|
-
}
|
|
113302
|
-
if (!OPTIONAL_BLANK_PROMPT_VARIABLES.has(key) && isMissingPromptVariableValue(normalized[key])) {
|
|
113303
|
-
throw new Error(`Missing required prompt variable value: ${key}`);
|
|
113304
|
-
}
|
|
113305
|
-
}
|
|
113306
|
-
return normalized;
|
|
113307
|
-
};
|
|
113308
|
-
}
|
|
113309
|
-
});
|
|
113310
|
-
|
|
113311
113666
|
// lib/runtime/prompt-contract.ts
|
|
113312
|
-
var PROMPT_PLACEHOLDER_MAP, DATA_FORMAT_TAG_ALIASES, buildDecisionInstructionVariables,
|
|
113667
|
+
var PROMPT_PLACEHOLDER_MAP, DATA_FORMAT_TAG_ALIASES, buildDecisionInstructionVariables, renderCandleIndicatorDefinitions, NEWS_COLUMN_DESCRIPTIONS, isNewsPromptTag, newsTagBlock, newsRowColumns, renderNewsLegendLine, behaviorStateHasObjectField, candleBlockPayload, candlesHaveLiveField, templateReferencesTag, templateTagOrder, renderDataFormatLegend, replaceEmbeddedDataFormatLegend, SIZE_AMOUNT_USDC_LABEL_PATTERN, labelSizeAmountInUsd, canonicalizePromptPlaceholders, normalizePromptWhitespace, formatInstructionTemplate, constructPromptSystemTemplate;
|
|
113313
113668
|
var init_prompt_contract = __esm({
|
|
113314
113669
|
"lib/runtime/prompt-contract.ts"() {
|
|
113315
113670
|
"use strict";
|
|
@@ -113317,6 +113672,8 @@ var init_prompt_contract = __esm({
|
|
|
113317
113672
|
init_define_VTX_GROK_POLICY();
|
|
113318
113673
|
init_define_VTX_PI_MODEL_POLICY();
|
|
113319
113674
|
init_prompt_variable_validation_contract();
|
|
113675
|
+
init_prompt_variable_validation_contract();
|
|
113676
|
+
init_candle_prompt_contract();
|
|
113320
113677
|
init_constants();
|
|
113321
113678
|
PROMPT_PLACEHOLDER_MAP = {};
|
|
113322
113679
|
DATA_FORMAT_TAG_ALIASES = {};
|
|
@@ -113341,38 +113698,22 @@ var init_prompt_contract = __esm({
|
|
|
113341
113698
|
max_trades: Math.trunc(maxTrades)
|
|
113342
113699
|
};
|
|
113343
113700
|
};
|
|
113344
|
-
candlesRowColumns = (activeIndicators) => {
|
|
113345
|
-
const flags = activeIndicators ?? {};
|
|
113346
|
-
const cols = ["ts", "o", "h", "l", "c", "v"];
|
|
113347
|
-
if (flags.rsi) cols.push("rsi");
|
|
113348
|
-
if (flags.macd) cols.push("macd_line", "macd_signal", "macd_hist");
|
|
113349
|
-
if (flags.bollinger) cols.push("bb_upper", "bb_lower");
|
|
113350
|
-
if (flags.atr) cols.push("atr");
|
|
113351
|
-
if (flags.ema_9) cols.push("ema_9");
|
|
113352
|
-
if (flags.ema_21) cols.push("ema_21");
|
|
113353
|
-
if (flags.ema_50) cols.push("ema_50");
|
|
113354
|
-
if (flags.ema_200) cols.push("ema_200");
|
|
113355
|
-
return cols;
|
|
113356
|
-
};
|
|
113357
113701
|
renderCandleIndicatorDefinitions = (activeIndicators, indicatorSchemas) => {
|
|
113358
113702
|
const flags = activeIndicators ?? {};
|
|
113359
113703
|
const schemas = indicatorSchemas ?? {};
|
|
113360
|
-
const
|
|
113361
|
-
for (const key of
|
|
113704
|
+
const schemaKeys = [];
|
|
113705
|
+
for (const key of AI_INDICATOR_KEYS) {
|
|
113362
113706
|
if (!flags[key]) continue;
|
|
113363
|
-
const
|
|
113364
|
-
if (!
|
|
113365
|
-
throw new Error(`Missing prompts config key: instructions.data_format.candle_indicators.${key}`);
|
|
113366
|
-
}
|
|
113367
|
-
definitions.push(definition);
|
|
113707
|
+
const schemaKey = EMA_INDICATOR_KEYS.includes(key) ? "ema" : key;
|
|
113708
|
+
if (!schemaKeys.includes(schemaKey)) schemaKeys.push(schemaKey);
|
|
113368
113709
|
}
|
|
113369
|
-
|
|
113370
|
-
const definition = String(schemas
|
|
113710
|
+
const definitions = schemaKeys.map((schemaKey) => {
|
|
113711
|
+
const definition = String(schemas[schemaKey] ?? "").trim();
|
|
113371
113712
|
if (!definition) {
|
|
113372
|
-
throw new Error(
|
|
113713
|
+
throw new Error(`Missing prompts config key: instructions.data_format.candle_indicators.${schemaKey}`);
|
|
113373
113714
|
}
|
|
113374
|
-
|
|
113375
|
-
}
|
|
113715
|
+
return definition;
|
|
113716
|
+
});
|
|
113376
113717
|
return definitions.length > 0 ? `; indicators: ${definitions.join("; ")}` : "";
|
|
113377
113718
|
};
|
|
113378
113719
|
NEWS_COLUMN_DESCRIPTIONS = {
|
|
@@ -113419,41 +113760,47 @@ var init_prompt_contract = __esm({
|
|
|
113419
113760
|
return false;
|
|
113420
113761
|
}
|
|
113421
113762
|
};
|
|
113422
|
-
|
|
113423
|
-
const rawSummary = String(
|
|
113424
|
-
const match = rawSummary.match(
|
|
113763
|
+
candleBlockPayload = (summary, tag, allowBareJson) => {
|
|
113764
|
+
const rawSummary = String(summary ?? "").trim();
|
|
113765
|
+
const match = rawSummary.match(new RegExp(`<${tag}>\\s*([\\s\\S]*?)\\s*<\\/${tag}>`, "i"));
|
|
113766
|
+
if (!match && !allowBareJson) return null;
|
|
113425
113767
|
const rawPayload = match?.[1] ?? rawSummary;
|
|
113426
113768
|
try {
|
|
113427
113769
|
const payload = JSON.parse(rawPayload);
|
|
113428
|
-
if (!payload || typeof payload !== "object" || Array.isArray(payload)) return
|
|
113429
|
-
return
|
|
113430
|
-
if (!symbolPayload || typeof symbolPayload !== "object" || Array.isArray(symbolPayload)) {
|
|
113431
|
-
return false;
|
|
113432
|
-
}
|
|
113433
|
-
const data4 = symbolPayload.data;
|
|
113434
|
-
if (!data4 || typeof data4 !== "object" || Array.isArray(data4)) return false;
|
|
113435
|
-
return Object.values(data4).some(
|
|
113436
|
-
(component) => Boolean(
|
|
113437
|
-
component && typeof component === "object" && !Array.isArray(component) && Object.prototype.hasOwnProperty.call(component, "l")
|
|
113438
|
-
)
|
|
113439
|
-
);
|
|
113440
|
-
});
|
|
113770
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload)) return null;
|
|
113771
|
+
return payload;
|
|
113441
113772
|
} catch {
|
|
113442
|
-
return
|
|
113773
|
+
return null;
|
|
113443
113774
|
}
|
|
113444
113775
|
};
|
|
113776
|
+
candlesHaveLiveField = (candlesSummary, tag = "candles", allowBareJson = true) => {
|
|
113777
|
+
const payload = candleBlockPayload(candlesSummary, tag, allowBareJson);
|
|
113778
|
+
if (!payload) return false;
|
|
113779
|
+
return Object.values(payload).some((symbolPayload) => {
|
|
113780
|
+
if (!symbolPayload || typeof symbolPayload !== "object" || Array.isArray(symbolPayload)) {
|
|
113781
|
+
return false;
|
|
113782
|
+
}
|
|
113783
|
+
const data4 = symbolPayload.data;
|
|
113784
|
+
if (!data4 || typeof data4 !== "object" || Array.isArray(data4)) return false;
|
|
113785
|
+
return Object.values(data4).some(
|
|
113786
|
+
(component) => Boolean(
|
|
113787
|
+
component && typeof component === "object" && !Array.isArray(component) && Object.prototype.hasOwnProperty.call(component, "l")
|
|
113788
|
+
)
|
|
113789
|
+
);
|
|
113790
|
+
});
|
|
113791
|
+
};
|
|
113445
113792
|
templateReferencesTag = (template, tag) => {
|
|
113446
113793
|
const canonicalTag = DATA_FORMAT_TAG_ALIASES[tag] ?? tag;
|
|
113447
113794
|
const aliases = /* @__PURE__ */ new Set([tag, canonicalTag]);
|
|
113448
113795
|
for (const [alias, canonical] of Object.entries(DATA_FORMAT_TAG_ALIASES)) {
|
|
113449
113796
|
if (canonical === canonicalTag) aliases.add(alias);
|
|
113450
113797
|
}
|
|
113451
|
-
return
|
|
113798
|
+
return promptTemplatePlaceholders(template).some((name) => aliases.has(name));
|
|
113452
113799
|
};
|
|
113453
113800
|
templateTagOrder = (template) => {
|
|
113454
113801
|
const ordered = [];
|
|
113455
|
-
for (const
|
|
113456
|
-
const tag = DATA_FORMAT_TAG_ALIASES[
|
|
113802
|
+
for (const name of promptTemplatePlaceholders(template)) {
|
|
113803
|
+
const tag = DATA_FORMAT_TAG_ALIASES[name] ?? name;
|
|
113457
113804
|
if (!ordered.includes(tag)) ordered.push(tag);
|
|
113458
113805
|
}
|
|
113459
113806
|
return ordered;
|
|
@@ -113486,6 +113833,29 @@ var init_prompt_contract = __esm({
|
|
|
113486
113833
|
legend = legend.replaceAll(candleLiveFieldToken, liveField);
|
|
113487
113834
|
legend = legend.replaceAll(candleLiveGuidanceToken, liveGuidance);
|
|
113488
113835
|
}
|
|
113836
|
+
const referenceLiveFieldToken = "{reference_candle_live_field}";
|
|
113837
|
+
const referenceLiveGuidanceToken = "{reference_candle_live_guidance}";
|
|
113838
|
+
const referenceBlockPresent = candleBlockPayload(
|
|
113839
|
+
options.referenceCandlesSummary,
|
|
113840
|
+
REFERENCE_CANDLES_PROMPT_VARIABLE,
|
|
113841
|
+
false
|
|
113842
|
+
) !== null;
|
|
113843
|
+
if (legend.includes(referenceLiveFieldToken) || legend.includes(referenceLiveGuidanceToken)) {
|
|
113844
|
+
let referenceLiveField = "";
|
|
113845
|
+
let referenceLiveGuidance = "";
|
|
113846
|
+
if (candlesHaveLiveField(options.referenceCandlesSummary, REFERENCE_CANDLES_PROMPT_VARIABLE, false)) {
|
|
113847
|
+
referenceLiveField = String(options.candleLiveFieldSchema ?? "").trim();
|
|
113848
|
+
referenceLiveGuidance = String(options.candleLiveGuidance ?? "").trim();
|
|
113849
|
+
if (!referenceLiveField) {
|
|
113850
|
+
throw new Error("Missing prompts config key: instructions.data_format.candle_live_field");
|
|
113851
|
+
}
|
|
113852
|
+
if (!referenceLiveGuidance) {
|
|
113853
|
+
throw new Error("Missing prompts config key: instructions.data_format.candle_live_guidance");
|
|
113854
|
+
}
|
|
113855
|
+
}
|
|
113856
|
+
legend = legend.replaceAll(referenceLiveFieldToken, referenceLiveField);
|
|
113857
|
+
legend = legend.replaceAll(referenceLiveGuidanceToken, referenceLiveGuidance);
|
|
113858
|
+
}
|
|
113489
113859
|
const behaviorLastTradeToken = "{behavior_last_trade}";
|
|
113490
113860
|
if (legend.includes(behaviorLastTradeToken)) {
|
|
113491
113861
|
let behaviorLastTrade = "";
|
|
@@ -113579,6 +113949,28 @@ var init_prompt_contract = __esm({
|
|
|
113579
113949
|
);
|
|
113580
113950
|
}
|
|
113581
113951
|
}
|
|
113952
|
+
if (tag === REFERENCE_CANDLES_PROMPT_VARIABLE) {
|
|
113953
|
+
const referenceColumnsToken = "{reference_candle_columns}";
|
|
113954
|
+
if (!line.includes(referenceColumnsToken)) {
|
|
113955
|
+
throw new Error(
|
|
113956
|
+
"Missing prompts placeholder: instructions.data_format.legend reference_candles line requires {reference_candle_columns}"
|
|
113957
|
+
);
|
|
113958
|
+
}
|
|
113959
|
+
line = line.replaceAll(
|
|
113960
|
+
referenceColumnsToken,
|
|
113961
|
+
candlesRowColumns(options.referenceIndicatorFlags).join(",")
|
|
113962
|
+
);
|
|
113963
|
+
line = line.replaceAll(
|
|
113964
|
+
"{reference_candle_indicator_definitions}",
|
|
113965
|
+
renderCandleIndicatorDefinitions(
|
|
113966
|
+
options.referenceIndicatorFlags,
|
|
113967
|
+
options.candleIndicatorSchemas
|
|
113968
|
+
)
|
|
113969
|
+
);
|
|
113970
|
+
if (shouldFilter && !referenceBlockPresent) {
|
|
113971
|
+
continue;
|
|
113972
|
+
}
|
|
113973
|
+
}
|
|
113582
113974
|
if (isNewsPromptTag(tag)) {
|
|
113583
113975
|
line = renderNewsLegendLine(line, options.newsSummary, tag);
|
|
113584
113976
|
if (shouldFilter && !newsTagBlock(options.newsSummary, tag)) {
|
|
@@ -113647,6 +114039,25 @@ var init_prompt_contract = __esm({
|
|
|
113647
114039
|
}
|
|
113648
114040
|
return replacedLines.join("\n").trim();
|
|
113649
114041
|
};
|
|
114042
|
+
SIZE_AMOUNT_USDC_LABEL_PATTERN = / USDC(?![\p{L}\p{N}_])/uy;
|
|
114043
|
+
labelSizeAmountInUsd = (template) => {
|
|
114044
|
+
const rewritten = [];
|
|
114045
|
+
let cursor = 0;
|
|
114046
|
+
for (const { name, end } of promptTemplatePlaceholderSpans(template)) {
|
|
114047
|
+
if (name !== "size") {
|
|
114048
|
+
continue;
|
|
114049
|
+
}
|
|
114050
|
+
SIZE_AMOUNT_USDC_LABEL_PATTERN.lastIndex = end;
|
|
114051
|
+
const label2 = SIZE_AMOUNT_USDC_LABEL_PATTERN.exec(template);
|
|
114052
|
+
if (!label2) {
|
|
114053
|
+
continue;
|
|
114054
|
+
}
|
|
114055
|
+
rewritten.push(template.slice(cursor, label2.index), " USD");
|
|
114056
|
+
cursor = label2.index + label2[0].length;
|
|
114057
|
+
}
|
|
114058
|
+
rewritten.push(template.slice(cursor));
|
|
114059
|
+
return rewritten.join("");
|
|
114060
|
+
};
|
|
113650
114061
|
canonicalizePromptPlaceholders = (template) => {
|
|
113651
114062
|
if (typeof template !== "string" || !template) {
|
|
113652
114063
|
return { template: "", changed: false };
|
|
@@ -113659,7 +114070,7 @@ var init_prompt_contract = __esm({
|
|
|
113659
114070
|
changed = true;
|
|
113660
114071
|
}
|
|
113661
114072
|
}
|
|
113662
|
-
const usdTemplate = updated
|
|
114073
|
+
const usdTemplate = labelSizeAmountInUsd(updated);
|
|
113663
114074
|
changed ||= usdTemplate !== updated;
|
|
113664
114075
|
updated = usdTemplate;
|
|
113665
114076
|
return { template: updated, changed };
|
|
@@ -113670,16 +114081,6 @@ var init_prompt_contract = __esm({
|
|
|
113670
114081
|
}
|
|
113671
114082
|
return text.replace(/\r\n/g, "\n").replace(/[\t ]{2,}\n/g, "\n").replace(/\n{3,}/g, "\n\n").trim();
|
|
113672
114083
|
};
|
|
113673
|
-
renderPromptTemplate = (template, contextVars) => {
|
|
113674
|
-
const escapedOpen = "__VTX_PROMPT_OPEN_BRACE__";
|
|
113675
|
-
const escapedClose = "__VTX_PROMPT_CLOSE_BRACE__";
|
|
113676
|
-
const prepared = template.replaceAll("{{", escapedOpen).replaceAll("}}", escapedClose);
|
|
113677
|
-
const rendered = prepared.replace(/\{([a-zA-Z0-9_]+)\}/g, (_match, key) => {
|
|
113678
|
-
const value = contextVars[key];
|
|
113679
|
-
return value === null || value === void 0 ? "" : String(value);
|
|
113680
|
-
});
|
|
113681
|
-
return rendered.replaceAll(escapedOpen, "{").replaceAll(escapedClose, "}");
|
|
113682
|
-
};
|
|
113683
114084
|
formatInstructionTemplate = (template, vars) => {
|
|
113684
114085
|
const escapedOpen = "__VTX_INSTR_OPEN_BRACE__";
|
|
113685
114086
|
const escapedClose = "__VTX_INSTR_CLOSE_BRACE__";
|
|
@@ -113742,7 +114143,9 @@ ${jsonInstruction}`.trim();
|
|
|
113742
114143
|
behaviorPreviousDecisionSchema: instructions.data_format?.behavior_previous_decision,
|
|
113743
114144
|
behaviorPreviousCampaignSchema: instructions.data_format?.behavior_previous_campaign,
|
|
113744
114145
|
behaviorEntryTradeSchema: instructions.data_format?.behavior_entry_trade,
|
|
113745
|
-
candleIndicatorSchemas: instructions.data_format?.candle_indicators
|
|
114146
|
+
candleIndicatorSchemas: instructions.data_format?.candle_indicators,
|
|
114147
|
+
referenceCandlesSummary: options.referenceCandlesSummary,
|
|
114148
|
+
referenceIndicatorFlags: options.referenceIndicatorFlags
|
|
113746
114149
|
});
|
|
113747
114150
|
const hasDataFormatInstructions = /^[ \t]*DATA FORMAT(?: INSTRUCTIONS)?:/m.test(template);
|
|
113748
114151
|
if (legend && !hasDataFormatInstructions) {
|
|
@@ -113759,7 +114162,9 @@ ${legend}`.trim();
|
|
|
113759
114162
|
behaviorPreviousDecisionSchema: instructions.data_format?.behavior_previous_decision,
|
|
113760
114163
|
behaviorPreviousCampaignSchema: instructions.data_format?.behavior_previous_campaign,
|
|
113761
114164
|
behaviorEntryTradeSchema: instructions.data_format?.behavior_entry_trade,
|
|
113762
|
-
candleIndicatorSchemas: instructions.data_format?.candle_indicators
|
|
114165
|
+
candleIndicatorSchemas: instructions.data_format?.candle_indicators,
|
|
114166
|
+
referenceCandlesSummary: options.referenceCandlesSummary,
|
|
114167
|
+
referenceIndicatorFlags: options.referenceIndicatorFlags
|
|
113763
114168
|
});
|
|
113764
114169
|
template = replaceEmbeddedDataFormatLegend(template, canonicalLegend, legend);
|
|
113765
114170
|
}
|
|
@@ -113945,7 +114350,7 @@ var init_behavior_memory_prompt_observability = __esm({
|
|
|
113945
114350
|
});
|
|
113946
114351
|
|
|
113947
114352
|
// lib/runtime/prompt-number-contract.ts
|
|
113948
|
-
var finiteNumber3, roundPromptFixed, roundPromptSignificant, roundPromptNonnegativeUnits;
|
|
114353
|
+
var finiteNumber3, roundPromptFixed, roundPromptSignificant, roundPromptRelativeVolume, roundPromptNonnegativeUnits;
|
|
113949
114354
|
var init_prompt_number_contract = __esm({
|
|
113950
114355
|
"lib/runtime/prompt-number-contract.ts"() {
|
|
113951
114356
|
"use strict";
|
|
@@ -113979,6 +114384,27 @@ var init_prompt_number_contract = __esm({
|
|
|
113979
114384
|
const rounded = Number(numeric2.toPrecision(digits));
|
|
113980
114385
|
return Object.is(rounded, -0) ? 0 : rounded;
|
|
113981
114386
|
};
|
|
114387
|
+
roundPromptRelativeVolume = (value) => {
|
|
114388
|
+
if (value === null || value === void 0 || typeof value === "boolean") {
|
|
114389
|
+
return null;
|
|
114390
|
+
}
|
|
114391
|
+
if (typeof value === "string" && !value.trim()) {
|
|
114392
|
+
return null;
|
|
114393
|
+
}
|
|
114394
|
+
const numeric2 = finiteNumber3(value);
|
|
114395
|
+
if (numeric2 == null) {
|
|
114396
|
+
return null;
|
|
114397
|
+
}
|
|
114398
|
+
const digits = PROMPT_RELATIVE_VOLUME_DIGITS;
|
|
114399
|
+
const awayFromZero = numeric2.toFixed(digits);
|
|
114400
|
+
const tieNumerator = numeric2 * BINARY_RADIX ** (digits + 1);
|
|
114401
|
+
if (!Number.isInteger(tieNumerator) || Math.abs(tieNumerator) % BINARY_RADIX !== 1) {
|
|
114402
|
+
return Number(awayFromZero);
|
|
114403
|
+
}
|
|
114404
|
+
const towardZero = numeric2.toFixed(digits + 1).slice(0, -1);
|
|
114405
|
+
const towardZeroIsEven = Number(towardZero.at(-1)) % BINARY_RADIX === 0;
|
|
114406
|
+
return Number(towardZeroIsEven ? towardZero : awayFromZero);
|
|
114407
|
+
};
|
|
113982
114408
|
roundPromptNonnegativeUnits = (value) => {
|
|
113983
114409
|
const numeric2 = finiteNumber3(value);
|
|
113984
114410
|
if (numeric2 == null || numeric2 <= 0) {
|
|
@@ -114532,6 +114958,7 @@ __export(local_analysis_exports, {
|
|
|
114532
114958
|
buildLocalRuntimePromptArtifacts: () => buildLocalRuntimePromptArtifacts,
|
|
114533
114959
|
buildPromptBehaviorStateArtifacts: () => buildPromptBehaviorStateArtifacts,
|
|
114534
114960
|
buildPromptBehaviorStateValue: () => buildPromptBehaviorStateValue,
|
|
114961
|
+
buildPromptCandleTimeframeComponent: () => buildPromptCandleTimeframeComponent,
|
|
114535
114962
|
capacityUnitSize: () => capacityUnitSize,
|
|
114536
114963
|
derivePromptVisibleSections: () => derivePromptVisibleSections,
|
|
114537
114964
|
isClientRuntimeAgentInstructionEmpty: () => isClientRuntimeAgentInstructionEmpty,
|
|
@@ -114547,7 +114974,7 @@ __export(local_analysis_exports, {
|
|
|
114547
114974
|
runLocalRuntimeCycle: () => runLocalRuntimeCycle,
|
|
114548
114975
|
summarizeReviewFailureExplanation: () => summarizeReviewFailureExplanation
|
|
114549
114976
|
});
|
|
114550
|
-
var CYCLE_TIMEOUT_FLOOR_MS, DECISION_SETTLEMENT_RESERVE_MAX_BUDGET_DIVISOR, MIN_AGENT_INSTRUCTION_RETRY_AFTER_MS, PROMPT_PARITY_ERROR_DETAIL_MAX_CHARS, EXTERNAL_INFERENCE_RUNTIME_POLL_INTERVAL_MS, REVIEW_PROVIDER_SERVER_ERROR_STATUSES, TRUNCATION_ELLIPSIS2, normalizeNativeValues, assertPromptModelController, resolveRuntimeReasoningControlsForModel, modelScopedKey, resolveNativeValuesForModel, observeRuntimeCycle, observeAccountState, aiOrderSlippageFraction, serverBehaviorStateArtifacts, ClientRuntimeAgentInstructionEmpty, isClientRuntimeAgentInstructionEmpty, ClientRuntimeAiSchedulePaused, ClientRuntimeAiScheduleStillActive, isClientRuntimeAiScheduleStillActive, ServerDispatchAccountStateStale, isServerDispatchAccountStateStale, isClientRuntimeAiSchedulePaused, acceptancePositionCaps, accountSnapshotCapturedAt, buildClaimedAgentRuntimeCycleResult, resolveRuntimeMarginModePreference, resolveRuntimeLeveragePreference, resolveBooleanSetting2, CLIENT_RUNTIME_LIVE_CONTEXT_UNAVAILABLE_ERRORS, BEHAVIOR_STATE_UNAVAILABLE_ERROR, CriticalBehaviorStateError, clampNumber, resolveExternalInferenceRuntimeTimeoutSeconds, toPositiveFinite3, compactSnippet, hashRuntimeDebugText, EFFECTIVE_INPUT_MANIFEST_SCHEMA_VERSION, PROMPT_ASSEMBLY_DEFINITION_VERSION, RUNTIME_SOURCE_DEFINITION_VERSION, DECISION_INPUT_DEFINITION_VERSION, CONTEXT_ENVELOPE_DEFINITION_VERSION, CLIENT_RUNTIME_SOURCE_VERSION, CLIENT_MAIN_PROMPT_RENDERER, SERVER_MAIN_PROMPT_RENDERER, CLIENT_REVIEW_PROMPT_RENDERER, SERVER_REVIEW_PROMPT_RENDERER, resolveEffectivePromptRuntimeProvenance, canonicalManifestValue, canonicalManifestJson, sha256ManifestHex, effectiveInputComponent, buildEffectiveInputManifest, derivePromptVisibleSections, decodeDecisionTracePayload, extractDecisionSymbolTrace, formatDecisionSymbolTrace, formatActionableDecisionSymbols, decisionRecordsBySymbol, normalizePromptSymbols, JSON_MODEL_OUTPUT_FENCE_PATTERN, STRICT_MODEL_OUTPUT_KEYS, currentModelOutputValidationErrors, currentModelOutputMatchesContract, projectCurrentModelDecisionContent, modelOutputValidationError, 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,
|
|
114977
|
+
var CYCLE_TIMEOUT_FLOOR_MS, DECISION_SETTLEMENT_RESERVE_MAX_BUDGET_DIVISOR, MIN_AGENT_INSTRUCTION_RETRY_AFTER_MS, PROMPT_PARITY_ERROR_DETAIL_MAX_CHARS, EXTERNAL_INFERENCE_RUNTIME_POLL_INTERVAL_MS, REVIEW_PROVIDER_SERVER_ERROR_STATUSES, TRUNCATION_ELLIPSIS2, normalizeNativeValues, assertPromptModelController, resolveRuntimeReasoningControlsForModel, modelScopedKey, resolveNativeValuesForModel, observeRuntimeCycle, observeAccountState, aiOrderSlippageFraction, serverBehaviorStateArtifacts, ClientRuntimeAgentInstructionEmpty, isClientRuntimeAgentInstructionEmpty, ClientRuntimeAiSchedulePaused, ClientRuntimeAiScheduleStillActive, isClientRuntimeAiScheduleStillActive, ServerDispatchAccountStateStale, isServerDispatchAccountStateStale, isClientRuntimeAiSchedulePaused, acceptancePositionCaps, accountSnapshotCapturedAt, buildClaimedAgentRuntimeCycleResult, resolveRuntimeMarginModePreference, resolveRuntimeLeveragePreference, resolveBooleanSetting2, CLIENT_RUNTIME_LIVE_CONTEXT_UNAVAILABLE_ERRORS, BEHAVIOR_STATE_UNAVAILABLE_ERROR, CriticalBehaviorStateError, clampNumber, resolveExternalInferenceRuntimeTimeoutSeconds, toPositiveFinite3, compactSnippet, hashRuntimeDebugText, EFFECTIVE_INPUT_MANIFEST_SCHEMA_VERSION, PROMPT_ASSEMBLY_DEFINITION_VERSION, RUNTIME_SOURCE_DEFINITION_VERSION, DECISION_INPUT_DEFINITION_VERSION, CONTEXT_ENVELOPE_DEFINITION_VERSION, CLIENT_RUNTIME_SOURCE_VERSION, CLIENT_MAIN_PROMPT_RENDERER, SERVER_MAIN_PROMPT_RENDERER, CLIENT_REVIEW_PROMPT_RENDERER, SERVER_REVIEW_PROMPT_RENDERER, resolveEffectivePromptRuntimeProvenance, canonicalManifestValue, canonicalManifestJson, sha256ManifestHex, effectiveInputComponent, buildEffectiveInputManifest, 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, formatTemplateWithNamedVariables, carryReturnedModelCalls, runLocalRuntimeCycle;
|
|
114551
114978
|
var init_local_analysis = __esm({
|
|
114552
114979
|
"lib/runtime/local-analysis.ts"() {
|
|
114553
114980
|
"use strict";
|
|
@@ -115275,13 +115702,12 @@ var init_local_analysis = __esm({
|
|
|
115275
115702
|
}
|
|
115276
115703
|
};
|
|
115277
115704
|
};
|
|
115705
|
+
MANIFEST_COMPONENT_NAME = /^[a-z][a-z0-9_]{0,63}$/;
|
|
115278
115706
|
derivePromptVisibleSections = (input) => {
|
|
115279
115707
|
const configuredTemplate = input.configuredTemplates.filter((value) => typeof value === "string").join("\n");
|
|
115280
|
-
const placeholders =
|
|
115281
|
-
|
|
115282
|
-
|
|
115283
|
-
placeholders.add(match[1]);
|
|
115284
|
-
}
|
|
115708
|
+
const placeholders = new Set(
|
|
115709
|
+
promptTemplatePlaceholders(configuredTemplate).filter((name) => MANIFEST_COMPONENT_NAME.test(name))
|
|
115710
|
+
);
|
|
115285
115711
|
const finalPromptText = input.renderedPrompts.filter((value) => typeof value === "string").join("\n");
|
|
115286
115712
|
return new Set(Object.entries(input.dynamicComponents).filter(([name, value]) => {
|
|
115287
115713
|
if (placeholders.has(name)) {
|
|
@@ -115668,21 +116094,11 @@ var init_local_analysis = __esm({
|
|
|
115668
116094
|
`No usable candle data was available for configured symbol ${normalizedSymbol || plan.symbol}; forced HOLD.`
|
|
115669
116095
|
);
|
|
115670
116096
|
});
|
|
115671
|
-
extractTemplatePlaceholders = (template) =>
|
|
115672
|
-
const matches2 = Array.from(template.matchAll(/(?<!\{)\{([a-zA-Z0-9_]+)\}(?!\})/g));
|
|
115673
|
-
const unique = /* @__PURE__ */ new Set();
|
|
115674
|
-
for (const match of matches2) {
|
|
115675
|
-
const key = String(match[1] || "").trim();
|
|
115676
|
-
if (key) {
|
|
115677
|
-
unique.add(key);
|
|
115678
|
-
}
|
|
115679
|
-
}
|
|
115680
|
-
return Array.from(unique).sort();
|
|
115681
|
-
};
|
|
116097
|
+
extractTemplatePlaceholders = (template) => Array.from(new Set(promptTemplatePlaceholders(template))).sort();
|
|
115682
116098
|
requireReviewPrimaryUserPromptTemplate = (template) => {
|
|
115683
116099
|
const canonical = canonicalizePromptPlaceholders(template).template;
|
|
115684
|
-
const activePrimaryPlaceholders =
|
|
115685
|
-
|
|
116100
|
+
const activePrimaryPlaceholders = promptTemplatePlaceholders(canonical).filter(
|
|
116101
|
+
(name) => name === "primary_user_prompt"
|
|
115686
116102
|
);
|
|
115687
116103
|
if (activePrimaryPlaceholders.length > 1 || /<\/?behavior_state\b/.test(canonical)) {
|
|
115688
116104
|
throw new CriticalBehaviorStateError();
|
|
@@ -116288,16 +116704,7 @@ ${reviewOutputContract}`;
|
|
|
116288
116704
|
}
|
|
116289
116705
|
return 0;
|
|
116290
116706
|
};
|
|
116291
|
-
|
|
116292
|
-
"rsi",
|
|
116293
|
-
"macd",
|
|
116294
|
-
"bollinger",
|
|
116295
|
-
"atr",
|
|
116296
|
-
"ema_9",
|
|
116297
|
-
"ema_21",
|
|
116298
|
-
"ema_50",
|
|
116299
|
-
"ema_200"
|
|
116300
|
-
];
|
|
116707
|
+
AI_INDICATOR_KEYS_NEWER_THAN_SOME_SERVERS = ["rv"];
|
|
116301
116708
|
sortTradingTimeframes = (timeframes) => sortCandleTimeframes(Array.from(
|
|
116302
116709
|
new Set(
|
|
116303
116710
|
timeframes.map((value) => String(value || "").trim()).filter(Boolean)
|
|
@@ -116330,19 +116737,25 @@ ${reviewOutputContract}`;
|
|
|
116330
116737
|
throw new Error("Missing required client runtime config: default_ai_indicators.");
|
|
116331
116738
|
}
|
|
116332
116739
|
const normalizedDefaults = Object.fromEntries(
|
|
116333
|
-
|
|
116740
|
+
AI_INDICATOR_KEYS.flatMap((key) => {
|
|
116334
116741
|
const rawValue = defaultsValue[key];
|
|
116742
|
+
if (rawValue === void 0 && AI_INDICATOR_KEYS_NEWER_THAN_SOME_SERVERS.includes(key)) {
|
|
116743
|
+
return [];
|
|
116744
|
+
}
|
|
116335
116745
|
if (typeof rawValue !== "boolean") {
|
|
116336
116746
|
throw new Error(`Invalid client runtime config: default_ai_indicators.${key} must be boolean.`);
|
|
116337
116747
|
}
|
|
116338
|
-
return [key, rawValue];
|
|
116748
|
+
return [[key, rawValue]];
|
|
116339
116749
|
})
|
|
116340
116750
|
);
|
|
116341
116751
|
if (!overridesValue || typeof overridesValue !== "object" || Array.isArray(overridesValue)) {
|
|
116342
116752
|
return normalizedDefaults;
|
|
116343
116753
|
}
|
|
116344
116754
|
const merged = { ...normalizedDefaults };
|
|
116345
|
-
for (const key of
|
|
116755
|
+
for (const key of AI_INDICATOR_KEYS) {
|
|
116756
|
+
if (!Object.prototype.hasOwnProperty.call(normalizedDefaults, key)) {
|
|
116757
|
+
continue;
|
|
116758
|
+
}
|
|
116346
116759
|
const overrideValue = overridesValue[key];
|
|
116347
116760
|
if (overrideValue == null) {
|
|
116348
116761
|
continue;
|
|
@@ -116550,7 +116963,7 @@ ${reviewOutputContract}`;
|
|
|
116550
116963
|
}
|
|
116551
116964
|
return roundPromptSignificant(value, roundDigits);
|
|
116552
116965
|
};
|
|
116553
|
-
buildPromptCandlesComponent = (candles, promptLookback, activeIndicators) => {
|
|
116966
|
+
buildPromptCandlesComponent = (candles, promptLookback, activeIndicators, relativeVolume) => {
|
|
116554
116967
|
const sortedCandles = [...candles].sort(
|
|
116555
116968
|
(left, right) => toEpochSeconds(left.timestamp) - toEpochSeconds(right.timestamp)
|
|
116556
116969
|
);
|
|
@@ -116590,6 +117003,18 @@ ${reviewOutputContract}`;
|
|
|
116590
117003
|
if (activeIndicators.ema_200) {
|
|
116591
117004
|
indicators.ema_200 = computeEma(closes, PROMPT_EMA_PERIODS.ema_200);
|
|
116592
117005
|
}
|
|
117006
|
+
if (activeIndicators.rv) {
|
|
117007
|
+
indicators.rv = calculateRelativeVolumeSeries({
|
|
117008
|
+
candles: sortedCandles,
|
|
117009
|
+
closedCount: relativeVolume ? closedCandleCount({
|
|
117010
|
+
openTimestamps: sortedCandles.map((candle) => toEpochSeconds(candle.timestamp)),
|
|
117011
|
+
timeframe: relativeVolume.timeframe,
|
|
117012
|
+
asOfTimestamp: relativeVolume.asOfTimestamp
|
|
117013
|
+
}) : 0,
|
|
117014
|
+
baselineDollarVolume: relativeVolume?.baselineDollarVolume ?? null,
|
|
117015
|
+
recentCandles: relativeVolume?.recentCandles ?? 0
|
|
117016
|
+
});
|
|
117017
|
+
}
|
|
116593
117018
|
const recentCandles = sortedCandles.slice(-Math.max(promptLookback, 1));
|
|
116594
117019
|
const startIndex = sortedCandles.length - recentCandles.length;
|
|
116595
117020
|
const summarized = recentCandles.map((candle, index) => {
|
|
@@ -116602,38 +117027,55 @@ ${reviewOutputContract}`;
|
|
|
116602
117027
|
roundPromptSignificant(candle.close, PROMPT_SIGNIFICANT_DIGITS),
|
|
116603
117028
|
Math.trunc(Number(candle.volume) || 0)
|
|
116604
117029
|
];
|
|
116605
|
-
|
|
116606
|
-
|
|
116607
|
-
|
|
116608
|
-
|
|
116609
|
-
|
|
116610
|
-
|
|
116611
|
-
|
|
116612
|
-
|
|
116613
|
-
|
|
116614
|
-
|
|
116615
|
-
|
|
116616
|
-
|
|
116617
|
-
}
|
|
116618
|
-
if (activeIndicators.atr) {
|
|
116619
|
-
row.push(getIndicatorValue(indicators.atr, currentIndex));
|
|
116620
|
-
}
|
|
116621
|
-
if (activeIndicators.ema_9) {
|
|
116622
|
-
row.push(getIndicatorValue(indicators.ema_9, currentIndex));
|
|
116623
|
-
}
|
|
116624
|
-
if (activeIndicators.ema_21) {
|
|
116625
|
-
row.push(getIndicatorValue(indicators.ema_21, currentIndex));
|
|
116626
|
-
}
|
|
116627
|
-
if (activeIndicators.ema_50) {
|
|
116628
|
-
row.push(getIndicatorValue(indicators.ema_50, currentIndex));
|
|
116629
|
-
}
|
|
116630
|
-
if (activeIndicators.ema_200) {
|
|
116631
|
-
row.push(getIndicatorValue(indicators.ema_200, currentIndex));
|
|
117030
|
+
for (const indicatorKey of AI_INDICATOR_KEYS) {
|
|
117031
|
+
if (!activeIndicators[indicatorKey]) {
|
|
117032
|
+
continue;
|
|
117033
|
+
}
|
|
117034
|
+
for (const column of AI_INDICATOR_ROW_COLUMNS[indicatorKey]) {
|
|
117035
|
+
if (column === "rv") {
|
|
117036
|
+
row.push(roundPromptRelativeVolume(indicators.rv?.[currentIndex] ?? null));
|
|
117037
|
+
continue;
|
|
117038
|
+
}
|
|
117039
|
+
const value = getIndicatorValue(indicators[column], currentIndex);
|
|
117040
|
+
row.push(column === "rsi" && value != null ? roundPromptFixed(value, 1) : value);
|
|
117041
|
+
}
|
|
116632
117042
|
}
|
|
116633
117043
|
return row;
|
|
116634
117044
|
});
|
|
116635
117045
|
return { c: summarized };
|
|
116636
117046
|
};
|
|
117047
|
+
buildPromptCandleTimeframeComponent = (input) => projectCandlePromptComponent({
|
|
117048
|
+
component: buildPromptCandlesComponent(
|
|
117049
|
+
input.candles,
|
|
117050
|
+
input.promptLookback,
|
|
117051
|
+
input.activeIndicators,
|
|
117052
|
+
input.relativeVolume ? { ...input.relativeVolume, timeframe: input.timeframe, asOfTimestamp: input.asOfTimestamp } : null
|
|
117053
|
+
),
|
|
117054
|
+
timeframe: input.timeframe,
|
|
117055
|
+
asOfTimestamp: input.asOfTimestamp
|
|
117056
|
+
});
|
|
117057
|
+
resolvePromptRelativeVolumeContext = (derivedContext) => {
|
|
117058
|
+
const baselinesBySymbol = derivedContext.relative_volume_baselines;
|
|
117059
|
+
const recentCandles = derivedContext.relative_volume_recent_candles;
|
|
117060
|
+
if (!baselinesBySymbol || typeof baselinesBySymbol !== "object" || Array.isArray(baselinesBySymbol)) {
|
|
117061
|
+
return null;
|
|
117062
|
+
}
|
|
117063
|
+
if (typeof recentCandles !== "number" || !Number.isInteger(recentCandles) || recentCandles <= 0) {
|
|
117064
|
+
return null;
|
|
117065
|
+
}
|
|
117066
|
+
return { baselinesBySymbol, recentCandles };
|
|
117067
|
+
};
|
|
117068
|
+
promptRelativeVolumeBaseline = (context, symbol2, timeframe) => {
|
|
117069
|
+
const symbolKey = Object.prototype.hasOwnProperty.call(context.baselinesBySymbol, symbol2) ? symbol2 : Object.keys(context.baselinesBySymbol).find(
|
|
117070
|
+
(candidate) => normalizeHyperliquidMarketSymbol(candidate) === normalizeHyperliquidMarketSymbol(symbol2)
|
|
117071
|
+
);
|
|
117072
|
+
const timeframeBaselines = symbolKey === void 0 ? null : context.baselinesBySymbol[symbolKey];
|
|
117073
|
+
if (!timeframeBaselines || typeof timeframeBaselines !== "object" || Array.isArray(timeframeBaselines)) {
|
|
117074
|
+
return null;
|
|
117075
|
+
}
|
|
117076
|
+
const baseline = timeframeBaselines[timeframe];
|
|
117077
|
+
return typeof baseline === "number" && Number.isFinite(baseline) ? baseline : null;
|
|
117078
|
+
};
|
|
116637
117079
|
CANDLE_CLOSE_TICKER_TIMEFRAME = "5m";
|
|
116638
117080
|
candleCloseTicker = (symbol2, candlesByTimeframe) => {
|
|
116639
117081
|
const preferred = candlesByTimeframe[CANDLE_CLOSE_TICKER_TIMEFRAME] ?? [];
|
|
@@ -116653,10 +117095,16 @@ ${reviewOutputContract}`;
|
|
|
116653
117095
|
for (const timeframe of input.timeframes) {
|
|
116654
117096
|
const candles = input.candlesBySymbol[symbol2]?.[timeframe] ?? [];
|
|
116655
117097
|
const promptLookback = getPromptLookback(input.lookbackSettings, timeframe, input.defaultLookbacks, input.maxLookback);
|
|
116656
|
-
symbolData.data[timeframe] =
|
|
116657
|
-
|
|
117098
|
+
symbolData.data[timeframe] = buildPromptCandleTimeframeComponent({
|
|
117099
|
+
candles,
|
|
116658
117100
|
timeframe,
|
|
116659
|
-
|
|
117101
|
+
promptLookback,
|
|
117102
|
+
activeIndicators: input.activeIndicators,
|
|
117103
|
+
asOfTimestamp,
|
|
117104
|
+
relativeVolume: input.relativeVolume ? {
|
|
117105
|
+
baselineDollarVolume: promptRelativeVolumeBaseline(input.relativeVolume, symbol2, timeframe),
|
|
117106
|
+
recentCandles: input.relativeVolume.recentCandles
|
|
117107
|
+
} : null
|
|
116660
117108
|
});
|
|
116661
117109
|
}
|
|
116662
117110
|
payload[symbol2] = symbolData;
|
|
@@ -117632,7 +118080,7 @@ ${behaviorJson}
|
|
|
117632
118080
|
};
|
|
117633
118081
|
buildLocalRuntimePromptArtifacts = (input) => {
|
|
117634
118082
|
const { template: effectiveUserTemplate } = canonicalizePromptPlaceholders(input.userTemplate);
|
|
117635
|
-
const activePlaceholders = new Set(
|
|
118083
|
+
const activePlaceholders = new Set(promptTemplatePlaceholders(effectiveUserTemplate));
|
|
117636
118084
|
const systemPrompt = constructPromptSystemTemplate(input.systemTemplate, {
|
|
117637
118085
|
instructions: input.instructions,
|
|
117638
118086
|
symbols: input.symbols,
|
|
@@ -117644,7 +118092,9 @@ ${behaviorJson}
|
|
|
117644
118092
|
candlesSummary: String(input.contextVars.candles ?? ""),
|
|
117645
118093
|
newsSummary: NEWS_PROMPT_VARIABLES.map((key) => String(input.contextVars[key] ?? "")).filter((block) => block.trim().length > 0).join("\n"),
|
|
117646
118094
|
calendarSummary: String(input.contextVars.calendar ?? ""),
|
|
117647
|
-
behaviorStateSummary: String(input.contextVars.behavior_state ?? "")
|
|
118095
|
+
behaviorStateSummary: String(input.contextVars.behavior_state ?? ""),
|
|
118096
|
+
referenceCandlesSummary: String(input.contextVars[REFERENCE_CANDLES_PROMPT_VARIABLE] ?? ""),
|
|
118097
|
+
referenceIndicatorFlags: input.referenceIndicators
|
|
117648
118098
|
});
|
|
117649
118099
|
const templateContextVars = Object.fromEntries(
|
|
117650
118100
|
Object.entries(input.contextVars).filter(([key]) => activePlaceholders.has(key))
|
|
@@ -118701,30 +119151,9 @@ ${behaviorJson}
|
|
|
118701
119151
|
const getLatestTotalUnrealizedPnl = () => _latestTotalUnrealizedPnl;
|
|
118702
119152
|
const getAccountStateResolvedAtMs = () => _accountStateResolvedAtMs;
|
|
118703
119153
|
const accountStateStartedAtMs = Date.now();
|
|
118704
|
-
let promptRescueSequence = 0;
|
|
119154
|
+
let promptRescueSequence = input.dispatchContextRebuild === true ? PROMPT_RESCUE_ASKS_PER_CYCLE_BUILD : 0;
|
|
118705
119155
|
observeRuntimeCycle(input, { stage: "market_context" });
|
|
118706
|
-
const
|
|
118707
|
-
publicRequestPriority: "trading_analysis",
|
|
118708
|
-
config: config2,
|
|
118709
|
-
walletAddress,
|
|
118710
|
-
symbol: localFallbackSymbol,
|
|
118711
|
-
tickerPrice: 0,
|
|
118712
|
-
leverage: resolveRuntimeLeveragePreference(settings, config2),
|
|
118713
|
-
aggregatePerpDexs: true,
|
|
118714
|
-
perpDexScope: perpDexScopeForSymbols(symbols),
|
|
118715
|
-
feeSymbols: symbols,
|
|
118716
|
-
includeEffectiveTakerRate: true,
|
|
118717
|
-
// A Server bot's cycle reads the account authoritatively, as the Python
|
|
118718
|
-
// Server loop does: never a cached or rate-limit-stale observation.
|
|
118719
|
-
forceRefresh: input.executionMode === "server",
|
|
118720
|
-
// And values it as that loop does: Perps equity alone unless the loop's
|
|
118721
|
-
// own tests count Spot (serverLoopAccountValue). A Client bot's cycle
|
|
118722
|
-
// keeps the device rule.
|
|
118723
|
-
serverLoopAccountValue: input.executionMode === "server",
|
|
118724
|
-
sessionId,
|
|
118725
|
-
signal: timeoutController.signal
|
|
118726
|
-
}).catch(async (error48) => {
|
|
118727
|
-
if (input.executionMode !== "server" || !(error48 instanceof HyperliquidPublicReadError)) throw error48;
|
|
119156
|
+
const rescueAccountState = async (serverReason) => {
|
|
118728
119157
|
promptRescueSequence += 1;
|
|
118729
119158
|
try {
|
|
118730
119159
|
const rescued = await requestServerHostPromptRescue(profileId, {
|
|
@@ -118737,20 +119166,59 @@ ${behaviorJson}
|
|
|
118737
119166
|
symbol: localFallbackSymbol,
|
|
118738
119167
|
symbols,
|
|
118739
119168
|
requestSequence: promptRescueSequence,
|
|
118740
|
-
serverReason
|
|
119169
|
+
serverReason
|
|
118741
119170
|
}, {
|
|
118742
119171
|
schedulerInstanceId: String(input.schedulerInstanceId || "").trim(),
|
|
118743
119172
|
signal: timeoutController.signal
|
|
118744
119173
|
});
|
|
118745
|
-
appendRuntimeDebugEvent({ label: "account_state_prompt_rescued", note: `job=${rescued.job_id} reason=${
|
|
119174
|
+
appendRuntimeDebugEvent({ label: "account_state_prompt_rescued", note: `job=${rescued.job_id} reason=${serverReason}` });
|
|
118746
119175
|
return accountStateFromServerPromptRescueSnapshot(rescued.snapshot, localFallbackSymbol);
|
|
119176
|
+
} catch (rescueError) {
|
|
119177
|
+
if (!timeoutController.signal.aborted) {
|
|
119178
|
+
appendRuntimeDebugEvent({
|
|
119179
|
+
label: "account_state_prompt_rescue_unavailable",
|
|
119180
|
+
note: `reason=${serverReason} ${rescueError instanceof Error ? rescueError.message : String(rescueError)}`,
|
|
119181
|
+
outcome: "error"
|
|
119182
|
+
});
|
|
119183
|
+
}
|
|
119184
|
+
throw rescueError;
|
|
119185
|
+
}
|
|
119186
|
+
};
|
|
119187
|
+
const browserAccountStateTask = (async () => {
|
|
119188
|
+
if (input.executionMode === "server" && input.dispatchContextRebuild !== true && await hyperliquidPrivateInfoHeldOff()) {
|
|
119189
|
+
try {
|
|
119190
|
+
return await rescueAccountState(SERVER_PROMPT_RESCUE_NODE_OUTAGE_REASON);
|
|
119191
|
+
} catch (rescueError) {
|
|
119192
|
+
if (timeoutController.signal.aborted) throw rescueError;
|
|
119193
|
+
}
|
|
119194
|
+
}
|
|
119195
|
+
return fetchBrowserAccountState2({
|
|
119196
|
+
publicRequestPriority: "trading_analysis",
|
|
119197
|
+
config: config2,
|
|
119198
|
+
walletAddress,
|
|
119199
|
+
symbol: localFallbackSymbol,
|
|
119200
|
+
tickerPrice: 0,
|
|
119201
|
+
leverage: resolveRuntimeLeveragePreference(settings, config2),
|
|
119202
|
+
aggregatePerpDexs: true,
|
|
119203
|
+
perpDexScope: perpDexScopeForSymbols(symbols),
|
|
119204
|
+
feeSymbols: symbols,
|
|
119205
|
+
includeEffectiveTakerRate: true,
|
|
119206
|
+
// A Server bot's cycle reads the account authoritatively, as the Python
|
|
119207
|
+
// Server loop does: never a cached or rate-limit-stale observation.
|
|
119208
|
+
forceRefresh: input.executionMode === "server",
|
|
119209
|
+
// And values it as that loop does: Perps equity alone unless the loop's
|
|
119210
|
+
// own tests count Spot (serverLoopAccountValue). A Client bot's cycle
|
|
119211
|
+
// keeps the device rule.
|
|
119212
|
+
serverLoopAccountValue: input.executionMode === "server",
|
|
119213
|
+
sessionId,
|
|
119214
|
+
signal: timeoutController.signal
|
|
119215
|
+
});
|
|
119216
|
+
})().catch(async (error48) => {
|
|
119217
|
+
if (input.executionMode !== "server" || !(error48 instanceof HyperliquidPublicReadError)) throw error48;
|
|
119218
|
+
try {
|
|
119219
|
+
return await rescueAccountState(error48.code);
|
|
118747
119220
|
} catch (rescueError) {
|
|
118748
119221
|
if (timeoutController.signal.aborted) throw rescueError;
|
|
118749
|
-
appendRuntimeDebugEvent({
|
|
118750
|
-
label: "account_state_prompt_rescue_unavailable",
|
|
118751
|
-
note: rescueError instanceof Error ? rescueError.message : String(rescueError),
|
|
118752
|
-
outcome: "error"
|
|
118753
|
-
});
|
|
118754
119222
|
throw error48;
|
|
118755
119223
|
}
|
|
118756
119224
|
}).then((state2) => {
|
|
@@ -119077,6 +119545,8 @@ ${behaviorJson}
|
|
|
119077
119545
|
const contractPrefersLocalSource = isClientOnlyModelSource(authoritativeModelSource);
|
|
119078
119546
|
const temperature = clampNumber(settings.temperature, config2.default_temperature);
|
|
119079
119547
|
const maxTokens = Math.round(clampNumber(settings.max_tokens, config2.default_max_tokens));
|
|
119548
|
+
const derivedContext = asRecord(promptDerivedContext.derived_context);
|
|
119549
|
+
const relativeVolumeContext = activeIndicators.rv ? resolvePromptRelativeVolumeContext(derivedContext) : null;
|
|
119080
119550
|
const candlesPayload = buildPromptCandlesPayload({
|
|
119081
119551
|
symbols: promptSymbols,
|
|
119082
119552
|
timeframes: promptTimeframes,
|
|
@@ -119085,7 +119555,8 @@ ${behaviorJson}
|
|
|
119085
119555
|
lookbackSettings,
|
|
119086
119556
|
defaultLookbacks: effectiveDefaultLookbacks,
|
|
119087
119557
|
maxLookback: config2.max_analysis_lookback,
|
|
119088
|
-
activeIndicators
|
|
119558
|
+
activeIndicators,
|
|
119559
|
+
relativeVolume: relativeVolumeContext
|
|
119089
119560
|
});
|
|
119090
119561
|
if (!Object.prototype.hasOwnProperty.call(candlesPayload, symbol2)) {
|
|
119091
119562
|
throw new Error(`Prompt contract symbol is missing from local market payload: ${symbol2}`);
|
|
@@ -119240,7 +119711,6 @@ ${behaviorJson}
|
|
|
119240
119711
|
"configured_user_template"
|
|
119241
119712
|
);
|
|
119242
119713
|
const templatePlaceholders = extractTemplatePlaceholders(userTemplate);
|
|
119243
|
-
const derivedContext = asRecord(promptDerivedContext.derived_context);
|
|
119244
119714
|
const cycleCutoff = normalizePromptIdentityTimestamp(
|
|
119245
119715
|
derivedContext.behavior_memory_cutoff ?? promptDerivedContext.derived_context_generated_at
|
|
119246
119716
|
);
|
|
@@ -119255,6 +119725,9 @@ ${behaviorJson}
|
|
|
119255
119725
|
"market_regime",
|
|
119256
119726
|
...NEWS_PROMPT_VARIABLES,
|
|
119257
119727
|
"calendar",
|
|
119728
|
+
// The server renders the whole <reference_candles> block; it is
|
|
119729
|
+
// present, possibly blank, whenever the template uses the variable.
|
|
119730
|
+
REFERENCE_CANDLES_PROMPT_VARIABLE,
|
|
119258
119731
|
"interval"
|
|
119259
119732
|
].includes(key));
|
|
119260
119733
|
for (const key of requiredDerivedKeys) {
|
|
@@ -119264,6 +119737,11 @@ ${behaviorJson}
|
|
|
119264
119737
|
}
|
|
119265
119738
|
const intervalContext = String(derivedContext.interval ?? "").trim();
|
|
119266
119739
|
const calendarContext = String(derivedContext.calendar ?? "");
|
|
119740
|
+
const referenceCandlesContext = String(derivedContext[REFERENCE_CANDLES_PROMPT_VARIABLE] ?? "");
|
|
119741
|
+
const rawReferenceIndicators = derivedContext.reference_candles_indicators;
|
|
119742
|
+
const referenceIndicators = rawReferenceIndicators && typeof rawReferenceIndicators === "object" && !Array.isArray(rawReferenceIndicators) ? Object.fromEntries(
|
|
119743
|
+
Object.entries(rawReferenceIndicators).map(([key, value]) => [key, Boolean(value)])
|
|
119744
|
+
) : void 0;
|
|
119267
119745
|
if (typeof promptKnobs.behavior_memory_enabled !== "boolean") {
|
|
119268
119746
|
throw new Error("Prompt metadata missing lane-effective behavior_memory_enabled Boolean.");
|
|
119269
119747
|
}
|
|
@@ -119325,6 +119803,7 @@ ${behaviorJson}
|
|
|
119325
119803
|
candles: `<candles>
|
|
119326
119804
|
${stringifyPromptJson(candlesPayload)}
|
|
119327
119805
|
</candles>`,
|
|
119806
|
+
[REFERENCE_CANDLES_PROMPT_VARIABLE]: referenceCandlesContext,
|
|
119328
119807
|
market_stats: String(derivedContext.market_stats ?? ""),
|
|
119329
119808
|
account_status: buildPromptAccountStatusValue(
|
|
119330
119809
|
accountSummary,
|
|
@@ -119408,7 +119887,9 @@ ${stringifyPromptJson(candlesPayload)}
|
|
|
119408
119887
|
note: [
|
|
119409
119888
|
`interval_source=${intervalContext ? "derived_context" : "missing"}`,
|
|
119410
119889
|
`calendar_source=${calendarContext ? "derived_context" : "missing"}`,
|
|
119411
|
-
...NEWS_PROMPT_VARIABLES.map((key) => `${key}_source=${Object.prototype.hasOwnProperty.call(derivedContext, key) ? "derived_context" : "missing"}`)
|
|
119890
|
+
...NEWS_PROMPT_VARIABLES.map((key) => `${key}_source=${Object.prototype.hasOwnProperty.call(derivedContext, key) ? "derived_context" : "missing"}`),
|
|
119891
|
+
`${REFERENCE_CANDLES_PROMPT_VARIABLE}_source=${Object.prototype.hasOwnProperty.call(derivedContext, REFERENCE_CANDLES_PROMPT_VARIABLE) ? "derived_context" : "missing"}`,
|
|
119892
|
+
...activeIndicators.rv ? [`relative_volume_baselines_source=${relativeVolumeContext ? "derived_context" : "missing"}`] : []
|
|
119412
119893
|
].join(" ")
|
|
119413
119894
|
});
|
|
119414
119895
|
const contextSnapshots = {
|
|
@@ -119434,6 +119915,7 @@ ${stringifyPromptJson(candlesPayload)}
|
|
|
119434
119915
|
const contextValueSummary = [
|
|
119435
119916
|
"current_time",
|
|
119436
119917
|
"candles",
|
|
119918
|
+
REFERENCE_CANDLES_PROMPT_VARIABLE,
|
|
119437
119919
|
"market_stats",
|
|
119438
119920
|
"account_status",
|
|
119439
119921
|
"calendar",
|
|
@@ -119474,6 +119956,7 @@ ${stringifyPromptJson(candlesPayload)}
|
|
|
119474
119956
|
systemTemplate,
|
|
119475
119957
|
instructions: asRecord(promptMetadata.prompt_instructions),
|
|
119476
119958
|
activeIndicators,
|
|
119959
|
+
referenceIndicators,
|
|
119477
119960
|
symbols: promptSymbols,
|
|
119478
119961
|
maxTradesPerPrompt,
|
|
119479
119962
|
metricsWindowHours,
|
|
@@ -119598,7 +120081,11 @@ ${stringifyPromptJson(candlesPayload)}
|
|
|
119598
120081
|
leverage: metadataLeverage,
|
|
119599
120082
|
active_indicators: activeIndicators,
|
|
119600
120083
|
candles_payload: stringifyPromptJson(candlesPayload),
|
|
119601
|
-
context_vars: contextVars
|
|
120084
|
+
context_vars: contextVars,
|
|
120085
|
+
// The server's re-render needs the flags its reference block was built
|
|
120086
|
+
// with for that block's legend line; the block itself is echoed in
|
|
120087
|
+
// context_vars.reference_candles.
|
|
120088
|
+
...referenceIndicators ? { reference_active_indicators: referenceIndicators } : {}
|
|
119602
120089
|
};
|
|
119603
120090
|
if (input.requireServerPromptParity && shouldCompareServerPromptParity()) {
|
|
119604
120091
|
try {
|
|
@@ -120777,6 +121264,7 @@ var init_engine = __esm({
|
|
|
120777
121264
|
init_api2();
|
|
120778
121265
|
init_history_evidence();
|
|
120779
121266
|
init_portfolio_evidence();
|
|
121267
|
+
init_signing_key_messages();
|
|
120780
121268
|
init_copy_trading_evidence();
|
|
120781
121269
|
DEVICE_DIAGNOSTICS3 = runtime_policy_generated_default2.trading.engine.client_runtime.device_diagnostics;
|
|
120782
121270
|
FALLBACK_ERROR_MAX_CHARS = runtime_policy_generated_default2.trading.engine.client_runtime.request_bounds.max_fallback_error_length;
|
|
@@ -121466,6 +121954,9 @@ var init_engine = __esm({
|
|
|
121466
121954
|
this._lastErrorReportCalls = null;
|
|
121467
121955
|
// The retry wait the API returned for this runtime's latest error report.
|
|
121468
121956
|
this._reportedProviderRetryAfterSeconds = null;
|
|
121957
|
+
// Whether the server answered the last error report with the failure shown
|
|
121958
|
+
// on its decision's card.
|
|
121959
|
+
this._reportedOrderFailureOnDecisionCard = false;
|
|
121469
121960
|
this._activeRuntimeContractIdentity = null;
|
|
121470
121961
|
this._contractRebindInFlight = false;
|
|
121471
121962
|
this._contractRebindExhausted = false;
|
|
@@ -123853,6 +124344,7 @@ var init_engine = __esm({
|
|
|
123853
124344
|
let cycleObservation = { stage: "setup" };
|
|
123854
124345
|
let cycleOutcome = "unknown";
|
|
123855
124346
|
let cycleReason = null;
|
|
124347
|
+
let cycleOrderFailure = null;
|
|
123856
124348
|
let cycleFailureStage = null;
|
|
123857
124349
|
let decisionSnapshotId = null;
|
|
123858
124350
|
let observationClosed = false;
|
|
@@ -123964,10 +124456,11 @@ var init_engine = __esm({
|
|
|
123964
124456
|
if (analysisAbortController.signal.aborted || this._isStopping || this._analysisRequestId !== requestId) {
|
|
123965
124457
|
throw new DOMException("The operation was aborted.", "AbortError");
|
|
123966
124458
|
}
|
|
123967
|
-
const runCycle = (secrets) => runLocalRuntimeCycle2({
|
|
124459
|
+
const runCycle = (secrets, dispatchContextRebuild = false) => runLocalRuntimeCycle2({
|
|
123968
124460
|
profileId,
|
|
123969
124461
|
mode: runtimeMode,
|
|
123970
124462
|
analysisRunId: requestId,
|
|
124463
|
+
dispatchContextRebuild,
|
|
123971
124464
|
secrets,
|
|
123972
124465
|
sessionId,
|
|
123973
124466
|
deviceId,
|
|
@@ -124053,7 +124546,7 @@ var init_engine = __esm({
|
|
|
124053
124546
|
throw error48;
|
|
124054
124547
|
}
|
|
124055
124548
|
appendRuntimeDebugEvent({ label: "server_dispatch_context_rebuilt", note: "attempt=2", outcome: "ok" });
|
|
124056
|
-
return runCycle(secrets);
|
|
124549
|
+
return runCycle(secrets, true);
|
|
124057
124550
|
});
|
|
124058
124551
|
let result;
|
|
124059
124552
|
try {
|
|
@@ -124463,6 +124956,7 @@ var init_engine = __esm({
|
|
|
124463
124956
|
}
|
|
124464
124957
|
const runPlan = async (plan, planIndex) => {
|
|
124465
124958
|
let planEntryOrderDispatched = false;
|
|
124959
|
+
let planExitOrderDispatched = false;
|
|
124466
124960
|
const decisionWallet = String(
|
|
124467
124961
|
plan.executionContext.walletAddress || ""
|
|
124468
124962
|
).trim().toLowerCase();
|
|
@@ -124555,98 +125049,150 @@ var init_engine = __esm({
|
|
|
124555
125049
|
if (dispatchKind === "entry") {
|
|
124556
125050
|
planEntryOrderDispatched = true;
|
|
124557
125051
|
}
|
|
125052
|
+
if (dispatchKind === "exit") {
|
|
125053
|
+
planExitOrderDispatched = true;
|
|
125054
|
+
}
|
|
124558
125055
|
this._executionFinalizationRequired = true;
|
|
124559
125056
|
},
|
|
124560
125057
|
shouldCancelBeforeExchangeOrderDispatch: () => this._windowHandoffRequested
|
|
124561
125058
|
});
|
|
124562
125059
|
} catch (executionError) {
|
|
125060
|
+
const committedReports = getCommittedExecutionReports(executionError);
|
|
125061
|
+
const committedOrder = getCommittedDecisionOrder(executionError);
|
|
125062
|
+
const plannedUnits = Number.isFinite(Number(plan.units)) ? Math.max(0, Math.trunc(Number(plan.units))) : 0;
|
|
124563
125063
|
if (isClientRuntimeWindowHandoffBeforePlanDispatch(executionError)) {
|
|
124564
125064
|
const handoffCleanup = getClientRuntimeWindowHandoffCleanup(executionError);
|
|
124565
|
-
if (handoffCleanup) {
|
|
125065
|
+
if (handoffCleanup || committedReports.length > 0) {
|
|
124566
125066
|
this._executionFinalizationRequired = true;
|
|
124567
125067
|
return { control: "break", result: {
|
|
124568
|
-
status: "skipped",
|
|
125068
|
+
status: committedReports.length > 0 ? "executed" : "skipped",
|
|
124569
125069
|
intent: "hold",
|
|
124570
125070
|
side: null,
|
|
124571
125071
|
reduceOnly: false,
|
|
124572
|
-
requestedUnits:
|
|
125072
|
+
requestedUnits: plannedUnits,
|
|
124573
125073
|
targetSignedUnits: 0,
|
|
124574
125074
|
executedSizeAsset: 0,
|
|
124575
|
-
|
|
124576
|
-
|
|
124577
|
-
handoffCleanup,
|
|
125075
|
+
...committedOrder ?? {},
|
|
125076
|
+
executionReports: committedReports,
|
|
125077
|
+
message: handoffCleanup ? "Stopped before protective replacement dispatch; cleanup remains blocked." : "Stopped after the order for ownership handoff.",
|
|
125078
|
+
...handoffCleanup ? { handoffCleanup } : {},
|
|
124578
125079
|
executionSnapshotId: `handoff-cleanup-${planIndex + 1}-${Date.now()}`,
|
|
124579
125080
|
executionSnapshotCapturedAt: (/* @__PURE__ */ new Date()).toISOString()
|
|
124580
125081
|
} };
|
|
124581
125082
|
}
|
|
124582
125083
|
return { control: "break" };
|
|
124583
125084
|
}
|
|
124584
|
-
const committedReports = getCommittedExecutionReports(executionError);
|
|
124585
125085
|
const abortedAfterCommittedOrder = committedReports.length > 0 && (analysisAbortController.signal.aborted || isRuntimeAbortError(executionError));
|
|
124586
125086
|
if (!abortedAfterCommittedOrder && (analysisAbortController.signal.aborted || isRuntimeAbortError(executionError)) || isRuntimeContractMismatchError(executionError) || isClientExecutionModeMismatchError(executionError) || isClientRuntimeSessionStoppedError(executionError) || isClientRuntimeLeaseAuthError(executionError) || isTransientRuntimeConflictError(executionError) && committedReports.length === 0) {
|
|
124587
125087
|
throw executionError;
|
|
124588
125088
|
}
|
|
124589
125089
|
const sanitizedReason = getSanitizedRuntimeErrorMessage(executionError) || "Unknown runtime execution error.";
|
|
124590
|
-
|
|
124591
|
-
|
|
124592
|
-
|
|
124593
|
-
|
|
124594
|
-
reasonCode: typeof typedExecutionError?.reasonCode === "string" ? typedExecutionError.reasonCode : planEntryOrderDispatched ? "outcome_unknown" : "local_safety_block"
|
|
124595
|
-
});
|
|
124596
|
-
const failureDiagnostics = getExchangeFailureDiagnostics(executionError);
|
|
124597
|
-
if (!abortedAfterCommittedOrder) {
|
|
124598
|
-
executionFailures.push({
|
|
124599
|
-
symbol: plan.executionContext.symbol,
|
|
124600
|
-
projection: projectedFailure
|
|
125090
|
+
if (committedOrder !== null) {
|
|
125091
|
+
const stepFailure = projectExecutionErrorContract({
|
|
125092
|
+
error: executionError,
|
|
125093
|
+
symbol: plan.executionContext.symbol
|
|
124601
125094
|
});
|
|
124602
|
-
|
|
124603
|
-
|
|
124604
|
-
|
|
124605
|
-
|
|
124606
|
-
|
|
124607
|
-
|
|
124608
|
-
|
|
124609
|
-
|
|
124610
|
-
|
|
124611
|
-
|
|
124612
|
-
|
|
124613
|
-
|
|
124614
|
-
|
|
124615
|
-
|
|
124616
|
-
|
|
124617
|
-
|
|
124618
|
-
|
|
124619
|
-
|
|
124620
|
-
|
|
124621
|
-
|
|
124622
|
-
|
|
124623
|
-
|
|
124624
|
-
|
|
124625
|
-
|
|
124626
|
-
|
|
124627
|
-
|
|
124628
|
-
|
|
124629
|
-
|
|
124630
|
-
|
|
124631
|
-
|
|
125095
|
+
appendRuntimeDebugEvent({
|
|
125096
|
+
label: "execution_plan_failed_after_order",
|
|
125097
|
+
note: [
|
|
125098
|
+
`cycle_id=${result.cycleId}`,
|
|
125099
|
+
`decision_snapshot_id=${result.decisionSnapshotId}`,
|
|
125100
|
+
`index=${planIndex + 1}/${executionPlans.length}`,
|
|
125101
|
+
`symbol=${plan.executionContext.symbol}`,
|
|
125102
|
+
`decision=${plan.decision}`,
|
|
125103
|
+
`error=${sanitizedReason}`
|
|
125104
|
+
].join(" "),
|
|
125105
|
+
outcome: "error"
|
|
125106
|
+
});
|
|
125107
|
+
executionResult = {
|
|
125108
|
+
status: "executed",
|
|
125109
|
+
...committedOrder,
|
|
125110
|
+
message: stepFailure.message,
|
|
125111
|
+
executionSnapshotId: `execution-error-${planIndex + 1}-${Date.now()}`,
|
|
125112
|
+
executionSnapshotCapturedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
125113
|
+
executionReports: abortedAfterCommittedOrder ? committedReports : [...committedReports, {
|
|
125114
|
+
order_id: null,
|
|
125115
|
+
symbol: plan.executionContext.symbol,
|
|
125116
|
+
action: "PROTECTIVE_RECONCILIATION",
|
|
125117
|
+
status: "failed",
|
|
125118
|
+
execution_metadata: {
|
|
125119
|
+
reason_code: stepFailure.reason_code,
|
|
125120
|
+
execution_stage: stepFailure.execution_stage,
|
|
125121
|
+
dispatch_outcome: stepFailure.dispatch_outcome,
|
|
125122
|
+
operation_stage: committedOrder.intent === "close" ? "post_close_protection" : "post_entry_protection",
|
|
125123
|
+
error: stepFailure.message,
|
|
125124
|
+
cycle_id: result.cycleId,
|
|
125125
|
+
decision_snapshot_id: result.decisionSnapshotId
|
|
125126
|
+
}
|
|
125127
|
+
}]
|
|
125128
|
+
};
|
|
125129
|
+
if (abortedAfterCommittedOrder) {
|
|
125130
|
+
this._executionFinalizationRequired = true;
|
|
125131
|
+
return { control: "break", result: executionResult };
|
|
125132
|
+
}
|
|
125133
|
+
} else {
|
|
125134
|
+
const typedExecutionError = executionError;
|
|
125135
|
+
const planOrderMayHaveGoneOut = planEntryOrderDispatched || planExitOrderDispatched && committedReports.length === 0;
|
|
125136
|
+
const projectedFailure = projectExecutionErrorContract({
|
|
125137
|
+
error: executionError,
|
|
124632
125138
|
symbol: plan.executionContext.symbol,
|
|
124633
|
-
|
|
124634
|
-
|
|
124635
|
-
|
|
124636
|
-
|
|
124637
|
-
|
|
124638
|
-
|
|
124639
|
-
|
|
124640
|
-
|
|
124641
|
-
|
|
124642
|
-
|
|
124643
|
-
|
|
124644
|
-
|
|
124645
|
-
|
|
124646
|
-
|
|
124647
|
-
|
|
124648
|
-
|
|
124649
|
-
|
|
125139
|
+
reasonCode: typeof typedExecutionError?.reasonCode === "string" ? typedExecutionError.reasonCode : planOrderMayHaveGoneOut ? "outcome_unknown" : "local_safety_block"
|
|
125140
|
+
});
|
|
125141
|
+
const failureDiagnostics = getExchangeFailureDiagnostics(executionError);
|
|
125142
|
+
if (!abortedAfterCommittedOrder) {
|
|
125143
|
+
executionFailures.push({
|
|
125144
|
+
symbol: plan.executionContext.symbol,
|
|
125145
|
+
projection: projectedFailure
|
|
125146
|
+
});
|
|
125147
|
+
executionFailureCauses.push(executionError);
|
|
125148
|
+
}
|
|
125149
|
+
appendRuntimeDebugEvent({
|
|
125150
|
+
label: "execution_plan_failed",
|
|
125151
|
+
note: [
|
|
125152
|
+
`cycle_id=${result.cycleId}`,
|
|
125153
|
+
`decision_snapshot_id=${result.decisionSnapshotId}`,
|
|
125154
|
+
`index=${planIndex + 1}/${executionPlans.length}`,
|
|
125155
|
+
`symbol=${plan.executionContext.symbol}`,
|
|
125156
|
+
`decision=${plan.decision}`,
|
|
125157
|
+
`units=${plan.units}`,
|
|
125158
|
+
`error=${sanitizedReason}`
|
|
125159
|
+
].join(" "),
|
|
125160
|
+
outcome: "error"
|
|
125161
|
+
});
|
|
125162
|
+
const flipCloseCommitted = committedReports.some((report) => report.status === "executed" && report.execution_metadata?.decision_leg === "flip_close");
|
|
125163
|
+
const planSide = String(plan.decision || "").toUpperCase() === "BUY" ? "buy" : String(plan.decision || "").toUpperCase() === "SELL" ? "sell" : null;
|
|
125164
|
+
executionResult = {
|
|
125165
|
+
status: committedReports.length > 0 ? "executed" : "skipped",
|
|
125166
|
+
intent: flipCloseCommitted ? "flip" : "hold",
|
|
125167
|
+
side: flipCloseCommitted ? planSide : null,
|
|
125168
|
+
reduceOnly: false,
|
|
125169
|
+
requestedUnits: plannedUnits,
|
|
125170
|
+
targetSignedUnits: 0,
|
|
125171
|
+
executedSizeAsset: 0,
|
|
125172
|
+
message: projectedFailure.message,
|
|
125173
|
+
executionSnapshotId: `execution-error-${planIndex + 1}-${Date.now()}`,
|
|
125174
|
+
executionSnapshotCapturedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
125175
|
+
executionReports: [...committedReports, {
|
|
125176
|
+
order_id: null,
|
|
125177
|
+
symbol: plan.executionContext.symbol,
|
|
125178
|
+
action: String(plan.decision || "UNKNOWN").toUpperCase(),
|
|
125179
|
+
status: "failed",
|
|
125180
|
+
execution_metadata: {
|
|
125181
|
+
error: projectedFailure.message,
|
|
125182
|
+
reason_code: projectedFailure.reason_code,
|
|
125183
|
+
execution_stage: projectedFailure.execution_stage,
|
|
125184
|
+
dispatch_outcome: projectedFailure.dispatch_outcome,
|
|
125185
|
+
cycle_id: result.cycleId,
|
|
125186
|
+
decision_snapshot_id: result.decisionSnapshotId,
|
|
125187
|
+
...flipCloseCommitted ? { decision_leg: "entry" } : {},
|
|
125188
|
+
...failureDiagnostics ?? {}
|
|
125189
|
+
}
|
|
125190
|
+
}]
|
|
125191
|
+
};
|
|
125192
|
+
if (abortedAfterCommittedOrder) {
|
|
125193
|
+
this._executionFinalizationRequired = true;
|
|
125194
|
+
return { control: "break", result: executionResult };
|
|
125195
|
+
}
|
|
124650
125196
|
}
|
|
124651
125197
|
}
|
|
124652
125198
|
}
|
|
@@ -124871,6 +125417,7 @@ var init_engine = __esm({
|
|
|
124871
125417
|
cycleFailureStage = "execution";
|
|
124872
125418
|
const primaryFailure = selectPrimaryExecutionFailure(executionFailures);
|
|
124873
125419
|
const reportedFailures = this._expectedExecutionMode === "server" ? executionFailures.filter((_, index) => executionFailureCauses.indexOf(executionFailureCauses[index]) === index) : primaryFailure ? [primaryFailure] : [];
|
|
125420
|
+
this._lastError = null;
|
|
124874
125421
|
for (const failure2 of reportedFailures) {
|
|
124875
125422
|
await this.reportError(failure2.projection.message, {
|
|
124876
125423
|
fatal: false,
|
|
@@ -124879,8 +125426,12 @@ var init_engine = __esm({
|
|
|
124879
125426
|
executionSymbol: failure2.symbol,
|
|
124880
125427
|
executionReasonCode: failure2.projection.reason_code,
|
|
124881
125428
|
executionStage: failure2.projection.execution_stage,
|
|
124882
|
-
dispatchOutcome: failure2.projection.dispatch_outcome
|
|
125429
|
+
dispatchOutcome: failure2.projection.dispatch_outcome,
|
|
125430
|
+
recordedOrderFailure: true
|
|
124883
125431
|
});
|
|
125432
|
+
if (this._reportedOrderFailureOnDecisionCard) {
|
|
125433
|
+
cycleOrderFailure = failure2.projection.message;
|
|
125434
|
+
}
|
|
124884
125435
|
}
|
|
124885
125436
|
return;
|
|
124886
125437
|
}
|
|
@@ -125148,7 +125699,7 @@ var init_engine = __esm({
|
|
|
125148
125699
|
requestId,
|
|
125149
125700
|
outcome: cycleOutcome,
|
|
125150
125701
|
reason: cycleReason,
|
|
125151
|
-
error: cycleOutcome === "failed" ? this._lastError : null,
|
|
125702
|
+
error: cycleOutcome === "failed" ? this._lastError ?? cycleOrderFailure : null,
|
|
125152
125703
|
decisionSubmitted,
|
|
125153
125704
|
executionOccurred: executedExchangeOrderInCycle
|
|
125154
125705
|
};
|
|
@@ -125296,7 +125847,7 @@ var init_engine = __esm({
|
|
|
125296
125847
|
// this owner session, or null when the report was not accepted.
|
|
125297
125848
|
async _reportDeviceSigningKeyStartFailure(reason, failure2) {
|
|
125298
125849
|
if (!this._profileId || !this._sessionId || !this._deviceId) return null;
|
|
125299
|
-
const sanitizedReason = getSanitizedRuntimeErrorMessage(reason) ||
|
|
125850
|
+
const sanitizedReason = getSanitizedRuntimeErrorMessage(reason) || SIGNING_KEY_INVALID;
|
|
125300
125851
|
try {
|
|
125301
125852
|
const response = await reportClientRuntimeError(
|
|
125302
125853
|
this._profileId,
|
|
@@ -125341,6 +125892,7 @@ var init_engine = __esm({
|
|
|
125341
125892
|
}
|
|
125342
125893
|
async reportError(reason, options) {
|
|
125343
125894
|
this._reportedProviderRetryAfterSeconds = null;
|
|
125895
|
+
this._reportedOrderFailureOnDecisionCard = false;
|
|
125344
125896
|
if (this._isStopping) {
|
|
125345
125897
|
this._lastError = null;
|
|
125346
125898
|
return null;
|
|
@@ -125375,10 +125927,13 @@ var init_engine = __esm({
|
|
|
125375
125927
|
});
|
|
125376
125928
|
const projectedErrorWithoutWarning = String(projected.error_message || "").replace(/^\s*⚠️?\s*/u, "").trim();
|
|
125377
125929
|
const persistedError = executionProjection?.message ?? (projectedErrorWithoutWarning === sanitizedReason ? sanitizedReason : projected.error_message);
|
|
125378
|
-
|
|
125930
|
+
const awaitsDecisionCardAnswer = options?.recordedOrderFailure === true && !isFatal;
|
|
125931
|
+
if (!awaitsDecisionCardAnswer) {
|
|
125932
|
+
this._lastError = persistedError;
|
|
125933
|
+
}
|
|
125379
125934
|
if (isFatal) {
|
|
125380
125935
|
this._setState("error");
|
|
125381
|
-
} else {
|
|
125936
|
+
} else if (!awaitsDecisionCardAnswer) {
|
|
125382
125937
|
this._notifyListeners();
|
|
125383
125938
|
}
|
|
125384
125939
|
this.recordLocalBreadcrumb("runtime_error_detected", projected.error_message, {
|
|
@@ -125418,13 +125973,18 @@ var init_engine = __esm({
|
|
|
125418
125973
|
requestTimeoutMs: this._settlementRequestTimeoutMs ?? void 0
|
|
125419
125974
|
}
|
|
125420
125975
|
);
|
|
125976
|
+
const shownOnDecisionCard = awaitsDecisionCardAnswer && response.shown_on_decision_card === true;
|
|
125977
|
+
this._reportedOrderFailureOnDecisionCard = shownOnDecisionCard;
|
|
125978
|
+
if (!shownOnDecisionCard) {
|
|
125979
|
+
this._lastError = persistedError;
|
|
125980
|
+
}
|
|
125421
125981
|
const accepted = this._setRuntimeStatus(response.runtime, "error_report");
|
|
125422
125982
|
const retryAfterSeconds = Number(response.provider_retry_after_seconds);
|
|
125423
125983
|
this._reportedProviderRetryAfterSeconds = accepted && response.provider_retry_after_seconds != null && Number.isFinite(retryAfterSeconds) && retryAfterSeconds >= 0 ? retryAfterSeconds : null;
|
|
125424
|
-
this._lastError = persistedError;
|
|
125425
125984
|
this._notifyListeners();
|
|
125426
125985
|
return accepted ? response.runtime ?? null : null;
|
|
125427
125986
|
} catch (error48) {
|
|
125987
|
+
this._lastError = persistedError;
|
|
125428
125988
|
if (isClientRuntimeReleasedError(error48)) {
|
|
125429
125989
|
await this._handleRuntimeReleased("error_report", { deferUntilExecutionLoopSettles: true });
|
|
125430
125990
|
return null;
|