@vtxmacro/cli 2026.10.31 → 2026.10.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/vtx-mcp.js +1 -1
- package/bin/vtx-service-bootstrap.js +1 -1
- package/bin/vtx.js +609 -43
- package/package.json +1 -1
package/bin/vtx-mcp.js
CHANGED
|
@@ -37,7 +37,7 @@ var init_define_VTX_PI_MODEL_POLICY = __esm({
|
|
|
37
37
|
var agent_cli_release_default;
|
|
38
38
|
var init_agent_cli_release = __esm({
|
|
39
39
|
"agent-cli-release.json"() {
|
|
40
|
-
agent_cli_release_default = { package_name: "@vtxmacro/cli", package_version: "2026.10.
|
|
40
|
+
agent_cli_release_default = { package_name: "@vtxmacro/cli", package_version: "2026.10.32", 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" } } };
|
|
41
41
|
}
|
|
42
42
|
});
|
|
43
43
|
|
|
@@ -14,7 +14,7 @@ import { dirname as dirname4, relative as relative4, resolve as resolve4 } from
|
|
|
14
14
|
import { fileURLToPath } from "node:url";
|
|
15
15
|
|
|
16
16
|
// agent-cli-release.json
|
|
17
|
-
var agent_cli_release_default = { package_name: "@vtxmacro/cli", package_version: "2026.10.
|
|
17
|
+
var agent_cli_release_default = { package_name: "@vtxmacro/cli", package_version: "2026.10.32", 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" } } };
|
|
18
18
|
|
|
19
19
|
// lib/runtime-policy.generated.json
|
|
20
20
|
var runtime_policy_generated_default = {
|
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.32", 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
|
|
|
@@ -1472,7 +1472,7 @@ var init_runtime_policy_generated = __esm({
|
|
|
1472
1472
|
});
|
|
1473
1473
|
|
|
1474
1474
|
// lib/constants.ts
|
|
1475
|
-
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;
|
|
1475
|
+
var MS_PER_SECOND, SECONDS_PER_MINUTE, MINUTES_PER_HOUR, HOURS_PER_DAY, DAYS_PER_WEEK, MS_PER_MINUTE, SECONDS_PER_HOUR, SECONDS_PER_DAY, SECONDS_PER_WEEK, MINUTES_PER_DAY, MINUTES_PER_WEEK, MS_PER_HOUR, MS_PER_DAY, READ_STAMP_TIE_MS, READ_STAMP_STEP_BACK_MS, CLOCK_FIELD_DIGITS, BACKOFF_GROWTH_FACTOR, BYTES_PER_KIB, BYTES_PER_MIB, BITS_PER_BYTE, BYTE_MASK, OWNER_ONLY_FILE_MODE, OWNER_ONLY_DIRECTORY_MODE, GROUP_OTHER_PERMISSION_BITS, DECIMAL_RADIX, HEX_RADIX, BASE36_RADIX, BYTE_HEX_DIGITS, UINT32_HEX_DIGITS, RANDOM_FRACTION_PREFIX_LENGTH, PERCENT_SCALE, MIDPOINT_DIVISOR, SQUARE_EXPONENT, FNV1A_32_OFFSET_BASIS, FNV1A_32_PRIME, JSON_INDENT_SPACES, INT32_MIN, INT32_MAX, SET_TIMEOUT_MAX_DELAY_MS, POSITION_SIZE_EPSILON, CANDLE_TIMEFRAME_SECONDS, HTTP_STATUS, HTTP_STATUS_MIN, HTTP_STATUS_MAX, HTTP_CLIENT_ERROR_MIN, HTTP_SERVER_ERROR_MIN, PROMPT_RESCUE_ASKS_PER_CYCLE_BUILD, USD_DISPLAY_DECIMALS, AI_COST_ESTIMATE_PERIOD_DAYS, SECONDS_PER_AI_COST_ESTIMATE_PERIOD, DATE_FIELD_DIGITS, EXTERNAL_INFERENCE_LIMITS, NODE_ARGV_COMMAND_ARGS_START, EXIT_CODE_TEMPFAIL, SHA256_INITIAL_STATE, SHA256_ROUND_CONSTANTS, SHA256, UINT64_HIGH_WORD_DIVISOR, CANONICAL_BASE64URL, INFERENCE_ENVELOPE_CRYPTO, EXTERNAL_INFERENCE_SCHEMA_BOUNDS, JSON_RPC_ERROR_CODES, INFERENCE_MCP_SCHEMA_PROBE_MAX_DEPTH, INFERENCE_HOST_PROCESS_LOCK_RECORD_SCHEMA_VERSION, NATIVE_PROTECTION_RECORD_WITH_LOTS_VERSION, INFERENCE_HOST_RECLAIM_GUARD_CREATE_PASSES, LINUX_PROC_STAT_COMM_TERMINATOR_CHARS, INFERENCE_HOST_RANDOM_BYTES, INFERENCE_OAUTH_TOKEN_MAX_LENGTH, INFERENCE_CREDENTIAL_WINDOWS_NOT_FOUND_EXIT_CODE, MACOS_SECURITY_ITEM_NOT_FOUND_EXIT_CODE, INFERENCE_CREDENTIAL_LABEL_ACCOUNT_KEY_CHARS, INFERENCE_HOST_STABLE_OPERATION_ID_HASH_CHARS, INFERENCE_HOST_DRAIN_PRIORITY, INFERENCE_JOB_CLAIM_SCHEMA_VERSION, INFERENCE_HOST_WINDOWS_TASK_IDENTITY_MAX_CHARS, INFERENCE_HOST_OWNER_ONLY_EXECUTABLE_MODE, WINDOWS_TASKKILL_PROCESS_NOT_FOUND_EXIT_CODE, INFERENCE_HOST_CLI_MAX_SERVICE_POSITIONALS, INFERENCE_HOST_CLI_MAX_COMMAND_POSITIONALS, INFERENCE_HOST_DISPLAY_NAME_MAX_CHARS, INFERENCE_HOST_REVOCATION_CHECKPOINT_MAX_CHARS, INFERENCE_HOST_MODEL_ID_MAX_CHARS, CODEX_RECOVERY_RECEIPT_MAX_CHARS, CODEX_HOSTED_ATTEMPT_PATH_SEGMENTS, CODEX_GUARDIAN_PROCESS_TOKEN_BYTES, CODEX_RATE_LIMIT_EXHAUSTED_PERCENT, INFERENCE_HOST_PROXY_TOKEN_BYTES, 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;
|
|
1476
1476
|
var init_constants = __esm({
|
|
1477
1477
|
"lib/constants.ts"() {
|
|
1478
1478
|
"use strict";
|
|
@@ -1772,6 +1772,7 @@ var init_constants = __esm({
|
|
|
1772
1772
|
};
|
|
1773
1773
|
INFERENCE_MCP_SCHEMA_PROBE_MAX_DEPTH = 4;
|
|
1774
1774
|
INFERENCE_HOST_PROCESS_LOCK_RECORD_SCHEMA_VERSION = 2;
|
|
1775
|
+
NATIVE_PROTECTION_RECORD_WITH_LOTS_VERSION = 2;
|
|
1775
1776
|
INFERENCE_HOST_RECLAIM_GUARD_CREATE_PASSES = 2;
|
|
1776
1777
|
LINUX_PROC_STAT_COMM_TERMINATOR_CHARS = 2;
|
|
1777
1778
|
INFERENCE_HOST_RANDOM_BYTES = {
|
|
@@ -21860,8 +21861,8 @@ var init_external_inference_contract = __esm({
|
|
|
21860
21861
|
if (value.runtime_binding.binding_kind !== value.execution_mode && !(value.runtime_binding.binding_kind === "historical_chat" && value.execution_mode === "server" && value.use_case === "decision_chat")) {
|
|
21861
21862
|
context.addIssue({ code: "custom", message: "runtime binding must match execution_mode", path: ["runtime_binding", "binding_kind"] });
|
|
21862
21863
|
}
|
|
21863
|
-
if (value.lane === "screener" && value.runtime_binding.bot_mode
|
|
21864
|
-
context.addIssue({ code: "custom", message: "screener jobs require a confirmed
|
|
21864
|
+
if (value.lane === "screener" && !["trader", "assistant"].includes(value.runtime_binding.bot_mode)) {
|
|
21865
|
+
context.addIssue({ code: "custom", message: "screener jobs require a confirmed bot binding", path: ["runtime_binding", "bot_mode"] });
|
|
21865
21866
|
}
|
|
21866
21867
|
if (value.controller.host_id !== value.host_id) {
|
|
21867
21868
|
context.addIssue({ code: "custom", message: "controller host_id must match job host_id", path: ["controller", "host_id"] });
|
|
@@ -59393,9 +59394,15 @@ var init_runtime_error_reason_rules = __esm({
|
|
|
59393
59394
|
{ contains: "hyperliquid fresh public read returned non-json" },
|
|
59394
59395
|
{ contains: "hyperliquid public freshness bracket moved backwards" }
|
|
59395
59396
|
] } },
|
|
59396
|
-
{ reason_code: "behavior_state_unavailable", when: {
|
|
59397
|
-
{
|
|
59398
|
-
|
|
59397
|
+
{ reason_code: "behavior_state_unavailable", when: { any: [
|
|
59398
|
+
{ all: [
|
|
59399
|
+
{ contains: "your prompt on the ai page contains something vtx can't use" },
|
|
59400
|
+
{ contains: "next scheduled cycle" }
|
|
59401
|
+
] },
|
|
59402
|
+
{ all: [
|
|
59403
|
+
{ contains: "critical behavior context could not be constructed" },
|
|
59404
|
+
{ contains: "next scheduled cycle" }
|
|
59405
|
+
] }
|
|
59399
59406
|
] } },
|
|
59400
59407
|
{ reason_code: "hyperliquid_wallet_not_authorized", when: { any: [
|
|
59401
59408
|
{ contains: "hyperliquid api wallet is not authorized" },
|
|
@@ -59514,6 +59521,8 @@ var init_runtime_error_reason_rules = __esm({
|
|
|
59514
59521
|
model_unavailable: { transient: false, severity: "ERROR" },
|
|
59515
59522
|
outcome_unknown: { transient: true, severity: "ERROR" },
|
|
59516
59523
|
private_node_stale: { transient: true, severity: "ERROR" },
|
|
59524
|
+
protective_order_not_placed: { transient: false, severity: "WARN" },
|
|
59525
|
+
protective_order_unmanaged: { transient: false, severity: "WARN" },
|
|
59517
59526
|
provider_network_failure: { transient: true, severity: "ERROR" },
|
|
59518
59527
|
provider_not_configured: { transient: false, severity: "ERROR" },
|
|
59519
59528
|
provider_unavailable: { transient: true, severity: "ERROR" },
|
|
@@ -59869,9 +59878,12 @@ var init_error_surface_contract = __esm({
|
|
|
59869
59878
|
const detailLower = normalizedDetail.toLowerCase();
|
|
59870
59879
|
const classificationBasis = detailLower || lowered;
|
|
59871
59880
|
const pausePrefix = runtimePausePrefix(Boolean(isAssistantActive));
|
|
59872
|
-
if (classificationBasis.includes("
|
|
59881
|
+
if (classificationBasis.includes("behavior memory is unavailable for this trading cycle")) {
|
|
59873
59882
|
return `${pausePrefix}: Critical behavior context could not be constructed for this cycle. The cycle was skipped safely; VTX will retry at the next scheduled cycle.`;
|
|
59874
59883
|
}
|
|
59884
|
+
if (classificationBasis.includes("critical behavior state is unavailable for this trading cycle")) {
|
|
59885
|
+
return `${pausePrefix}: Your prompt on the AI page contains something VTX can't use, for example copied DATA FORMAT definitions in the System Prompt. Fix the prompt; VTX skipped this cycle and will retry at the next scheduled cycle.`;
|
|
59886
|
+
}
|
|
59875
59887
|
if (classificationBasis.includes(
|
|
59876
59888
|
"client runtime decision persistence deadline exceeded after the ai run completed"
|
|
59877
59889
|
)) {
|
|
@@ -68468,12 +68480,12 @@ function getKzgLibrary(kzg) {
|
|
|
68468
68480
|
return { blobToKzgCommitment, computeBlobKzgProof };
|
|
68469
68481
|
}
|
|
68470
68482
|
function getVersionedHash(version3, hash5) {
|
|
68471
|
-
let
|
|
68472
|
-
while (
|
|
68473
|
-
|
|
68483
|
+
let versioned2 = version3.toString(16);
|
|
68484
|
+
while (versioned2.length < 2) {
|
|
68485
|
+
versioned2 = "0" + versioned2;
|
|
68474
68486
|
}
|
|
68475
|
-
|
|
68476
|
-
return "0x" +
|
|
68487
|
+
versioned2 += sha2563(hash5).substring(4);
|
|
68488
|
+
return "0x" + versioned2;
|
|
68477
68489
|
}
|
|
68478
68490
|
function handleAddress(value) {
|
|
68479
68491
|
if (value === "0x") {
|
|
@@ -90550,7 +90562,7 @@ var init_hyperliquid_signer = __esm({
|
|
|
90550
90562
|
});
|
|
90551
90563
|
|
|
90552
90564
|
// lib/runtime/hyperliquid-client.ts
|
|
90553
|
-
var HyperliquidExchangeRejectionError, durableMutationAuthorityArgs, assertFreshPreparedExecutionContext, normalizeSymbol, HYPERLIQUID_NONCE_STORAGE_KEY, HYPERLIQUID_NONCE_LOCK_NAME, lastGeneratedNonce, readBrowserStoredHyperliquidNonce, writeBrowserStoredHyperliquidNonce, browserNonceCoordinator, allocateHyperliquidNonce, hostNonceAllocator, allocateActionNonce, generateHyperliquidNonce, normalizeDecimalString, HYPERLIQUID_PRICE_SIGNIFICANT_FIGURES, HYPERLIQUID_INTEGER_PRICE_MINIMUM, shortestDecimalParts, formatHyperliquidPerpPriceGrid, formatHyperliquidTriggerPriceWire, hyperliquidOrderPriceRounding, formatHyperliquidOrderPriceWire, countSignificantDigits, countDecimalPlaces, validateHyperliquidPerpPriceWire, validateHyperliquidSizeWire, formatSizeWire, inferApiUrl, inferIsTestnet, postHyperliquidInfoRead, postHyperliquidInfo, fetchBrowserHyperliquidInfoPayload, fetchBrowserHyperliquidInfoRead, fetchBrowserHyperliquidInfoText, coerceMarketMaxLeverage, toFiniteNumber, OPEN_ORDER_NUMERIC_STRING, OPEN_ORDER_ID_STRING, parseCanonicalOpenOrderId, parseOpenOrderFiniteNumber, parseOpenOrderNonNegativeNumber, NATIVE_FIRED_TRIGGER_CONDITION, parseOpenOrderPositiveNumber, parseOpenOrderPresentationNumber, readOpenOrderField, firstFiniteNumber, parseFundingUsdcFromInfoPosition, isExchangeIsolatedOnly, resolveLeverageTarget, computeHip3AssetId, getPerpDexIndexMap, buildAssetInfosFromMetaResponse, requireWalletAddress, assertPositiveInteger, assertPositiveNumber, normalizeOrderSide, normalizeHyperliquidClientOrderId, resolveAssets, findResolvedAsset, normalizeExecutionAssetMetadata, resolveHyperliquidAsset, resolveHyperliquidAssetIndex, decimalUnits, quantizeHyperliquidOrderSizeValue, hyperliquidSignedSizeMatchesRequestedSize, finitePositive, readDevicePrivateExecutionContext, quantizeHyperliquidOrderSize, fetchBrowserAvailableAssets, fetchBrowserAllMids, fetchBrowserSymbolMidPrice, fetchBrowserOpenOrders, parseCanonicalHyperliquidOrderStatusEvidence, fetchBrowserOrderStatusEvidence, fetchBrowserUserRole, fetchBrowserAccountState, fetchBrowserPosition, buildHyperliquidOrderWire, buildHyperliquidTriggerOrderWire, signHyperliquidPayload, signHyperliquidPreparedAction, buildHyperliquidCancelPayload, buildHyperliquidUpdateLeveragePayload, buildHyperliquidMarketOrderPayload, buildHyperliquidLimitOrderPayload, buildHyperliquidTriggerOrderPayload, buildHyperliquidOrderBatchPayload, buildHyperliquidModifyOrderPayload, extractHyperliquidExchangeError, acknowledgementLookupPacing, lookupUntilListed, resolveHyperliquidTriggerAcknowledgements, resolveHyperliquidModifyAcknowledgement, isDefinitiveHyperliquidExchangeResponse, extractDefinitiveHyperliquidOrderId, CANONICAL_POSITIVE_DECIMAL_PATTERN, extractCanonicalHyperliquidOrderStateAcknowledgement, extractCanonicalHyperliquidOrderStateAcknowledgements, extractCanonicalHyperliquidFilledOrderAcknowledgement, extractDefinitiveHyperliquidOrderMemberResults, buildHyperliquidOrderDiagnostics, loadClientExecutionReferenceEvidence, sha256Hex, extractSignedPayloadClientOrderId, extractSignedPayloadMutationCorrelation, assertDurableMutationMatchesSignedAction, exchangeRejectionReason, exchangeActionPriority, submitHyperliquidExchangePayload;
|
|
90565
|
+
var HyperliquidExchangeRejectionError, durableMutationAuthorityArgs, assertFreshPreparedExecutionContext, normalizeSymbol, HYPERLIQUID_NONCE_STORAGE_KEY, HYPERLIQUID_NONCE_LOCK_NAME, lastGeneratedNonce, readBrowserStoredHyperliquidNonce, writeBrowserStoredHyperliquidNonce, browserNonceCoordinator, allocateHyperliquidNonce, hostNonceAllocator, allocateActionNonce, generateHyperliquidNonce, normalizeDecimalString, HYPERLIQUID_PRICE_SIGNIFICANT_FIGURES, HYPERLIQUID_INTEGER_PRICE_MINIMUM, shortestDecimalParts, formatHyperliquidPerpPriceGrid, formatHyperliquidTriggerPriceWire, hyperliquidOrderPriceRounding, formatHyperliquidOrderPriceWire, countSignificantDigits, countDecimalPlaces, validateHyperliquidPerpPriceWire, validateHyperliquidSizeWire, formatSizeWire, inferApiUrl, inferIsTestnet, postHyperliquidInfoRead, postHyperliquidInfo, fetchBrowserHyperliquidInfoPayload, fetchBrowserHyperliquidInfoRead, fetchBrowserHyperliquidInfoText, coerceMarketMaxLeverage, toFiniteNumber, OPEN_ORDER_NUMERIC_STRING, OPEN_ORDER_ID_STRING, parseCanonicalOpenOrderId, parseOpenOrderFiniteNumber, parseOpenOrderNonNegativeNumber, NATIVE_FIRED_TRIGGER_CONDITION, parseOpenOrderPositiveNumber, parseOpenOrderPresentationNumber, readOpenOrderField, firstFiniteNumber, parseFundingUsdcFromInfoPosition, isExchangeIsolatedOnly, resolveLeverageTarget, computeHip3AssetId, getPerpDexIndexMap, buildAssetInfosFromMetaResponse, requireWalletAddress, assertPositiveInteger, assertPositiveNumber, normalizeOrderSide, normalizeHyperliquidClientOrderId, resolveAssets, findResolvedAsset, normalizeExecutionAssetMetadata, resolveHyperliquidAsset, resolveHyperliquidAssetIndex, decimalUnits, quantizeHyperliquidOrderSizeValue, hyperliquidSignedSizeMatchesRequestedSize, finitePositive, readDevicePrivateExecutionContext, quantizeHyperliquidOrderSize, fetchBrowserAvailableAssets, fetchBrowserAllMids, fetchBrowserSymbolMidPrice, fetchBrowserOpenOrders, parseCanonicalHyperliquidOrderStatusEvidence, fetchBrowserOrderStatusEvidence, fetchBrowserUserRole, fetchBrowserAccountState, fetchBrowserPosition, buildHyperliquidOrderWire, buildHyperliquidTriggerOrderWire, signHyperliquidPayload, signHyperliquidPreparedAction, buildHyperliquidCancelPayload, buildHyperliquidUpdateLeveragePayload, buildHyperliquidMarketOrderPayload, buildHyperliquidLimitOrderPayload, buildHyperliquidTriggerOrderPayload, buildHyperliquidOrderBatchPayload, buildHyperliquidModifyOrderPayload, TRAILING_PCT_PATTERN, buildHyperliquidTrailingStopPayload, extractHyperliquidExchangeError, acknowledgementLookupPacing, lookupUntilListed, resolveHyperliquidTriggerAcknowledgements, readHyperliquidTrailingStopAcknowledgement, resolveHyperliquidModifyAcknowledgement, isDefinitiveHyperliquidExchangeResponse, extractDefinitiveHyperliquidOrderId, CANONICAL_POSITIVE_DECIMAL_PATTERN, extractCanonicalHyperliquidOrderStateAcknowledgement, extractCanonicalHyperliquidOrderStateAcknowledgements, extractCanonicalHyperliquidFilledOrderAcknowledgement, extractDefinitiveHyperliquidOrderMemberResults, buildHyperliquidOrderDiagnostics, loadClientExecutionReferenceEvidence, sha256Hex, extractSignedPayloadClientOrderId, extractSignedPayloadMutationCorrelation, assertDurableMutationMatchesSignedAction, exchangeRejectionReason, exchangeActionPriority, submitHyperliquidExchangePayload;
|
|
90554
90566
|
var init_hyperliquid_client = __esm({
|
|
90555
90567
|
"lib/runtime/hyperliquid-client.ts"() {
|
|
90556
90568
|
"use strict";
|
|
@@ -92029,6 +92041,52 @@ var init_hyperliquid_client = __esm({
|
|
|
92029
92041
|
order
|
|
92030
92042
|
});
|
|
92031
92043
|
};
|
|
92044
|
+
TRAILING_PCT_PATTERN = /^\d+(\.\d+)?%$/;
|
|
92045
|
+
buildHyperliquidTrailingStopPayload = async (input) => {
|
|
92046
|
+
input = { ...input, publicRequestPriority: "trading_reduce" };
|
|
92047
|
+
assertPositiveNumber(input.size, "Hyperliquid trailing stop size");
|
|
92048
|
+
const { asset_index: assetIndex, sz_decimals: sizeDecimals } = await resolveHyperliquidAsset(input);
|
|
92049
|
+
const side = normalizeOrderSide(input.side);
|
|
92050
|
+
const roundedSize = quantizeHyperliquidOrderSizeValue(input.size, sizeDecimals, "nearest");
|
|
92051
|
+
assertPositiveNumber(roundedSize, "Hyperliquid trailing stop size");
|
|
92052
|
+
const sizeWire = formatSizeWire(roundedSize, sizeDecimals);
|
|
92053
|
+
const sizeValidation = validateHyperliquidSizeWire(sizeWire, sizeDecimals);
|
|
92054
|
+
if (!sizeValidation.valid) {
|
|
92055
|
+
throw new Error(`Invalid Hyperliquid trailing stop size wire: ${sizeValidation.reason}.`);
|
|
92056
|
+
}
|
|
92057
|
+
let retracement;
|
|
92058
|
+
if ("pct" in input.retracement) {
|
|
92059
|
+
const pct = input.retracement.pct.trim();
|
|
92060
|
+
const decimals = pct.includes(".") ? pct.slice(pct.indexOf(".") + 1, -1).length : 0;
|
|
92061
|
+
if (!TRAILING_PCT_PATTERN.test(pct) || !(Number(pct.slice(0, -1)) > 0) || decimals > HYPERLIQUID_EXCHANGE_SPECIFICATION.trailing_retracement_pct_max_decimals) {
|
|
92062
|
+
throw new Error(
|
|
92063
|
+
`Hyperliquid trailing stop percent must be positive with at most ${HYPERLIQUID_EXCHANGE_SPECIFICATION.trailing_retracement_pct_max_decimals} decimals.`
|
|
92064
|
+
);
|
|
92065
|
+
}
|
|
92066
|
+
retracement = { pct };
|
|
92067
|
+
} else {
|
|
92068
|
+
const px = input.retracement.px.trim();
|
|
92069
|
+
const pxValidation = validateHyperliquidPerpPriceWire(px, sizeDecimals);
|
|
92070
|
+
if (!(Number(px) > 0) || !pxValidation.valid) {
|
|
92071
|
+
throw new Error("Hyperliquid trailing stop distance must be a positive price on the market grid.");
|
|
92072
|
+
}
|
|
92073
|
+
retracement = { px };
|
|
92074
|
+
}
|
|
92075
|
+
let activationPx = null;
|
|
92076
|
+
if (input.activationPrice != null) {
|
|
92077
|
+
assertPositiveNumber(input.activationPrice, "Hyperliquid trailing stop activation price");
|
|
92078
|
+
activationPx = formatHyperliquidTriggerPriceWire(input.activationPrice, sizeDecimals);
|
|
92079
|
+
}
|
|
92080
|
+
return signHyperliquidPayload(input, {
|
|
92081
|
+
type: "trailingStop",
|
|
92082
|
+
asset: assetIndex,
|
|
92083
|
+
isBuy: side === "buy",
|
|
92084
|
+
sz: sizeWire,
|
|
92085
|
+
reduceOnly: true,
|
|
92086
|
+
retracement,
|
|
92087
|
+
activationPx
|
|
92088
|
+
});
|
|
92089
|
+
};
|
|
92032
92090
|
extractHyperliquidExchangeError = (payload) => {
|
|
92033
92091
|
if (!payload || typeof payload !== "object") {
|
|
92034
92092
|
return null;
|
|
@@ -92107,6 +92165,19 @@ var init_hyperliquid_client = __esm({
|
|
|
92107
92165
|
}
|
|
92108
92166
|
return { ...root, response: { ...response, data: { ...data4, statuses: resolved } } };
|
|
92109
92167
|
};
|
|
92168
|
+
readHyperliquidTrailingStopAcknowledgement = (payload) => {
|
|
92169
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload)) return { outcome: "unknown" };
|
|
92170
|
+
const record5 = payload;
|
|
92171
|
+
const body = record5.response;
|
|
92172
|
+
if (record5.status === "err" && typeof body === "string" && body.trim()) return { outcome: "refused", reason: body };
|
|
92173
|
+
if (record5.status !== "ok" || !body || typeof body !== "object") return { outcome: "unknown" };
|
|
92174
|
+
const answer = body;
|
|
92175
|
+
const orderId = answer.data?.oid;
|
|
92176
|
+
if (answer.type === "trailingStop" && typeof orderId === "number" && Number.isSafeInteger(orderId) && orderId > 0) {
|
|
92177
|
+
return { outcome: "placed", order_id: orderId };
|
|
92178
|
+
}
|
|
92179
|
+
return { outcome: "unknown" };
|
|
92180
|
+
};
|
|
92110
92181
|
resolveHyperliquidModifyAcknowledgement = async (payload, action, lookup, pacing = acknowledgementLookupPacing()) => {
|
|
92111
92182
|
if (action.type !== "modify" || payload == null || typeof payload !== "object" || Array.isArray(payload)) {
|
|
92112
92183
|
return payload;
|
|
@@ -92149,6 +92220,9 @@ var init_hyperliquid_client = __esm({
|
|
|
92149
92220
|
if (action.type === "updateLeverage") {
|
|
92150
92221
|
return exchangeResponse.type === "default";
|
|
92151
92222
|
}
|
|
92223
|
+
if (action.type === "trailingStop") {
|
|
92224
|
+
return readHyperliquidTrailingStopAcknowledgement(payload).outcome === "placed";
|
|
92225
|
+
}
|
|
92152
92226
|
const actionItems = action.type === "order" ? action.orders : action.type === "modify" ? [action.order] : action.type === "cancel" || action.type === "cancelByCloid" ? action.cancels : null;
|
|
92153
92227
|
const expectedCount = Array.isArray(actionItems) ? actionItems.length : 0;
|
|
92154
92228
|
const data4 = exchangeResponse.data && typeof exchangeResponse.data === "object" && !Array.isArray(exchangeResponse.data) ? exchangeResponse.data : null;
|
|
@@ -92564,6 +92638,13 @@ var init_hyperliquid_client = __esm({
|
|
|
92564
92638
|
}
|
|
92565
92639
|
return signedAssetId2;
|
|
92566
92640
|
}
|
|
92641
|
+
if (durableMutation.operationKind === "trailing_stop") {
|
|
92642
|
+
const signedAssetId2 = Number(action.asset);
|
|
92643
|
+
if (action.type !== "trailingStop" || !Number.isInteger(signedAssetId2) || signedAssetId2 < 0 || action.reduceOnly !== true) {
|
|
92644
|
+
throw new Error("Durable trailing stop authority requires exactly one signed reduce-only trailingStop.");
|
|
92645
|
+
}
|
|
92646
|
+
return signedAssetId2;
|
|
92647
|
+
}
|
|
92567
92648
|
const signedAssetId = Number(action.asset);
|
|
92568
92649
|
if (action.type !== "updateLeverage" || !Number.isInteger(signedAssetId) || signedAssetId < 0 || !Number.isInteger(Number(action.leverage)) || Number(action.leverage) <= 0 || typeof action.isCross !== "boolean") {
|
|
92569
92650
|
throw new Error(
|
|
@@ -92585,6 +92666,7 @@ var init_hyperliquid_client = __esm({
|
|
|
92585
92666
|
};
|
|
92586
92667
|
exchangeActionPriority = (action, requested) => {
|
|
92587
92668
|
if (action.type === "cancel" || action.type === "cancelByCloid") return requested === "trading_reduce" ? "trading_reduce" : "trading_execute";
|
|
92669
|
+
if (action.type === "trailingStop") return action.reduceOnly === true ? "trading_reduce" : "trading_execute";
|
|
92588
92670
|
const orders = action.type === "order" && Array.isArray(action.orders) ? action.orders : action.type === "modify" ? [action.order] : [];
|
|
92589
92671
|
return orders.length > 0 && orders.every((order) => order && typeof order === "object" && order.r === true) ? "trading_reduce" : "trading_execute";
|
|
92590
92672
|
};
|
|
@@ -92653,7 +92735,8 @@ var init_hyperliquid_client = __esm({
|
|
|
92653
92735
|
clientOrderIds: durableMutation.clientOrderIds ?? null,
|
|
92654
92736
|
...durableMutation.protection ? { protection: durableMutation.protection } : {},
|
|
92655
92737
|
...durableMutation.protectiveActionId ? { protectiveActionId: durableMutation.protectiveActionId } : {},
|
|
92656
|
-
|
|
92738
|
+
// A trailing stop has no CLOID: the server binds the lot it signs.
|
|
92739
|
+
...durableMutation.protection || durableMutation.protectiveActionId || durableMutation.operationKind === "trailing_stop" ? { signedPayload: serializedPayload } : {},
|
|
92657
92740
|
attemptEvidence: diagnostics.first_order ? {
|
|
92658
92741
|
requestedExchangeSize: diagnostics.first_order.size,
|
|
92659
92742
|
submittedLimitPrice: diagnostics.first_order.price,
|
|
@@ -92904,7 +92987,7 @@ var init_hyperliquid_client = __esm({
|
|
|
92904
92987
|
})
|
|
92905
92988
|
);
|
|
92906
92989
|
}
|
|
92907
|
-
const exchangeError = extractHyperliquidExchangeError(payload);
|
|
92990
|
+
const exchangeError = durableMutation?.operationKind === "trailing_stop" && readHyperliquidTrailingStopAcknowledgement(payload).outcome !== "refused" ? null : extractHyperliquidExchangeError(payload);
|
|
92908
92991
|
if (exchangeError) {
|
|
92909
92992
|
emitHyperliquidExchangeRejection(String(exchangeError.message ?? ""));
|
|
92910
92993
|
await settleDurableMutation(
|
|
@@ -92944,7 +93027,8 @@ var init_hyperliquid_client = __esm({
|
|
|
92944
93027
|
"outcome_unknown"
|
|
92945
93028
|
);
|
|
92946
93029
|
}
|
|
92947
|
-
const
|
|
93030
|
+
const trailingAcknowledgement = durableMutation?.operationKind === "trailing_stop" ? readHyperliquidTrailingStopAcknowledgement(payload) : null;
|
|
93031
|
+
const exactExchangeOrderId = durableMutation?.operationKind === "order" ? extractDefinitiveHyperliquidOrderId(payload, input.payload.action) : trailingAcknowledgement?.outcome === "placed" ? String(trailingAcknowledgement.order_id) : null;
|
|
92948
93032
|
const extractedOrderMemberResults = durableMutation?.operationKind === "order" ? extractDefinitiveHyperliquidOrderMemberResults(
|
|
92949
93033
|
payload,
|
|
92950
93034
|
input.payload.action
|
|
@@ -93042,12 +93126,21 @@ var init_exchange_mutation_evidence = __esm({
|
|
|
93042
93126
|
{ type: "activeAssetData", user: wallet, coin },
|
|
93043
93127
|
"hyperliquid.activeAssetData"
|
|
93044
93128
|
) : null;
|
|
93129
|
+
const dex = input.required.open_orders_dex;
|
|
93130
|
+
const openOrders = dex == null ? void 0 : await fetchBrowserHyperliquidInfoPayload(
|
|
93131
|
+
readInput,
|
|
93132
|
+
{ type: "frontendOpenOrders", user: wallet, ...dex ? { dex } : {} },
|
|
93133
|
+
"hyperliquid.frontendOpenOrders"
|
|
93134
|
+
);
|
|
93135
|
+
const historicalOrders = input.required.historical_orders === true ? await fetchBrowserHyperliquidInfoPayload(readInput, { type: "historicalOrders", user: wallet }, "hyperliquid.historicalOrders") : void 0;
|
|
93045
93136
|
return {
|
|
93046
93137
|
evidence: {
|
|
93047
93138
|
wallet_address: wallet,
|
|
93048
93139
|
observed_at: observedAt,
|
|
93049
93140
|
order_statuses: orderStatuses,
|
|
93050
|
-
active_asset_data: activeAssetData
|
|
93141
|
+
active_asset_data: activeAssetData,
|
|
93142
|
+
...openOrders === void 0 ? {} : { open_orders: openOrders },
|
|
93143
|
+
...historicalOrders === void 0 ? {} : { historical_orders: historicalOrders }
|
|
93051
93144
|
},
|
|
93052
93145
|
startedAtMonotonicMs
|
|
93053
93146
|
};
|
|
@@ -96333,7 +96426,7 @@ var init_vault = __esm({
|
|
|
96333
96426
|
});
|
|
96334
96427
|
|
|
96335
96428
|
// lib/runtime/browser-trading.ts
|
|
96336
|
-
var resolveProfileId, requirePositiveNumber, assertFreshPreparedContext, throwIfAborted, UUID_PATTERN, createExchangeMutationIdentity, requireClientExchangeExpiresAfterSeconds, loadSigningKey, priorityOf, resolveSigningKey, requireWalletAddress2, resolveEstimatedPrice, executeClientLeverageUpdate, executeClientMarketOrder, resolveClientProtectiveSigningKey, executeClientPreparedProtectiveAction, executeClientLimitOrder, executeClientTriggerOrder, executeClientOrderBatch, executeClientModifyOrder, executeClientCancelOrder, executeClientClosePosition;
|
|
96429
|
+
var resolveProfileId, requirePositiveNumber, assertFreshPreparedContext, throwIfAborted, UUID_PATTERN, createExchangeMutationIdentity, requireClientExchangeExpiresAfterSeconds, loadSigningKey, priorityOf, resolveSigningKey, requireWalletAddress2, resolveEstimatedPrice, executeClientLeverageUpdate, executeClientMarketOrder, resolveClientProtectiveSigningKey, executeClientPreparedProtectiveAction, executeClientLimitOrder, executeClientTriggerOrder, executeClientOrderBatch, executeClientModifyOrder, executeClientCancelOrder, executeClientTrailingStop, executeClientClosePosition;
|
|
96337
96430
|
var init_browser_trading = __esm({
|
|
96338
96431
|
"lib/runtime/browser-trading.ts"() {
|
|
96339
96432
|
"use strict";
|
|
@@ -96794,6 +96887,41 @@ var init_browser_trading = __esm({
|
|
|
96794
96887
|
}
|
|
96795
96888
|
});
|
|
96796
96889
|
};
|
|
96890
|
+
executeClientTrailingStop = async (input) => {
|
|
96891
|
+
input = { ...input, publicRequestPriority: "trading_reduce" };
|
|
96892
|
+
throwIfAborted(input.signal);
|
|
96893
|
+
const signingKey = await resolveSigningKey(input);
|
|
96894
|
+
throwIfAborted(input.signal);
|
|
96895
|
+
const mutation = createExchangeMutationIdentity(false, input);
|
|
96896
|
+
const payload = await buildHyperliquidTrailingStopPayload({
|
|
96897
|
+
config: input.config ?? null,
|
|
96898
|
+
publicRequestPriority: priorityOf(input),
|
|
96899
|
+
signingKey,
|
|
96900
|
+
symbol: input.symbol,
|
|
96901
|
+
side: input.side,
|
|
96902
|
+
size: input.size,
|
|
96903
|
+
retracement: input.retracement,
|
|
96904
|
+
expiresAfterSeconds: requireClientExchangeExpiresAfterSeconds(input.config)
|
|
96905
|
+
});
|
|
96906
|
+
return submitHyperliquidExchangePayload({
|
|
96907
|
+
config: input.config ?? null,
|
|
96908
|
+
publicRequestPriority: priorityOf(input),
|
|
96909
|
+
payload,
|
|
96910
|
+
signal: input.signal,
|
|
96911
|
+
mutationScope: resolveProfileId(input.profileId),
|
|
96912
|
+
durableMutation: {
|
|
96913
|
+
profileId: input.profileId,
|
|
96914
|
+
requiredRuntimeSessionId: input.runtimeSessionId,
|
|
96915
|
+
runtimeLeaseToken: input.runtimeLeaseToken,
|
|
96916
|
+
runtimeDeviceId: input.runtimeDeviceId,
|
|
96917
|
+
schedulerInstanceId: input.schedulerInstanceId,
|
|
96918
|
+
mutationId: mutation.mutationId,
|
|
96919
|
+
operationKind: "trailing_stop",
|
|
96920
|
+
symbol: input.symbol,
|
|
96921
|
+
onExchangeOrderDispatched: input.onExchangeOrderDispatched
|
|
96922
|
+
}
|
|
96923
|
+
});
|
|
96924
|
+
};
|
|
96797
96925
|
executeClientClosePosition = async (input) => {
|
|
96798
96926
|
input = { ...input, publicRequestPriority: "trading_reduce" };
|
|
96799
96927
|
throwIfAborted(input.signal);
|
|
@@ -99819,7 +99947,7 @@ var init_protective_entry_cover = __esm({
|
|
|
99819
99947
|
});
|
|
99820
99948
|
|
|
99821
99949
|
// lib/runtime/native-position-protection.ts
|
|
99822
|
-
var nativeProtectionSettings, memberSetting, KINDS, formatTriggerOrNull, nativePositionTriggerPrice, nativeEntryRequest, HALF_UP_DIGIT, roundDecimalHalfUp, nativeTrailingRetracement, nativeAfterFillActions, classifyNativeOrderEnd, isOpenInDirection, nativePlacementGate, nativeStrayOrderDecision, FIRED_TRIGGER_CONDITION, closingSide, DECIMAL_PATTERN, decimalUnits2, fractionDigits, nativePlaceCover, nativeRearmDecision, nativeLostStopCrossed, explainAbsentProtectiveOrder, readServerNativeProtectionState;
|
|
99950
|
+
var nativeProtectionSettings, memberSetting, KINDS, formatTriggerOrNull, nativePositionTriggerPrice, nativeEntryRequest, HALF_UP_DIGIT, roundDecimalHalfUp, nativeTrailingRetracement, nativeAfterFillActions, classifyNativeOrderEnd, isOpenInDirection, nativePlacementGate, nativeStrayOrderDecision, FIRED_TRIGGER_CONDITION, TRAILING_ORDER_TYPE, closingSide, DECIMAL_PATTERN, decimalUnits2, fractionDigits, nativePlaceCover, positiveOrderId, nativeRearmDecision, nativeLostStopCrossed, readListedProtectiveRow, explainAbsentProtectiveOrder, readServerNativeProtectionState;
|
|
99823
99951
|
var init_native_position_protection = __esm({
|
|
99824
99952
|
"lib/runtime/native-position-protection.ts"() {
|
|
99825
99953
|
"use strict";
|
|
@@ -99966,6 +100094,7 @@ var init_native_position_protection = __esm({
|
|
|
99966
100094
|
return input.positionStateMs > input.placedMs ? "cancel" : "need_reads";
|
|
99967
100095
|
};
|
|
99968
100096
|
FIRED_TRIGGER_CONDITION = "Triggered";
|
|
100097
|
+
TRAILING_ORDER_TYPE = "trailing stop market";
|
|
99969
100098
|
closingSide = (isLong) => isLong ? "a" : "b";
|
|
99970
100099
|
DECIMAL_PATTERN = /^-?\d+(\.\d+)?$/;
|
|
99971
100100
|
decimalUnits2 = (value, scale) => {
|
|
@@ -99979,6 +100108,7 @@ var init_native_position_protection = __esm({
|
|
|
99979
100108
|
nativePlaceCover = (input) => {
|
|
99980
100109
|
const market = normalizeHyperliquidMarketSymbol(input.symbol);
|
|
99981
100110
|
const own = new Set(input.ownClientOrderIds.map((value) => String(value).trim().toLowerCase()).filter(Boolean));
|
|
100111
|
+
const ownTrailing = new Set((input.ownTrailingOrderIds ?? []).map(positiveOrderId).filter((id2) => id2 != null));
|
|
99982
100112
|
const positionText = String(input.positionSize).replace(/^-/, "");
|
|
99983
100113
|
const sized = [];
|
|
99984
100114
|
for (const row of input.rows) {
|
|
@@ -99986,7 +100116,9 @@ var init_native_position_protection = __esm({
|
|
|
99986
100116
|
if (row.reduceOnly !== true || row.isTrigger !== true) continue;
|
|
99987
100117
|
if (String(row.triggerCondition ?? "").trim() === FIRED_TRIGGER_CONDITION) continue;
|
|
99988
100118
|
if (String(row.side ?? "").trim().toLowerCase() !== closingSide(input.isLong)) continue;
|
|
99989
|
-
const orderType = String(row.orderType ?? "").toLowerCase();
|
|
100119
|
+
const orderType = String(row.orderType ?? "").trim().toLowerCase();
|
|
100120
|
+
const rowOrderId = positiveOrderId(row.oid);
|
|
100121
|
+
if (orderType === TRAILING_ORDER_TYPE && rowOrderId != null && ownTrailing.has(rowOrderId)) continue;
|
|
99990
100122
|
const rowKind = orderType.includes("take profit") ? "tp" : orderType.includes("stop") ? "sl" : null;
|
|
99991
100123
|
if (rowKind !== input.kind) continue;
|
|
99992
100124
|
if (own.has(String(row.cloid ?? "").trim().toLowerCase())) {
|
|
@@ -100004,6 +100136,13 @@ var init_native_position_protection = __esm({
|
|
|
100004
100136
|
const covered = sized.reduce((total, size) => total + decimalUnits2(size, scale), BigInt(0));
|
|
100005
100137
|
return position > BigInt(0) && covered >= position ? { decision: "covered" } : { decision: "place" };
|
|
100006
100138
|
};
|
|
100139
|
+
positiveOrderId = (value) => {
|
|
100140
|
+
if (typeof value === "boolean") return null;
|
|
100141
|
+
const text = String(value ?? "").trim();
|
|
100142
|
+
if (!/^\d+$/.test(text)) return null;
|
|
100143
|
+
const orderId = Number(text);
|
|
100144
|
+
return orderId > 0 && Number.isSafeInteger(orderId) ? orderId : null;
|
|
100145
|
+
};
|
|
100007
100146
|
nativeRearmDecision = (input) => {
|
|
100008
100147
|
if (!isOpenInDirection(input.position, input.isLong)) return "retire";
|
|
100009
100148
|
if (input.endedMs == null || !(input.positionStateMs > input.endedMs)) return "need_reads";
|
|
@@ -100013,6 +100152,7 @@ var init_native_position_protection = __esm({
|
|
|
100013
100152
|
if (input.mark == null || !Number.isFinite(input.mark)) return false;
|
|
100014
100153
|
return input.isLong ? input.mark <= input.trigger : input.mark >= input.trigger;
|
|
100015
100154
|
};
|
|
100155
|
+
readListedProtectiveRow = (row) => String(row.triggerCondition ?? "").trim() === FIRED_TRIGGER_CONDITION ? "not_resting_status_read_decides" : "resting";
|
|
100016
100156
|
explainAbsentProtectiveOrder = (input) => {
|
|
100017
100157
|
if (isOpenInDirection(input.position, input.isLong)) return "status_read";
|
|
100018
100158
|
return input.positionStateMs > input.lastSeenRestingMs ? "ended_with_position" : "need_reads";
|
|
@@ -100031,13 +100171,14 @@ var init_native_position_protection = __esm({
|
|
|
100031
100171
|
});
|
|
100032
100172
|
|
|
100033
100173
|
// lib/runtime/native-protection-device.ts
|
|
100034
|
-
var NATIVE_PROTECTION_RECORD_VERSION, nativeProtectionStorage, resolveStorage, setNativeProtectionStorage, recordKey, isMember, readNativeProtectionRecord, writeNativeProtectionRecord, NativeOrderNotSentError, withDispatchBoundary, attempt, notSentRestores, errorText, actionOf, isOpenInDirection2, coverRows, restingOrderIdAt, definitivelyRefused, planNativeOpen, recordEntryChildren, observeMembers, UNKNOWN_ORDER_RESPONSE, resolveUnknownOrderIds, settleNativeProtectionAfterFill, reconcileNativeProtection;
|
|
100174
|
+
var NATIVE_PROTECTION_RECORD_VERSION, nativeProtectionStorage, resolveStorage, setNativeProtectionStorage, recordKey, isMember, isRetracement, isLot, readNativeProtectionRecord, versioned, writeNativeProtectionRecord, NativeOrderNotSentError, withDispatchBoundary, attempt, notSentRestores, errorText, actionOf, isOpenInDirection2, coverRows, restingOrderIdAt, definitivelyRefused, TRAILING_LOT_FIRED, ownLotOrderIds, lotRetracement, lotReport, sendTrailingLot, planNativeFillLot, dropNativePendingLot, planNativePendingLot, planNativeOpen, recordEntryChildren, observeMembers, UNKNOWN_ORDER_RESPONSE, resolveUnknownOrderIds, settleNativeProtectionAfterFill, reconcileNativeProtection;
|
|
100035
100175
|
var init_native_protection_device = __esm({
|
|
100036
100176
|
"lib/runtime/native-protection-device.ts"() {
|
|
100037
100177
|
"use strict";
|
|
100038
100178
|
init_define_VTX_EXO_POLICY();
|
|
100039
100179
|
init_define_VTX_GROK_POLICY();
|
|
100040
100180
|
init_define_VTX_PI_MODEL_POLICY();
|
|
100181
|
+
init_constants();
|
|
100041
100182
|
init_order_identity();
|
|
100042
100183
|
init_native_position_protection();
|
|
100043
100184
|
NATIVE_PROTECTION_RECORD_VERSION = 1;
|
|
@@ -100060,23 +100201,38 @@ var init_native_protection_device = __esm({
|
|
|
100060
100201
|
const member = value;
|
|
100061
100202
|
return (member.kind === "sl" || member.kind === "tp") && typeof member.clientOrderId === "string" && (member.orderId === null || typeof member.orderId === "number" && Number.isSafeInteger(member.orderId)) && typeof member.trigger === "string" && (member.placedAtMs === null || typeof member.placedAtMs === "number") && typeof member.sentAtMs === "number" && typeof member.replacedOnce === "boolean" && (member.pendingModify === void 0 || typeof member.pendingModify === "object" && member.pendingModify !== null && typeof member.pendingModify.clientOrderId === "string" && typeof member.pendingModify.trigger === "string" && typeof member.pendingModify.sentAtMs === "number");
|
|
100062
100203
|
};
|
|
100204
|
+
isRetracement = (value) => {
|
|
100205
|
+
if (!value || typeof value !== "object") return false;
|
|
100206
|
+
const keys = Object.keys(value);
|
|
100207
|
+
const record5 = value;
|
|
100208
|
+
return keys.length === 1 && (typeof record5.pct === "string" || typeof record5.px === "string");
|
|
100209
|
+
};
|
|
100210
|
+
isLot = (value) => {
|
|
100211
|
+
if (!value || typeof value !== "object") return false;
|
|
100212
|
+
const lot = value;
|
|
100213
|
+
return (lot.mutationId === null || typeof lot.mutationId === "string") && typeof lot.fillKey === "string" && typeof lot.fillEventMs === "number" && typeof lot.size === "string" && isRetracement(lot.retracement) && (lot.orderId === null || typeof lot.orderId === "number" && Number.isSafeInteger(lot.orderId)) && (lot.placedAtMs === null || typeof lot.placedAtMs === "number") && typeof lot.sentAtMs === "number" && typeof lot.replacedOnce === "boolean" && (lot.userCancelledOrderId === void 0 || typeof lot.userCancelledOrderId === "number") && (lot.fillEventFromDevice === void 0 || typeof lot.fillEventFromDevice === "boolean") && (lot.retiredReason === void 0 || typeof lot.retiredReason === "string");
|
|
100214
|
+
};
|
|
100063
100215
|
readNativeProtectionRecord = (profileId, symbol2) => {
|
|
100064
100216
|
const storage3 = resolveStorage();
|
|
100065
100217
|
if (!storage3) return null;
|
|
100066
100218
|
const raw = storage3.getItem(recordKey(profileId, symbol2));
|
|
100067
100219
|
if (raw == null) return null;
|
|
100068
100220
|
const parsed = JSON.parse(raw);
|
|
100069
|
-
if (parsed?.version !== NATIVE_PROTECTION_RECORD_VERSION || parsed.profileId !== profileId || parsed.symbol !== symbol2 || typeof parsed.walletAddress !== "string" || typeof parsed.isLong !== "boolean" || parsed.phase !== "entry_pending" && parsed.phase !== "active" || typeof parsed.entryMutationId !== "string" || typeof parsed.entryClientOrderId !== "string" || typeof parsed.createdAtMs !== "number" || !Array.isArray(parsed.members) || !parsed.members.every(isMember)) {
|
|
100221
|
+
if (parsed?.version !== NATIVE_PROTECTION_RECORD_VERSION && parsed?.version !== NATIVE_PROTECTION_RECORD_WITH_LOTS_VERSION || parsed.profileId !== profileId || parsed.symbol !== symbol2 || typeof parsed.walletAddress !== "string" || typeof parsed.isLong !== "boolean" || parsed.phase !== "entry_pending" && parsed.phase !== "active" || typeof parsed.entryMutationId !== "string" || typeof parsed.entryClientOrderId !== "string" || typeof parsed.createdAtMs !== "number" || !Array.isArray(parsed.members) || !parsed.members.every(isMember) || parsed.lots !== void 0 && (parsed.version !== NATIVE_PROTECTION_RECORD_WITH_LOTS_VERSION || !Array.isArray(parsed.lots) || !parsed.lots.every(isLot))) {
|
|
100070
100222
|
throw new Error("Stored native protection record is invalid.");
|
|
100071
100223
|
}
|
|
100072
100224
|
return parsed;
|
|
100073
100225
|
};
|
|
100226
|
+
versioned = (record5) => {
|
|
100227
|
+
const { lots, ...rest } = record5;
|
|
100228
|
+
return lots && lots.length > 0 ? { ...rest, version: NATIVE_PROTECTION_RECORD_WITH_LOTS_VERSION, lots } : { ...rest, version: NATIVE_PROTECTION_RECORD_VERSION };
|
|
100229
|
+
};
|
|
100074
100230
|
writeNativeProtectionRecord = (profileId, symbol2, record5) => {
|
|
100075
100231
|
const storage3 = resolveStorage();
|
|
100076
100232
|
if (!storage3) return false;
|
|
100077
100233
|
try {
|
|
100078
100234
|
if (record5 == null) storage3.removeItem(recordKey(profileId, symbol2));
|
|
100079
|
-
else storage3.setItem(recordKey(profileId, symbol2), JSON.stringify(record5));
|
|
100235
|
+
else storage3.setItem(recordKey(profileId, symbol2), JSON.stringify(versioned(record5)));
|
|
100080
100236
|
return true;
|
|
100081
100237
|
} catch {
|
|
100082
100238
|
return false;
|
|
@@ -100146,8 +100302,113 @@ var init_native_protection_device = __esm({
|
|
|
100146
100302
|
const statuses = root?.response?.data?.statuses;
|
|
100147
100303
|
return Array.isArray(statuses) && statuses.length > 0 && statuses.every((status) => Boolean(status && typeof status === "object" && "error" in status));
|
|
100148
100304
|
};
|
|
100305
|
+
TRAILING_LOT_FIRED = "protective_trailing_lot_fired";
|
|
100306
|
+
ownLotOrderIds = (record5) => (record5.lots ?? []).flatMap((lot) => lot.orderId == null ? [] : [lot.orderId]);
|
|
100307
|
+
lotRetracement = (settings, size, sizeDecimals) => {
|
|
100308
|
+
const stopLoss = settings.stopLoss;
|
|
100309
|
+
if (!stopLoss?.trailing || !(Number(size) > 0)) return null;
|
|
100310
|
+
return nativeTrailingRetracement({ mode: stopLoss.mode, value: stopLoss.value, lotSize: Number(size), sizeDecimals });
|
|
100311
|
+
};
|
|
100312
|
+
lotReport = (symbol2, lot, status, metadata) => ({
|
|
100313
|
+
order_id: lot.orderId == null ? null : String(lot.orderId),
|
|
100314
|
+
symbol: symbol2,
|
|
100315
|
+
action: "AUTO_SL",
|
|
100316
|
+
status,
|
|
100317
|
+
execution_metadata: { trailing_lot: true, protected_size: lot.size, retracement: lot.retracement, ...metadata }
|
|
100318
|
+
});
|
|
100319
|
+
sendTrailingLot = async (args) => {
|
|
100320
|
+
const { io } = args;
|
|
100321
|
+
if (!io.placeTrailingLot) return { lot: args.lot, report: null };
|
|
100322
|
+
const mutationId = io.newMutationId();
|
|
100323
|
+
const journaled = {
|
|
100324
|
+
...args.lot,
|
|
100325
|
+
mutationId,
|
|
100326
|
+
orderId: null,
|
|
100327
|
+
placedAtMs: null,
|
|
100328
|
+
sentAtMs: io.nowMs()
|
|
100329
|
+
};
|
|
100330
|
+
if (!args.journal(journaled)) {
|
|
100331
|
+
return {
|
|
100332
|
+
lot: args.lot,
|
|
100333
|
+
report: lotReport(args.symbol, args.lot, "failed", { reason_code: "protective_lifecycle_persistence_failed" })
|
|
100334
|
+
};
|
|
100335
|
+
}
|
|
100336
|
+
const place = io.placeTrailingLot;
|
|
100337
|
+
const outcome = await notSentRestores(
|
|
100338
|
+
() => attempt(io, () => place({ mutationId, size: journaled.size, retracement: journaled.retracement })),
|
|
100339
|
+
() => args.journal(args.lot)
|
|
100340
|
+
);
|
|
100341
|
+
if (!outcome.ok && outcome.error instanceof NativeOrderNotSentError) {
|
|
100342
|
+
args.journal(args.lot);
|
|
100343
|
+
return {
|
|
100344
|
+
lot: args.lot,
|
|
100345
|
+
report: lotReport(args.symbol, args.lot, "failed", { reason_code: "protective_place_not_sent", error: errorText(outcome.error) })
|
|
100346
|
+
};
|
|
100347
|
+
}
|
|
100348
|
+
if (!outcome.ok && outcome.refused) {
|
|
100349
|
+
const retired = { ...journaled, retiredReason: "protective_place_rejected" };
|
|
100350
|
+
return {
|
|
100351
|
+
lot: retired,
|
|
100352
|
+
report: lotReport(args.symbol, retired, "failed", { reason_code: "protective_place_rejected", error: errorText(outcome.error) })
|
|
100353
|
+
};
|
|
100354
|
+
}
|
|
100355
|
+
const orderId = outcome.ok ? outcome.response?.orderId ?? null : null;
|
|
100356
|
+
const placed = { ...journaled, orderId };
|
|
100357
|
+
return {
|
|
100358
|
+
lot: placed,
|
|
100359
|
+
report: lotReport(args.symbol, placed, "executed", {
|
|
100360
|
+
...args.reasonCode ? { reason_code: args.reasonCode } : {},
|
|
100361
|
+
...args.lot.orderId != null ? { replaced_order_id: String(args.lot.orderId) } : {}
|
|
100362
|
+
})
|
|
100363
|
+
};
|
|
100364
|
+
};
|
|
100365
|
+
planNativeFillLot = (record5, input) => {
|
|
100366
|
+
const fillKey = input.fillKey.trim();
|
|
100367
|
+
const retracement = lotRetracement(input.settings, input.fillSize, input.sizeDecimals);
|
|
100368
|
+
if (!fillKey || retracement == null) return record5;
|
|
100369
|
+
const lots = [...record5.lots ?? []];
|
|
100370
|
+
if (lots.some((lot) => lot.fillKey === fillKey)) return record5;
|
|
100371
|
+
const planned = {
|
|
100372
|
+
mutationId: null,
|
|
100373
|
+
fillKey,
|
|
100374
|
+
fillEventMs: input.nowMs,
|
|
100375
|
+
size: input.fillSize,
|
|
100376
|
+
retracement,
|
|
100377
|
+
orderId: null,
|
|
100378
|
+
placedAtMs: null,
|
|
100379
|
+
sentAtMs: input.nowMs,
|
|
100380
|
+
replacedOnce: false,
|
|
100381
|
+
fillEventFromDevice: true
|
|
100382
|
+
};
|
|
100383
|
+
const pendingIndex = input.pendingKey ? lots.findIndex((lot) => lot.fillKey === input.pendingKey && lot.mutationId == null && lot.size === "") : -1;
|
|
100384
|
+
if (pendingIndex >= 0) lots[pendingIndex] = planned;
|
|
100385
|
+
else lots.push(planned);
|
|
100386
|
+
return { ...record5, lots };
|
|
100387
|
+
};
|
|
100388
|
+
dropNativePendingLot = (record5, key) => versioned({
|
|
100389
|
+
...record5,
|
|
100390
|
+
lots: (record5.lots ?? []).filter((lot) => !(lot.fillKey === key && lot.mutationId == null && lot.size === ""))
|
|
100391
|
+
});
|
|
100392
|
+
planNativePendingLot = (record5, input) => {
|
|
100393
|
+
const retracement = lotRetracement(input.settings, String(input.sizeHint), input.sizeDecimals);
|
|
100394
|
+
if (retracement == null || !input.key || (record5.lots ?? []).some((lot) => lot.fillKey === input.key)) return record5;
|
|
100395
|
+
return versioned({
|
|
100396
|
+
...record5,
|
|
100397
|
+
lots: [...record5.lots ?? [], {
|
|
100398
|
+
mutationId: null,
|
|
100399
|
+
fillKey: input.key,
|
|
100400
|
+
fillEventMs: input.nowMs,
|
|
100401
|
+
fillEventFromDevice: true,
|
|
100402
|
+
size: "",
|
|
100403
|
+
retracement,
|
|
100404
|
+
orderId: null,
|
|
100405
|
+
placedAtMs: null,
|
|
100406
|
+
sentAtMs: input.nowMs,
|
|
100407
|
+
replacedOnce: false
|
|
100408
|
+
}]
|
|
100409
|
+
});
|
|
100410
|
+
};
|
|
100149
100411
|
planNativeOpen = (input) => {
|
|
100150
|
-
if (input.settings.stopLoss?.trailing) return null;
|
|
100151
100412
|
const request = nativeEntryRequest({
|
|
100152
100413
|
settings: input.settings,
|
|
100153
100414
|
isLong: input.isLong,
|
|
@@ -100173,7 +100434,9 @@ var init_native_protection_device = __esm({
|
|
|
100173
100434
|
triggerPrice: Number(member.trigger),
|
|
100174
100435
|
clientOrderId: member.clientOrderId
|
|
100175
100436
|
})),
|
|
100176
|
-
|
|
100437
|
+
// Trailing mode: the open's lot is journaled with the entry, sized once
|
|
100438
|
+
// its fill is known (or from the position it opened), so no settle can lose it.
|
|
100439
|
+
record: planNativePendingLot({
|
|
100177
100440
|
version: NATIVE_PROTECTION_RECORD_VERSION,
|
|
100178
100441
|
profileId: input.profileId,
|
|
100179
100442
|
symbol: input.symbol,
|
|
@@ -100184,7 +100447,13 @@ var init_native_protection_device = __esm({
|
|
|
100184
100447
|
entryClientOrderId: input.entryClientOrderId,
|
|
100185
100448
|
createdAtMs: input.nowMs,
|
|
100186
100449
|
members
|
|
100187
|
-
}
|
|
100450
|
+
}, {
|
|
100451
|
+
settings: input.settings,
|
|
100452
|
+
sizeDecimals: input.sizeDecimals,
|
|
100453
|
+
key: input.entryClientOrderId,
|
|
100454
|
+
sizeHint: input.entrySize,
|
|
100455
|
+
nowMs: input.nowMs
|
|
100456
|
+
})
|
|
100188
100457
|
};
|
|
100189
100458
|
};
|
|
100190
100459
|
recordEntryChildren = (record5, entryResponse) => ({
|
|
@@ -100386,7 +100655,8 @@ var init_native_protection_device = __esm({
|
|
|
100386
100655
|
symbol: symbol2,
|
|
100387
100656
|
positionSize: String(position.size),
|
|
100388
100657
|
ownClientOrderIds: [],
|
|
100389
|
-
rows: coverRows(page)
|
|
100658
|
+
rows: coverRows(page),
|
|
100659
|
+
ownTrailingOrderIds: ownLotOrderIds(record5)
|
|
100390
100660
|
});
|
|
100391
100661
|
if (cover.decision !== "place") {
|
|
100392
100662
|
continue;
|
|
@@ -100424,7 +100694,7 @@ var init_native_protection_device = __esm({
|
|
|
100424
100694
|
() => io.persist({ ...record5, phase: "active", members: before })
|
|
100425
100695
|
);
|
|
100426
100696
|
if (!outcome.ok && outcome.refused) {
|
|
100427
|
-
members.splice(0, members.length, ...before);
|
|
100697
|
+
if (outcome.error instanceof NativeOrderNotSentError) members.splice(0, members.length, ...before);
|
|
100428
100698
|
reports.push({
|
|
100429
100699
|
order_id: null,
|
|
100430
100700
|
symbol: symbol2,
|
|
@@ -100433,6 +100703,8 @@ var init_native_protection_device = __esm({
|
|
|
100433
100703
|
execution_metadata: {
|
|
100434
100704
|
reason_code: outcome.error instanceof NativeOrderNotSentError ? "protective_place_not_sent" : "protective_place_rejected",
|
|
100435
100705
|
trigger_price: step.trigger,
|
|
100706
|
+
// The fill this stop protects: its warning is shown once per stop.
|
|
100707
|
+
entry_order_id: input.entryOrderId,
|
|
100436
100708
|
error: errorText(outcome.error)
|
|
100437
100709
|
}
|
|
100438
100710
|
});
|
|
@@ -100456,6 +100728,52 @@ var init_native_protection_device = __esm({
|
|
|
100456
100728
|
}
|
|
100457
100729
|
});
|
|
100458
100730
|
}
|
|
100731
|
+
const lots = [...record5.lots ?? []];
|
|
100732
|
+
const fillKey = String(input.entryOrderId ?? "").trim();
|
|
100733
|
+
let lotIndex = fillKey ? lots.findIndex((lot) => lot.fillKey === fillKey) : -1;
|
|
100734
|
+
const fillLotSize = Number(input.fillSize) > 0 ? input.fillSize : record5.phase === "entry_pending" ? String(Math.abs(position.size)) : "0";
|
|
100735
|
+
const fillRetracement = lotRetracement(input.settings, fillLotSize, input.sizeDecimals);
|
|
100736
|
+
if (lotIndex < 0 && fillKey && fillRetracement) {
|
|
100737
|
+
lots.push({
|
|
100738
|
+
mutationId: null,
|
|
100739
|
+
fillKey,
|
|
100740
|
+
fillEventMs: eventMs,
|
|
100741
|
+
size: fillLotSize,
|
|
100742
|
+
retracement: fillRetracement,
|
|
100743
|
+
orderId: null,
|
|
100744
|
+
placedAtMs: null,
|
|
100745
|
+
sentAtMs: io.nowMs(),
|
|
100746
|
+
replacedOnce: false
|
|
100747
|
+
});
|
|
100748
|
+
lotIndex = lots.length - 1;
|
|
100749
|
+
}
|
|
100750
|
+
const journaledLot = lotIndex >= 0 ? lots[lotIndex] : null;
|
|
100751
|
+
if (journaledLot && journaledLot.mutationId == null && !journaledLot.retiredReason && journaledLot.userCancelledOrderId == null && io.placeTrailingLot) {
|
|
100752
|
+
const size = journaledLot.size || fillLotSize;
|
|
100753
|
+
const retracement = lotRetracement(input.settings, size, input.sizeDecimals);
|
|
100754
|
+
if (retracement) {
|
|
100755
|
+
const { fillEventFromDevice: _deviceTime, ...withoutDeviceTime } = journaledLot;
|
|
100756
|
+
const planned = eventMs > 0 ? { ...withoutDeviceTime, size, retracement, fillEventMs: eventMs } : { ...journaledLot, size, retracement };
|
|
100757
|
+
if (gate === "place") {
|
|
100758
|
+
const index = lotIndex;
|
|
100759
|
+
const sent = await sendTrailingLot({
|
|
100760
|
+
io,
|
|
100761
|
+
symbol: symbol2,
|
|
100762
|
+
lot: planned,
|
|
100763
|
+
journal: (lot) => io.persist({
|
|
100764
|
+
...record5,
|
|
100765
|
+
phase: "active",
|
|
100766
|
+
members,
|
|
100767
|
+
lots: [...lots.slice(0, index), lot, ...lots.slice(index + 1)]
|
|
100768
|
+
})
|
|
100769
|
+
});
|
|
100770
|
+
lots[index] = sent.lot;
|
|
100771
|
+
if (sent.report) reports.push(sent.report);
|
|
100772
|
+
} else {
|
|
100773
|
+
lots[lotIndex] = planned;
|
|
100774
|
+
}
|
|
100775
|
+
}
|
|
100776
|
+
}
|
|
100459
100777
|
for (const entry of observations) {
|
|
100460
100778
|
if (!entry.row || reports.some((report) => report.order_id === String(entry.row?.oid))) continue;
|
|
100461
100779
|
reports.push({
|
|
@@ -100470,7 +100788,7 @@ var init_native_protection_device = __esm({
|
|
|
100470
100788
|
}
|
|
100471
100789
|
});
|
|
100472
100790
|
}
|
|
100473
|
-
record5 = { ...record5, phase: "active", members };
|
|
100791
|
+
record5 = { ...record5, phase: "active", members, ...lots.length > 0 ? { lots } : {} };
|
|
100474
100792
|
return { record: record5, reports };
|
|
100475
100793
|
};
|
|
100476
100794
|
reconcileNativeProtection = async (input) => {
|
|
@@ -100516,7 +100834,8 @@ var init_native_protection_device = __esm({
|
|
|
100516
100834
|
symbol: symbol2,
|
|
100517
100835
|
positionSize: String(position.size),
|
|
100518
100836
|
ownClientOrderIds: [],
|
|
100519
|
-
rows: coverRows(page)
|
|
100837
|
+
rows: coverRows(page),
|
|
100838
|
+
ownTrailingOrderIds: ownLotOrderIds(record5)
|
|
100520
100839
|
});
|
|
100521
100840
|
if (cover.decision !== "place") return args.member;
|
|
100522
100841
|
const clientOrderId = clientOrderIdForMutation(io.newMutationId());
|
|
@@ -100606,7 +100925,8 @@ var init_native_protection_device = __esm({
|
|
|
100606
100925
|
trigger_price: args.trigger,
|
|
100607
100926
|
position_tpsl: true,
|
|
100608
100927
|
protected_size: Math.abs(position.size),
|
|
100609
|
-
|
|
100928
|
+
// A refused replacement or re-arm is not placed again: left to a person.
|
|
100929
|
+
...refused ? { error: errorText(outcome.error), manual_intervention: true } : {}
|
|
100610
100930
|
}
|
|
100611
100931
|
});
|
|
100612
100932
|
return placed;
|
|
@@ -100792,10 +101112,192 @@ var init_native_protection_device = __esm({
|
|
|
100792
101112
|
members.push(replacement);
|
|
100793
101113
|
if (replacement !== member && !replacement.retiredReason) anyResting = true;
|
|
100794
101114
|
}
|
|
101115
|
+
const lots = [];
|
|
101116
|
+
const storedLots = record5.lots ?? [];
|
|
101117
|
+
const isUnsized = (lot) => lot.mutationId == null && lot.size === "";
|
|
101118
|
+
const priorLots = [...storedLots.filter((lot) => !isUnsized(lot)), ...storedLots.filter(isUnsized)];
|
|
101119
|
+
const journalLot = (index, lot) => io.persist({
|
|
101120
|
+
...record5,
|
|
101121
|
+
members,
|
|
101122
|
+
lots: [...lots, lot, ...priorLots.slice(index + 1)]
|
|
101123
|
+
});
|
|
101124
|
+
for (const [index, prior] of priorLots.entries()) {
|
|
101125
|
+
let lot = prior;
|
|
101126
|
+
const restingRow = lot.orderId == null ? null : page.find((order) => order.oid === lot.orderId) ?? null;
|
|
101127
|
+
if ((lot.retiredReason || lot.userCancelledOrderId != null) && !(restingRow && readListedProtectiveRow({ triggerCondition: restingRow.trigger_condition }) === "resting")) {
|
|
101128
|
+
lots.push(lot);
|
|
101129
|
+
continue;
|
|
101130
|
+
}
|
|
101131
|
+
if (lot.mutationId == null) {
|
|
101132
|
+
if (lot.fillEventFromDevice) {
|
|
101133
|
+
const entryStatus = await io.readOrderStatus(lot.fillKey);
|
|
101134
|
+
if (entryStatus.responseValid && entryStatus.orderMatches && entryStatus.statusTimestampMs != null) {
|
|
101135
|
+
const { fillEventFromDevice: _deviceTime, ...exchangeTimed } = lot;
|
|
101136
|
+
lot = { ...exchangeTimed, fillEventMs: entryStatus.statusTimestampMs };
|
|
101137
|
+
} else if (entryStatus.responseStatus === UNKNOWN_ORDER_RESPONSE && io.nowMs() > io.neverLandsAfterMs(lot.sentAtMs)) {
|
|
101138
|
+
continue;
|
|
101139
|
+
} else {
|
|
101140
|
+
anyResting = true;
|
|
101141
|
+
lots.push(lot);
|
|
101142
|
+
continue;
|
|
101143
|
+
}
|
|
101144
|
+
}
|
|
101145
|
+
const gate = nativePlacementGate({
|
|
101146
|
+
eventMs: lot.fillEventMs,
|
|
101147
|
+
position: position.size,
|
|
101148
|
+
positionStateMs: stateMs,
|
|
101149
|
+
isLong: record5.isLong
|
|
101150
|
+
});
|
|
101151
|
+
if (gate === "not_required") continue;
|
|
101152
|
+
if (gate !== "place") {
|
|
101153
|
+
anyResting = true;
|
|
101154
|
+
lots.push(lot);
|
|
101155
|
+
continue;
|
|
101156
|
+
}
|
|
101157
|
+
if (!lot.size) {
|
|
101158
|
+
const others = [...lots, ...priorLots.slice(index + 1)];
|
|
101159
|
+
const covered = others.reduce((total, other) => other.size && other.retiredReason !== TRAILING_LOT_FIRED ? total + Number(other.size) : total, 0);
|
|
101160
|
+
const uncovered = Number((Math.abs(position.size) - covered).toFixed(input.sizeDecimals));
|
|
101161
|
+
if (!(uncovered > 0)) continue;
|
|
101162
|
+
lot = { ...lot, size: String(uncovered) };
|
|
101163
|
+
}
|
|
101164
|
+
const retracement2 = lotRetracement(input.settings, lot.size, input.sizeDecimals);
|
|
101165
|
+
if (retracement2 == null) {
|
|
101166
|
+
lots.push(lot);
|
|
101167
|
+
continue;
|
|
101168
|
+
}
|
|
101169
|
+
const sent2 = await sendTrailingLot({ io, symbol: symbol2, lot: { ...lot, retracement: retracement2 }, journal: (next) => journalLot(index, next) });
|
|
101170
|
+
lots.push(sent2.lot);
|
|
101171
|
+
if (sent2.report) reports.push(sent2.report);
|
|
101172
|
+
if (!sent2.lot.retiredReason) anyResting = true;
|
|
101173
|
+
continue;
|
|
101174
|
+
}
|
|
101175
|
+
if (lot.orderId == null) {
|
|
101176
|
+
let answer = null;
|
|
101177
|
+
try {
|
|
101178
|
+
answer = io.readLotMutation ? await io.readLotMutation(lot.mutationId) : null;
|
|
101179
|
+
} catch (error48) {
|
|
101180
|
+
if (io.endsPass?.(error48)) throw error48;
|
|
101181
|
+
}
|
|
101182
|
+
const orderId = Number(answer?.exchange_order_id);
|
|
101183
|
+
const named = answer != null && (answer.status === "settled" && answer.outcome_code === "success" || answer.status === "reconciled" && answer.outcome_code === "exchange_effect_observed") && Number.isSafeInteger(orderId) && orderId > 0;
|
|
101184
|
+
if (named) {
|
|
101185
|
+
lot = { ...lot, orderId };
|
|
101186
|
+
} else if (answer?.status === "settled" && answer.outcome_code === "rejected") {
|
|
101187
|
+
lots.push({ ...lot, retiredReason: "protective_place_rejected" });
|
|
101188
|
+
continue;
|
|
101189
|
+
} else if (answer?.status === "reconciled" && answer.outcome_code === "exchange_expired_unconfirmed" || answer?.status === "absent" && io.nowMs() > io.neverLandsAfterMs(lot.sentAtMs)) {
|
|
101190
|
+
if (!positionOpen) continue;
|
|
101191
|
+
const sent2 = await sendTrailingLot({ io, symbol: symbol2, lot: { ...lot, mutationId: null }, journal: (next) => journalLot(index, next) });
|
|
101192
|
+
lots.push(sent2.lot);
|
|
101193
|
+
if (sent2.report) reports.push(sent2.report);
|
|
101194
|
+
if (!sent2.lot.retiredReason) anyResting = true;
|
|
101195
|
+
continue;
|
|
101196
|
+
} else {
|
|
101197
|
+
anyResting = true;
|
|
101198
|
+
lots.push(lot);
|
|
101199
|
+
continue;
|
|
101200
|
+
}
|
|
101201
|
+
}
|
|
101202
|
+
const lotOrderId = lot.orderId;
|
|
101203
|
+
const row = lot === prior ? restingRow : page.find((order) => order.oid === lotOrderId) ?? null;
|
|
101204
|
+
if (row && readListedProtectiveRow({ triggerCondition: row.trigger_condition }) === "resting") {
|
|
101205
|
+
lot = { ...lot, placedAtMs: row.timestamp || lot.placedAtMs };
|
|
101206
|
+
const stray = nativeStrayOrderDecision({
|
|
101207
|
+
placedMs: lot.placedAtMs ?? Number.POSITIVE_INFINITY,
|
|
101208
|
+
position: position.size,
|
|
101209
|
+
positionStateMs: stateMs,
|
|
101210
|
+
isLong: record5.isLong
|
|
101211
|
+
});
|
|
101212
|
+
if (stray === "cancel") {
|
|
101213
|
+
const outcome = await attempt(io, () => io.cancelOrder(lotOrderId));
|
|
101214
|
+
reports.push(lotReport(symbol2, lot, outcome.ok ? "executed" : "failed", {
|
|
101215
|
+
reason_code: outcome.ok ? "protective_native_stray_cancelled" : "protective_native_stray_cancel_failed",
|
|
101216
|
+
live_position_size: position.size,
|
|
101217
|
+
...outcome.ok ? {} : { error: errorText(outcome.error) }
|
|
101218
|
+
}));
|
|
101219
|
+
if (!outcome.ok) {
|
|
101220
|
+
anyResting = true;
|
|
101221
|
+
lots.push(lot);
|
|
101222
|
+
}
|
|
101223
|
+
continue;
|
|
101224
|
+
}
|
|
101225
|
+
anyResting = true;
|
|
101226
|
+
lots.push(lot);
|
|
101227
|
+
continue;
|
|
101228
|
+
}
|
|
101229
|
+
if (lot.retiredReason || lot.userCancelledOrderId != null) {
|
|
101230
|
+
lots.push(lot);
|
|
101231
|
+
continue;
|
|
101232
|
+
}
|
|
101233
|
+
if (!positionOpen) {
|
|
101234
|
+
const explained = lot.placedAtMs != null ? explainAbsentProtectiveOrder({
|
|
101235
|
+
lastSeenRestingMs: lot.placedAtMs,
|
|
101236
|
+
position: position.size,
|
|
101237
|
+
positionStateMs: stateMs,
|
|
101238
|
+
isLong: record5.isLong
|
|
101239
|
+
}) : "status_read";
|
|
101240
|
+
if (explained === "ended_with_position") continue;
|
|
101241
|
+
const evidence2 = await io.readOrderStatus(lotOrderId);
|
|
101242
|
+
const end2 = classifyNativeOrderEnd({
|
|
101243
|
+
orderStatus: evidence2.responseValid ? String(evidence2.orderStatus ?? "") : "",
|
|
101244
|
+
replacedByOwnModify: false,
|
|
101245
|
+
userCancelledThroughVtx: false
|
|
101246
|
+
});
|
|
101247
|
+
if (end2 === "resting" || end2 === "pending" || end2 === "unknown") {
|
|
101248
|
+
anyResting = true;
|
|
101249
|
+
lots.push(lot);
|
|
101250
|
+
}
|
|
101251
|
+
continue;
|
|
101252
|
+
}
|
|
101253
|
+
const evidence = await io.readOrderStatus(lotOrderId);
|
|
101254
|
+
const end = classifyNativeOrderEnd({
|
|
101255
|
+
orderStatus: evidence.responseValid ? String(evidence.orderStatus ?? "") : "",
|
|
101256
|
+
replacedByOwnModify: false,
|
|
101257
|
+
userCancelledThroughVtx: false
|
|
101258
|
+
});
|
|
101259
|
+
if (end === "resting" || end === "pending" || end === "unknown" || end === "superseded" || end === "user_cancelled") {
|
|
101260
|
+
anyResting = true;
|
|
101261
|
+
lots.push(lot);
|
|
101262
|
+
continue;
|
|
101263
|
+
}
|
|
101264
|
+
if (end === "fired" || end === "ended_with_position") {
|
|
101265
|
+
lots.push({ ...lot, retiredReason: TRAILING_LOT_FIRED });
|
|
101266
|
+
continue;
|
|
101267
|
+
}
|
|
101268
|
+
if (end === "lost_permanent" || lot.replacedOnce) {
|
|
101269
|
+
const reason = end === "lost_permanent" ? "protective_stop_execution_rejected" : "protective_replacement_lost";
|
|
101270
|
+
lots.push({ ...lot, retiredReason: reason });
|
|
101271
|
+
reports.push(lotReport(symbol2, lot, "failed", { reason_code: reason, order_status: evidence.orderStatus, manual_intervention: true }));
|
|
101272
|
+
continue;
|
|
101273
|
+
}
|
|
101274
|
+
const lostGate = nativePlacementGate({
|
|
101275
|
+
eventMs: evidence.statusTimestampMs ?? Number.POSITIVE_INFINITY,
|
|
101276
|
+
position: position.size,
|
|
101277
|
+
positionStateMs: stateMs,
|
|
101278
|
+
isLong: record5.isLong
|
|
101279
|
+
});
|
|
101280
|
+
const retracement = lotRetracement(input.settings, lot.size, input.sizeDecimals);
|
|
101281
|
+
if (lostGate !== "place" || retracement == null) {
|
|
101282
|
+
lots.push(lot);
|
|
101283
|
+
continue;
|
|
101284
|
+
}
|
|
101285
|
+
const sent = await sendTrailingLot({
|
|
101286
|
+
io,
|
|
101287
|
+
symbol: symbol2,
|
|
101288
|
+
lot: { ...lot, retracement, replacedOnce: true },
|
|
101289
|
+
journal: (next) => journalLot(index, next),
|
|
101290
|
+
reasonCode: "protective_stop_replaced"
|
|
101291
|
+
});
|
|
101292
|
+
lots.push(sent.lot);
|
|
101293
|
+
if (sent.report) reports.push(sent.report);
|
|
101294
|
+
if (!sent.lot.retiredReason) anyResting = true;
|
|
101295
|
+
}
|
|
100795
101296
|
if (!positionOpen && !anyResting) {
|
|
100796
101297
|
return { record: null, reports };
|
|
100797
101298
|
}
|
|
100798
|
-
|
|
101299
|
+
const { lots: _priorLots, ...withoutLots } = record5;
|
|
101300
|
+
record5 = { ...withoutLots, members, ...lots.length > 0 ? { lots } : {} };
|
|
100799
101301
|
return { record: record5, reports };
|
|
100800
101302
|
};
|
|
100801
101303
|
}
|
|
@@ -104500,6 +105002,24 @@ var init_runtime_execution = __esm({
|
|
|
104500
105002
|
publicRequestPriority: "trading_reduce",
|
|
104501
105003
|
orderId
|
|
104502
105004
|
})),
|
|
105005
|
+
placeTrailingLot: async ({ mutationId, size, retracement }) => {
|
|
105006
|
+
const response = await fenced((onExchangeOrderDispatched) => executeClientTrailingStop({
|
|
105007
|
+
...common,
|
|
105008
|
+
onExchangeOrderDispatched,
|
|
105009
|
+
mutationId,
|
|
105010
|
+
side: exitSide,
|
|
105011
|
+
size: Number(size),
|
|
105012
|
+
retracement
|
|
105013
|
+
}));
|
|
105014
|
+
const answer = readHyperliquidTrailingStopAcknowledgement(response);
|
|
105015
|
+
return { orderId: answer.outcome === "placed" ? answer.order_id : null };
|
|
105016
|
+
},
|
|
105017
|
+
readLotMutation: async (mutationId) => {
|
|
105018
|
+
const mutation = await getClientRuntimeExchangeMutation(request.profileId, mutationId, request.signal);
|
|
105019
|
+
if (mutation == null) return { status: "absent" };
|
|
105020
|
+
if (mutation.operation_kind !== "trailing_stop") throw new Error("The ledger names another action for this trailing lot.");
|
|
105021
|
+
return { status: mutation.status, outcome_code: mutation.outcome_code, exchange_order_id: mutation.exchange_order_id };
|
|
105022
|
+
},
|
|
104503
105023
|
isDefinitiveRefusal: (error48) => error48 instanceof HyperliquidExchangeRejectionError || error48 instanceof NativeOrderNotSentError,
|
|
104504
105024
|
neverLandsAfterMs: (sentAtMs) => clientOrderNeverLandsAfterMs(request.config, { kind: "absent", ageStartMs: sentAtMs }),
|
|
104505
105025
|
newMutationId: () => createRuntimeId().toLowerCase(),
|
|
@@ -107877,6 +108397,7 @@ var init_runtime_execution = __esm({
|
|
|
107877
108397
|
if (entryMutationId) entryClientOrderId = clientOrderIdForMutation(entryMutationId);
|
|
107878
108398
|
let nativeOpen = null;
|
|
107879
108399
|
let nativeAddRecord = null;
|
|
108400
|
+
let nativePendingLotKey = null;
|
|
107880
108401
|
const nativeProfileId = String(input.profileId).trim();
|
|
107881
108402
|
const nativeBlocked = (reasonCode, message) => ({
|
|
107882
108403
|
// A flip whose close already filled reports that close as executed.
|
|
@@ -107915,7 +108436,22 @@ var init_runtime_execution = __esm({
|
|
|
107915
108436
|
}
|
|
107916
108437
|
if (classified.intent === "add") {
|
|
107917
108438
|
if (existingNative.kind === "record" && existingNative.record.isLong === (classified.side === "buy")) {
|
|
107918
|
-
|
|
108439
|
+
entryMutationId ??= createRuntimeId().toLowerCase();
|
|
108440
|
+
entryClientOrderId = clientOrderIdForMutation(entryMutationId);
|
|
108441
|
+
nativePendingLotKey = entryClientOrderId;
|
|
108442
|
+
nativeAddRecord = planNativePendingLot(existingNative.record, {
|
|
108443
|
+
settings: nativeSettingsOf(input.executionContext),
|
|
108444
|
+
sizeDecimals: input.executionContext.sizeDecimals,
|
|
108445
|
+
key: entryClientOrderId,
|
|
108446
|
+
sizeHint: sizeAsset,
|
|
108447
|
+
nowMs: Date.now()
|
|
108448
|
+
});
|
|
108449
|
+
if (nativeAddRecord !== existingNative.record && !writeNativeProtectionRecord(nativeProfileId, input.executionContext.symbol, nativeAddRecord)) {
|
|
108450
|
+
return nativeBlocked(
|
|
108451
|
+
"protective_lifecycle_persistence_failed",
|
|
108452
|
+
"Blocked new exposure because its position protection could not be stored."
|
|
108453
|
+
);
|
|
108454
|
+
}
|
|
107919
108455
|
}
|
|
107920
108456
|
} else if (existingNative.kind === "record") {
|
|
107921
108457
|
return nativeBlocked(
|
|
@@ -108090,6 +108626,16 @@ var init_runtime_execution = __esm({
|
|
|
108090
108626
|
if (nativeOpen != null && (!entryDispatchBoundaryPassed || isDefinitiveEntryRejection(entryDispatchError, entryMutationId))) {
|
|
108091
108627
|
writeNativeProtectionRecord(nativeProfileId, input.executionContext.symbol, null);
|
|
108092
108628
|
}
|
|
108629
|
+
if (nativePendingLotKey != null && nativeOpen == null && (!entryDispatchBoundaryPassed || isDefinitiveEntryRejection(entryDispatchError, entryMutationId))) {
|
|
108630
|
+
const stored = readNativeRecord(nativeProfileId, input.executionContext.symbol);
|
|
108631
|
+
if (stored.kind === "record") {
|
|
108632
|
+
writeNativeProtectionRecord(
|
|
108633
|
+
nativeProfileId,
|
|
108634
|
+
input.executionContext.symbol,
|
|
108635
|
+
dropNativePendingLot(stored.record, nativePendingLotKey)
|
|
108636
|
+
);
|
|
108637
|
+
}
|
|
108638
|
+
}
|
|
108093
108639
|
const handoffVeto = isClientRuntimeWindowHandoffBeforePlanDispatch(entryDispatchError);
|
|
108094
108640
|
const handoffBeforeDispatch = handoffVeto || !entryDispatchBoundaryPassed && input.shouldCancelBeforeExchangeOrderDispatch?.() === true;
|
|
108095
108641
|
const hasCommittedReports = executionReports.some((report) => report.status === "executed" && String(report.order_id || "").trim().length > 0);
|
|
@@ -108212,7 +108758,17 @@ var init_runtime_execution = __esm({
|
|
|
108212
108758
|
const symbol2 = input.executionContext.symbol;
|
|
108213
108759
|
let record5 = nativeOpen != null ? recordEntryChildren(nativeOpen.record, marketOrderResponse) : nativeAddRecord;
|
|
108214
108760
|
let keepNativeJournal = false;
|
|
108215
|
-
if (
|
|
108761
|
+
if (confirmedMarketFill?.orderId) {
|
|
108762
|
+
record5 = planNativeFillLot(record5, {
|
|
108763
|
+
settings: nativeSettingsOf(input.executionContext),
|
|
108764
|
+
sizeDecimals: input.executionContext.sizeDecimals,
|
|
108765
|
+
fillKey: String(confirmedMarketFill.orderId),
|
|
108766
|
+
fillSize: String(confirmedMarketFill.filledSize),
|
|
108767
|
+
nowMs: Date.now(),
|
|
108768
|
+
pendingKey: nativeOpen != null ? record5.entryClientOrderId : nativePendingLotKey
|
|
108769
|
+
});
|
|
108770
|
+
}
|
|
108771
|
+
if ((nativeOpen != null || nativePendingLotKey != null || record5 !== nativeAddRecord) && !writeNativeProtectionRecord(nativeProfileId, symbol2, record5)) {
|
|
108216
108772
|
executionReports.push(nativeStorageReport(symbol2, "protective_lifecycle_persistence_failed"));
|
|
108217
108773
|
}
|
|
108218
108774
|
if (confirmedMarketFill == null) {
|
|
@@ -119174,7 +119730,7 @@ __export(local_analysis_exports, {
|
|
|
119174
119730
|
runLocalRuntimeCycle: () => runLocalRuntimeCycle,
|
|
119175
119731
|
summarizeReviewFailureExplanation: () => summarizeReviewFailureExplanation
|
|
119176
119732
|
});
|
|
119177
|
-
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;
|
|
119733
|
+
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, BEHAVIOR_MEMORY_UNAVAILABLE_ERROR, BehaviorMemoryUnavailableError, clampNumber, resolveExternalInferenceRuntimeTimeoutSeconds, toPositiveFinite3, compactSnippet, hashRuntimeDebugText, EFFECTIVE_INPUT_MANIFEST_SCHEMA_VERSION, PROMPT_ASSEMBLY_DEFINITION_VERSION, RUNTIME_SOURCE_DEFINITION_VERSION, DECISION_INPUT_DEFINITION_VERSION, CONTEXT_ENVELOPE_DEFINITION_VERSION, CLIENT_RUNTIME_SOURCE_VERSION, CLIENT_MAIN_PROMPT_RENDERER, SERVER_MAIN_PROMPT_RENDERER, CLIENT_REVIEW_PROMPT_RENDERER, SERVER_REVIEW_PROMPT_RENDERER, resolveEffectivePromptRuntimeProvenance, canonicalManifestValue, canonicalManifestJson, sha256ManifestHex, effectiveInputComponent, buildEffectiveInputManifest, MANIFEST_COMPONENT_NAME, derivePromptVisibleSections, decodeDecisionTracePayload, extractDecisionSymbolTrace, formatDecisionSymbolTrace, formatActionableDecisionSymbols, decisionRecordsBySymbol, normalizePromptSymbols, JSON_MODEL_OUTPUT_FENCE_PATTERN, STRICT_MODEL_OUTPUT_KEYS, currentModelOutputValidationErrors, currentModelOutputMatchesContract, projectCurrentModelDecisionContent, modelOutputValidationError, SERVER_UNREADABLE_REPLY_HOLD_REASONING, buildMissingDecisionHold, buildDecisionPlansFromResponse, buildReviewCandidatePlansFromResponse, forceUnavailableSymbolsToHold, extractTemplatePlaceholders, requireReviewPrimaryUserPromptTemplate, containsCompetingBehaviorStateMarkup, containsCompetingMainBehaviorStateMarkup, requireStrategyReviewTemplates, preflightStrategyReviewPromptContract, extractRuntimeReasoningSelection, isAbortError, isRuntimeTimeoutAbortReason, REVIEW_FAILURE_SENSITIVE_DB_TOKENS, REVIEW_FAILURE_SCHEMA_DISCLOSURE_TOKENS, REVIEW_FAILURE_SQL_STATEMENT_PATTERN, REVIEW_FAILURE_TRACEBACK_PATTERN, isSensitiveReviewFailureDetail, summarizeReviewFailureExplanation, buildReviewFailureHoldReason, createAbortError2, settleRuntimeCyclePromise, unwrapRuntimeCycleSettledResult, normalizeDecisionLabel, normalizeRuntimeSymbol, PromptContractFetchError, isLivePromptContextUnavailableError, buildFailClosedHoldResult, buildPromptConstructionFailureResult, buildLivePromptContextUnavailableFailureResult, pickFirstString, normalizeRuntimeStringList, requirePositiveRuntimeLimit, resolveRuntimeTradingScope, normalizeRuntimeProviderAlias, resolveCatalogModelEntry, createClientRuntimeProviderSetupError, createProviderSetupRejectionError, evaluateModelEligibility, extractReviewRuntimeReasoningSelection, isUsableRuntimeSettingsFallback, resolveRuntimeSettings, formatRuntimeDurationMs, normalizeRuntimeTimingNote, appendRuntimeTimingEvent, reportPromptParityTelemetry, resolveLocalRuntimeSecretRequirements, resolveLocalRuntimeSecretProvider, toEpochSeconds, AI_INDICATOR_KEYS_NEWER_THAN_SOME_SERVERS, sortTradingTimeframes, normalizePromptIdentityTimestamp, resolveCompletedCandleBoundary, normalizeAiIndicatorFlags, getPromptLookback, computeSma, computeEma, computeRsi, computeAtr, computeMacd, computeBollingerBands, getIndicatorValue, buildPromptCandlesComponent, buildPromptCandleTimeframeComponent, resolvePromptRelativeVolumeContext, promptRelativeVolumeBaseline, CANDLE_CLOSE_TICKER_TIMEFRAME, candleCloseTicker, buildPromptCandlesPayload, formatUtcTimestampWithWeekday, formatUtcNowWithWeekday, formatPromptPrice, capacityUnitSize, computePromptUnitsUsedForPosition, buildPromptAccountStatusValue, buildPromptPositionsValue, sanitizePromptSymbol, fillTimeMs, fillSize, normalizeFillSide, normalizeFillOrderId, normalizeFillRiskOrderIdentity, fillStartPosition, fillSortValue, sortFillsAscending, sortFillsDescending, inferEntryFromStartPositionChain, inferEntryFromCurrentPositionSize, calculateCurrentPositionState, calculatePositionEntryTimes, countPositionAdds, latestPositionRiskIncreaseTimeMs, latestPositionRiskIncreaseEvidence, compactPromptRiskIncrease, roundPositiveDecimalHalfUp, compactPromptLastTrade, ENTRY_TRADE_FIELDS, PREVIOUS_DECISION_FIELDS, PREVIOUS_CAMPAIGN_FIELDS, hasExactKeys2, isNonnegativeInteger, isFiniteNumber, isExactEnumString, isNonemptyPromptText, isCampaignReasoningText, projectBackendDecisionMemoryItem, requireRenderedStrategyBehaviorState, canonicalFillSideForRiskEvidence, isValidRiskEvidenceFill, isValidCampaignBoundaryFill, normalizeFillHistoryCoverage, resolveFillHistoryCoverageForSymbol, buildPromptBehaviorStateArtifacts, buildPromptBehaviorStateValue, shouldCompareServerPromptParity, buildLocalRuntimePromptArtifacts, createRuntimeId2, asRecord, buildRuntimeConstraintRejectionMessage, hasDeviceProviderSecret, requireNonEmptyStringField, requirePositiveIntegerField, compareContractVersion, parsePromptContractTimestamp, assertPromptContractCompatibility, assertPromptContractTemporalBounds, sleepWithAbort, requireAgentPollRetryAfterMs, materializeClaimedClientRuntimeAgentInstruction, attachClientRuntimeErrorProvenance, isExternalRuntimeProviderResult, invokeClientExternalInference, assertPromptContractBindingTupleEqual, assertPromptContractScopeMatch, fetchBoundPromptContracts, formatTemplateWithNamedVariables, carryReturnedModelCalls, runLocalRuntimeCycle;
|
|
119178
119734
|
var init_local_analysis = __esm({
|
|
119179
119735
|
"lib/runtime/local-analysis.ts"() {
|
|
119180
119736
|
"use strict";
|
|
@@ -119728,6 +120284,13 @@ var init_local_analysis = __esm({
|
|
|
119728
120284
|
this.name = "CriticalBehaviorStateError";
|
|
119729
120285
|
}
|
|
119730
120286
|
};
|
|
120287
|
+
BEHAVIOR_MEMORY_UNAVAILABLE_ERROR = "Behavior memory is unavailable for this trading cycle";
|
|
120288
|
+
BehaviorMemoryUnavailableError = class extends Error {
|
|
120289
|
+
constructor(cause) {
|
|
120290
|
+
super(BEHAVIOR_MEMORY_UNAVAILABLE_ERROR, cause === void 0 ? void 0 : { cause });
|
|
120291
|
+
this.name = "BehaviorMemoryUnavailableError";
|
|
120292
|
+
}
|
|
120293
|
+
};
|
|
119731
120294
|
clampNumber = (value, fallback) => {
|
|
119732
120295
|
const numeric2 = Number(value);
|
|
119733
120296
|
return Number.isFinite(numeric2) ? numeric2 : fallback;
|
|
@@ -122006,7 +122569,7 @@ ${reviewOutputContract}`;
|
|
|
122006
122569
|
projectBackendDecisionMemoryItem(entry.et, "et");
|
|
122007
122570
|
}
|
|
122008
122571
|
} catch (error48) {
|
|
122009
|
-
throw new
|
|
122572
|
+
throw new BehaviorMemoryUnavailableError(error48);
|
|
122010
122573
|
}
|
|
122011
122574
|
};
|
|
122012
122575
|
canonicalFillSideForRiskEvidence = (fill) => {
|
|
@@ -123665,7 +124228,7 @@ ${behaviorJson}
|
|
|
123665
124228
|
};
|
|
123666
124229
|
tradeHistory = browserUserFills?.tradeHistory ?? [];
|
|
123667
124230
|
if (input.mode === "trader" && !serverOwnsBehaviorState && browserUserFills?.evidence?.source !== "live") {
|
|
123668
|
-
throw new
|
|
124231
|
+
throw new BehaviorMemoryUnavailableError();
|
|
123669
124232
|
}
|
|
123670
124233
|
const metadataSymbol = requireNonEmptyStringField(promptMetadata.symbol, "symbol");
|
|
123671
124234
|
const metadataTimeframe = requireNonEmptyStringField(promptMetadata.timeframe, "timeframe");
|
|
@@ -123974,7 +124537,7 @@ ${behaviorJson}
|
|
|
123974
124537
|
let preMemoryBehaviorState = "";
|
|
123975
124538
|
try {
|
|
123976
124539
|
if (input.mode === "trader" && !behaviorMemoryEnabled) {
|
|
123977
|
-
throw new
|
|
124540
|
+
throw new BehaviorMemoryUnavailableError();
|
|
123978
124541
|
}
|
|
123979
124542
|
const browserFillEvidence = browserUserFills?.evidence;
|
|
123980
124543
|
const behaviorFillCoverage = browserFillEvidence?.source === "live" && browserFillEvidence.exactTerminalFillEvidenceComplete === true ? "complete" : "capped";
|
|
@@ -123994,7 +124557,7 @@ ${behaviorJson}
|
|
|
123994
124557
|
fillHistoryCoverage: behaviorFillCoverage
|
|
123995
124558
|
});
|
|
123996
124559
|
} catch (error48) {
|
|
123997
|
-
throw new
|
|
124560
|
+
throw new BehaviorMemoryUnavailableError(error48);
|
|
123998
124561
|
}
|
|
123999
124562
|
preMemoryBehaviorState = behaviorStateArtifacts.preMemoryRendered;
|
|
124000
124563
|
behaviorPolicyState = behaviorStateArtifacts.policyState;
|
|
@@ -124049,7 +124612,7 @@ ${stringifyPromptJson(candlesPayload)}
|
|
|
124049
124612
|
note: detail,
|
|
124050
124613
|
outcome: "error"
|
|
124051
124614
|
});
|
|
124052
|
-
if (input.mode !== "trader" || error48 instanceof CriticalBehaviorStateError) {
|
|
124615
|
+
if (input.mode !== "trader" || error48 instanceof CriticalBehaviorStateError || error48 instanceof BehaviorMemoryUnavailableError) {
|
|
124053
124616
|
throw error48;
|
|
124054
124617
|
}
|
|
124055
124618
|
return attachDecisionSettlementDeadline(buildPromptConstructionFailureResult({
|
|
@@ -124179,7 +124742,7 @@ ${stringifyPromptJson(candlesPayload)}
|
|
|
124179
124742
|
outcome: "error"
|
|
124180
124743
|
});
|
|
124181
124744
|
appendRuntimeTimingEvent("prompt_render_failed", promptRenderStartedAtMs, detail, "error");
|
|
124182
|
-
if (input.mode !== "trader" || error48 instanceof CriticalBehaviorStateError) {
|
|
124745
|
+
if (input.mode !== "trader" || error48 instanceof CriticalBehaviorStateError || error48 instanceof BehaviorMemoryUnavailableError) {
|
|
124183
124746
|
throw error48;
|
|
124184
124747
|
}
|
|
124185
124748
|
return attachDecisionSettlementDeadline(buildPromptConstructionFailureResult({
|
|
@@ -124989,7 +125552,10 @@ ${reviewOutputContract}`;
|
|
|
124989
125552
|
});
|
|
124990
125553
|
} catch (error48) {
|
|
124991
125554
|
const detail = error48 instanceof Error ? error48.message : String(error48);
|
|
124992
|
-
if (error48 instanceof
|
|
125555
|
+
if (error48 instanceof BehaviorMemoryUnavailableError || detail.includes(BEHAVIOR_MEMORY_UNAVAILABLE_ERROR) || detail.includes("Critical behavior context could not be constructed")) {
|
|
125556
|
+
throw new BehaviorMemoryUnavailableError(error48);
|
|
125557
|
+
}
|
|
125558
|
+
if (error48 instanceof CriticalBehaviorStateError || detail.includes(BEHAVIOR_STATE_UNAVAILABLE_ERROR) || detail.includes("Your prompt on the AI page contains something VTX can't use")) {
|
|
124993
125559
|
throw new CriticalBehaviorStateError(error48);
|
|
124994
125560
|
}
|
|
124995
125561
|
if (input.executionMode === "server" && error48?.code === "settings_superseded") {
|