@vtxmacro/cli 2026.10.16 → 2026.10.18
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/exo-harness.ts +2 -0
- package/bin/vtx-mcp.js +3 -1
- package/bin/vtx-service-bootstrap.js +3 -1
- package/bin/vtx-service-launcher.js +2 -0
- package/bin/vtx.js +972 -318
- package/package.json +1 -1
package/bin/vtx.js
CHANGED
|
@@ -113,7 +113,7 @@ var init_routing = __esm({
|
|
|
113
113
|
var agent_cli_release_default;
|
|
114
114
|
var init_agent_cli_release = __esm({
|
|
115
115
|
"agent-cli-release.json"() {
|
|
116
|
-
agent_cli_release_default = { package_name: "@vtxmacro/cli", package_version: "2026.10.
|
|
116
|
+
agent_cli_release_default = { package_name: "@vtxmacro/cli", package_version: "2026.10.18", codex_package_name: "@openai/codex", codex_version: "0.155.0", copilot_sdk_package_name: "@github/copilot-sdk", copilot_sdk_version: "1.0.0-beta.8", copilot_cli_package_name: "@github/copilot", copilot_cli_version: "1.0.80", deepseek_harness_version: "0.1.1-rc.2", deepseek_harness_packages: ["@deepseek-ai/dsh-agent", "@deepseek-ai/dsh-agent-instructions", "@deepseek-ai/dsh-agent-loop", "@deepseek-ai/dsh-agent-spine-demo", "@deepseek-ai/dsh-anonymous-user-id", "@deepseek-ai/dsh-atomic-write", "@deepseek-ai/dsh-attachment", "@deepseek-ai/dsh-brand", "@deepseek-ai/dsh-code-runtime", "@deepseek-ai/dsh-credentials", "@deepseek-ai/dsh-fs", "@deepseek-ai/dsh-goal", "@deepseek-ai/dsh-goal-round-driver", "@deepseek-ai/dsh-home-paths", "@deepseek-ai/dsh-invariants", "@deepseek-ai/dsh-jobs", "@deepseek-ai/dsh-jobs-local", "@deepseek-ai/dsh-launch-environment", "@deepseek-ai/dsh-llm", "@deepseek-ai/dsh-llm-deepseek", "@deepseek-ai/dsh-llm-retry", "@deepseek-ai/dsh-output-retention", "@deepseek-ai/dsh-sandbox", "@deepseek-ai/dsh-sandbox-policy", "@deepseek-ai/dsh-scope", "@deepseek-ai/dsh-session", "@deepseek-ai/dsh-session-checkpoint-policy", "@deepseek-ai/dsh-session-persistence", "@deepseek-ai/dsh-session-persistence-jsonl", "@deepseek-ai/dsh-session-projection", "@deepseek-ai/dsh-session-title", "@deepseek-ai/dsh-settings", "@deepseek-ai/dsh-shell", "@deepseek-ai/dsh-shell-env", "@deepseek-ai/dsh-skill", "@deepseek-ai/dsh-skill-filesystem", "@deepseek-ai/dsh-subprocess", "@deepseek-ai/dsh-system-prompt", "@deepseek-ai/dsh-timeout", "@deepseek-ai/dsh-tool-bash", "@deepseek-ai/dsh-tool-goal", "@deepseek-ai/dsh-tool-jobs", "@deepseek-ai/dsh-tool-skill", "@deepseek-ai/dsh-tools", "@deepseek-ai/dsh-typert-protocol", "@deepseek-ai/dsh-user-approval"], deepseek_cordis_package_name: "@deepseek-ai/cordis", deepseek_cordis_version: "4.0.1", deepseek_support_packages: { "@deepseek-ai/cordis-plugin-timer": "1.1.3" }, platforms: { "linux-x64": { package_name: "@openai/codex-linux-x64", target: "x86_64-unknown-linux-musl", binary_name: "codex", sha256: "660e159a49e823ac8e5986cb238f73158ce4b957d40d9292f8de90862644b501" }, "win32-x64": { package_name: "@openai/codex-win32-x64", target: "x86_64-pc-windows-msvc", binary_name: "codex.exe", sha256: "e4c11374bd9de8ad5c3b7617fd4654bb7839901edb0863f9930666863c7a021b" } }, pi_coding_agent_package_name: "@earendil-works/pi-coding-agent", pi_ai_package_name: "@earendil-works/pi-ai", pi_version: "0.85.1", pi_support_packages: ["@earendil-works/pi-agent-core", "@earendil-works/pi-telemetry", "@earendil-works/pi-tui", "@earendil-works/chord"], grok_version: "1.0.30", grok_platforms: { "linux-x64": { package_name: "@xai-official/grok-linux-x64", binary_name: "grok", sha256: "504dd6546ab991b75d36698242875ce461489cd1f8cd84285873cb55bd5c7d54" }, "win32-x64": { package_name: "@xai-official/grok-win32-x64", binary_name: "grok.exe", sha256: "48736d1a4342a801ea26d0ecde4c516b653f791399065adaa55973f83abd8867" } } };
|
|
117
117
|
}
|
|
118
118
|
});
|
|
119
119
|
|
|
@@ -1014,6 +1014,7 @@ var init_runtime_policy_generated = __esm({
|
|
|
1014
1014
|
update_failure_reason_max_chars: 160,
|
|
1015
1015
|
launcher_poll_interval_ms: 100,
|
|
1016
1016
|
log_tail_default_lines: 100,
|
|
1017
|
+
log_rotate_bytes: 134217728,
|
|
1017
1018
|
worker_output_line_max_chars: 4096,
|
|
1018
1019
|
worker_stdout_tail_max_chars: 65536,
|
|
1019
1020
|
control_lock_wait_attempts: 400,
|
|
@@ -1253,6 +1254,7 @@ var init_runtime_policy_generated = __esm({
|
|
|
1253
1254
|
public_recovery: {
|
|
1254
1255
|
fallback_initial_seconds: 2,
|
|
1255
1256
|
fallback_max_seconds: 60,
|
|
1257
|
+
fallback_jitter_min_factor: 0.5,
|
|
1256
1258
|
permit_lease_seconds: 60,
|
|
1257
1259
|
recovery_initial_concurrency: 1,
|
|
1258
1260
|
recovery_max_concurrency: 8,
|
|
@@ -1455,7 +1457,7 @@ var init_runtime_policy_generated = __esm({
|
|
|
1455
1457
|
});
|
|
1456
1458
|
|
|
1457
1459
|
// lib/constants.ts
|
|
1458
|
-
var MS_PER_SECOND, SECONDS_PER_MINUTE, MINUTES_PER_HOUR, HOURS_PER_DAY, DAYS_PER_WEEK, MS_PER_MINUTE, SECONDS_PER_HOUR, SECONDS_PER_DAY, SECONDS_PER_WEEK, MINUTES_PER_DAY, MINUTES_PER_WEEK, MS_PER_HOUR, MS_PER_DAY, READ_STAMP_TIE_MS, READ_STAMP_STEP_BACK_MS, CLOCK_FIELD_DIGITS, BACKOFF_GROWTH_FACTOR, BYTES_PER_KIB, BYTES_PER_MIB, BITS_PER_BYTE, BYTE_MASK, OWNER_ONLY_FILE_MODE, OWNER_ONLY_DIRECTORY_MODE, GROUP_OTHER_PERMISSION_BITS, DECIMAL_RADIX, HEX_RADIX, BASE36_RADIX, BYTE_HEX_DIGITS, UINT32_HEX_DIGITS, RANDOM_FRACTION_PREFIX_LENGTH, PERCENT_SCALE, MIDPOINT_DIVISOR, SQUARE_EXPONENT, FNV1A_32_OFFSET_BASIS, FNV1A_32_PRIME, JSON_INDENT_SPACES, INT32_MIN, INT32_MAX, SET_TIMEOUT_MAX_DELAY_MS, POSITION_SIZE_EPSILON, CANDLE_TIMEFRAME_SECONDS, HTTP_STATUS, HTTP_STATUS_MIN, HTTP_STATUS_MAX, HTTP_CLIENT_ERROR_MIN, HTTP_SERVER_ERROR_MIN, AI_COST_ESTIMATE_PERIOD_DAYS, SECONDS_PER_AI_COST_ESTIMATE_PERIOD, DATE_FIELD_DIGITS, EXTERNAL_INFERENCE_LIMITS, NODE_ARGV_COMMAND_ARGS_START, EXIT_CODE_TEMPFAIL, SHA256_INITIAL_STATE, SHA256_ROUND_CONSTANTS, SHA256, UINT64_HIGH_WORD_DIVISOR, CANONICAL_BASE64URL, INFERENCE_ENVELOPE_CRYPTO, EXTERNAL_INFERENCE_SCHEMA_BOUNDS, JSON_RPC_ERROR_CODES, INFERENCE_MCP_SCHEMA_PROBE_MAX_DEPTH, INFERENCE_HOST_PROCESS_LOCK_RECORD_SCHEMA_VERSION, INFERENCE_HOST_RECLAIM_GUARD_CREATE_PASSES, LINUX_PROC_STAT_COMM_TERMINATOR_CHARS, INFERENCE_HOST_RANDOM_BYTES, INFERENCE_OAUTH_TOKEN_MAX_LENGTH, INFERENCE_CREDENTIAL_WINDOWS_NOT_FOUND_EXIT_CODE, MACOS_SECURITY_ITEM_NOT_FOUND_EXIT_CODE, INFERENCE_CREDENTIAL_LABEL_ACCOUNT_KEY_CHARS, INFERENCE_HOST_STABLE_OPERATION_ID_HASH_CHARS, INFERENCE_HOST_DRAIN_PRIORITY, INFERENCE_JOB_CLAIM_SCHEMA_VERSION, INFERENCE_HOST_WINDOWS_TASK_IDENTITY_MAX_CHARS, INFERENCE_HOST_OWNER_ONLY_EXECUTABLE_MODE, WINDOWS_TASKKILL_PROCESS_NOT_FOUND_EXIT_CODE, INFERENCE_HOST_CLI_MAX_SERVICE_POSITIONALS, INFERENCE_HOST_CLI_MAX_COMMAND_POSITIONALS, INFERENCE_HOST_DISPLAY_NAME_MAX_CHARS, INFERENCE_HOST_REVOCATION_CHECKPOINT_MAX_CHARS, INFERENCE_HOST_MODEL_ID_MAX_CHARS, CODEX_RECOVERY_RECEIPT_MAX_CHARS, CODEX_HOSTED_ATTEMPT_PATH_SEGMENTS, CODEX_GUARDIAN_PROCESS_TOKEN_BYTES, CODEX_RATE_LIMIT_EXHAUSTED_PERCENT, INFERENCE_HOST_PROXY_TOKEN_BYTES, GROK_TOOL_SERVER_TOKEN_BYTES, GROK_NATIVE_SESSION_GROUP_NAME_MAX_CHARS, GROK_POLICY_TRANSPORT_MAX_BYTES, EXO_POLICY_MAX_TOOL_ROUNDS, EXO_POLICY_MAX_MODELS, EXO_POLICY_MODEL_NAME_MAX_CHARS, EXO_RUNTIME_VERSION_COMMIT_CHARS, PI_QUALIFIED_MODEL_ID_MAX_CHARS, PI_STRUCTURED_OUTPUT_MAX_DEPTH, PI_STRUCTURED_OUTPUT_MAX_PROPERTIES, INFERENCE_HOST_API_KEY_MIN_CHARS, INFERENCE_HOST_API_KEY_MAX_BYTES, INFERENCE_HOST_API_KEY_IDENTITY_HEX_CHARS, DEEPSEEK_HARNESS_NODE_LTS_MAJOR, DEEPSEEK_HARNESS_NODE_LTS_MIN_MINOR, DEEPSEEK_HARNESS_NODE_CURRENT_MAJOR, PROMPT_FIXED_DIGITS, PROMPT_SIGNIFICANT_DIGITS, PROMPT_NUMBER_MAX_DIGITS, PROMPT_PRICE_INTEGER_THRESHOLD, PROMPT_MARGIN_UTILIZATION_DECIMALS, PROMPT_SYMBOL_MAX_CHARS, PROMPT_PARTIAL_UNIT_ROUND_UP_FRACTION, HALF_UP_ROUNDING_OFFSET, PROMPT_ENTRY_PRICE_MATCH_ABS_TOLERANCE, PROMPT_ENTRY_PRICE_MATCH_REL_TOLERANCE, DECISION_OUTPUT_EXAMPLE_TRADABILITY, INDICATOR_RSI_PERIOD, INDICATOR_ATR_PERIOD, INDICATOR_MACD_FAST_PERIOD, INDICATOR_MACD_SLOW_PERIOD, INDICATOR_MACD_SIGNAL_PERIOD, INDICATOR_BOLLINGER_PERIOD, INDICATOR_BOLLINGER_STD_DEV, INDICATOR_OSCILLATOR_MAX, EMA_SMOOTHING_NUMERATOR, PROMPT_EMA_PERIODS, JSON_UNICODE_ESCAPE_PREFIX_LENGTH, JSON_UNICODE_ESCAPE_HEX_DIGITS, JSON_CONTROL_CHARACTER_MAX, RUNTIME_DEBUG_SNIPPET_CHARS, RUNTIME_DEBUG_PROMPT_SNIPPET_CHARS, RUNTIME_DEBUG_TOKEN_PREFIX_CHARS, RUNTIME_DEBUG_USD_DECIMALS, REVIEW_FAILURE_DETAIL_MAX_CHARS, RUNTIME_LATENCY_SECONDS_DECIMALS, AI_SCHEDULE_CLOCK_PARTS, ESTIMATED_CHARS_PER_TOKEN, PROVIDER_ERROR_RAW_TEXT_MAX_CHARS, AI_CALL_COST_DECIMALS, PROVIDER_DIAGNOSTIC_LIMITS, AI_INVOCATION_CONTRACT_VERSION, AI_INVOCATION_TELEMETRY_LIMITS, PROVIDER_USAGE_DETAIL_LIMITS, HYPERLIQUID_EXCHANGE_SPECIFICATION, HYPERLIQUID_TPSL_BATCH_MIN_ORDERS, HYPERLIQUID_USER_FILLS_PROVIDER_PAGE_CAP, HYPERLIQUID_META_AND_ASSET_CTXS_PARTS, HYPERLIQUID_SIDE_PAIR_LENGTH, HYPERLIQUID_SIGNED_SIZE_MATCH_EXTRA_DECIMALS, HYPERLIQUID_OPEN_ORDERS_MAX_NESTING_DEPTH, ACCOUNT_PAYLOAD_MODE_SEARCH_MAX_DEPTH, HYPERLIQUID_ACCOUNT_ROUNDING_DECIMALS, HYPERLIQUID_UNREALIZED_PNL_ZERO_TOLERANCE, HYPERLIQUID_MAX_DEPLOYER_FEE_SCALE, HYPERLIQUID_DEPLOYER_FEE_SCALE_MULTIPLIER, HYPERLIQUID_GROWTH_MODE_FEE_FACTOR, HYPERLIQUID_ALIGNED_QUOTE_NON_DEPLOYER_FEE_FACTOR, HYPERLIQUID_CLOSE_SIZE_RELATIVE_TOLERANCE, HYPERLIQUID_POSITION_SIZE_MATCH_ABS_TOLERANCE, HYPERLIQUID_POSITION_SIZE_MATCH_RELATIVE_TOLERANCE, HYPERLIQUID_LOT_FLOOR_NOISE_DECIMALS, HYPERLIQUID_RECOVERY_BACKOFF_MAX_EXPONENT,
|
|
1460
|
+
var MS_PER_SECOND, SECONDS_PER_MINUTE, MINUTES_PER_HOUR, HOURS_PER_DAY, DAYS_PER_WEEK, MS_PER_MINUTE, SECONDS_PER_HOUR, SECONDS_PER_DAY, SECONDS_PER_WEEK, MINUTES_PER_DAY, MINUTES_PER_WEEK, MS_PER_HOUR, MS_PER_DAY, READ_STAMP_TIE_MS, READ_STAMP_STEP_BACK_MS, CLOCK_FIELD_DIGITS, BACKOFF_GROWTH_FACTOR, BYTES_PER_KIB, BYTES_PER_MIB, BITS_PER_BYTE, BYTE_MASK, OWNER_ONLY_FILE_MODE, OWNER_ONLY_DIRECTORY_MODE, GROUP_OTHER_PERMISSION_BITS, DECIMAL_RADIX, HEX_RADIX, BASE36_RADIX, BYTE_HEX_DIGITS, UINT32_HEX_DIGITS, RANDOM_FRACTION_PREFIX_LENGTH, PERCENT_SCALE, MIDPOINT_DIVISOR, SQUARE_EXPONENT, FNV1A_32_OFFSET_BASIS, FNV1A_32_PRIME, JSON_INDENT_SPACES, INT32_MIN, INT32_MAX, SET_TIMEOUT_MAX_DELAY_MS, POSITION_SIZE_EPSILON, CANDLE_TIMEFRAME_SECONDS, HTTP_STATUS, HTTP_STATUS_MIN, HTTP_STATUS_MAX, HTTP_CLIENT_ERROR_MIN, HTTP_SERVER_ERROR_MIN, AI_COST_ESTIMATE_PERIOD_DAYS, SECONDS_PER_AI_COST_ESTIMATE_PERIOD, DATE_FIELD_DIGITS, EXTERNAL_INFERENCE_LIMITS, NODE_ARGV_COMMAND_ARGS_START, EXIT_CODE_TEMPFAIL, SHA256_INITIAL_STATE, SHA256_ROUND_CONSTANTS, SHA256, UINT64_HIGH_WORD_DIVISOR, CANONICAL_BASE64URL, INFERENCE_ENVELOPE_CRYPTO, EXTERNAL_INFERENCE_SCHEMA_BOUNDS, JSON_RPC_ERROR_CODES, INFERENCE_MCP_SCHEMA_PROBE_MAX_DEPTH, INFERENCE_HOST_PROCESS_LOCK_RECORD_SCHEMA_VERSION, INFERENCE_HOST_RECLAIM_GUARD_CREATE_PASSES, LINUX_PROC_STAT_COMM_TERMINATOR_CHARS, INFERENCE_HOST_RANDOM_BYTES, INFERENCE_OAUTH_TOKEN_MAX_LENGTH, INFERENCE_CREDENTIAL_WINDOWS_NOT_FOUND_EXIT_CODE, MACOS_SECURITY_ITEM_NOT_FOUND_EXIT_CODE, INFERENCE_CREDENTIAL_LABEL_ACCOUNT_KEY_CHARS, INFERENCE_HOST_STABLE_OPERATION_ID_HASH_CHARS, INFERENCE_HOST_DRAIN_PRIORITY, INFERENCE_JOB_CLAIM_SCHEMA_VERSION, INFERENCE_HOST_WINDOWS_TASK_IDENTITY_MAX_CHARS, INFERENCE_HOST_OWNER_ONLY_EXECUTABLE_MODE, WINDOWS_TASKKILL_PROCESS_NOT_FOUND_EXIT_CODE, INFERENCE_HOST_CLI_MAX_SERVICE_POSITIONALS, INFERENCE_HOST_CLI_MAX_COMMAND_POSITIONALS, INFERENCE_HOST_DISPLAY_NAME_MAX_CHARS, INFERENCE_HOST_REVOCATION_CHECKPOINT_MAX_CHARS, INFERENCE_HOST_MODEL_ID_MAX_CHARS, CODEX_RECOVERY_RECEIPT_MAX_CHARS, CODEX_HOSTED_ATTEMPT_PATH_SEGMENTS, CODEX_GUARDIAN_PROCESS_TOKEN_BYTES, CODEX_RATE_LIMIT_EXHAUSTED_PERCENT, INFERENCE_HOST_PROXY_TOKEN_BYTES, GROK_TOOL_SERVER_TOKEN_BYTES, GROK_NATIVE_SESSION_GROUP_NAME_MAX_CHARS, GROK_POLICY_TRANSPORT_MAX_BYTES, EXO_POLICY_MAX_TOOL_ROUNDS, EXO_POLICY_MAX_MODELS, EXO_POLICY_MODEL_NAME_MAX_CHARS, EXO_RUNTIME_VERSION_COMMIT_CHARS, PI_QUALIFIED_MODEL_ID_MAX_CHARS, PI_STRUCTURED_OUTPUT_MAX_DEPTH, PI_STRUCTURED_OUTPUT_MAX_PROPERTIES, INFERENCE_HOST_API_KEY_MIN_CHARS, INFERENCE_HOST_API_KEY_MAX_BYTES, INFERENCE_HOST_API_KEY_IDENTITY_HEX_CHARS, DEEPSEEK_HARNESS_NODE_LTS_MAJOR, DEEPSEEK_HARNESS_NODE_LTS_MIN_MINOR, DEEPSEEK_HARNESS_NODE_CURRENT_MAJOR, PROMPT_FIXED_DIGITS, PROMPT_SIGNIFICANT_DIGITS, PROMPT_NUMBER_MAX_DIGITS, PROMPT_PRICE_INTEGER_THRESHOLD, PROMPT_MARGIN_UTILIZATION_DECIMALS, PROMPT_SYMBOL_MAX_CHARS, PROMPT_PARTIAL_UNIT_ROUND_UP_FRACTION, HALF_UP_ROUNDING_OFFSET, PROMPT_ENTRY_PRICE_MATCH_ABS_TOLERANCE, PROMPT_ENTRY_PRICE_MATCH_REL_TOLERANCE, DECISION_OUTPUT_EXAMPLE_TRADABILITY, INDICATOR_RSI_PERIOD, INDICATOR_ATR_PERIOD, INDICATOR_MACD_FAST_PERIOD, INDICATOR_MACD_SLOW_PERIOD, INDICATOR_MACD_SIGNAL_PERIOD, INDICATOR_BOLLINGER_PERIOD, INDICATOR_BOLLINGER_STD_DEV, INDICATOR_OSCILLATOR_MAX, EMA_SMOOTHING_NUMERATOR, PROMPT_EMA_PERIODS, JSON_UNICODE_ESCAPE_PREFIX_LENGTH, JSON_UNICODE_ESCAPE_HEX_DIGITS, JSON_CONTROL_CHARACTER_MAX, RUNTIME_DEBUG_SNIPPET_CHARS, RUNTIME_DEBUG_PROMPT_SNIPPET_CHARS, RUNTIME_DEBUG_TOKEN_PREFIX_CHARS, RUNTIME_DEBUG_USD_DECIMALS, REVIEW_FAILURE_DETAIL_MAX_CHARS, RUNTIME_LATENCY_SECONDS_DECIMALS, AI_SCHEDULE_CLOCK_PARTS, ESTIMATED_CHARS_PER_TOKEN, PROVIDER_ERROR_RAW_TEXT_MAX_CHARS, AI_CALL_COST_DECIMALS, PROVIDER_DIAGNOSTIC_LIMITS, AI_INVOCATION_CONTRACT_VERSION, AI_INVOCATION_TELEMETRY_LIMITS, PROVIDER_USAGE_DETAIL_LIMITS, HYPERLIQUID_EXCHANGE_SPECIFICATION, HYPERLIQUID_TPSL_BATCH_MIN_ORDERS, HYPERLIQUID_USER_FILLS_PROVIDER_PAGE_CAP, HYPERLIQUID_ROW_WEIGHTED_INFO_REQUESTS, HYPERLIQUID_INFO_ROWS_PER_EXTRA_WEIGHT, HYPERLIQUID_META_AND_ASSET_CTXS_PARTS, HYPERLIQUID_SIDE_PAIR_LENGTH, HYPERLIQUID_SIGNED_SIZE_MATCH_EXTRA_DECIMALS, HYPERLIQUID_OPEN_ORDERS_MAX_NESTING_DEPTH, ACCOUNT_PAYLOAD_MODE_SEARCH_MAX_DEPTH, HYPERLIQUID_ACCOUNT_ROUNDING_DECIMALS, HYPERLIQUID_UNREALIZED_PNL_ZERO_TOLERANCE, HYPERLIQUID_MAX_DEPLOYER_FEE_SCALE, HYPERLIQUID_DEPLOYER_FEE_SCALE_MULTIPLIER, HYPERLIQUID_GROWTH_MODE_FEE_FACTOR, HYPERLIQUID_ALIGNED_QUOTE_NON_DEPLOYER_FEE_FACTOR, HYPERLIQUID_CLOSE_SIZE_RELATIVE_TOLERANCE, HYPERLIQUID_POSITION_SIZE_MATCH_ABS_TOLERANCE, HYPERLIQUID_POSITION_SIZE_MATCH_RELATIVE_TOLERANCE, HYPERLIQUID_LOT_FLOOR_NOISE_DECIMALS, HYPERLIQUID_RECOVERY_BACKOFF_MAX_EXPONENT, HYPERLIQUID_RECOVERY_CONCURRENCY_GROWTH_FACTOR, UUID_BYTES, UUID_HEX_GROUP_ENDS, MSGPACK, CLIENT_RUNTIME_DEFAULT_RETRY_SECONDS, CLIENT_RUNTIME_PROVIDER_ATTEMPT_SUMMARY_MAX_CHARS, CLIENT_RUNTIME_HL_REQUEST_TYPE_MAX_CHARS, CLIENT_RUNTIME_DRAWDOWN_DEBUG_DECIMALS, CLIENT_PROTECTIVE_GROUP_VERSION, CLIENT_PROTECTIVE_TPSL_PAIR_LEGS, CLIENT_PROTECTIVE_FILL_MATCH_ABS_TOLERANCE, CLIENT_PROTECTIVE_FILL_MATCH_REL_TOLERANCE, CLIENT_CLOSE_FILL_EPSILON_ULPS, COPY_TRADING_SIZE_EPSILON, COPY_TRADING_RELATIVE_SIZE_TOLERANCE, COPY_TRADING_NOTIONAL_CAP_TOLERANCE_USD, CLIENT_ACCOUNT_PNL_NONZERO_MIN_USD, RUNTIME_PORTFOLIO_PERIOD_ENTRY_LENGTH, CLIENT_EXCHANGE_RECONCILIATION_MAX_DELAY_MS, RFC1918_172_BLOCK_SECOND_OCTET, AGENT_CLI_TAKEOVER_REQUIRED_EXIT_CODE, EXIT_CODE_INTERRUPTED, EXIT_CODE_SIGNAL_BASE, BYOK_PROVIDER_DISPLAY_ORDER_STEP, TOKENS_PER_MILLION, RENDER_DEBUG_ID_RANDOM_CHARS;
|
|
1459
1461
|
var init_constants = __esm({
|
|
1460
1462
|
"lib/constants.ts"() {
|
|
1461
1463
|
"use strict";
|
|
@@ -1902,6 +1904,16 @@ var init_constants = __esm({
|
|
|
1902
1904
|
};
|
|
1903
1905
|
HYPERLIQUID_TPSL_BATCH_MIN_ORDERS = 2;
|
|
1904
1906
|
HYPERLIQUID_USER_FILLS_PROVIDER_PAGE_CAP = 2e3;
|
|
1907
|
+
HYPERLIQUID_ROW_WEIGHTED_INFO_REQUESTS = [
|
|
1908
|
+
"userFills",
|
|
1909
|
+
"userFillsByTime",
|
|
1910
|
+
"historicalOrders",
|
|
1911
|
+
"twapHistory",
|
|
1912
|
+
"userTwapSliceFills",
|
|
1913
|
+
"userFunding",
|
|
1914
|
+
"userNonFundingLedgerUpdates"
|
|
1915
|
+
];
|
|
1916
|
+
HYPERLIQUID_INFO_ROWS_PER_EXTRA_WEIGHT = 20;
|
|
1905
1917
|
HYPERLIQUID_META_AND_ASSET_CTXS_PARTS = 2;
|
|
1906
1918
|
HYPERLIQUID_SIDE_PAIR_LENGTH = 2;
|
|
1907
1919
|
HYPERLIQUID_SIGNED_SIZE_MATCH_EXTRA_DECIMALS = 4;
|
|
@@ -1918,7 +1930,6 @@ var init_constants = __esm({
|
|
|
1918
1930
|
HYPERLIQUID_POSITION_SIZE_MATCH_RELATIVE_TOLERANCE = 1e-8;
|
|
1919
1931
|
HYPERLIQUID_LOT_FLOOR_NOISE_DECIMALS = 6;
|
|
1920
1932
|
HYPERLIQUID_RECOVERY_BACKOFF_MAX_EXPONENT = 30;
|
|
1921
|
-
HYPERLIQUID_RECOVERY_JITTER_MIN_FACTOR = 0.5;
|
|
1922
1933
|
HYPERLIQUID_RECOVERY_CONCURRENCY_GROWTH_FACTOR = 2;
|
|
1923
1934
|
UUID_BYTES = 16;
|
|
1924
1935
|
UUID_HEX_GROUP_ENDS = [8, 12, 16, 20, 32];
|
|
@@ -4105,8 +4116,8 @@ while(($line=[Console]::In.ReadLine()) -ne $null) {
|
|
|
4105
4116
|
return { state: "busy" };
|
|
4106
4117
|
}
|
|
4107
4118
|
const raw = opened.size > PROCESS_LOCK_MAX_RECORD_BYTES ? "" : await handle.readFile("utf8");
|
|
4108
|
-
const
|
|
4109
|
-
if (!sameProcessLockFile(opened,
|
|
4119
|
+
const stat2 = await handle.stat();
|
|
4120
|
+
if (!sameProcessLockFile(opened, stat2)) return { state: "busy" };
|
|
4110
4121
|
let record5 = null;
|
|
4111
4122
|
try {
|
|
4112
4123
|
const parsed = JSON.parse(raw);
|
|
@@ -4115,22 +4126,22 @@ while(($line=[Console]::In.ReadLine()) -ne $null) {
|
|
|
4115
4126
|
record5 = null;
|
|
4116
4127
|
}
|
|
4117
4128
|
if (!record5 || record5.schema_version !== INFERENCE_HOST_PROCESS_LOCK_RECORD_SCHEMA_VERSION || !Number.isSafeInteger(record5.pid) || Number(record5.pid) < 1 || typeof record5.owner_token !== "string" || !record5.owner_token || typeof record5.process_identity !== "string" || !record5.process_identity || typeof record5.boot_identity !== "string" || !record5.boot_identity) {
|
|
4118
|
-
if (Date.now() -
|
|
4129
|
+
if (Date.now() - stat2.mtimeMs < PROCESS_LOCK_PUBLICATION_GRACE_MS) return { state: "busy" };
|
|
4119
4130
|
stale = true;
|
|
4120
|
-
return { state: "stale", handle, stat };
|
|
4131
|
+
return { state: "stale", handle, stat: stat2 };
|
|
4121
4132
|
}
|
|
4122
4133
|
const ownerPid = Number(record5.pid);
|
|
4123
4134
|
const storedIdentity = record5.process_identity;
|
|
4124
4135
|
const cacheKey = resolve(path);
|
|
4125
4136
|
if (await probes.currentBootIdentity() === record5.boot_identity && probes.isProcessAlive(ownerPid)) {
|
|
4126
4137
|
const cached2 = processLockObservationCache.get(cacheKey);
|
|
4127
|
-
const observedIdentity = cached2 && cached2.dev ===
|
|
4138
|
+
const observedIdentity = cached2 && cached2.dev === stat2.dev && cached2.ino === stat2.ino && cached2.pid === ownerPid && cached2.storedIdentity === storedIdentity && Date.now() - cached2.observedAtMs < HOST_CORE_POLICY.process_lock_identity_cache_ms ? cached2.observedIdentity : await probes.observeIdentity(ownerPid);
|
|
4128
4139
|
if (!observedIdentity) {
|
|
4129
4140
|
throw new Error("Inference host could not verify the existing lock owner identity.");
|
|
4130
4141
|
}
|
|
4131
4142
|
processLockObservationCache.set(cacheKey, {
|
|
4132
|
-
dev:
|
|
4133
|
-
ino:
|
|
4143
|
+
dev: stat2.dev,
|
|
4144
|
+
ino: stat2.ino,
|
|
4134
4145
|
pid: ownerPid,
|
|
4135
4146
|
storedIdentity,
|
|
4136
4147
|
observedIdentity,
|
|
@@ -4141,7 +4152,7 @@ while(($line=[Console]::In.ReadLine()) -ne $null) {
|
|
|
4141
4152
|
}
|
|
4142
4153
|
}
|
|
4143
4154
|
stale = true;
|
|
4144
|
-
return { state: "stale", handle, stat };
|
|
4155
|
+
return { state: "stale", handle, stat: stat2 };
|
|
4145
4156
|
} finally {
|
|
4146
4157
|
if (!stale) await handle.close().catch(() => void 0);
|
|
4147
4158
|
}
|
|
@@ -20808,6 +20819,7 @@ var init_runtime_policy_generated2 = __esm({
|
|
|
20808
20819
|
update_failure_reason_max_chars: 160,
|
|
20809
20820
|
launcher_poll_interval_ms: 100,
|
|
20810
20821
|
log_tail_default_lines: 100,
|
|
20822
|
+
log_rotate_bytes: 134217728,
|
|
20811
20823
|
worker_output_line_max_chars: 4096,
|
|
20812
20824
|
worker_stdout_tail_max_chars: 65536,
|
|
20813
20825
|
control_lock_wait_attempts: 400,
|
|
@@ -21047,6 +21059,7 @@ var init_runtime_policy_generated2 = __esm({
|
|
|
21047
21059
|
public_recovery: {
|
|
21048
21060
|
fallback_initial_seconds: 2,
|
|
21049
21061
|
fallback_max_seconds: 60,
|
|
21062
|
+
fallback_jitter_min_factor: 0.5,
|
|
21050
21063
|
permit_lease_seconds: 60,
|
|
21051
21064
|
recovery_initial_concurrency: 1,
|
|
21052
21065
|
recovery_max_concurrency: 8,
|
|
@@ -26083,7 +26096,12 @@ var init_mcp_client = __esm({
|
|
|
26083
26096
|
} catch (error48) {
|
|
26084
26097
|
if (timing) timing.cancelBody();
|
|
26085
26098
|
else await response.body?.cancel().catch(() => void 0);
|
|
26086
|
-
throw error48;
|
|
26099
|
+
if (error48 instanceof ExternalInferenceMcpError) throw error48;
|
|
26100
|
+
throw new ExternalInferenceMcpError(
|
|
26101
|
+
options.signal?.aborted ? "request_aborted" : "network_error",
|
|
26102
|
+
options.signal?.aborted ? "Insights MCP request was aborted." : "Insights MCP response body could not be read.",
|
|
26103
|
+
{ cause: error48 }
|
|
26104
|
+
);
|
|
26087
26105
|
}
|
|
26088
26106
|
timing?.enter("response_validation_ms");
|
|
26089
26107
|
const document2 = documents.find((candidate) => candidate.id === requestId);
|
|
@@ -37653,6 +37671,11 @@ var init_runner = __esm({
|
|
|
37653
37671
|
} catch (error48) {
|
|
37654
37672
|
if (claimTiming) emitDiagnostic("claim_request_failed", {
|
|
37655
37673
|
claim_request_id: request.claim_request_id,
|
|
37674
|
+
failure_code: safeFailureCode(
|
|
37675
|
+
error48 instanceof ExternalInferenceMcpError ? error48.code : "",
|
|
37676
|
+
"claim_failed"
|
|
37677
|
+
),
|
|
37678
|
+
http_status_code: error48 instanceof ExternalInferenceMcpError ? error48.httpStatusCode : null,
|
|
37656
37679
|
client_timing: claimTiming
|
|
37657
37680
|
});
|
|
37658
37681
|
if (!this.options.signal?.aborted && request.schema_version === "external_inference_job_claim_v3" && error48 instanceof ExternalInferenceMcpError && error48.serverFailureCode === "schema_validation") {
|
|
@@ -47190,11 +47213,13 @@ var init_service_launcher_state = __esm({
|
|
|
47190
47213
|
// lib/inference-host/service.ts
|
|
47191
47214
|
import { spawn as spawn11 } from "node:child_process";
|
|
47192
47215
|
import { randomUUID as randomUUID11 } from "node:crypto";
|
|
47193
|
-
import { createWriteStream, readFileSync as readFileSync2 } from "node:fs";
|
|
47194
|
-
import { access as access6, chmod as chmod4, mkdir as mkdir5, readFile as readFile12, rm as rm14, writeFile as writeFile5 } from "node:fs/promises";
|
|
47216
|
+
import { createReadStream, createWriteStream, readFileSync as readFileSync2 } from "node:fs";
|
|
47217
|
+
import { access as access6, appendFile as appendFile2, chmod as chmod4, mkdir as mkdir5, readFile as readFile12, rm as rm14, stat, truncate, writeFile as writeFile5 } from "node:fs/promises";
|
|
47195
47218
|
import { homedir as homedir4 } from "node:os";
|
|
47196
47219
|
import { dirname as dirname15, join as join16, resolve as resolve12 } from "node:path";
|
|
47197
|
-
|
|
47220
|
+
import { Transform } from "node:stream";
|
|
47221
|
+
import { pipeline } from "node:stream/promises";
|
|
47222
|
+
var SERVICE_NAME, SYSTEMD_UNIT, LAUNCHD_LABEL, SERVICE_POLICY, ATOMIC_REPLACEMENT_READ_ATTEMPTS, SERVICE_COOPERATIVE_STOP_SECONDS, pollAttemptsWithin, INFERENCE_HOST_SERVICE_DRAIN_COMMAND, INFERENCE_HOST_SERVICE_QUIESCE_COMMAND, InferenceHostBootstrapRestartRequiredError, inferenceHostServiceChildEnvironment, isWindowsSubsystemForLinux, inferenceHostServiceManifestPath, inferenceHostServiceDesiredPath, inferenceHostServiceLogPath, inferenceHostServiceRotatedLogPath, inferenceHostServiceRuntimePath, xmlEscape, plistEscape, systemdQuote, defaultRunCommand, probeInferenceHostLauncher, managerName, assertRuntimeEnvironment, withoutConcurrencyLimit, assertServicePath, manifestGeneration, assertWorker, assertManifest, assertServiceRuntimeState, assertDesiredState, readInferenceHostServiceManifest, readManifestAcrossAtomicReplacement, readInferenceHostServiceRuntime, readRuntimeAcrossAtomicReplacement, readInferenceHostServiceDesired, readDesiredAcrossAtomicReplacement, writeDesired, runtimeEnvironment, serviceBootstrapArguments, windowsOwnedCommandLine, vbScriptString, windowsServiceLauncher, windowsTaskXml, systemdUnit, launchAgentPlist, sameWorker, sameServiceDefinition, sameWorkerSet, InferenceHostServiceManager, serviceLogSinks, serviceLogSize, rotateServiceLog, writeServiceLog, appendServiceLog, spawnInferenceHostServiceChild, runInferenceHostServiceSupervisor;
|
|
47198
47223
|
var init_service = __esm({
|
|
47199
47224
|
"lib/inference-host/service.ts"() {
|
|
47200
47225
|
"use strict";
|
|
@@ -47246,6 +47271,7 @@ var init_service = __esm({
|
|
|
47246
47271
|
inferenceHostServiceManifestPath = (config2) => `${config2.supervisorStatePath}.service.json`;
|
|
47247
47272
|
inferenceHostServiceDesiredPath = (config2) => `${config2.supervisorStatePath}.service-desired.json`;
|
|
47248
47273
|
inferenceHostServiceLogPath = (config2) => `${config2.supervisorStatePath}.service.log`;
|
|
47274
|
+
inferenceHostServiceRotatedLogPath = (logPath) => `${logPath}.1`;
|
|
47249
47275
|
inferenceHostServiceRuntimePath = (config2) => `${config2.supervisorStatePath}.service-runtime.json`;
|
|
47250
47276
|
xmlEscape = (value) => value.replaceAll("&", "&").replaceAll("<", "<").replaceAll(">", ">").replaceAll('"', """).replaceAll("'", "'");
|
|
47251
47277
|
plistEscape = xmlEscape;
|
|
@@ -48285,10 +48311,16 @@ ${result.stderr}`)) {
|
|
|
48285
48311
|
async logs(lines = SERVICE_POLICY.log_tail_default_lines, instanceName) {
|
|
48286
48312
|
const manifest = await readInferenceHostServiceManifest(this.manifestPath());
|
|
48287
48313
|
const path = manifest?.log_path ?? this.logPath();
|
|
48288
|
-
|
|
48289
|
-
|
|
48290
|
-
|
|
48291
|
-
|
|
48314
|
+
const matching = async (file2) => {
|
|
48315
|
+
let contents;
|
|
48316
|
+
try {
|
|
48317
|
+
contents = await readFile12(file2, "utf8");
|
|
48318
|
+
} catch (error48) {
|
|
48319
|
+
if (error48.code === "ENOENT") return [];
|
|
48320
|
+
throw error48;
|
|
48321
|
+
}
|
|
48322
|
+
const logLines = contents.trimEnd() ? contents.trimEnd().split(/\r?\n/u) : [];
|
|
48323
|
+
return instanceName ? logLines.filter((line) => {
|
|
48292
48324
|
try {
|
|
48293
48325
|
const parsed = JSON.parse(line);
|
|
48294
48326
|
return parsed.instance_name === instanceName || Array.isArray(parsed.instances) && parsed.instances.includes(instanceName);
|
|
@@ -48296,12 +48328,11 @@ ${result.stderr}`)) {
|
|
|
48296
48328
|
return false;
|
|
48297
48329
|
}
|
|
48298
48330
|
}) : logLines;
|
|
48299
|
-
|
|
48331
|
+
};
|
|
48332
|
+
const current = await matching(path);
|
|
48333
|
+
const filtered = current.length >= lines ? current : [...await matching(inferenceHostServiceRotatedLogPath(path)), ...current];
|
|
48334
|
+
return filtered.length > 0 ? `${filtered.slice(-lines).join("\n")}
|
|
48300
48335
|
` : "";
|
|
48301
|
-
} catch (error48) {
|
|
48302
|
-
if (error48.code === "ENOENT") return "";
|
|
48303
|
-
throw error48;
|
|
48304
|
-
}
|
|
48305
48336
|
}
|
|
48306
48337
|
async uninstallInstance(instanceName) {
|
|
48307
48338
|
return await this.withControlLock(async () => {
|
|
@@ -48366,14 +48397,71 @@ ${result.stderr}`)) {
|
|
|
48366
48397
|
};
|
|
48367
48398
|
}
|
|
48368
48399
|
};
|
|
48369
|
-
|
|
48370
|
-
|
|
48371
|
-
|
|
48372
|
-
|
|
48373
|
-
|
|
48374
|
-
|
|
48375
|
-
|
|
48400
|
+
serviceLogSinks = /* @__PURE__ */ new Map();
|
|
48401
|
+
serviceLogSize = async (path) => await stat(path).then((entry) => entry.size, (error48) => {
|
|
48402
|
+
if (error48.code === "ENOENT") return 0;
|
|
48403
|
+
throw error48;
|
|
48404
|
+
});
|
|
48405
|
+
rotateServiceLog = async (path, size) => {
|
|
48406
|
+
const start = Math.max(0, size - SERVICE_POLICY.log_rotate_bytes);
|
|
48407
|
+
let aligned = start === 0;
|
|
48408
|
+
await pipeline(
|
|
48409
|
+
createReadStream(path, { start, end: size - 1 }),
|
|
48410
|
+
new Transform({
|
|
48411
|
+
transform(chunk, _encoding, callback) {
|
|
48412
|
+
if (aligned) {
|
|
48413
|
+
callback(null, chunk);
|
|
48414
|
+
return;
|
|
48415
|
+
}
|
|
48416
|
+
const newline = chunk.indexOf("\n");
|
|
48417
|
+
if (newline < 0) {
|
|
48418
|
+
callback();
|
|
48419
|
+
return;
|
|
48420
|
+
}
|
|
48421
|
+
aligned = true;
|
|
48422
|
+
callback(null, chunk.subarray(newline + 1));
|
|
48423
|
+
}
|
|
48424
|
+
}),
|
|
48425
|
+
createWriteStream(inferenceHostServiceRotatedLogPath(path), { flags: "w", mode: OWNER_ONLY_FILE_MODE })
|
|
48426
|
+
);
|
|
48427
|
+
await truncate(path, 0);
|
|
48428
|
+
};
|
|
48429
|
+
writeServiceLog = (path, text) => {
|
|
48430
|
+
let sink = serviceLogSinks.get(path);
|
|
48431
|
+
if (!sink) {
|
|
48432
|
+
sink = { tail: Promise.resolve(), bytes: null, rotateAtBytes: SERVICE_POLICY.log_rotate_bytes };
|
|
48433
|
+
serviceLogSinks.set(path, sink);
|
|
48434
|
+
}
|
|
48435
|
+
const state2 = sink;
|
|
48436
|
+
const write = state2.tail.then(async () => {
|
|
48437
|
+
if (state2.bytes === null) {
|
|
48438
|
+
await mkdir5(dirname15(path), { recursive: true, mode: OWNER_ONLY_DIRECTORY_MODE });
|
|
48439
|
+
state2.bytes = await serviceLogSize(path);
|
|
48440
|
+
}
|
|
48441
|
+
await appendFile2(path, text, { encoding: "utf8", mode: OWNER_ONLY_FILE_MODE });
|
|
48442
|
+
state2.bytes += Buffer.byteLength(text);
|
|
48443
|
+
if (state2.bytes < state2.rotateAtBytes) return;
|
|
48444
|
+
try {
|
|
48445
|
+
const size = await serviceLogSize(path);
|
|
48446
|
+
if (size >= SERVICE_POLICY.log_rotate_bytes) await rotateServiceLog(path, size);
|
|
48447
|
+
state2.bytes = size >= SERVICE_POLICY.log_rotate_bytes ? 0 : size;
|
|
48448
|
+
state2.rotateAtBytes = SERVICE_POLICY.log_rotate_bytes;
|
|
48449
|
+
} catch (error48) {
|
|
48450
|
+
state2.rotateAtBytes = state2.bytes + SERVICE_POLICY.log_rotate_bytes;
|
|
48451
|
+
await appendFile2(path, `${JSON.stringify({
|
|
48452
|
+
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
48453
|
+
event: "service_log_rotation_failed",
|
|
48454
|
+
error_code: String(error48.code ?? "unknown")
|
|
48455
|
+
})}
|
|
48456
|
+
`, { encoding: "utf8", mode: OWNER_ONLY_FILE_MODE }).catch(() => void 0);
|
|
48457
|
+
}
|
|
48376
48458
|
});
|
|
48459
|
+
state2.tail = write.catch(() => void 0);
|
|
48460
|
+
return write;
|
|
48461
|
+
};
|
|
48462
|
+
appendServiceLog = async (path, event, fields = {}) => {
|
|
48463
|
+
await writeServiceLog(path, `${JSON.stringify({ at: (/* @__PURE__ */ new Date()).toISOString(), event, ...fields })}
|
|
48464
|
+
`);
|
|
48377
48465
|
};
|
|
48378
48466
|
spawnInferenceHostServiceChild = async (manifest, worker, signal, onReady = () => {
|
|
48379
48467
|
}, quiesceSignal) => {
|
|
@@ -48388,7 +48476,12 @@ ${result.stderr}`)) {
|
|
|
48388
48476
|
worker.display_name
|
|
48389
48477
|
];
|
|
48390
48478
|
const startedAt = Date.now();
|
|
48391
|
-
const log =
|
|
48479
|
+
const log = (line) => {
|
|
48480
|
+
void writeServiceLog(manifest.log_path, line).catch(() => void 0);
|
|
48481
|
+
};
|
|
48482
|
+
const logSettled = async () => {
|
|
48483
|
+
await serviceLogSinks.get(manifest.log_path)?.tail;
|
|
48484
|
+
};
|
|
48392
48485
|
return await new Promise((resolvePromise, reject) => {
|
|
48393
48486
|
let stdout = "";
|
|
48394
48487
|
let cooperativeStopTimedOut = false;
|
|
@@ -48406,7 +48499,7 @@ ${result.stderr}`)) {
|
|
|
48406
48499
|
const parsed = JSON.parse(line);
|
|
48407
48500
|
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
48408
48501
|
if (parsed.event === "runtime_started") onReady();
|
|
48409
|
-
log
|
|
48502
|
+
log(`${JSON.stringify({
|
|
48410
48503
|
...parsed,
|
|
48411
48504
|
instance_name: worker.instance_name
|
|
48412
48505
|
})}
|
|
@@ -48415,7 +48508,7 @@ ${result.stderr}`)) {
|
|
|
48415
48508
|
}
|
|
48416
48509
|
} catch {
|
|
48417
48510
|
}
|
|
48418
|
-
log
|
|
48511
|
+
log(`${JSON.stringify({
|
|
48419
48512
|
at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
48420
48513
|
event: "worker_output",
|
|
48421
48514
|
instance_name: worker.instance_name,
|
|
@@ -48461,8 +48554,7 @@ ${result.stderr}`)) {
|
|
|
48461
48554
|
if (cooperativeStopTimer) clearTimeout(cooperativeStopTimer);
|
|
48462
48555
|
writeTaggedOutput("stdout", "", true);
|
|
48463
48556
|
writeTaggedOutput("stderr", "", true);
|
|
48464
|
-
|
|
48465
|
-
reject(error48);
|
|
48557
|
+
void logSettled().then(() => reject(error48));
|
|
48466
48558
|
});
|
|
48467
48559
|
child.once("exit", (code) => {
|
|
48468
48560
|
signal.removeEventListener("abort", onAbort);
|
|
@@ -48470,7 +48562,6 @@ ${result.stderr}`)) {
|
|
|
48470
48562
|
if (cooperativeStopTimer) clearTimeout(cooperativeStopTimer);
|
|
48471
48563
|
writeTaggedOutput("stdout", "", true);
|
|
48472
48564
|
writeTaggedOutput("stderr", "", true);
|
|
48473
|
-
log.end();
|
|
48474
48565
|
let drainReason = null;
|
|
48475
48566
|
for (const line of stdout.trim().split("\n").reverse()) {
|
|
48476
48567
|
try {
|
|
@@ -48484,12 +48575,13 @@ ${result.stderr}`)) {
|
|
|
48484
48575
|
} catch {
|
|
48485
48576
|
}
|
|
48486
48577
|
}
|
|
48487
|
-
|
|
48578
|
+
const uptimeMs = Date.now() - startedAt;
|
|
48579
|
+
void logSettled().then(() => resolvePromise({
|
|
48488
48580
|
exitCode: code ?? 1,
|
|
48489
|
-
uptimeMs
|
|
48581
|
+
uptimeMs,
|
|
48490
48582
|
drainReason,
|
|
48491
48583
|
cooperativeStopTimedOut
|
|
48492
|
-
});
|
|
48584
|
+
}));
|
|
48493
48585
|
});
|
|
48494
48586
|
});
|
|
48495
48587
|
};
|
|
@@ -54162,6 +54254,101 @@ var init_monotonic_clock = __esm({
|
|
|
54162
54254
|
}
|
|
54163
54255
|
});
|
|
54164
54256
|
|
|
54257
|
+
// lib/runtime/hyperliquid-market-symbol.ts
|
|
54258
|
+
var configuredCaseSensitiveSymbols, isHyperliquidSpotSymbol, normalizeCaseSensitiveSymbols, configureHyperliquidMarketSymbolCasing, canonicalBaseSymbol, normalizeHyperliquidMarketSymbol, getHyperliquidMarketDex;
|
|
54259
|
+
var init_hyperliquid_market_symbol = __esm({
|
|
54260
|
+
"lib/runtime/hyperliquid-market-symbol.ts"() {
|
|
54261
|
+
"use strict";
|
|
54262
|
+
init_define_VTX_EXO_POLICY();
|
|
54263
|
+
init_define_VTX_GROK_POLICY();
|
|
54264
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
54265
|
+
configuredCaseSensitiveSymbols = [];
|
|
54266
|
+
isHyperliquidSpotSymbol = (value) => {
|
|
54267
|
+
const symbol2 = typeof value === "string" ? value.trim() : "";
|
|
54268
|
+
return symbol2.startsWith("@") || symbol2.includes("/");
|
|
54269
|
+
};
|
|
54270
|
+
normalizeCaseSensitiveSymbols = (symbols) => {
|
|
54271
|
+
if (!Array.isArray(symbols)) return [];
|
|
54272
|
+
const out = [];
|
|
54273
|
+
const seen = /* @__PURE__ */ new Set();
|
|
54274
|
+
for (const item of symbols) {
|
|
54275
|
+
const value = String(item ?? "").trim();
|
|
54276
|
+
if (!value) continue;
|
|
54277
|
+
const key = value.toUpperCase();
|
|
54278
|
+
if (seen.has(key)) continue;
|
|
54279
|
+
seen.add(key);
|
|
54280
|
+
out.push(value);
|
|
54281
|
+
}
|
|
54282
|
+
return out;
|
|
54283
|
+
};
|
|
54284
|
+
configureHyperliquidMarketSymbolCasing = (symbols) => {
|
|
54285
|
+
configuredCaseSensitiveSymbols = normalizeCaseSensitiveSymbols(symbols);
|
|
54286
|
+
};
|
|
54287
|
+
canonicalBaseSymbol = (base) => {
|
|
54288
|
+
const trimmed = base.trim();
|
|
54289
|
+
if (!trimmed) return "";
|
|
54290
|
+
const upper = trimmed.toUpperCase();
|
|
54291
|
+
for (const candidate of configuredCaseSensitiveSymbols) {
|
|
54292
|
+
if (candidate.toUpperCase() === upper) {
|
|
54293
|
+
return candidate;
|
|
54294
|
+
}
|
|
54295
|
+
}
|
|
54296
|
+
return upper;
|
|
54297
|
+
};
|
|
54298
|
+
normalizeHyperliquidMarketSymbol = (value) => {
|
|
54299
|
+
const raw = String(value ?? "").trim();
|
|
54300
|
+
if (!raw) return "";
|
|
54301
|
+
if (!raw.includes(":")) return canonicalBaseSymbol(raw);
|
|
54302
|
+
const [dex, ...rest] = raw.split(":");
|
|
54303
|
+
const base = rest.join(":").trim();
|
|
54304
|
+
const normalizedDex = dex.trim().toLowerCase();
|
|
54305
|
+
if (!normalizedDex || !base) return "";
|
|
54306
|
+
return `${normalizedDex}:${canonicalBaseSymbol(base)}`;
|
|
54307
|
+
};
|
|
54308
|
+
getHyperliquidMarketDex = (value) => {
|
|
54309
|
+
const normalized = normalizeHyperliquidMarketSymbol(value);
|
|
54310
|
+
if (!normalized.includes(":")) return "";
|
|
54311
|
+
return normalized.split(":", 1)[0];
|
|
54312
|
+
};
|
|
54313
|
+
}
|
|
54314
|
+
});
|
|
54315
|
+
|
|
54316
|
+
// lib/runtime/bot-exchanges.ts
|
|
54317
|
+
var exchangesByProfile, profileKey, dexList, recordBotExchanges, recordStatusExchanges;
|
|
54318
|
+
var init_bot_exchanges = __esm({
|
|
54319
|
+
"lib/runtime/bot-exchanges.ts"() {
|
|
54320
|
+
"use strict";
|
|
54321
|
+
init_define_VTX_EXO_POLICY();
|
|
54322
|
+
init_define_VTX_GROK_POLICY();
|
|
54323
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
54324
|
+
init_hyperliquid_market_symbol();
|
|
54325
|
+
exchangesByProfile = /* @__PURE__ */ new Map();
|
|
54326
|
+
profileKey = (profileId) => {
|
|
54327
|
+
const id2 = Number(profileId);
|
|
54328
|
+
return Number.isInteger(id2) && id2 > 0 ? id2 : null;
|
|
54329
|
+
};
|
|
54330
|
+
dexList = (value) => Array.isArray(value) && value.every((dex) => typeof dex === "string") ? value.map((dex) => dex.trim().toLowerCase()) : null;
|
|
54331
|
+
recordBotExchanges = (profileId, equityVenues, readVenues) => {
|
|
54332
|
+
const id2 = profileKey(profileId);
|
|
54333
|
+
if (id2 === null) return;
|
|
54334
|
+
const equity = dexList(equityVenues);
|
|
54335
|
+
const read = readVenues === void 0 ? equity : dexList(readVenues);
|
|
54336
|
+
if (!equity || !read) {
|
|
54337
|
+
exchangesByProfile.delete(id2);
|
|
54338
|
+
return;
|
|
54339
|
+
}
|
|
54340
|
+
exchangesByProfile.set(id2, { equity, read });
|
|
54341
|
+
};
|
|
54342
|
+
recordStatusExchanges = (status) => {
|
|
54343
|
+
const fields = status;
|
|
54344
|
+
if (fields && typeof fields === "object" && "equity_venues" in fields) {
|
|
54345
|
+
recordBotExchanges(fields.profile_id, fields.equity_venues, fields.read_venues);
|
|
54346
|
+
}
|
|
54347
|
+
return status;
|
|
54348
|
+
};
|
|
54349
|
+
}
|
|
54350
|
+
});
|
|
54351
|
+
|
|
54165
54352
|
// lib/runtime/local-breadcrumbs.ts
|
|
54166
54353
|
var LOCAL_RUNTIME_BREADCRUMBS_STORAGE_KEY, DEVICE_DIAGNOSTICS2, LOCAL_RUNTIME_BREADCRUMBS_MAX_ENTRIES, LOCAL_RUNTIME_BREADCRUMBS_MAX_DETAIL_LENGTH, TRUNCATION_ELLIPSIS, safeWindow, sanitizeText, sanitizeOptionalString, clonePayload, buildBreadcrumbId, coerceBreadcrumb, readLocalRuntimeBreadcrumbs, writeLocalRuntimeBreadcrumbs, buildLocalRuntimeEnvironmentSnapshot, appendClientRuntimeLocalBreadcrumb, clearLocalRuntimeBreadcrumbs, flushLocalRuntimeBreadcrumbs;
|
|
54167
54354
|
var init_local_breadcrumbs = __esm({
|
|
@@ -54674,6 +54861,17 @@ var init_updates = __esm({
|
|
|
54674
54861
|
}
|
|
54675
54862
|
});
|
|
54676
54863
|
|
|
54864
|
+
// lib/api/profile-emoji.ts
|
|
54865
|
+
var init_profile_emoji = __esm({
|
|
54866
|
+
"lib/api/profile-emoji.ts"() {
|
|
54867
|
+
"use strict";
|
|
54868
|
+
init_define_VTX_EXO_POLICY();
|
|
54869
|
+
init_define_VTX_GROK_POLICY();
|
|
54870
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
54871
|
+
init_shared();
|
|
54872
|
+
}
|
|
54873
|
+
});
|
|
54874
|
+
|
|
54677
54875
|
// lib/runtime/host-storage.ts
|
|
54678
54876
|
function configureRuntimeHostStorage(storage3) {
|
|
54679
54877
|
configuredStorage = storage3;
|
|
@@ -55280,7 +55478,7 @@ var init_hyperliquid_order_status = __esm({
|
|
|
55280
55478
|
});
|
|
55281
55479
|
|
|
55282
55480
|
// lib/runtime/hyperliquid-public-read.ts
|
|
55283
|
-
var policy, weights, recoveryPolicy, budgets, unpersistedBudgets, cache, pending2, PREFIX, priorityRank, createHyperliquidPublicPriorityScope, promoteHyperliquidPublicPriority, hostTransport, abortError2, checkAbort, wait, waitUnlessPromoted, storage, loadBudget, saveBudget, withBudgetLock, HyperliquidPublicReadError, getHyperliquidPublicReadBudget, cooldownError, recoveryWaitError, nonTradingWeightCap, nonTradingWaitMs, fallbackDelayMs, admit, cooldown, finishHyperliquidRecoveryRequest, assertHyperliquidRecoveryDispatch, validateHyperliquidRecoveryDispatch, cacheTtlMs, eligibleCache, reserveHyperliquidPublicReads, releaseHyperliquidPublicReadReservation, admitHyperliquidExchangeRequest, recordHyperliquidExchangeResponse, readHyperliquidPublicInfo;
|
|
55481
|
+
var policy, weights, recoveryPolicy, budgets, unpersistedBudgets, cache, pending2, PREFIX, priorityRank, createHyperliquidPublicPriorityScope, promoteHyperliquidPublicPriority, hostTransport, abortError2, checkAbort, wait, waitUnlessPromoted, storage, loadBudget, saveBudget, withBudgetLock, HyperliquidPublicReadError, getHyperliquidPublicReadBudget, cooldownError, recoveryWaitError, nonTradingWeightCap, nonTradingWaitMs, fallbackDelayMs, admit, settleRowWeightedReservation, cooldown, finishHyperliquidRecoveryRequest, assertHyperliquidRecoveryDispatch, validateHyperliquidRecoveryDispatch, cacheTtlMs, eligibleCache, reserveHyperliquidPublicReads, releaseHyperliquidPublicReadReservation, admitHyperliquidExchangeRequest, recordHyperliquidExchangeResponse, readHyperliquidPublicInfo;
|
|
55284
55482
|
var init_hyperliquid_public_read = __esm({
|
|
55285
55483
|
"lib/runtime/hyperliquid-public-read.ts"() {
|
|
55286
55484
|
"use strict";
|
|
@@ -55436,9 +55634,9 @@ var init_hyperliquid_public_read = __esm({
|
|
|
55436
55634
|
};
|
|
55437
55635
|
fallbackDelayMs = (failures) => Math.min(
|
|
55438
55636
|
recoveryPolicy.fallback_max_seconds * MS_PER_SECOND,
|
|
55439
|
-
recoveryPolicy.fallback_initial_seconds * MS_PER_SECOND * BACKOFF_GROWTH_FACTOR ** Math.min(HYPERLIQUID_RECOVERY_BACKOFF_MAX_EXPONENT, Math.max(0, failures - 1)) * (
|
|
55637
|
+
recoveryPolicy.fallback_initial_seconds * MS_PER_SECOND * BACKOFF_GROWTH_FACTOR ** Math.min(HYPERLIQUID_RECOVERY_BACKOFF_MAX_EXPONENT, Math.max(0, failures - 1)) * (recoveryPolicy.fallback_jitter_min_factor + Math.random())
|
|
55440
55638
|
);
|
|
55441
|
-
admit = async (apiUrl, requestType, signal, weightOverride, deadlineMs, priority) => {
|
|
55639
|
+
admit = async (apiUrl, requestType, signal, weightOverride, deadlineMs, priority, reservationId) => {
|
|
55442
55640
|
const key = `${PREFIX}${apiUrl}`;
|
|
55443
55641
|
const weight = weightOverride ?? weights[requestType] ?? policy.default_request_weight;
|
|
55444
55642
|
const ticket = crypto.randomUUID();
|
|
@@ -55497,7 +55695,7 @@ var init_hyperliquid_public_read = __esm({
|
|
|
55497
55695
|
permit = { endpoint: apiUrl, id: ticket, generation: recovery.generation, expiresAt };
|
|
55498
55696
|
}
|
|
55499
55697
|
budget.reservations = budget.reservations.filter((entry) => entry.at > now - policy.window_seconds * MS_PER_SECOND);
|
|
55500
|
-
budget.reservations.push({ at: now, weight });
|
|
55698
|
+
budget.reservations.push({ at: now, weight, ...reservationId ? { id: reservationId } : {} });
|
|
55501
55699
|
saveBudget(key, budget);
|
|
55502
55700
|
return { ready: true, permit, waitMs: 0 };
|
|
55503
55701
|
});
|
|
@@ -55517,9 +55715,20 @@ var init_hyperliquid_public_read = __esm({
|
|
|
55517
55715
|
});
|
|
55518
55716
|
}
|
|
55519
55717
|
};
|
|
55520
|
-
|
|
55718
|
+
settleRowWeightedReservation = async (apiUrl, reservationId, rows) => {
|
|
55719
|
+
const key = `${PREFIX}${apiUrl}`;
|
|
55720
|
+
const charged = policy.default_request_weight + Math.floor(rows / HYPERLIQUID_INFO_ROWS_PER_EXTRA_WEIGHT);
|
|
55721
|
+
await withBudgetLock(key, void 0, () => {
|
|
55722
|
+
const budget = loadBudget(key);
|
|
55723
|
+
const reservation = budget.reservations.find((entry) => entry.id === reservationId);
|
|
55724
|
+
if (!reservation || charged >= reservation.weight) return;
|
|
55725
|
+
reservation.weight = charged;
|
|
55726
|
+
saveBudget(key, budget);
|
|
55727
|
+
});
|
|
55728
|
+
};
|
|
55729
|
+
cooldown = async (apiUrl, retryAfter, requestType, priority) => {
|
|
55521
55730
|
if (hostTransport) {
|
|
55522
|
-
await hostTransport.admission.record429(retryAfter, requestType);
|
|
55731
|
+
await hostTransport.admission.record429(retryAfter, requestType, priority);
|
|
55523
55732
|
return;
|
|
55524
55733
|
}
|
|
55525
55734
|
const key = `${PREFIX}${apiUrl}`;
|
|
@@ -55625,8 +55834,8 @@ var init_hyperliquid_public_read = __esm({
|
|
|
55625
55834
|
const weight = weights.exchange + Math.floor(batchLength / runtime_policy_generated_default2.exchange.hyperliquid.read_budget.exchange_action_batch_size);
|
|
55626
55835
|
return admit(endpoint.replace(/\/$/, ""), "exchange", signal, weight, void 0, createHyperliquidPublicPriorityScope(priority));
|
|
55627
55836
|
};
|
|
55628
|
-
recordHyperliquidExchangeResponse = async (endpoint, response, permit) => {
|
|
55629
|
-
if (response.status === HTTP_STATUS.TOO_MANY_REQUESTS) await cooldown(endpoint.replace(/\/$/, ""), response.headers.get("Retry-After"), "exchange");
|
|
55837
|
+
recordHyperliquidExchangeResponse = async (endpoint, response, permit, priority) => {
|
|
55838
|
+
if (response.status === HTTP_STATUS.TOO_MANY_REQUESTS) await cooldown(endpoint.replace(/\/$/, ""), response.headers.get("Retry-After"), "exchange", priority);
|
|
55630
55839
|
await finishHyperliquidRecoveryRequest(permit, response.status < HTTP_CLIENT_ERROR_MIN ? "success" : "failure");
|
|
55631
55840
|
};
|
|
55632
55841
|
readHyperliquidPublicInfo = async (endpoint, body, options) => {
|
|
@@ -55656,6 +55865,7 @@ var init_hyperliquid_public_read = __esm({
|
|
|
55656
55865
|
};
|
|
55657
55866
|
armDeadline(deadline);
|
|
55658
55867
|
let permit = null;
|
|
55868
|
+
const rowWeightedReservationId = !hostTransport && HYPERLIQUID_ROW_WEIGHTED_INFO_REQUESTS.includes(requestType) ? crypto.randomUUID() : void 0;
|
|
55659
55869
|
let outcome = "cancelled";
|
|
55660
55870
|
let settled;
|
|
55661
55871
|
let acquiring = false;
|
|
@@ -55710,12 +55920,15 @@ var init_hyperliquid_public_read = __esm({
|
|
|
55710
55920
|
if (!privateRoute) {
|
|
55711
55921
|
acquiring = true;
|
|
55712
55922
|
setPendingPhase("admission");
|
|
55713
|
-
permit = await admit(apiUrl, requestType, signal, void 0, deadline, priority);
|
|
55923
|
+
permit = await admit(apiUrl, requestType, signal, void 0, deadline, priority, rowWeightedReservationId);
|
|
55714
55924
|
acquiring = false;
|
|
55715
55925
|
armDeadline(Math.min(deadline, permit?.expiresAt ?? Infinity));
|
|
55716
55926
|
checkAbort(signal);
|
|
55717
55927
|
if (options.reservation?.closed) throw new DOMException("Hyperliquid account read was cancelled.", "AbortError");
|
|
55718
55928
|
await validateHyperliquidRecoveryDispatch(apiUrl, permit, requestType);
|
|
55929
|
+
checkAbort(signal);
|
|
55930
|
+
if (options.reservation?.closed) throw new DOMException("Hyperliquid account read was cancelled.", "AbortError");
|
|
55931
|
+
hostTransport?.onPublicInfoSent?.(body);
|
|
55719
55932
|
}
|
|
55720
55933
|
outcome = "failure";
|
|
55721
55934
|
let transportAborted;
|
|
@@ -55738,7 +55951,7 @@ var init_hyperliquid_public_read = __esm({
|
|
|
55738
55951
|
checkAbort(signal);
|
|
55739
55952
|
if (received.status === HTTP_STATUS.TOO_MANY_REQUESTS) {
|
|
55740
55953
|
observedRateLimit = new HyperliquidPublicReadError("public_rate_limited", "Hyperliquid public API returned HTTP 429.", requestType, HTTP_STATUS.TOO_MANY_REQUESTS);
|
|
55741
|
-
if (!privateRoute) await cooldown(apiUrl, received.headers.get("Retry-After"), requestType);
|
|
55954
|
+
if (!privateRoute) await cooldown(apiUrl, received.headers.get("Retry-After"), requestType, priority.value);
|
|
55742
55955
|
throw observedRateLimit;
|
|
55743
55956
|
}
|
|
55744
55957
|
let receivedText;
|
|
@@ -55773,6 +55986,12 @@ var init_hyperliquid_public_read = __esm({
|
|
|
55773
55986
|
});
|
|
55774
55987
|
}
|
|
55775
55988
|
outcome = "success";
|
|
55989
|
+
if (rowWeightedReservationId && !privateRoute && Array.isArray(payload)) {
|
|
55990
|
+
try {
|
|
55991
|
+
await settleRowWeightedReservation(apiUrl, rowWeightedReservationId, payload.length);
|
|
55992
|
+
} catch {
|
|
55993
|
+
}
|
|
55994
|
+
}
|
|
55776
55995
|
const result = { payload, fetchedAtMs: Date.now(), ...bodyText !== void 0 ? { bodyText } : {} };
|
|
55777
55996
|
if (ttlMs) {
|
|
55778
55997
|
cache.set(key, result);
|
|
@@ -55841,65 +56060,6 @@ var init_hyperliquid_exchange_rejections = __esm({
|
|
|
55841
56060
|
}
|
|
55842
56061
|
});
|
|
55843
56062
|
|
|
55844
|
-
// lib/runtime/hyperliquid-market-symbol.ts
|
|
55845
|
-
var configuredCaseSensitiveSymbols, isHyperliquidSpotSymbol, normalizeCaseSensitiveSymbols, configureHyperliquidMarketSymbolCasing, canonicalBaseSymbol, normalizeHyperliquidMarketSymbol, getHyperliquidMarketDex;
|
|
55846
|
-
var init_hyperliquid_market_symbol = __esm({
|
|
55847
|
-
"lib/runtime/hyperliquid-market-symbol.ts"() {
|
|
55848
|
-
"use strict";
|
|
55849
|
-
init_define_VTX_EXO_POLICY();
|
|
55850
|
-
init_define_VTX_GROK_POLICY();
|
|
55851
|
-
init_define_VTX_PI_MODEL_POLICY();
|
|
55852
|
-
configuredCaseSensitiveSymbols = [];
|
|
55853
|
-
isHyperliquidSpotSymbol = (value) => {
|
|
55854
|
-
const symbol2 = typeof value === "string" ? value.trim() : "";
|
|
55855
|
-
return symbol2.startsWith("@") || symbol2.includes("/");
|
|
55856
|
-
};
|
|
55857
|
-
normalizeCaseSensitiveSymbols = (symbols) => {
|
|
55858
|
-
if (!Array.isArray(symbols)) return [];
|
|
55859
|
-
const out = [];
|
|
55860
|
-
const seen = /* @__PURE__ */ new Set();
|
|
55861
|
-
for (const item of symbols) {
|
|
55862
|
-
const value = String(item ?? "").trim();
|
|
55863
|
-
if (!value) continue;
|
|
55864
|
-
const key = value.toUpperCase();
|
|
55865
|
-
if (seen.has(key)) continue;
|
|
55866
|
-
seen.add(key);
|
|
55867
|
-
out.push(value);
|
|
55868
|
-
}
|
|
55869
|
-
return out;
|
|
55870
|
-
};
|
|
55871
|
-
configureHyperliquidMarketSymbolCasing = (symbols) => {
|
|
55872
|
-
configuredCaseSensitiveSymbols = normalizeCaseSensitiveSymbols(symbols);
|
|
55873
|
-
};
|
|
55874
|
-
canonicalBaseSymbol = (base) => {
|
|
55875
|
-
const trimmed = base.trim();
|
|
55876
|
-
if (!trimmed) return "";
|
|
55877
|
-
const upper = trimmed.toUpperCase();
|
|
55878
|
-
for (const candidate of configuredCaseSensitiveSymbols) {
|
|
55879
|
-
if (candidate.toUpperCase() === upper) {
|
|
55880
|
-
return candidate;
|
|
55881
|
-
}
|
|
55882
|
-
}
|
|
55883
|
-
return upper;
|
|
55884
|
-
};
|
|
55885
|
-
normalizeHyperliquidMarketSymbol = (value) => {
|
|
55886
|
-
const raw = String(value ?? "").trim();
|
|
55887
|
-
if (!raw) return "";
|
|
55888
|
-
if (!raw.includes(":")) return canonicalBaseSymbol(raw);
|
|
55889
|
-
const [dex, ...rest] = raw.split(":");
|
|
55890
|
-
const base = rest.join(":").trim();
|
|
55891
|
-
const normalizedDex = dex.trim().toLowerCase();
|
|
55892
|
-
if (!normalizedDex || !base) return "";
|
|
55893
|
-
return `${normalizedDex}:${canonicalBaseSymbol(base)}`;
|
|
55894
|
-
};
|
|
55895
|
-
getHyperliquidMarketDex = (value) => {
|
|
55896
|
-
const normalized = normalizeHyperliquidMarketSymbol(value);
|
|
55897
|
-
if (!normalized.includes(":")) return "";
|
|
55898
|
-
return normalized.split(":", 1)[0];
|
|
55899
|
-
};
|
|
55900
|
-
}
|
|
55901
|
-
});
|
|
55902
|
-
|
|
55903
56063
|
// lib/runtime/exchange-mutation-fence.ts
|
|
55904
56064
|
var activeSettlementsByScope, normalizeScope, trackBrowserExchangeMutation, waitForBrowserExchangeMutationSettlement;
|
|
55905
56065
|
var init_exchange_mutation_fence = __esm({
|
|
@@ -89474,7 +89634,7 @@ var init_hyperliquid_client = __esm({
|
|
|
89474
89634
|
});
|
|
89475
89635
|
if (transportController.signal.aborted) throw transportController.signal.reason;
|
|
89476
89636
|
responseStatus = received.status;
|
|
89477
|
-
await recordHyperliquidExchangeResponse(apiUrl, received);
|
|
89637
|
+
await recordHyperliquidExchangeResponse(apiUrl, received, void 0, input.publicRequestPriority);
|
|
89478
89638
|
const body = await received.json().catch(() => ({}));
|
|
89479
89639
|
if (transportController.signal.aborted) throw transportController.signal.reason;
|
|
89480
89640
|
return { response: received, payload: body };
|
|
@@ -90011,7 +90171,7 @@ async function getAiTradingStatus(cookie, profileId, options) {
|
|
|
90011
90171
|
const message = await getErrorMessageFromResponse(response, "Failed to get AI Trader status", { fallbackDetail: true });
|
|
90012
90172
|
throw new Error(message);
|
|
90013
90173
|
}
|
|
90014
|
-
return response.json();
|
|
90174
|
+
return recordStatusExchanges(await response.json());
|
|
90015
90175
|
}, { cookie });
|
|
90016
90176
|
}
|
|
90017
90177
|
async function postClientRuntime(path, profileId, body, options) {
|
|
@@ -90587,7 +90747,7 @@ async function recordServerHostExecutionAudit(profileId, payload, signal, requir
|
|
|
90587
90747
|
{ ...authority.requestOptions, signal }
|
|
90588
90748
|
);
|
|
90589
90749
|
}
|
|
90590
|
-
async function checkServerHostExecutionCapacity(profileId, plans, signal, requiredRuntimeSessionId, explicitRuntimeLeaseToken, explicitRuntimeDeviceId, explicitSchedulerInstanceId) {
|
|
90750
|
+
async function checkServerHostExecutionCapacity(profileId, plans, signal, requiredRuntimeSessionId, explicitRuntimeLeaseToken, explicitRuntimeDeviceId, explicitSchedulerInstanceId, cycleStartedAt) {
|
|
90591
90751
|
const authority = resolveClientExchangeMutationAuthority(
|
|
90592
90752
|
profileId,
|
|
90593
90753
|
requiredRuntimeSessionId,
|
|
@@ -90600,7 +90760,9 @@ async function checkServerHostExecutionCapacity(profileId, plans, signal, requir
|
|
|
90600
90760
|
authority.numericProfileId,
|
|
90601
90761
|
JSON.stringify({
|
|
90602
90762
|
...clientExchangeMutationAuthorityBody(authority),
|
|
90603
|
-
plans
|
|
90763
|
+
plans,
|
|
90764
|
+
cycle_started_at: cycleStartedAt || void 0
|
|
90765
|
+
// an order VTX sent since then refuses the batch
|
|
90604
90766
|
}),
|
|
90605
90767
|
{ ...authority.requestOptions, signal }
|
|
90606
90768
|
);
|
|
@@ -91244,6 +91406,7 @@ var init_api2 = __esm({
|
|
|
91244
91406
|
init_google_auth_url();
|
|
91245
91407
|
init_network_debug();
|
|
91246
91408
|
init_monotonic_clock();
|
|
91409
|
+
init_bot_exchanges();
|
|
91247
91410
|
init_local_breadcrumbs();
|
|
91248
91411
|
init_abort();
|
|
91249
91412
|
init_client_runtime_ownership_errors();
|
|
@@ -91256,6 +91419,7 @@ var init_api2 = __esm({
|
|
|
91256
91419
|
init_client_host_commands();
|
|
91257
91420
|
init_insights_access_center();
|
|
91258
91421
|
init_updates();
|
|
91422
|
+
init_profile_emoji();
|
|
91259
91423
|
init_server_runtime_lease();
|
|
91260
91424
|
clientRuntimeSecretHeaders = (profileId) => {
|
|
91261
91425
|
const headers = getProfileHeaders({}, profileId);
|
|
@@ -91600,7 +91764,7 @@ var init_api2 = __esm({
|
|
|
91600
91764
|
if (!isRetryableClientRuntimeStatus(status)) {
|
|
91601
91765
|
return false;
|
|
91602
91766
|
}
|
|
91603
|
-
if (path === "/runtime/event") {
|
|
91767
|
+
if (path === "/runtime/event" || path === "/runtime/server-prompt-rescue") {
|
|
91604
91768
|
return false;
|
|
91605
91769
|
}
|
|
91606
91770
|
return true;
|
|
@@ -93795,7 +93959,7 @@ var init_hyperliquid_fee_contract = __esm({
|
|
|
93795
93959
|
});
|
|
93796
93960
|
|
|
93797
93961
|
// lib/runtime/hyperliquid-account-state-adapter.ts
|
|
93798
|
-
var USER_FILLS_CACHE_STORAGE_PREFIX, ACCOUNT_STATE_CACHE_STORAGE_PREFIX, browserUserFillsCache, browserUserFillsInFlight, browserAccountStateCache, browserAccountStateInFlight, toPositiveFinite, toFinite, firstFiniteNumber2, parseFundingUsdcFromInfoPosition2, buildUserFillsCacheKey, buildUserFillsStorageKey, buildAccountStateCacheKey, buildAccountStateStorageKey, hasActiveInfoRateLimitCooldown, requireNonNegativeConfigSeconds, requireAccountStateCacheConfig, requireUserFillsCacheConfig, normalizeFillSymbol, buildSymbolFilter, filterFillsBySymbols, readBrowserUserFillsCache, writeBrowserUserFillsCache, cloneBrowserAccountStateResult, withAccountStateEvidence, readBrowserAccountStateCache, writeBrowserAccountStateCache, isRateLimitError, createAbortError, waitForSharedBrowserRequest, waitForSharedBrowserUserFills, normalizeHyperliquidErrorDetail, parseInfoPositions, requireFinitePromptMetric, requirePromptClearinghouseState, requirePromptSpotState, normalizePerpDexName, listConfiguredPerpDexs, listPerpDexsForAccountState, prefixHip3PositionCoins, aggregateClearinghouseResponses, hasCompletePerpDexAccountMetrics, normalizeBrowserFillToTradeHistory, isPerpFill, settleAccountReads, fetchHyperliquidInfoRead, fetchHyperliquidInfoPayload, requireHyperliquidApiUrl, requireWalletAddress3, parseInfoPositionSnapshot, fetchBrowserAccountState2, fetchBrowserAccountStateUncached, fetchBrowserUserFills, fetchBrowserPositionSnapshot;
|
|
93962
|
+
var USER_FILLS_CACHE_STORAGE_PREFIX, ACCOUNT_STATE_CACHE_STORAGE_PREFIX, browserUserFillsCache, browserUserFillsPages, browserUserFillsInFlight, browserAccountStateCache, browserAccountStateInFlight, toPositiveFinite, toFinite, firstFiniteNumber2, parseFundingUsdcFromInfoPosition2, buildUserFillsCacheKey, buildUserFillsStorageKey, buildAccountStateCacheKey, buildAccountStateStorageKey, hasActiveInfoRateLimitCooldown, requireNonNegativeConfigSeconds, requireAccountStateCacheConfig, requireUserFillsCacheConfig, normalizeFillSymbol, buildSymbolFilter, filterFillsBySymbols, readBrowserUserFillsCache, writeBrowserUserFillsCache, cloneBrowserAccountStateResult, withAccountStateEvidence, readBrowserAccountStateCache, writeBrowserAccountStateCache, isRateLimitError, createAbortError, waitForSharedBrowserRequest, waitForSharedBrowserUserFills, normalizeHyperliquidErrorDetail, parseInfoPositions, requireFinitePromptMetric, requirePromptClearinghouseState, requirePromptSpotState, normalizePerpDexName, listConfiguredPerpDexs, listPerpDexsForAccountState, prefixHip3PositionCoins, aggregateClearinghouseResponses, hasCompletePerpDexAccountMetrics, normalizeBrowserFillToTradeHistory, isPerpFill, settleAccountReads, fetchHyperliquidInfoRead, fetchHyperliquidInfoPayload, requireHyperliquidApiUrl, requireWalletAddress3, parseInfoPositionSnapshot, fetchBrowserAccountState2, fetchBrowserAccountStateUncached, mergeNewerUserFills, fetchBrowserUserFills, fetchBrowserPositionSnapshot;
|
|
93799
93963
|
var init_hyperliquid_account_state_adapter = __esm({
|
|
93800
93964
|
"lib/runtime/hyperliquid-account-state-adapter.ts"() {
|
|
93801
93965
|
"use strict";
|
|
@@ -93816,6 +93980,7 @@ var init_hyperliquid_account_state_adapter = __esm({
|
|
|
93816
93980
|
USER_FILLS_CACHE_STORAGE_PREFIX = "vtx:hyperliquid:user-fills:v1:";
|
|
93817
93981
|
ACCOUNT_STATE_CACHE_STORAGE_PREFIX = "vtx:hyperliquid:account-state:v1:";
|
|
93818
93982
|
browserUserFillsCache = /* @__PURE__ */ new Map();
|
|
93983
|
+
browserUserFillsPages = /* @__PURE__ */ new Map();
|
|
93819
93984
|
browserUserFillsInFlight = /* @__PURE__ */ new Map();
|
|
93820
93985
|
browserAccountStateCache = /* @__PURE__ */ new Map();
|
|
93821
93986
|
browserAccountStateInFlight = /* @__PURE__ */ new Map();
|
|
@@ -94741,7 +94906,9 @@ var init_hyperliquid_account_state_adapter = __esm({
|
|
|
94741
94906
|
);
|
|
94742
94907
|
const accountSummary = {
|
|
94743
94908
|
...normalizedSummary,
|
|
94744
|
-
|
|
94909
|
+
// Every read keeps its per-DEX pools, a chart-scoped Trade read too, so
|
|
94910
|
+
// the Trade page can measure the bot's venue equity (botVenueEquity).
|
|
94911
|
+
...{
|
|
94745
94912
|
perp_dex_accounts: perpsResult.dexPayloads.filter(({ payload }) => hasCompletePerpDexAccountMetrics(payload)).map(({ dex, payload }) => {
|
|
94746
94913
|
const summary = buildServerPromptRescueAccountSummary({
|
|
94747
94914
|
...payload,
|
|
@@ -94808,6 +94975,24 @@ var init_hyperliquid_account_state_adapter = __esm({
|
|
|
94808
94975
|
await releaseHyperliquidPublicReadReservation(reservation);
|
|
94809
94976
|
}
|
|
94810
94977
|
};
|
|
94978
|
+
mergeNewerUserFills = (page, newer) => {
|
|
94979
|
+
const startTime = Number(page[0]?.time);
|
|
94980
|
+
if (!Number.isSafeInteger(startTime) || newer.length >= HYPERLIQUID_USER_FILLS_PROVIDER_PAGE_CAP) return null;
|
|
94981
|
+
const overlap = page.filter((fill) => Number(fill.time) === startTime).reverse();
|
|
94982
|
+
if (newer.length < overlap.length) return null;
|
|
94983
|
+
const added = [];
|
|
94984
|
+
for (const [index, fill] of newer.entries()) {
|
|
94985
|
+
if (!fill || typeof fill !== "object" || Array.isArray(fill)) return null;
|
|
94986
|
+
if (index < overlap.length) {
|
|
94987
|
+
if (JSON.stringify(fill) !== JSON.stringify(overlap[index])) return null;
|
|
94988
|
+
continue;
|
|
94989
|
+
}
|
|
94990
|
+
const time3 = Number(fill.time);
|
|
94991
|
+
if (!Number.isSafeInteger(time3) || time3 < startTime) return null;
|
|
94992
|
+
added.push(fill);
|
|
94993
|
+
}
|
|
94994
|
+
return [...added.reverse(), ...page].slice(0, HYPERLIQUID_USER_FILLS_PROVIDER_PAGE_CAP);
|
|
94995
|
+
};
|
|
94811
94996
|
fetchBrowserUserFills = async (input) => {
|
|
94812
94997
|
configureHyperliquidMarketSymbolCasing(input.config.client_runtime_hyperliquid_case_sensitive_symbols);
|
|
94813
94998
|
const apiUrl = requireHyperliquidApiUrl(input.config);
|
|
@@ -94870,13 +95055,27 @@ var init_hyperliquid_account_state_adapter = __esm({
|
|
|
94870
95055
|
let inFlight = existingFlight?.promise;
|
|
94871
95056
|
if (!inFlight) {
|
|
94872
95057
|
let freshRequest;
|
|
94873
|
-
|
|
94874
|
-
|
|
94875
|
-
|
|
94876
|
-
|
|
94877
|
-
|
|
94878
|
-
|
|
94879
|
-
|
|
95058
|
+
const previousPage = browserUserFillsPages.get(cacheKey);
|
|
95059
|
+
freshRequest = (async () => {
|
|
95060
|
+
if (previousPage && previousPage.length > 0) {
|
|
95061
|
+
const newer = await fetchHyperliquidInfoPayload(
|
|
95062
|
+
apiUrl,
|
|
95063
|
+
{ type: "userFillsByTime", user: walletAddress, startTime: Number(previousPage[0].time), aggregateByTime: false },
|
|
95064
|
+
void 0,
|
|
95065
|
+
void 0,
|
|
95066
|
+
priority
|
|
95067
|
+
);
|
|
95068
|
+
const page = Array.isArray(newer) ? mergeNewerUserFills(previousPage, newer) : null;
|
|
95069
|
+
if (page) return page;
|
|
95070
|
+
}
|
|
95071
|
+
return fetchHyperliquidInfoPayload(
|
|
95072
|
+
apiUrl,
|
|
95073
|
+
{ type: "userFills", user: walletAddress },
|
|
95074
|
+
void 0,
|
|
95075
|
+
void 0,
|
|
95076
|
+
priority
|
|
95077
|
+
);
|
|
95078
|
+
})().then((payload) => {
|
|
94880
95079
|
const providerRowCount2 = Array.isArray(payload) ? payload.length : 0;
|
|
94881
95080
|
const rawFills2 = Array.isArray(payload) ? payload.filter(isPerpFill).map((fill) => ({ ...fill })) : [];
|
|
94882
95081
|
const fillTimes = Array.isArray(payload) ? payload.map((fill) => Number(fill?.time)).filter((time3) => Number.isSafeInteger(time3) && time3 > 0) : [];
|
|
@@ -94886,6 +95085,11 @@ var init_hyperliquid_account_state_adapter = __esm({
|
|
|
94886
95085
|
providerRowCount: providerRowCount2,
|
|
94887
95086
|
oldestFillTimeMs: fillTimes.length > 0 ? Math.min(...fillTimes) : null
|
|
94888
95087
|
};
|
|
95088
|
+
if (Array.isArray(payload) && payload.every((fill) => fill !== null && typeof fill === "object" && !Array.isArray(fill))) {
|
|
95089
|
+
browserUserFillsPages.set(cacheKey, payload);
|
|
95090
|
+
} else {
|
|
95091
|
+
browserUserFillsPages.delete(cacheKey);
|
|
95092
|
+
}
|
|
94889
95093
|
writeBrowserUserFillsCache(cacheKey, entry);
|
|
94890
95094
|
return entry;
|
|
94891
95095
|
}).finally(() => {
|
|
@@ -95141,8 +95345,8 @@ var init_protective_evidence = __esm({
|
|
|
95141
95345
|
const wallet = String(context.walletAddress ?? "").trim();
|
|
95142
95346
|
const items = evidenceItems(context.requests ?? []);
|
|
95143
95347
|
if (items.length === 0 || !wallet) return { reported: 0, nextEvidenceDueAtMs: listedDueAtMs };
|
|
95144
|
-
const
|
|
95145
|
-
const backoffUntil = evidenceBackoffUntil.get(
|
|
95348
|
+
const profileKey2 = String(context.profileId).trim();
|
|
95349
|
+
const backoffUntil = evidenceBackoffUntil.get(profileKey2) ?? 0;
|
|
95146
95350
|
if (Date.now() < backoffUntil) {
|
|
95147
95351
|
return { reported: 0, nextEvidenceDueAtMs: backoffUntil, skipped: "backoff" };
|
|
95148
95352
|
}
|
|
@@ -95185,15 +95389,15 @@ var init_protective_evidence = __esm({
|
|
|
95185
95389
|
}
|
|
95186
95390
|
if (failedCode) {
|
|
95187
95391
|
const until = Date.now() + EVIDENCE_FAILURE_BACKOFF_MS;
|
|
95188
|
-
evidenceBackoffUntil.set(
|
|
95392
|
+
evidenceBackoffUntil.set(profileKey2, until);
|
|
95189
95393
|
appendRuntimeDebugEvent({
|
|
95190
95394
|
label: "client_protective_evidence_rejected",
|
|
95191
|
-
note: `profile_id=${
|
|
95395
|
+
note: `profile_id=${profileKey2} code=${failedCode}`,
|
|
95192
95396
|
outcome: "error"
|
|
95193
95397
|
});
|
|
95194
95398
|
return { reported, nextEvidenceDueAtMs: until, failedCode, ...actions ? { actions } : {} };
|
|
95195
95399
|
}
|
|
95196
|
-
evidenceBackoffUntil.delete(
|
|
95400
|
+
evidenceBackoffUntil.delete(profileKey2);
|
|
95197
95401
|
return { reported, nextEvidenceDueAtMs, ...actions ? { actions } : {} };
|
|
95198
95402
|
},
|
|
95199
95403
|
() => ({ reported: 0, nextEvidenceDueAtMs: listedDueAtMs, skipped: "reporter_busy" })
|
|
@@ -95686,7 +95890,7 @@ var init_client_exchange_mutations = __esm({
|
|
|
95686
95890
|
});
|
|
95687
95891
|
|
|
95688
95892
|
// lib/runtime/execution-guard-contract.ts
|
|
95689
|
-
var unitsFromPosition, signedUnitsFromPosition, signedUnitsFromEntryPosition, classifyExecutionIntent, resolveExecutionTarget, decisionOrderSizeAsset, flipExecutionLegs;
|
|
95893
|
+
var unitsFromPosition, signedUnitsFromPosition, signedUnitsFromEntryPosition, classifyExecutionIntent, reductionFirstOrder, resolveExecutionTarget, decisionOrderSizeAsset, flipExecutionLegs, executedOrderPositionEvent;
|
|
95690
95894
|
var init_execution_guard_contract = __esm({
|
|
95691
95895
|
"lib/runtime/execution-guard-contract.ts"() {
|
|
95692
95896
|
"use strict";
|
|
@@ -95882,6 +96086,10 @@ var init_execution_guard_contract = __esm({
|
|
|
95882
96086
|
targetSignedUnits: -(units - Math.abs(snapshotSignedUnits))
|
|
95883
96087
|
};
|
|
95884
96088
|
};
|
|
96089
|
+
reductionFirstOrder = (plans) => {
|
|
96090
|
+
const reduces = plans.map((plan) => classifyExecutionIntent(plan.decision, plan.units, plan.signedUnits).reduceOnly);
|
|
96091
|
+
return plans.map((_, index) => index).sort((left, right) => Number(reduces[right]) - Number(reduces[left]));
|
|
96092
|
+
};
|
|
95885
96093
|
resolveExecutionTarget = (classified, liveSignedUnits, livePositionDirection) => {
|
|
95886
96094
|
const liveUnits = Number.isFinite(liveSignedUnits) ? Math.trunc(liveSignedUnits) : 0;
|
|
95887
96095
|
const exactLiveDirection = livePositionDirection == null ? liveUnits > 0 ? 1 : liveUnits < 0 ? -1 : 0 : livePositionDirection;
|
|
@@ -95956,11 +96164,24 @@ var init_execution_guard_contract = __esm({
|
|
|
95956
96164
|
}
|
|
95957
96165
|
];
|
|
95958
96166
|
};
|
|
96167
|
+
executedOrderPositionEvent = (intent, side, leg) => {
|
|
96168
|
+
if (side !== "buy" && side !== "sell") throw new Error("An executed order's side must be buy or sell");
|
|
96169
|
+
const sideDirection = side === "buy" ? "LONG" : "SHORT";
|
|
96170
|
+
const oppositeDirection = side === "buy" ? "SHORT" : "LONG";
|
|
96171
|
+
if (intent === "open" || intent === "add") return { positionEvent: intent, positionDirection: sideDirection };
|
|
96172
|
+
if (intent === "reduce" || intent === "close") return { positionEvent: intent, positionDirection: oppositeDirection };
|
|
96173
|
+
if (intent === "flip") {
|
|
96174
|
+
const [closeLeg, entryLeg] = flipExecutionLegs(side, "executed");
|
|
96175
|
+
const flipLeg = leg === entryLeg.leg ? entryLeg : closeLeg;
|
|
96176
|
+
return { positionEvent: flipLeg.positionEvent, positionDirection: flipLeg.positionDirection };
|
|
96177
|
+
}
|
|
96178
|
+
return { positionEvent: null, positionDirection: null };
|
|
96179
|
+
};
|
|
95959
96180
|
}
|
|
95960
96181
|
});
|
|
95961
96182
|
|
|
95962
96183
|
// lib/runtime/copy-trading-evidence.ts
|
|
95963
|
-
var ACCOUNT_MODE_CACHE_MS,
|
|
96184
|
+
var ACCOUNT_MODE_CACHE_MS, dexList2, normalizeRequest, openOrderRefs, EvidenceReadFailed, readClientCopyTradingAccountEvidence, accountEvidenceForUpload, readCopyOrderStatusEvidence, orderStatusEvidenceForAck;
|
|
95964
96185
|
var init_copy_trading_evidence = __esm({
|
|
95965
96186
|
"lib/runtime/copy-trading-evidence.ts"() {
|
|
95966
96187
|
"use strict";
|
|
@@ -95974,7 +96195,7 @@ var init_copy_trading_evidence = __esm({
|
|
|
95974
96195
|
init_monotonic_clock();
|
|
95975
96196
|
init_protective_evidence();
|
|
95976
96197
|
ACCOUNT_MODE_CACHE_MS = runtime_policy_generated_default2.exchange.hyperliquid.client_public_read_budget.account_mode_ttl_seconds * MS_PER_SECOND;
|
|
95977
|
-
|
|
96198
|
+
dexList2 = (value) => {
|
|
95978
96199
|
if (!Array.isArray(value) || value.some((dex) => typeof dex !== "string")) return null;
|
|
95979
96200
|
return [...new Set(value.map((dex) => dex.trim()))];
|
|
95980
96201
|
};
|
|
@@ -95982,8 +96203,8 @@ var init_copy_trading_evidence = __esm({
|
|
|
95982
96203
|
if (!request || typeof request !== "object") return null;
|
|
95983
96204
|
const requestId = typeof request.request_id === "string" ? request.request_id.trim() : "";
|
|
95984
96205
|
const walletAddress = typeof request.wallet_address === "string" ? request.wallet_address.trim() : "";
|
|
95985
|
-
const dexes =
|
|
95986
|
-
const openOrdersDexes =
|
|
96206
|
+
const dexes = dexList2(request.dexes);
|
|
96207
|
+
const openOrdersDexes = dexList2(request.open_orders_dexes);
|
|
95987
96208
|
const maxAgeSeconds = Number(request.max_age_seconds);
|
|
95988
96209
|
if (!requestId || !walletAddress || !dexes || !openOrdersDexes || !Array.isArray(request.order_refs) || !Number.isFinite(maxAgeSeconds) || maxAgeSeconds <= 0) return null;
|
|
95989
96210
|
const orderRefs = /* @__PURE__ */ new Map();
|
|
@@ -101046,7 +101267,7 @@ var init_runtime_execution = __esm({
|
|
|
101046
101267
|
isLong: group.isLong,
|
|
101047
101268
|
positionTpsl: leg.positionTpsl === true
|
|
101048
101269
|
}] : []));
|
|
101049
|
-
if (currentPositionSize === 0) {
|
|
101270
|
+
if (currentPositionSize === 0 || tracked.length === 0) {
|
|
101050
101271
|
writeTrackedTrailingStops(profileId, symbol2, []);
|
|
101051
101272
|
return [];
|
|
101052
101273
|
}
|
|
@@ -101515,6 +101736,7 @@ var init_runtime_execution = __esm({
|
|
|
101515
101736
|
});
|
|
101516
101737
|
runtimeProtectionOwners = /* @__PURE__ */ new WeakMap();
|
|
101517
101738
|
resolveRuntimeProtectionOwner = (request) => {
|
|
101739
|
+
if (request.executionMode === "server") return Promise.resolve("server");
|
|
101518
101740
|
const cached2 = runtimeProtectionOwners.get(request);
|
|
101519
101741
|
if (cached2) return cached2;
|
|
101520
101742
|
const authority = runtimeProtectionAuthority(request);
|
|
@@ -101656,7 +101878,7 @@ var init_runtime_execution = __esm({
|
|
|
101656
101878
|
() => withClientExecutionMutation(request, work),
|
|
101657
101879
|
request.signal
|
|
101658
101880
|
);
|
|
101659
|
-
allocateServerExecutionCapacity = async (authority, plans) => {
|
|
101881
|
+
allocateServerExecutionCapacity = async (authority, plans, cycleStartedAt) => {
|
|
101660
101882
|
if (plans.length === 0) return [];
|
|
101661
101883
|
try {
|
|
101662
101884
|
return await checkServerHostExecutionCapacity(
|
|
@@ -101666,11 +101888,12 @@ var init_runtime_execution = __esm({
|
|
|
101666
101888
|
authority.sessionId,
|
|
101667
101889
|
authority.runtimeLeaseToken,
|
|
101668
101890
|
authority.runtimeDeviceId,
|
|
101669
|
-
authority.schedulerInstanceId
|
|
101891
|
+
authority.schedulerInstanceId,
|
|
101892
|
+
cycleStartedAt
|
|
101670
101893
|
);
|
|
101671
|
-
} catch {
|
|
101894
|
+
} catch (error48) {
|
|
101672
101895
|
throwIfAborted2(authority.signal);
|
|
101673
|
-
return plans.map(() =>
|
|
101896
|
+
return plans.map(() => ({ unavailable: error48 }));
|
|
101674
101897
|
}
|
|
101675
101898
|
};
|
|
101676
101899
|
withClientProtectiveAdoptionMutation = (profileId, work, signal) => withClientExecutionMutation({ profileId: String(profileId).trim(), signal }, work);
|
|
@@ -101685,9 +101908,7 @@ var init_runtime_execution = __esm({
|
|
|
101685
101908
|
SERVER_AUDIT_RECORDED_ELSEWHERE = /* @__PURE__ */ new Set([
|
|
101686
101909
|
"suppressed_duplicate_decision",
|
|
101687
101910
|
"same_intent_cooldown",
|
|
101688
|
-
"
|
|
101689
|
-
"execution_capacity_refused",
|
|
101690
|
-
"execution_capacity_unavailable"
|
|
101911
|
+
"execution_capacity_refused"
|
|
101691
101912
|
]);
|
|
101692
101913
|
serverExecutionAuditOutcome = (result) => {
|
|
101693
101914
|
if (result.status === "executed") {
|
|
@@ -102294,10 +102515,10 @@ var init_runtime_execution = __esm({
|
|
|
102294
102515
|
});
|
|
102295
102516
|
const capacity = unsizedInput.serverCapacityAllocation ?? (await allocateServerExecutionCapacity(unsizedInput, [
|
|
102296
102517
|
{ symbol: unsizedInput.executionContext.symbol, decision: unsizedInput.decision, units: requestedUnits }
|
|
102297
|
-
]))[0];
|
|
102298
|
-
if (
|
|
102518
|
+
], unsizedInput.executionContext.decisionSnapshotCapturedAt))[0];
|
|
102519
|
+
if ("unavailable" in capacity) {
|
|
102299
102520
|
throwIfAborted2(unsizedInput.signal);
|
|
102300
|
-
|
|
102521
|
+
throw capacity.unavailable instanceof Error ? capacity.unavailable : new Error("Positions could not be read before the limit check.");
|
|
102301
102522
|
}
|
|
102302
102523
|
if (!capacity.accepted || !(capacity.units > 0)) {
|
|
102303
102524
|
appendRuntimeDebugEvent({
|
|
@@ -102557,6 +102778,9 @@ var init_runtime_execution = __esm({
|
|
|
102557
102778
|
input.runtimeDeviceId,
|
|
102558
102779
|
input.schedulerInstanceId
|
|
102559
102780
|
);
|
|
102781
|
+
if (!claim.allowed && claim.reason_code === "redis_unavailable") {
|
|
102782
|
+
throw Object.assign(new Error("Execution coordination was unavailable."), { reasonCode: "redis_unavailable" });
|
|
102783
|
+
}
|
|
102560
102784
|
if (input.serverExecutionAudit && typeof claim.audit_id === "number") {
|
|
102561
102785
|
input.serverExecutionAudit.auditId = claim.audit_id;
|
|
102562
102786
|
}
|
|
@@ -103080,7 +103304,7 @@ var init_runtime_execution = __esm({
|
|
|
103080
103304
|
symbol: input.executionContext.symbol,
|
|
103081
103305
|
action: classified.side.toUpperCase(),
|
|
103082
103306
|
status: "executed",
|
|
103083
|
-
execution_metadata: classified.intent === "flip" ? { ..._toExecutionMetadata(marketOrderResponse), decision_leg: "entry" } : _toExecutionMetadata(marketOrderResponse)
|
|
103307
|
+
execution_metadata: classified.intent === "flip" ? { ..._toExecutionMetadata(marketOrderResponse), decision_leg: "entry" } : { ..._toExecutionMetadata(marketOrderResponse), entry_began_flat: livePositionDirection === 0 }
|
|
103084
103308
|
});
|
|
103085
103309
|
const appendPostEntryProtectionFailure = (error48) => {
|
|
103086
103310
|
const projection = projectExecutionErrorContract({
|
|
@@ -107243,6 +107467,40 @@ var init_client_runtime_status_store = __esm({
|
|
|
107243
107467
|
}
|
|
107244
107468
|
});
|
|
107245
107469
|
|
|
107470
|
+
// lib/runtime/perp-dex-scope.ts
|
|
107471
|
+
var perpDexScopeForSymbols, equityVenuesForSymbols, profileEquityVenues, positionsOnVenues;
|
|
107472
|
+
var init_perp_dex_scope = __esm({
|
|
107473
|
+
"lib/runtime/perp-dex-scope.ts"() {
|
|
107474
|
+
"use strict";
|
|
107475
|
+
init_define_VTX_EXO_POLICY();
|
|
107476
|
+
init_define_VTX_GROK_POLICY();
|
|
107477
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
107478
|
+
init_hyperliquid_market_symbol();
|
|
107479
|
+
perpDexScopeForSymbols = (symbols) => {
|
|
107480
|
+
const dexes = /* @__PURE__ */ new Set();
|
|
107481
|
+
for (const raw of symbols) {
|
|
107482
|
+
if (!String(raw ?? "").trim()) continue;
|
|
107483
|
+
if (!normalizeHyperliquidMarketSymbol(raw)) return void 0;
|
|
107484
|
+
dexes.add(getHyperliquidMarketDex(raw));
|
|
107485
|
+
}
|
|
107486
|
+
return dexes.size > 0 ? [...dexes].filter(Boolean) : void 0;
|
|
107487
|
+
};
|
|
107488
|
+
equityVenuesForSymbols = (symbols) => {
|
|
107489
|
+
const venues = /* @__PURE__ */ new Set();
|
|
107490
|
+
for (const raw of symbols) {
|
|
107491
|
+
if (!String(raw ?? "").trim()) continue;
|
|
107492
|
+
if (!normalizeHyperliquidMarketSymbol(raw)) return null;
|
|
107493
|
+
venues.add(getHyperliquidMarketDex(raw));
|
|
107494
|
+
}
|
|
107495
|
+
return venues.size > 0 ? [...venues].sort() : null;
|
|
107496
|
+
};
|
|
107497
|
+
profileEquityVenues = (tradingSymbols, defaultTradingSymbols) => equityVenuesForSymbols(
|
|
107498
|
+
Array.isArray(tradingSymbols) && tradingSymbols.length > 0 ? tradingSymbols : defaultTradingSymbols ?? []
|
|
107499
|
+
);
|
|
107500
|
+
positionsOnVenues = (positions, venues) => venues ? positions.filter((position) => normalizeHyperliquidMarketSymbol(position.symbol) && venues.includes(getHyperliquidMarketDex(position.symbol))) : [...positions];
|
|
107501
|
+
}
|
|
107502
|
+
});
|
|
107503
|
+
|
|
107246
107504
|
// lib/runtime/client-killswitch.ts
|
|
107247
107505
|
var toPositiveFinite2, toNonNegativeFinite, firstConfiguredSymbol, calculateClientKillswitchDrawdownPercent, evaluateClientKillswitch, closeClientKillswitchPositions;
|
|
107248
107506
|
var init_client_killswitch = __esm({
|
|
@@ -107254,6 +107512,7 @@ var init_client_killswitch = __esm({
|
|
|
107254
107512
|
init_api2();
|
|
107255
107513
|
init_constants();
|
|
107256
107514
|
init_browser_trading();
|
|
107515
|
+
init_perp_dex_scope();
|
|
107257
107516
|
init_hyperliquid_account_state_adapter();
|
|
107258
107517
|
toPositiveFinite2 = (value) => {
|
|
107259
107518
|
const parsed = Number(value);
|
|
@@ -107307,6 +107566,7 @@ var init_client_killswitch = __esm({
|
|
|
107307
107566
|
}
|
|
107308
107567
|
const symbol2 = firstConfiguredSymbol(settings, input.config);
|
|
107309
107568
|
const leverage = toPositiveFinite2(settings.leverage) ?? 1;
|
|
107569
|
+
const equityVenues = profileEquityVenues(settings.trading_symbols, input.config.default_trading_symbols);
|
|
107310
107570
|
const accountState = await fetchBrowserAccountState2({
|
|
107311
107571
|
publicRequestPriority: "trading_reduce",
|
|
107312
107572
|
config: input.config,
|
|
@@ -107315,6 +107575,7 @@ var init_client_killswitch = __esm({
|
|
|
107315
107575
|
tickerPrice: 0,
|
|
107316
107576
|
leverage,
|
|
107317
107577
|
aggregatePerpDexs: true,
|
|
107578
|
+
perpDexScope: equityVenues?.filter(Boolean),
|
|
107318
107579
|
forceRefresh: true,
|
|
107319
107580
|
sessionId: input.sessionId,
|
|
107320
107581
|
signal: input.signal
|
|
@@ -107347,7 +107608,8 @@ var init_client_killswitch = __esm({
|
|
|
107347
107608
|
context,
|
|
107348
107609
|
accountState,
|
|
107349
107610
|
walletAddress,
|
|
107350
|
-
symbol: symbol2
|
|
107611
|
+
symbol: symbol2,
|
|
107612
|
+
equityVenues
|
|
107351
107613
|
};
|
|
107352
107614
|
}
|
|
107353
107615
|
if (!context.snapshot_trusted || context.status === "untrusted") {
|
|
@@ -107358,7 +107620,8 @@ var init_client_killswitch = __esm({
|
|
|
107358
107620
|
context,
|
|
107359
107621
|
accountState,
|
|
107360
107622
|
walletAddress,
|
|
107361
|
-
symbol: symbol2
|
|
107623
|
+
symbol: symbol2,
|
|
107624
|
+
equityVenues
|
|
107362
107625
|
};
|
|
107363
107626
|
}
|
|
107364
107627
|
const peakEquity = toPositiveFinite2(context.peak_equity);
|
|
@@ -107370,7 +107633,8 @@ var init_client_killswitch = __esm({
|
|
|
107370
107633
|
context,
|
|
107371
107634
|
accountState,
|
|
107372
107635
|
walletAddress,
|
|
107373
|
-
symbol: symbol2
|
|
107636
|
+
symbol: symbol2,
|
|
107637
|
+
equityVenues
|
|
107374
107638
|
};
|
|
107375
107639
|
}
|
|
107376
107640
|
const drawdownPercent = calculateClientKillswitchDrawdownPercent(
|
|
@@ -107385,11 +107649,12 @@ var init_client_killswitch = __esm({
|
|
|
107385
107649
|
context,
|
|
107386
107650
|
accountState,
|
|
107387
107651
|
walletAddress,
|
|
107388
|
-
symbol: symbol2
|
|
107652
|
+
symbol: symbol2,
|
|
107653
|
+
equityVenues
|
|
107389
107654
|
};
|
|
107390
107655
|
};
|
|
107391
107656
|
closeClientKillswitchPositions = async (input) => {
|
|
107392
|
-
const positions = input.positions.filter((position) => {
|
|
107657
|
+
const positions = positionsOnVenues(input.positions, input.venues).filter((position) => {
|
|
107393
107658
|
const size = Number(position.size);
|
|
107394
107659
|
return Number.isFinite(size) && size !== 0;
|
|
107395
107660
|
});
|
|
@@ -107524,13 +107789,13 @@ var init_history_evidence = __esm({
|
|
|
107524
107789
|
runClientHistoryAsks = async (context) => {
|
|
107525
107790
|
let asks = normalizeHistoryAsks(context.asks);
|
|
107526
107791
|
const wallet = String(context.walletAddress ?? "").trim();
|
|
107527
|
-
const
|
|
107528
|
-
if (asks.length === 0 || !wallet || !
|
|
107529
|
-
if (Date.now() < (historyBackoffUntil.get(
|
|
107792
|
+
const profileKey2 = String(context.profileId).trim();
|
|
107793
|
+
if (asks.length === 0 || !wallet || !profileKey2) return { reported: 0, rounds: 0, nextAsks: asks };
|
|
107794
|
+
if (Date.now() < (historyBackoffUntil.get(profileKey2) ?? 0)) {
|
|
107530
107795
|
return { reported: 0, rounds: 0, nextAsks: asks, skipped: "backoff" };
|
|
107531
107796
|
}
|
|
107532
|
-
if (runningProfiles.has(
|
|
107533
|
-
runningProfiles.add(
|
|
107797
|
+
if (runningProfiles.has(profileKey2)) return { reported: 0, rounds: 0, nextAsks: asks, skipped: "busy" };
|
|
107798
|
+
runningProfiles.add(profileKey2);
|
|
107534
107799
|
let reported = 0;
|
|
107535
107800
|
let rounds = 0;
|
|
107536
107801
|
const maxRounds = Math.max(1, Math.floor(context.maxRounds ?? HISTORY_ROUNDS_PER_BEAT));
|
|
@@ -107555,24 +107820,24 @@ var init_history_evidence = __esm({
|
|
|
107555
107820
|
reported += Number(answer?.accepted ?? 0);
|
|
107556
107821
|
asks = normalizeHistoryAsks(answer?.history_asks);
|
|
107557
107822
|
}
|
|
107558
|
-
historyBackoffUntil.delete(
|
|
107823
|
+
historyBackoffUntil.delete(profileKey2);
|
|
107559
107824
|
appendRuntimeDebugEvent({
|
|
107560
107825
|
label: "client_history_evidence_reported",
|
|
107561
|
-
note: `profile_id=${
|
|
107826
|
+
note: `profile_id=${profileKey2} rounds=${rounds} accepted=${reported} next=${asks.map((ask) => ask.stream).join(",") || "none"}`
|
|
107562
107827
|
});
|
|
107563
107828
|
return { reported, rounds, nextAsks: asks };
|
|
107564
107829
|
} catch (error48) {
|
|
107565
107830
|
if (context.signal?.aborted) return { reported, rounds, nextAsks: asks };
|
|
107566
107831
|
const failedCode = errorCode3(error48) || "history_evidence_read_failed";
|
|
107567
|
-
historyBackoffUntil.set(
|
|
107832
|
+
historyBackoffUntil.set(profileKey2, Date.now() + HISTORY_RETRY_MS);
|
|
107568
107833
|
appendRuntimeDebugEvent({
|
|
107569
107834
|
label: "client_history_evidence_failed",
|
|
107570
|
-
note: `profile_id=${
|
|
107835
|
+
note: `profile_id=${profileKey2} rounds=${rounds} code=${failedCode}`,
|
|
107571
107836
|
outcome: "error"
|
|
107572
107837
|
});
|
|
107573
107838
|
return { reported, rounds, nextAsks: asks, failedCode };
|
|
107574
107839
|
} finally {
|
|
107575
|
-
runningProfiles.delete(
|
|
107840
|
+
runningProfiles.delete(profileKey2);
|
|
107576
107841
|
}
|
|
107577
107842
|
};
|
|
107578
107843
|
}
|
|
@@ -107618,11 +107883,11 @@ var init_portfolio_evidence = __esm({
|
|
|
107618
107883
|
errorCode4 = (error48) => String(error48?.code ?? "").trim();
|
|
107619
107884
|
runClientPortfolioReport = async (context) => {
|
|
107620
107885
|
const wallet = String(context.walletAddress ?? "").trim();
|
|
107621
|
-
const
|
|
107622
|
-
if (context.due !== true || !wallet || !
|
|
107623
|
-
if (Date.now() < (portfolioBackoffUntil.get(
|
|
107624
|
-
if (runningProfiles2.has(
|
|
107625
|
-
runningProfiles2.add(
|
|
107886
|
+
const profileKey2 = String(context.profileId).trim();
|
|
107887
|
+
if (context.due !== true || !wallet || !profileKey2) return { reported: false };
|
|
107888
|
+
if (Date.now() < (portfolioBackoffUntil.get(profileKey2) ?? 0)) return { reported: false, skipped: "backoff" };
|
|
107889
|
+
if (runningProfiles2.has(profileKey2)) return { reported: false, skipped: "busy" };
|
|
107890
|
+
runningProfiles2.add(profileKey2);
|
|
107626
107891
|
try {
|
|
107627
107892
|
const startedAtMonotonicMs = monotonicNowMs();
|
|
107628
107893
|
const body = await fetchBrowserHyperliquidInfoText(
|
|
@@ -107638,25 +107903,25 @@ var init_portfolio_evidence = __esm({
|
|
|
107638
107903
|
observed_age_ms: monotonicAgeMs(startedAtMonotonicMs),
|
|
107639
107904
|
body
|
|
107640
107905
|
});
|
|
107641
|
-
portfolioBackoffUntil.delete(
|
|
107906
|
+
portfolioBackoffUntil.delete(profileKey2);
|
|
107642
107907
|
const reported = Number(answer?.accepted ?? 0) > 0;
|
|
107643
107908
|
appendRuntimeDebugEvent({
|
|
107644
107909
|
label: "client_portfolio_evidence_reported",
|
|
107645
|
-
note: `profile_id=${
|
|
107910
|
+
note: `profile_id=${profileKey2} accepted=${String(reported)} published=${String(Boolean(answer?.published))} ignored=${answer?.ignored ?? "none"}`
|
|
107646
107911
|
});
|
|
107647
107912
|
return { reported, published: Boolean(answer?.published) };
|
|
107648
107913
|
} catch (error48) {
|
|
107649
107914
|
if (context.signal?.aborted) return { reported: false };
|
|
107650
107915
|
const failedCode = errorCode4(error48) || "portfolio_evidence_read_failed";
|
|
107651
|
-
portfolioBackoffUntil.set(
|
|
107916
|
+
portfolioBackoffUntil.set(profileKey2, Date.now() + PORTFOLIO_RETRY_MS);
|
|
107652
107917
|
appendRuntimeDebugEvent({
|
|
107653
107918
|
label: "client_portfolio_evidence_failed",
|
|
107654
|
-
note: `profile_id=${
|
|
107919
|
+
note: `profile_id=${profileKey2} code=${failedCode}`,
|
|
107655
107920
|
outcome: "error"
|
|
107656
107921
|
});
|
|
107657
107922
|
return { reported: false, failedCode };
|
|
107658
107923
|
} finally {
|
|
107659
|
-
runningProfiles2.delete(
|
|
107924
|
+
runningProfiles2.delete(profileKey2);
|
|
107660
107925
|
}
|
|
107661
107926
|
};
|
|
107662
107927
|
}
|
|
@@ -109013,6 +109278,87 @@ var init_client_account_report = __esm({
|
|
|
109013
109278
|
}
|
|
109014
109279
|
});
|
|
109015
109280
|
|
|
109281
|
+
// lib/api/server-host-prompt-rescue.ts
|
|
109282
|
+
async function requestServerHostPromptRescue(profileId, payload, options) {
|
|
109283
|
+
return postClientRuntime(
|
|
109284
|
+
"/runtime/server-prompt-rescue",
|
|
109285
|
+
profileId,
|
|
109286
|
+
buildClientRuntimeBody(payload, {
|
|
109287
|
+
analysis_run_id: payload.analysisRunId,
|
|
109288
|
+
cycle_id: payload.cycleId,
|
|
109289
|
+
symbol: payload.symbol,
|
|
109290
|
+
symbols: payload.symbols,
|
|
109291
|
+
request_sequence: payload.requestSequence,
|
|
109292
|
+
server_reason: payload.serverReason
|
|
109293
|
+
}, { includeForceTakeover: false }),
|
|
109294
|
+
options
|
|
109295
|
+
);
|
|
109296
|
+
}
|
|
109297
|
+
var init_server_host_prompt_rescue = __esm({
|
|
109298
|
+
"lib/api/server-host-prompt-rescue.ts"() {
|
|
109299
|
+
"use strict";
|
|
109300
|
+
init_define_VTX_EXO_POLICY();
|
|
109301
|
+
init_define_VTX_GROK_POLICY();
|
|
109302
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
109303
|
+
init_api2();
|
|
109304
|
+
}
|
|
109305
|
+
});
|
|
109306
|
+
|
|
109307
|
+
// lib/runtime/server-prompt-rescue-snapshot.ts
|
|
109308
|
+
var accountStateFromServerPromptRescueSnapshot;
|
|
109309
|
+
var init_server_prompt_rescue_snapshot = __esm({
|
|
109310
|
+
"lib/runtime/server-prompt-rescue-snapshot.ts"() {
|
|
109311
|
+
"use strict";
|
|
109312
|
+
init_define_VTX_EXO_POLICY();
|
|
109313
|
+
init_define_VTX_GROK_POLICY();
|
|
109314
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
109315
|
+
init_hyperliquid_market_symbol();
|
|
109316
|
+
accountStateFromServerPromptRescueSnapshot = (snapshot, symbol2) => {
|
|
109317
|
+
const capturedAtMs = Date.parse(snapshot.captured_at);
|
|
109318
|
+
if (!Number.isFinite(capturedAtMs)) {
|
|
109319
|
+
throw new Error("Server prompt rescue timestamp is invalid.");
|
|
109320
|
+
}
|
|
109321
|
+
const positions = snapshot.positions.map((position) => ({
|
|
109322
|
+
symbol: position.symbol,
|
|
109323
|
+
dex: position.dex,
|
|
109324
|
+
coin: position.coin ?? null,
|
|
109325
|
+
base_symbol: position.base_symbol ?? null,
|
|
109326
|
+
market_type: position.market_type,
|
|
109327
|
+
size: position.size,
|
|
109328
|
+
entry_price: position.entry_price ?? null,
|
|
109329
|
+
unrealized_pnl: position.unrealized_pnl ?? null,
|
|
109330
|
+
realized_pnl: position.realized_pnl ?? null,
|
|
109331
|
+
leverage: position.leverage ?? null,
|
|
109332
|
+
margin_used: position.margin_used ?? null,
|
|
109333
|
+
liquidation_price: position.liquidation_price ?? null,
|
|
109334
|
+
funding_usdc: position.funding_usdc ?? null
|
|
109335
|
+
}));
|
|
109336
|
+
return {
|
|
109337
|
+
evidence: {
|
|
109338
|
+
source: "live",
|
|
109339
|
+
fetchedAtMs: capturedAtMs,
|
|
109340
|
+
observedAtMs: Date.now(),
|
|
109341
|
+
cacheAgeMs: 0,
|
|
109342
|
+
freshnessLimitMs: null
|
|
109343
|
+
},
|
|
109344
|
+
accountSummary: snapshot.account_summary,
|
|
109345
|
+
availableToTrade: {
|
|
109346
|
+
symbol: normalizeHyperliquidMarketSymbol(symbol2),
|
|
109347
|
+
available_to_trade_buy: 0,
|
|
109348
|
+
available_to_trade_sell: 0,
|
|
109349
|
+
max_trade_size_buy: 0,
|
|
109350
|
+
max_trade_size_sell: 0,
|
|
109351
|
+
mark_price: 0,
|
|
109352
|
+
source: "fallback"
|
|
109353
|
+
},
|
|
109354
|
+
positions,
|
|
109355
|
+
...snapshot.taker_rate == null ? {} : { takerRate: snapshot.taker_rate },
|
|
109356
|
+
...snapshot.effective_taker_rates == null ? {} : { effectiveTakerRates: { ...snapshot.effective_taker_rates } }
|
|
109357
|
+
};
|
|
109358
|
+
};
|
|
109359
|
+
}
|
|
109360
|
+
});
|
|
109361
|
+
|
|
109016
109362
|
// lib/runtime/google-egress.ts
|
|
109017
109363
|
function googleEgressPolicyForModel(policy2, model) {
|
|
109018
109364
|
if (!policy2?.enabled) return void 0;
|
|
@@ -109261,6 +109607,14 @@ function applyNativeRequestParameters(requestBody, parameters, selectedValues, a
|
|
|
109261
109607
|
}
|
|
109262
109608
|
return next;
|
|
109263
109609
|
}
|
|
109610
|
+
function hasUserSelectedNativeRequestParameters(parameters, selectedValues, apiSurface) {
|
|
109611
|
+
if (!selectedValues) return false;
|
|
109612
|
+
return (parameters || []).some((parameter) => {
|
|
109613
|
+
if (parameter.api_surface !== apiSurface || parameter.app_managed || !parameter.user_visible) return false;
|
|
109614
|
+
const value = selectedValues[nativeParameterIdentity(parameter)];
|
|
109615
|
+
return value !== null && value !== void 0 && value !== "";
|
|
109616
|
+
});
|
|
109617
|
+
}
|
|
109264
109618
|
function filterNativeRequestParameterValues(parameters, values, options = {}) {
|
|
109265
109619
|
const selectedValues = values || {};
|
|
109266
109620
|
const filtered = {};
|
|
@@ -109335,7 +109689,7 @@ var init_native_request_parameters = __esm({
|
|
|
109335
109689
|
});
|
|
109336
109690
|
|
|
109337
109691
|
// lib/runtime/provider-client.ts
|
|
109338
|
-
var mapOpenAiCompatibleNativeRequestPath, isRetryableProviderFailureForFallback, extractRuntimeProviderFailureStatusCode, isModelSpecificProviderFailure, isKeySpecificOrTransientProviderFailure, providerDispatchClockMs, beginProviderDispatch, providerDispatchLatencyMs, attachProviderDispatchFailure, attachProviderFailureTrace, toRuntimeExecutionMode, buildNoneReasoningPayload, normalizeLevelValue, buildRuntimeReasoningPayload, resolveProviderReasoningParameters, requestedReasoningParameters, usesReasoningCompletionTokens, shouldRequestReasoningTrace, normalizeProviderToken, runtimeProviderForByokProvider, findByokProviderForRuntime, findNativeRequestParametersForModel, modelHasNativeRequestApiSurface, setDottedRequestValue, normalizeProviderMaxTokens, applyRuntimeRequestContract, normalizeProvider2, requireProviderEndpoint, SSE_DATA_FIELD_PREFIX2, estimateTokenCount, normalizeUsageCount, buildOpenAiUsagePayload, buildAnthropicUsagePayload, buildGoogleUsagePayload, normalizeProviderUsageMetrics, providerResponseSignals, fetchProvider, readProviderPayload, emitRuntimeDelta, readProviderTextStream, extractOpenAiCompatibleDeltaText, readOpenAiCompatibleTextStream, rawProviderTextForDebug, extractProviderErrorDetail, buildCanonicalProviderFailureMessage, toProviderNetworkDebugError, REASONING_ONLY_CONTENT_TYPES, extractOpenAiContentPartText, extractOpenAiReasoningPartText, extractOpenAiMessageContent, extractOpenAiMessageReasoningContent, extractOpenAiCompatibleText, normalizeRuntimeChatHistory, calculateProviderCost, callOpenAiCompatible, extractOpenAiResponsesText, extractOpenAiResponsesReasoning, callOpenAiResponses, extractAnthropicMessageText, extractAnthropicReasoningContent, callAnthropic, isVertexExpressKey, googlePublicModelIdRegexes, shouldUseGooglePublicEndpointForModel, normalizeGoogleModelId, shouldRetryGoogleVertexRequestPublicly, GOOGLE_VERTEX_PUBLIC_RETRY_NOTE, buildGoogleRequest, isGoogleReasoningPart, extractGoogleMessageText, extractGoogleReasoningContent, extractGoogleSafetyMetadata, GOOGLE_BLOCKED_FINISH_REASONS, googleProviderBlockReason, callGoogle, resolveRuntimeProvider, defaultInvocationContext, defaultProviderTransport, invocationFailureCode, buildBrowserInvocation, resolveProviderSecretKey, resolveNativeProviderCredentialSlots, resolveProviderSecretKeySlots, requireOpenAiCompatibleRuntimeBaseUrl, runtimeSubscriptionPlan, runtimeKeySlotSupportsModel, invokeRuntimeProviderAttempt, runtimeProviderInvoker, invokeRuntimeProvider;
|
|
109692
|
+
var mapOpenAiCompatibleNativeRequestPath, isRetryableProviderFailureForFallback, extractRuntimeProviderFailureStatusCode, isModelSpecificProviderFailure, emptyProviderContentError, isEmptyProviderContentFailure, emptyReplyForInternalAttempt, isEmptyProviderMessageFailure, isRetryableProviderAttemptFailure, providerRejectedRequestError, OPTIONAL_CONTRACT_PARAMETER_TOKENS, OPTIONAL_CONTRACT_REJECTION_TOKENS, OPTIONAL_CONTRACT_GRAMMAR_TOKENS, isOptionalContractParameterRejection, OPTIONAL_CONTRACT_REQUEST_KEYS, OPTIONAL_CONTRACT_EXTRA_BODY_KEYS, resolveEmptyContentRetryPolicy, isKeySpecificOrTransientProviderFailure, providerDispatchClockMs, beginProviderDispatch, providerDispatchLatencyMs, attachProviderDispatchFailure, attachProviderFailureTrace, toRuntimeExecutionMode, buildNoneReasoningPayload, normalizeLevelValue, buildRuntimeReasoningPayload, resolveProviderReasoningParameters, requestedReasoningParameters, usesReasoningCompletionTokens, shouldRequestReasoningTrace, normalizeProviderToken, runtimeProviderForByokProvider, findByokProviderForRuntime, findNativeRequestParametersForModel, modelHasNativeRequestApiSurface, asRequestRecord, setDottedRequestValue, normalizeProviderMaxTokens, applyRuntimeRequestContract, normalizeProvider2, requireProviderEndpoint, SSE_DATA_FIELD_PREFIX2, estimateTokenCount, normalizeUsageCount, buildOpenAiUsagePayload, buildAnthropicUsagePayload, buildGoogleUsagePayload, normalizeProviderUsageMetrics, providerResponseSignals, fetchProvider, readProviderPayload, emitRuntimeDelta, readProviderTextStream, extractOpenAiCompatibleDeltaText, readOpenAiCompatibleTextStream, rawProviderTextForDebug, extractProviderErrorDetail, buildCanonicalProviderFailureMessage, toProviderNetworkDebugError, REASONING_ONLY_CONTENT_TYPES, extractOpenAiContentPartText, extractOpenAiReasoningPartText, extractOpenAiMessageContent, extractOpenAiMessageReasoningContent, extractOpenAiCompatibleText, normalizeRuntimeChatHistory, calculateProviderCost, callOpenAiCompatible, extractOpenAiResponsesText, extractOpenAiResponsesReasoning, callOpenAiResponses, extractAnthropicMessageText, extractAnthropicReasoningContent, callAnthropic, isVertexExpressKey, googlePublicModelIdRegexes, shouldUseGooglePublicEndpointForModel, normalizeGoogleModelId, shouldRetryGoogleVertexRequestPublicly, GOOGLE_VERTEX_PUBLIC_RETRY_NOTE, buildGoogleRequest, isGoogleReasoningPart, extractGoogleMessageText, extractGoogleReasoningContent, extractGoogleSafetyMetadata, GOOGLE_BLOCKED_FINISH_REASONS, googleProviderBlockReason, callGoogle, resolveRuntimeProvider, defaultInvocationContext, defaultProviderTransport, invocationFailureCode, buildBrowserInvocation, resolveProviderSecretKey, resolveNativeProviderCredentialSlots, resolveProviderSecretKeySlots, requireOpenAiCompatibleRuntimeBaseUrl, runtimeSubscriptionPlan, runtimeKeySlotSupportsModel, invokeRuntimeProviderAttempt, runtimeProviderInvoker, invokeRuntimeProvider;
|
|
109339
109693
|
var init_provider_client = __esm({
|
|
109340
109694
|
"lib/runtime/provider-client.ts"() {
|
|
109341
109695
|
"use strict";
|
|
@@ -109390,6 +109744,58 @@ var init_provider_client = __esm({
|
|
|
109390
109744
|
"no route to model"
|
|
109391
109745
|
].some((token) => normalized.includes(token));
|
|
109392
109746
|
};
|
|
109747
|
+
emptyProviderContentError = (message, reply) => Object.assign(new Error(message), {
|
|
109748
|
+
runtimeEmptyProviderContent: true,
|
|
109749
|
+
// Kept for the in-place retry's own row only (Venice): a model's final
|
|
109750
|
+
// empty reply is recorded with no result and never priced, as in Server Mode.
|
|
109751
|
+
...reply ? { runtimeEmptyProviderReply: reply.result, runtimeEmptyProviderMessage: reply.emptyMessage } : {}
|
|
109752
|
+
});
|
|
109753
|
+
isEmptyProviderContentFailure = (error48) => error48?.runtimeEmptyProviderContent === true;
|
|
109754
|
+
emptyReplyForInternalAttempt = (error48) => {
|
|
109755
|
+
const reply = error48?.runtimeEmptyProviderReply;
|
|
109756
|
+
return reply ? { ...reply, reasoningContent: null } : null;
|
|
109757
|
+
};
|
|
109758
|
+
isEmptyProviderMessageFailure = (error48) => error48?.runtimeEmptyProviderMessage === true;
|
|
109759
|
+
isRetryableProviderAttemptFailure = (failure2) => failure2.emptyContent || failure2.nativeFailureKind !== void 0 || failure2.statusCode === HTTP_STATUS.REQUEST_TIMEOUT || isRetryableProviderFailureForFallback(failure2.detail);
|
|
109760
|
+
providerRejectedRequestError = (message, detail) => Object.assign(new Error(message), { runtimeProviderRejectionDetail: String(detail || message) });
|
|
109761
|
+
OPTIONAL_CONTRACT_PARAMETER_TOKENS = [
|
|
109762
|
+
"response_format",
|
|
109763
|
+
"venice_parameters",
|
|
109764
|
+
"strip_thinking_response",
|
|
109765
|
+
"disable_thinking",
|
|
109766
|
+
"reasoning_effort",
|
|
109767
|
+
"thinking_budget",
|
|
109768
|
+
"thinking_level",
|
|
109769
|
+
"extra_body"
|
|
109770
|
+
];
|
|
109771
|
+
OPTIONAL_CONTRACT_REJECTION_TOKENS = [
|
|
109772
|
+
"unexpected keyword argument",
|
|
109773
|
+
"unknown parameter",
|
|
109774
|
+
"unsupported parameter",
|
|
109775
|
+
"not supported",
|
|
109776
|
+
"invalid parameter",
|
|
109777
|
+
"extra fields not permitted",
|
|
109778
|
+
"not permitted"
|
|
109779
|
+
];
|
|
109780
|
+
OPTIONAL_CONTRACT_GRAMMAR_TOKENS = ["failed to transform json schema into a grammar", "json_schema_converter"];
|
|
109781
|
+
isOptionalContractParameterRejection = (error48) => {
|
|
109782
|
+
const detail = error48?.runtimeProviderRejectionDetail;
|
|
109783
|
+
if (typeof detail !== "string" || !detail) return false;
|
|
109784
|
+
const normalized = detail.toLowerCase();
|
|
109785
|
+
if (OPTIONAL_CONTRACT_GRAMMAR_TOKENS.some((token) => normalized.includes(token))) return true;
|
|
109786
|
+
return OPTIONAL_CONTRACT_PARAMETER_TOKENS.some((token) => normalized.includes(token)) && OPTIONAL_CONTRACT_REJECTION_TOKENS.some((token) => normalized.includes(token));
|
|
109787
|
+
};
|
|
109788
|
+
OPTIONAL_CONTRACT_REQUEST_KEYS = ["response_format", "reasoning_effort", "reasoning_format"];
|
|
109789
|
+
OPTIONAL_CONTRACT_EXTRA_BODY_KEYS = ["thinking_level", "thinking_budget", "reasoning", "include_reasoning", "venice_parameters"];
|
|
109790
|
+
resolveEmptyContentRetryPolicy = (config2) => {
|
|
109791
|
+
const policy2 = config2.empty_content_retry;
|
|
109792
|
+
if (policy2 === void 0 || policy2 === null) return null;
|
|
109793
|
+
const values = [policy2.max_retries, policy2.delay_seconds, policy2.jitter_min_seconds, policy2.jitter_max_seconds];
|
|
109794
|
+
if (values.some((value) => typeof value !== "number" || !Number.isFinite(value) || value < 0) || !Number.isInteger(policy2.max_retries) || policy2.jitter_max_seconds < policy2.jitter_min_seconds) {
|
|
109795
|
+
throw new Error("Missing or invalid config key: empty_content_retry");
|
|
109796
|
+
}
|
|
109797
|
+
return policy2;
|
|
109798
|
+
};
|
|
109393
109799
|
isKeySpecificOrTransientProviderFailure = (detail) => {
|
|
109394
109800
|
const normalized = String(detail || "").toLowerCase();
|
|
109395
109801
|
return isRetryableProviderFailureForFallback(detail) || normalized.includes("http 401") || normalized.includes("http 403") || normalized.includes("(401)") || normalized.includes("(403)") || normalized.includes("unauthorized") || normalized.includes("forbidden") || normalized.includes("permission") || normalized.includes("quota");
|
|
@@ -109725,6 +110131,7 @@ var init_provider_client = __esm({
|
|
|
109725
110131
|
modelHasNativeRequestApiSurface = (config2, provider, model, apiSurface) => findNativeRequestParametersForModel(config2, provider, model).some(
|
|
109726
110132
|
(parameter) => parameter.api_surface === apiSurface
|
|
109727
110133
|
);
|
|
110134
|
+
asRequestRecord = (value) => value && typeof value === "object" && !Array.isArray(value) ? value : {};
|
|
109728
110135
|
setDottedRequestValue = (target, path, value) => {
|
|
109729
110136
|
const segments = path.split(".").map((segment) => segment.trim()).filter(Boolean);
|
|
109730
110137
|
if (segments.length === 0) return;
|
|
@@ -109995,7 +110402,7 @@ var init_provider_client = __esm({
|
|
|
109995
110402
|
const { payload, rawText: rawText2 } = await readProviderPayload(response);
|
|
109996
110403
|
onPayload?.(payload);
|
|
109997
110404
|
const detail = extractProviderErrorDetail(payload, rawText2);
|
|
109998
|
-
throw
|
|
110405
|
+
throw providerRejectedRequestError(buildCanonicalProviderFailureMessage({ response, detail, runtimeMode }), detail);
|
|
109999
110406
|
}
|
|
110000
110407
|
let content = "";
|
|
110001
110408
|
let reasoningContent = "";
|
|
@@ -110054,7 +110461,7 @@ var init_provider_client = __esm({
|
|
|
110054
110461
|
});
|
|
110055
110462
|
const finalContent = content.trim();
|
|
110056
110463
|
if (!finalContent) {
|
|
110057
|
-
throw
|
|
110464
|
+
throw emptyProviderContentError("Provider response did not include any message content.");
|
|
110058
110465
|
}
|
|
110059
110466
|
return {
|
|
110060
110467
|
rawText,
|
|
@@ -110243,12 +110650,9 @@ var init_provider_client = __esm({
|
|
|
110243
110650
|
}).filter((call) => Boolean(call));
|
|
110244
110651
|
if (!response.ok) {
|
|
110245
110652
|
const detail = extractProviderErrorDetail(payload, rawText);
|
|
110246
|
-
throw
|
|
110247
|
-
}
|
|
110248
|
-
if (!content && toolCalls.length === 0) {
|
|
110249
|
-
throw new Error("Provider response did not include any message content.");
|
|
110653
|
+
throw providerRejectedRequestError(buildCanonicalProviderFailureMessage({ response, detail, runtimeMode }), detail);
|
|
110250
110654
|
}
|
|
110251
|
-
|
|
110655
|
+
const result = {
|
|
110252
110656
|
content: content || "",
|
|
110253
110657
|
reasoningContent,
|
|
110254
110658
|
toolCalls,
|
|
@@ -110267,6 +110671,13 @@ var init_provider_client = __esm({
|
|
|
110267
110671
|
refusalStatus: typeof message?.refusal === "string" && message.refusal.trim() ? "refused" : "none",
|
|
110268
110672
|
reasoningTraceSource: reasoningContent ? "provider_native" : "none"
|
|
110269
110673
|
};
|
|
110674
|
+
if (!content && toolCalls.length === 0) {
|
|
110675
|
+
throw emptyProviderContentError("Provider response did not include any message content.", {
|
|
110676
|
+
result,
|
|
110677
|
+
emptyMessage: Array.isArray(payload?.choices) && payload.choices.length > 0
|
|
110678
|
+
});
|
|
110679
|
+
}
|
|
110680
|
+
return result;
|
|
110270
110681
|
};
|
|
110271
110682
|
normalizeRuntimeChatHistory = (messages) => {
|
|
110272
110683
|
if (!Array.isArray(messages)) {
|
|
@@ -110365,6 +110776,7 @@ var init_provider_client = __esm({
|
|
|
110365
110776
|
});
|
|
110366
110777
|
let response = null;
|
|
110367
110778
|
let dispatchMarker = null;
|
|
110779
|
+
const internalDispatchAttempts = [];
|
|
110368
110780
|
try {
|
|
110369
110781
|
const reasoningParams = resolveProviderReasoningParameters(provider, reasoningPayload);
|
|
110370
110782
|
const useReasoningCompletionTokens = usesReasoningCompletionTokens(provider, reasoningParams);
|
|
@@ -110498,50 +110910,131 @@ var init_provider_client = __esm({
|
|
|
110498
110910
|
if (useRelay && configuredPlans?.length && !relayPlan) {
|
|
110499
110911
|
throw new Error(`The selected ${provider} endpoint does not match a configured plan.`);
|
|
110500
110912
|
}
|
|
110501
|
-
|
|
110502
|
-
|
|
110503
|
-
|
|
110504
|
-
|
|
110505
|
-
|
|
110506
|
-
|
|
110507
|
-
|
|
110508
|
-
|
|
110509
|
-
|
|
110510
|
-
|
|
110511
|
-
|
|
110512
|
-
|
|
110513
|
-
|
|
110514
|
-
|
|
110515
|
-
|
|
110516
|
-
trace.attachResponse({
|
|
110517
|
-
status: response?.status ?? null,
|
|
110518
|
-
statusText: response?.statusText ?? "",
|
|
110519
|
-
body: null,
|
|
110520
|
-
rawText: rawProviderTextForDebug(null, rawText)
|
|
110913
|
+
const dispatch = async (body) => {
|
|
110914
|
+
if (body !== finalRequestBody) trace.attachRequest({ url: requestUrl, method: "POST", headers: requestHeaders, body });
|
|
110915
|
+
response = null;
|
|
110916
|
+
const marker = beginProviderDispatch(body);
|
|
110917
|
+
dispatchMarker = marker;
|
|
110918
|
+
const dispatched = useRelay ? await relayNativeProviderRequest(provider, String(apiKey || "").trim(), body, {
|
|
110919
|
+
profileId: profileId == null ? void 0 : Number(profileId),
|
|
110920
|
+
signal,
|
|
110921
|
+
planId: relayPlan?.id,
|
|
110922
|
+
traceId: trace.id
|
|
110923
|
+
}) : await fetchProvider(requestUrl, {
|
|
110924
|
+
method: "POST",
|
|
110925
|
+
headers: requestHeaders,
|
|
110926
|
+
body: JSON.stringify(body),
|
|
110927
|
+
signal
|
|
110521
110928
|
});
|
|
110522
|
-
|
|
110523
|
-
|
|
110524
|
-
|
|
110525
|
-
|
|
110526
|
-
|
|
110527
|
-
|
|
110528
|
-
|
|
110529
|
-
|
|
110929
|
+
response = dispatched;
|
|
110930
|
+
const payload = typeof onDelta === "function" ? await readOpenAiCompatibleTextStream(dispatched, runtimeMode, onDelta, (rawPayload) => {
|
|
110931
|
+
Object.assign(marker.effectiveReasoningParameters, extractProviderReasoningParameters(rawPayload));
|
|
110932
|
+
}).then(({ payload: streamPayload, rawText }) => {
|
|
110933
|
+
trace.attachResponse({
|
|
110934
|
+
status: dispatched.status,
|
|
110935
|
+
statusText: dispatched.statusText ?? "",
|
|
110936
|
+
body: null,
|
|
110937
|
+
rawText: rawProviderTextForDebug(null, rawText)
|
|
110938
|
+
});
|
|
110939
|
+
return streamPayload;
|
|
110940
|
+
}) : await extractOpenAiCompatibleText(dispatched, runtimeMode, (payloadJson, rawText) => {
|
|
110941
|
+
marker.effectiveReasoningParameters = extractProviderReasoningParameters(payloadJson);
|
|
110942
|
+
trace.attachResponse({
|
|
110943
|
+
status: dispatched.status,
|
|
110944
|
+
statusText: dispatched.statusText ?? "",
|
|
110945
|
+
body: payloadJson,
|
|
110946
|
+
rawText: rawProviderTextForDebug(payloadJson, rawText)
|
|
110947
|
+
});
|
|
110948
|
+
});
|
|
110949
|
+
return {
|
|
110950
|
+
...payload,
|
|
110951
|
+
sentReasoningParameters: marker.sentReasoningParameters,
|
|
110952
|
+
effectiveReasoningParameters: marker.effectiveReasoningParameters,
|
|
110953
|
+
requestInputTokens: marker.requestInputTokens,
|
|
110954
|
+
providerDiagnostics: marker.providerDiagnostics,
|
|
110955
|
+
providerStatusCode: dispatched.status,
|
|
110956
|
+
dispatchStartedAt: marker.startedAt,
|
|
110957
|
+
dispatchLatencyMs: providerDispatchLatencyMs(marker)
|
|
110958
|
+
};
|
|
110959
|
+
};
|
|
110960
|
+
const attemptDispatch = async (body) => {
|
|
110961
|
+
try {
|
|
110962
|
+
return { ok: true, payload: await dispatch(body) };
|
|
110963
|
+
} catch (error48) {
|
|
110964
|
+
return { ok: false, error: error48 };
|
|
110965
|
+
}
|
|
110966
|
+
};
|
|
110967
|
+
const recordInternalRetry = (error48) => {
|
|
110968
|
+
if (!dispatchMarker) return;
|
|
110969
|
+
internalDispatchAttempts.push({
|
|
110970
|
+
sentReasoningParameters: dispatchMarker.sentReasoningParameters,
|
|
110971
|
+
effectiveReasoningParameters: dispatchMarker.effectiveReasoningParameters,
|
|
110972
|
+
startedAt: dispatchMarker.startedAt,
|
|
110973
|
+
latencyMs: providerDispatchLatencyMs(dispatchMarker),
|
|
110974
|
+
transport: "openai_compatible_chat_completions",
|
|
110975
|
+
requestInputTokens: dispatchMarker.requestInputTokens,
|
|
110976
|
+
providerDiagnostics: dispatchMarker.providerDiagnostics,
|
|
110977
|
+
providerRequestId: providerRequestId(response),
|
|
110978
|
+
errorDetail: getSanitizedRuntimeErrorMessage(error48) || "Provider compatibility dispatch failed.",
|
|
110979
|
+
// An empty reply is an unknown outcome with no status, as in Server Mode.
|
|
110980
|
+
statusCode: isEmptyProviderContentFailure(error48) ? null : response?.status ?? null,
|
|
110981
|
+
retryable: isEmptyProviderContentFailure(error48),
|
|
110982
|
+
response: emptyReplyForInternalAttempt(error48)
|
|
110530
110983
|
});
|
|
110531
|
-
});
|
|
110532
|
-
trace.completeSuccess(response.status);
|
|
110533
|
-
return {
|
|
110534
|
-
...payload,
|
|
110535
|
-
sentReasoningParameters: dispatchMarker.sentReasoningParameters,
|
|
110536
|
-
effectiveReasoningParameters: dispatchMarker.effectiveReasoningParameters,
|
|
110537
|
-
requestInputTokens: dispatchMarker.requestInputTokens,
|
|
110538
|
-
providerDiagnostics: dispatchMarker.providerDiagnostics,
|
|
110539
|
-
providerStatusCode: response.status,
|
|
110540
|
-
dispatchStartedAt: dispatchMarker.startedAt,
|
|
110541
|
-
dispatchLatencyMs: providerDispatchLatencyMs(dispatchMarker)
|
|
110542
110984
|
};
|
|
110985
|
+
let dispatchedBody = finalRequestBody;
|
|
110986
|
+
let outcome = await attemptDispatch(dispatchedBody);
|
|
110987
|
+
if (!outcome.ok && !signal?.aborted && isOptionalContractParameterRejection(outcome.error)) {
|
|
110988
|
+
const withoutExtraBody = Object.fromEntries(
|
|
110989
|
+
Object.entries(requestBody).filter(([key]) => !OPTIONAL_CONTRACT_EXTRA_BODY_KEYS.includes(key))
|
|
110990
|
+
);
|
|
110991
|
+
const fallbackBody = applyNativeRequestParameters(
|
|
110992
|
+
withoutExtraBody,
|
|
110993
|
+
(nativeRequestParameters ?? []).filter((parameter) => parameter.request_path !== "extra_body" && !parameter.request_path.startsWith("extra_body.")),
|
|
110994
|
+
nativeRequestParameterValues,
|
|
110995
|
+
"openai_compatible_chat_completions",
|
|
110996
|
+
{ includeAppManaged: true, mapRequestPath: mapOpenAiCompatibleNativeRequestPath }
|
|
110997
|
+
);
|
|
110998
|
+
for (const key of OPTIONAL_CONTRACT_REQUEST_KEYS) delete fallbackBody[key];
|
|
110999
|
+
const hadOptionalContractArguments = Object.keys(finalRequestBody).some((key) => !(key in fallbackBody));
|
|
111000
|
+
if (hadOptionalContractArguments && !hasUserSelectedNativeRequestParameters(
|
|
111001
|
+
nativeRequestParameters,
|
|
111002
|
+
nativeRequestParameterValues,
|
|
111003
|
+
"openai_compatible_chat_completions"
|
|
111004
|
+
)) {
|
|
111005
|
+
recordInternalRetry(outcome.error);
|
|
111006
|
+
appendRuntimeDebugEvent({
|
|
111007
|
+
label: "optional_contract_arguments_rejected_retry",
|
|
111008
|
+
note: `provider=${provider} model=${model}`,
|
|
111009
|
+
outcome: "error"
|
|
111010
|
+
});
|
|
111011
|
+
dispatchedBody = fallbackBody;
|
|
111012
|
+
outcome = await attemptDispatch(dispatchedBody);
|
|
111013
|
+
}
|
|
111014
|
+
}
|
|
111015
|
+
if (!outcome.ok && provider === "venice" && typeof onDelta !== "function" && !signal?.aborted && isEmptyProviderMessageFailure(outcome.error)) {
|
|
111016
|
+
recordInternalRetry(outcome.error);
|
|
111017
|
+
appendRuntimeDebugEvent({
|
|
111018
|
+
label: "venice_empty_content_thinking_disabled_retry",
|
|
111019
|
+
note: `model=${model}`,
|
|
111020
|
+
outcome: "error"
|
|
111021
|
+
});
|
|
111022
|
+
dispatchedBody = {
|
|
111023
|
+
...dispatchedBody,
|
|
111024
|
+
venice_parameters: {
|
|
111025
|
+
...asRequestRecord(dispatchedBody.venice_parameters),
|
|
111026
|
+
strip_thinking_response: true,
|
|
111027
|
+
disable_thinking: true
|
|
111028
|
+
}
|
|
111029
|
+
};
|
|
111030
|
+
outcome = await attemptDispatch(dispatchedBody);
|
|
111031
|
+
}
|
|
111032
|
+
if (!outcome.ok) throw outcome.error;
|
|
111033
|
+
trace.completeSuccess(outcome.payload.providerStatusCode ?? null);
|
|
111034
|
+
return { ...outcome.payload, internalDispatchAttempts };
|
|
110543
111035
|
} catch (error48) {
|
|
110544
111036
|
const sanitizedError = attachProviderDispatchFailure(error48, dispatchMarker, response);
|
|
111037
|
+
sanitizedError.runtimeInternalDispatchAttempts = internalDispatchAttempts;
|
|
110545
111038
|
trace.completeError(toProviderNetworkDebugError(sanitizedError), response?.status ?? null);
|
|
110546
111039
|
throw attachProviderFailureTrace(sanitizedError, trace.id);
|
|
110547
111040
|
}
|
|
@@ -110643,7 +111136,7 @@ var init_provider_client = __esm({
|
|
|
110643
111136
|
}
|
|
110644
111137
|
const text = extractOpenAiResponsesText(payload);
|
|
110645
111138
|
if (!text) {
|
|
110646
|
-
throw
|
|
111139
|
+
throw emptyProviderContentError("OpenAI Responses API did not include any text content.");
|
|
110647
111140
|
}
|
|
110648
111141
|
trace.completeSuccess(response.status);
|
|
110649
111142
|
return {
|
|
@@ -110790,7 +111283,7 @@ var init_provider_client = __esm({
|
|
|
110790
111283
|
}
|
|
110791
111284
|
const text = extractAnthropicMessageText(payload);
|
|
110792
111285
|
if (!text) {
|
|
110793
|
-
throw
|
|
111286
|
+
throw emptyProviderContentError("Anthropic response did not include any text content.");
|
|
110794
111287
|
}
|
|
110795
111288
|
const reasoningContent = extractAnthropicReasoningContent(payload);
|
|
110796
111289
|
const anthropicUsage = buildAnthropicUsagePayload(payload?.usage);
|
|
@@ -111170,7 +111663,7 @@ var init_provider_client = __esm({
|
|
|
111170
111663
|
blockedError.runtimeProviderResult = providerResult;
|
|
111171
111664
|
throw blockedError;
|
|
111172
111665
|
}
|
|
111173
|
-
throw
|
|
111666
|
+
throw emptyProviderContentError("Google response did not include any text content.");
|
|
111174
111667
|
}
|
|
111175
111668
|
trace.completeSuccess(response.status);
|
|
111176
111669
|
return providerResult;
|
|
@@ -111478,6 +111971,8 @@ var init_provider_client = __esm({
|
|
|
111478
111971
|
});
|
|
111479
111972
|
const providerKeySlots = resolveProviderSecretKeySlots(provider, secrets);
|
|
111480
111973
|
let providerKeySlotIndex = Math.max(0, input.providerKeySlotIndex ?? 0);
|
|
111974
|
+
const keySweepStartSlotIndex = input.keySweepStartSlotIndex ?? providerKeySlotIndex;
|
|
111975
|
+
const emptyContentRetryPolicy = resolveEmptyContentRetryPolicy(config2);
|
|
111481
111976
|
if (input.allowFallback !== false) {
|
|
111482
111977
|
const eligibleSlot = providerKeySlots.findIndex((_, index) => index >= providerKeySlotIndex && runtimeKeySlotSupportsModel(config2, secrets, provider, index, model));
|
|
111483
111978
|
if (eligibleSlot >= 0) providerKeySlotIndex = eligibleSlot;
|
|
@@ -111564,6 +112059,7 @@ var init_provider_client = __esm({
|
|
|
111564
112059
|
requestInputTokens: attempt.requestInputTokens,
|
|
111565
112060
|
providerDiagnostics: attempt.providerDiagnostics,
|
|
111566
112061
|
providerRequestId: attempt.providerRequestId,
|
|
112062
|
+
response: attempt.response ?? null,
|
|
111567
112063
|
retryable: attempt.retryable ?? false,
|
|
111568
112064
|
fallbackFrom: chain.at(-1) ?? null
|
|
111569
112065
|
}));
|
|
@@ -111841,7 +112337,7 @@ var init_provider_client = __esm({
|
|
|
111841
112337
|
registerTraderProviderCallFinished(schedulerResourceKey, schedulerOwnerId, failedAtMs - startedAtMs);
|
|
111842
112338
|
const detail = getSanitizedRuntimeErrorMessage(error48) || String(error48 || "unknown provider error");
|
|
111843
112339
|
const nativeFailureKind = error48?.runtimeNativeFailureKind;
|
|
111844
|
-
const statusCode = extractRuntimeProviderFailureStatusCode(error48);
|
|
112340
|
+
const statusCode = isEmptyProviderContentFailure(error48) ? null : extractRuntimeProviderFailureStatusCode(error48);
|
|
111845
112341
|
const rawInternalDispatchAttempts = error48?.runtimeInternalDispatchAttempts;
|
|
111846
112342
|
const observedInvocationAttempts2 = await withInternalDispatchAttempts(
|
|
111847
112343
|
rawInternalDispatchAttempts
|
|
@@ -111902,7 +112398,12 @@ var init_provider_client = __esm({
|
|
|
111902
112398
|
errorDetail: detail,
|
|
111903
112399
|
statusCode,
|
|
111904
112400
|
failureCode: nativeFailureKind === "transport" ? "transport_error" : nativeFailureKind === "timeout" ? "timeout" : signal?.aborted || isAbortLikeError(error48) ? "cancelled" : void 0,
|
|
111905
|
-
retryable:
|
|
112401
|
+
retryable: isRetryableProviderAttemptFailure({
|
|
112402
|
+
detail,
|
|
112403
|
+
statusCode,
|
|
112404
|
+
nativeFailureKind,
|
|
112405
|
+
emptyContent: isEmptyProviderContentFailure(error48)
|
|
112406
|
+
}),
|
|
111906
112407
|
providerCost: failedCostInfo?.costStatus === "unavailable" ? null : failedCostInfo?.cost,
|
|
111907
112408
|
userCost: failedCostInfo?.costStatus === "unavailable" ? null : failedCostInfo?.costUser,
|
|
111908
112409
|
costStatus: failedCostInfo?.costStatus ?? "unavailable",
|
|
@@ -111940,7 +112441,9 @@ var init_provider_client = __esm({
|
|
|
111940
112441
|
});
|
|
111941
112442
|
}
|
|
111942
112443
|
}
|
|
111943
|
-
|
|
112444
|
+
const emptyContentFailure = isEmptyProviderContentFailure(error48);
|
|
112445
|
+
const keySpecificOrTransientFailure = isKeySpecificOrTransientProviderFailure(detail) || statusCode === HTTP_STATUS.REQUEST_TIMEOUT || nativeFailureKind === "transport" || emptyContentFailure;
|
|
112446
|
+
if ((!egress || googleEgressHasBudget(egress)) && !signal?.aborted && input.allowFallback !== false && !emittedDelta && (keySpecificOrTransientFailure || isModelSpecificProviderFailure(detail) || retryableRouteFailure)) {
|
|
111944
112447
|
const nextProviderKeySlotIndex = providerKeySlots.findIndex((_, index) => index > providerKeySlotIndex && runtimeKeySlotSupportsModel(config2, secrets, provider, index, model) && (!isModelSpecificProviderFailure(detail) || resolveNativeProviderCredentialSlots(provider, secrets)[index]?.baseUrl !== resolveNativeProviderCredentialSlots(provider, secrets)[providerKeySlotIndex]?.baseUrl));
|
|
111945
112448
|
if (provider !== "local" && nextProviderKeySlotIndex >= 0) {
|
|
111946
112449
|
const diagnostics = normalizeProviderDiagnostics(error48?.runtimeProviderDiagnostics);
|
|
@@ -111976,6 +112479,38 @@ var init_provider_client = __esm({
|
|
|
111976
112479
|
return await invokeRuntimeProviderAttempt({
|
|
111977
112480
|
...input,
|
|
111978
112481
|
providerKeySlotIndex: nextProviderKeySlotIndex,
|
|
112482
|
+
keySweepStartSlotIndex,
|
|
112483
|
+
googleEgressRoute: void 0,
|
|
112484
|
+
googleEgressTriedRoutes: [],
|
|
112485
|
+
nativeRecoverySafe,
|
|
112486
|
+
invocationAttemptChain: invocationAttempts2
|
|
112487
|
+
});
|
|
112488
|
+
}
|
|
112489
|
+
}
|
|
112490
|
+
if (emptyContentFailure && (!egress || googleEgressHasBudget(egress)) && !signal?.aborted && input.allowFallback !== false && !emittedDelta) {
|
|
112491
|
+
const retryPolicy = emptyContentRetryPolicy;
|
|
112492
|
+
const retryCount = input.emptyContentRetryCount ?? 0;
|
|
112493
|
+
const retryDelayMs = retryPolicy === null ? 0 : (retryPolicy.delay_seconds + retryPolicy.jitter_min_seconds + Math.random() * (retryPolicy.jitter_max_seconds - retryPolicy.jitter_min_seconds)) * MS_PER_SECOND;
|
|
112494
|
+
const remainingMs = input.nativeRequestDeadlineMs === void 0 ? Number.POSITIVE_INFINITY : input.nativeRequestDeadlineMs - Date.now();
|
|
112495
|
+
if (retryPolicy !== null && retryCount < retryPolicy.max_retries && retryDelayMs < remainingMs) {
|
|
112496
|
+
try {
|
|
112497
|
+
await waitForProviderRetry(retryDelayMs, signal);
|
|
112498
|
+
} catch (cancelled) {
|
|
112499
|
+
cancelled.runtimeInvocationAttempts = invocationAttempts2;
|
|
112500
|
+
cancelled.runtimePartialOutput = emittedDelta;
|
|
112501
|
+
cancelled.runtimeNativeRecoverySafe = nativeRecoverySafe;
|
|
112502
|
+
throw cancelled;
|
|
112503
|
+
}
|
|
112504
|
+
appendRuntimeDebugEvent({
|
|
112505
|
+
label: "provider_empty_content_retry",
|
|
112506
|
+
note: `provider=${provider} model=${model} retry=${retryCount + 1}/${retryPolicy.max_retries}`,
|
|
112507
|
+
outcome: "error"
|
|
112508
|
+
});
|
|
112509
|
+
return await invokeRuntimeProviderAttempt({
|
|
112510
|
+
...input,
|
|
112511
|
+
providerKeySlotIndex: keySweepStartSlotIndex,
|
|
112512
|
+
keySweepStartSlotIndex,
|
|
112513
|
+
emptyContentRetryCount: retryCount + 1,
|
|
111979
112514
|
googleEgressRoute: void 0,
|
|
111980
112515
|
googleEgressTriedRoutes: [],
|
|
111981
112516
|
nativeRecoverySafe,
|
|
@@ -113416,16 +113951,16 @@ __export(local_analysis_exports, {
|
|
|
113416
113951
|
isClientRuntimeAiSchedulePaused: () => isClientRuntimeAiSchedulePaused,
|
|
113417
113952
|
isClientRuntimeAiScheduleStillActive: () => isClientRuntimeAiScheduleStillActive,
|
|
113418
113953
|
isServerDispatchAccountStateStale: () => isServerDispatchAccountStateStale,
|
|
113954
|
+
perpDexScopeForSymbols: () => perpDexScopeForSymbols,
|
|
113419
113955
|
resolveEffectivePromptRuntimeProvenance: () => resolveEffectivePromptRuntimeProvenance,
|
|
113420
113956
|
resolveExternalInferenceRuntimeTimeoutSeconds: () => resolveExternalInferenceRuntimeTimeoutSeconds,
|
|
113421
113957
|
resolveLocalRuntimeSecretProvider: () => resolveLocalRuntimeSecretProvider,
|
|
113422
113958
|
resolveLocalRuntimeSecretRequirements: () => resolveLocalRuntimeSecretRequirements,
|
|
113423
113959
|
resolveNativeValuesForModel: () => resolveNativeValuesForModel,
|
|
113424
113960
|
runLocalRuntimeCycle: () => runLocalRuntimeCycle,
|
|
113425
|
-
serverPerpDexScope: () => serverPerpDexScope,
|
|
113426
113961
|
summarizeReviewFailureExplanation: () => summarizeReviewFailureExplanation
|
|
113427
113962
|
});
|
|
113428
|
-
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,
|
|
113963
|
+
var CYCLE_TIMEOUT_FLOOR_MS, DECISION_SETTLEMENT_RESERVE_MAX_BUDGET_DIVISOR, MIN_AGENT_INSTRUCTION_RETRY_AFTER_MS, PROMPT_PARITY_ERROR_DETAIL_MAX_CHARS, EXTERNAL_INFERENCE_RUNTIME_POLL_INTERVAL_MS, REVIEW_PROVIDER_SERVER_ERROR_STATUSES, TRUNCATION_ELLIPSIS2, normalizeNativeValues, assertPromptModelController, resolveRuntimeReasoningControlsForModel, modelScopedKey, resolveNativeValuesForModel, observeRuntimeCycle, observeAccountState, aiOrderSlippageFraction, serverBehaviorStateArtifacts, ClientRuntimeAgentInstructionEmpty, isClientRuntimeAgentInstructionEmpty, ClientRuntimeAiSchedulePaused, ClientRuntimeAiScheduleStillActive, isClientRuntimeAiScheduleStillActive, ServerDispatchAccountStateStale, isServerDispatchAccountStateStale, isClientRuntimeAiSchedulePaused, acceptancePositionCaps, accountSnapshotCapturedAt, buildClaimedAgentRuntimeCycleResult, resolveRuntimeMarginModePreference, resolveRuntimeLeveragePreference, resolveBooleanSetting2, CLIENT_RUNTIME_LIVE_CONTEXT_UNAVAILABLE_ERRORS, BEHAVIOR_STATE_UNAVAILABLE_ERROR, CriticalBehaviorStateError, clampNumber, resolveExternalInferenceRuntimeTimeoutSeconds, toPositiveFinite3, compactSnippet, hashRuntimeDebugText, EFFECTIVE_INPUT_MANIFEST_SCHEMA_VERSION, PROMPT_ASSEMBLY_DEFINITION_VERSION, RUNTIME_SOURCE_DEFINITION_VERSION, DECISION_INPUT_DEFINITION_VERSION, CONTEXT_ENVELOPE_DEFINITION_VERSION, CLIENT_RUNTIME_SOURCE_VERSION, CLIENT_MAIN_PROMPT_RENDERER, SERVER_MAIN_PROMPT_RENDERER, CLIENT_REVIEW_PROMPT_RENDERER, SERVER_REVIEW_PROMPT_RENDERER, resolveEffectivePromptRuntimeProvenance, canonicalManifestValue, canonicalManifestJson, sha256ManifestHex, effectiveInputComponent, buildEffectiveInputManifest, derivePromptVisibleSections, decodeDecisionTracePayload, extractDecisionSymbolTrace, formatDecisionSymbolTrace, formatActionableDecisionSymbols, decisionRecordsBySymbol, normalizePromptSymbols, JSON_MODEL_OUTPUT_FENCE_PATTERN, STRICT_MODEL_OUTPUT_KEYS, currentModelOutputValidationErrors, currentModelOutputMatchesContract, projectCurrentModelDecisionContent, modelOutputValidationError, buildMissingDecisionHold, buildDecisionPlansFromResponse, buildReviewCandidatePlansFromResponse, forceUnavailableSymbolsToHold, extractTemplatePlaceholders, requireReviewPrimaryUserPromptTemplate, containsCompetingBehaviorStateMarkup, containsCompetingMainBehaviorStateMarkup, requireStrategyReviewTemplates, preflightStrategyReviewPromptContract, extractRuntimeReasoningSelection, isAbortError, isRuntimeTimeoutAbortReason, REVIEW_FAILURE_SENSITIVE_DB_TOKENS, REVIEW_FAILURE_SCHEMA_DISCLOSURE_TOKENS, REVIEW_FAILURE_SQL_STATEMENT_PATTERN, REVIEW_FAILURE_TRACEBACK_PATTERN, isSensitiveReviewFailureDetail, summarizeReviewFailureExplanation, buildReviewFailureHoldReason, createAbortError2, settleRuntimeCyclePromise, unwrapRuntimeCycleSettledResult, normalizeDecisionLabel, normalizeRuntimeSymbol, PromptContractFetchError, isLivePromptContextUnavailableError, buildFailClosedHoldResult, buildPromptConstructionFailureResult, buildLivePromptContextUnavailableFailureResult, pickFirstString, normalizeRuntimeStringList, requirePositiveRuntimeLimit, resolveRuntimeTradingScope, normalizeRuntimeProviderAlias, resolveCatalogModelEntry, createClientRuntimeProviderSetupError, createProviderSetupRejectionError, evaluateModelEligibility, extractReviewRuntimeReasoningSelection, isUsableRuntimeSettingsFallback, resolveRuntimeSettings, formatRuntimeDurationMs, normalizeRuntimeTimingNote, appendRuntimeTimingEvent, reportPromptParityTelemetry, resolveLocalRuntimeSecretRequirements, resolveLocalRuntimeSecretProvider, toEpochSeconds, REQUIRED_AI_INDICATOR_KEYS, sortTradingTimeframes, normalizePromptIdentityTimestamp, resolveCompletedCandleBoundary, normalizeAiIndicatorFlags, getPromptLookback, computeSma, computeEma, computeRsi, computeAtr, computeMacd, computeBollingerBands, getIndicatorValue, buildPromptCandlesComponent, CANDLE_CLOSE_TICKER_TIMEFRAME, candleCloseTicker, buildPromptCandlesPayload, formatUtcTimestampWithWeekday, formatUtcNowWithWeekday, formatPromptPrice, capacityUnitSize, computePromptUnitsUsedForPosition, buildPromptAccountStatusValue, buildPromptPositionsValue, sanitizePromptSymbol, fillTimeMs, fillSize, normalizeFillSide, normalizeFillOrderId, normalizeFillRiskOrderIdentity, fillStartPosition, fillSortValue, sortFillsAscending, sortFillsDescending, inferEntryFromStartPositionChain, inferEntryFromCurrentPositionSize, calculateCurrentPositionState, calculatePositionEntryTimes, countPositionAdds, latestPositionRiskIncreaseTimeMs, latestPositionRiskIncreaseEvidence, compactPromptRiskIncrease, roundPositiveDecimalHalfUp, compactPromptLastTrade, ENTRY_TRADE_FIELDS, PREVIOUS_DECISION_FIELDS, PREVIOUS_CAMPAIGN_FIELDS, hasExactKeys2, isNonnegativeInteger, isFiniteNumber, isExactEnumString, isNonemptyPromptText, isCampaignReasoningText, projectBackendDecisionMemoryItem, requireRenderedStrategyBehaviorState, canonicalFillSideForRiskEvidence, isValidRiskEvidenceFill, isValidCampaignBoundaryFill, normalizeFillHistoryCoverage, resolveFillHistoryCoverageForSymbol, buildPromptBehaviorStateArtifacts, buildPromptBehaviorStateValue, shouldCompareServerPromptParity, buildLocalRuntimePromptArtifacts, createRuntimeId2, asRecord, buildRuntimeConstraintRejectionMessage, hasDeviceProviderSecret, requireNonEmptyStringField, requirePositiveIntegerField, compareContractVersion, parsePromptContractTimestamp, assertPromptContractCompatibility, assertPromptContractTemporalBounds, sleepWithAbort, requireAgentPollRetryAfterMs, materializeClaimedClientRuntimeAgentInstruction, attachClientRuntimeErrorProvenance, isExternalRuntimeProviderResult, invokeClientExternalInference, assertPromptContractBindingTupleEqual, assertPromptContractScopeMatch, fetchBoundPromptContracts, formatTemplateWithNamedVariables, carryReturnedModelCalls, runLocalRuntimeCycle;
|
|
113429
113964
|
var init_local_analysis = __esm({
|
|
113430
113965
|
"lib/runtime/local-analysis.ts"() {
|
|
113431
113966
|
"use strict";
|
|
@@ -113446,6 +113981,9 @@ var init_local_analysis = __esm({
|
|
|
113446
113981
|
init_execution_guard_contract();
|
|
113447
113982
|
init_hyperliquid_account_state_adapter();
|
|
113448
113983
|
init_client_account_report();
|
|
113984
|
+
init_hyperliquid_public_read();
|
|
113985
|
+
init_server_host_prompt_rescue();
|
|
113986
|
+
init_server_prompt_rescue_snapshot();
|
|
113449
113987
|
init_network_debug();
|
|
113450
113988
|
init_abort();
|
|
113451
113989
|
init_error_surface_contract();
|
|
@@ -113465,6 +114003,8 @@ var init_local_analysis = __esm({
|
|
|
113465
114003
|
init_native_request_parameters();
|
|
113466
114004
|
init_hyperliquid_market_symbol();
|
|
113467
114005
|
init_external_inference_contract();
|
|
114006
|
+
init_perp_dex_scope();
|
|
114007
|
+
init_perp_dex_scope();
|
|
113468
114008
|
init_model_controller_provenance();
|
|
113469
114009
|
init_ai_schedule();
|
|
113470
114010
|
init_runtime_policy_generated2();
|
|
@@ -113550,16 +114090,6 @@ var init_local_analysis = __esm({
|
|
|
113550
114090
|
});
|
|
113551
114091
|
};
|
|
113552
114092
|
aiOrderSlippageFraction = (config2, executionMode) => executionMode === "server" ? Number(config2.server_ai_max_slippage) / PERCENT_SCALE : clampNumber(void 0, config2.default_max_slippage) / PERCENT_SCALE;
|
|
113553
|
-
serverPerpDexScope = (symbols, executionMode) => {
|
|
113554
|
-
if (executionMode !== "server") return void 0;
|
|
113555
|
-
const dexes = /* @__PURE__ */ new Set();
|
|
113556
|
-
for (const raw of symbols) {
|
|
113557
|
-
if (!String(raw ?? "").trim()) continue;
|
|
113558
|
-
if (!normalizeHyperliquidMarketSymbol(raw)) return void 0;
|
|
113559
|
-
dexes.add(getHyperliquidMarketDex(raw));
|
|
113560
|
-
}
|
|
113561
|
-
return dexes.size > 0 ? [...dexes].filter(Boolean) : void 0;
|
|
113562
|
-
};
|
|
113563
114093
|
serverBehaviorStateArtifacts = (derived) => {
|
|
113564
114094
|
const rendered = derived.behavior_state;
|
|
113565
114095
|
if (derived.behavior_state_owner !== "server" || typeof rendered !== "string" || !rendered.trim()) {
|
|
@@ -113605,6 +114135,10 @@ var init_local_analysis = __esm({
|
|
|
113605
114135
|
};
|
|
113606
114136
|
isServerDispatchAccountStateStale = (value) => value instanceof Error && value.name === "ServerDispatchAccountStateStale";
|
|
113607
114137
|
isClientRuntimeAiSchedulePaused = (value) => value instanceof ClientRuntimeAiSchedulePaused;
|
|
114138
|
+
acceptancePositionCaps = (executionMode, caps) => executionMode === "server" ? { remaining_global_units: null, remaining_exchange_units: null, remaining_asset_units: null } : caps;
|
|
114139
|
+
accountSnapshotCapturedAt = (executionMode, accountStateFetchedAtMs) => new Date(
|
|
114140
|
+
(executionMode === "server" ? accountStateFetchedAtMs : null) ?? Date.now()
|
|
114141
|
+
).toISOString();
|
|
113608
114142
|
buildClaimedAgentRuntimeCycleResult = async (input) => {
|
|
113609
114143
|
const { config: config2, settings, instruction, runtimeInput, signal } = input;
|
|
113610
114144
|
const binding = runtimeInput.runtimeContractBinding;
|
|
@@ -113641,7 +114175,7 @@ var init_local_analysis = __esm({
|
|
|
113641
114175
|
tickerPrice: 0,
|
|
113642
114176
|
leverage,
|
|
113643
114177
|
aggregatePerpDexs: true,
|
|
113644
|
-
perpDexScope:
|
|
114178
|
+
perpDexScope: perpDexScopeForSymbols(symbols),
|
|
113645
114179
|
feeSymbols: symbols,
|
|
113646
114180
|
includeEffectiveTakerRate: true,
|
|
113647
114181
|
sessionId: String(runtimeInput.sessionId || "").trim(),
|
|
@@ -113801,9 +114335,11 @@ var init_local_analysis = __esm({
|
|
|
113801
114335
|
runtime_disabled: settings.main_model_enabled === false,
|
|
113802
114336
|
kill_switch_active: false,
|
|
113803
114337
|
max_trades_per_prompt: remainingPromptUnits,
|
|
113804
|
-
|
|
113805
|
-
|
|
113806
|
-
|
|
114338
|
+
...acceptancePositionCaps(runtimeInput.executionMode, {
|
|
114339
|
+
remaining_exchange_units: Math.max(0, maxTradesPerExchange - (exchangeUnitsUsed.get(getHyperliquidMarketDex(entry.symbol)) ?? 0)),
|
|
114340
|
+
remaining_global_units: remainingGlobalUnits,
|
|
114341
|
+
remaining_asset_units: remainingAssetUnits
|
|
114342
|
+
}),
|
|
113807
114343
|
current_symbol_signed_units: currentSignedUnits,
|
|
113808
114344
|
model_allowed: true,
|
|
113809
114345
|
provider_allowed: true
|
|
@@ -113925,7 +114461,7 @@ var init_local_analysis = __esm({
|
|
|
113925
114461
|
clientExchangeSnapshot: buildClientExchangeSnapshot({
|
|
113926
114462
|
walletAddress,
|
|
113927
114463
|
symbol: symbol2,
|
|
113928
|
-
capturedAt: (
|
|
114464
|
+
capturedAt: accountSnapshotCapturedAt(runtimeInput.executionMode, accountState.evidence?.fetchedAtMs),
|
|
113929
114465
|
markPrice: primaryPrice,
|
|
113930
114466
|
accountSummary: accountState.accountSummary,
|
|
113931
114467
|
positions: accountState.positions,
|
|
@@ -114267,6 +114803,12 @@ var init_local_analysis = __esm({
|
|
|
114267
114803
|
};
|
|
114268
114804
|
formatDecisionSymbolTrace = (symbols) => symbols.length > 0 ? symbols.map((entry) => `${entry.symbol}:${entry.decision}/${entry.units}`).join(",") : "none";
|
|
114269
114805
|
formatActionableDecisionSymbols = (symbols) => formatDecisionSymbolTrace(symbols.filter((entry) => entry.decision !== "HOLD" && entry.units > 0));
|
|
114806
|
+
decisionRecordsBySymbol = (plans) => Object.fromEntries(plans.map((plan) => [plan.symbol, {
|
|
114807
|
+
decision: plan.decision,
|
|
114808
|
+
reasoning: plan.reasoning,
|
|
114809
|
+
units: plan.units,
|
|
114810
|
+
tradability: plan.tradability
|
|
114811
|
+
}]));
|
|
114270
114812
|
normalizePromptSymbols = (symbols) => {
|
|
114271
114813
|
const seen = /* @__PURE__ */ new Set();
|
|
114272
114814
|
const normalized = [];
|
|
@@ -115501,10 +116043,19 @@ ${reviewOutputContract}`;
|
|
|
115501
116043
|
});
|
|
115502
116044
|
return { c: summarized };
|
|
115503
116045
|
};
|
|
116046
|
+
CANDLE_CLOSE_TICKER_TIMEFRAME = "5m";
|
|
116047
|
+
candleCloseTicker = (symbol2, candlesByTimeframe) => {
|
|
116048
|
+
const preferred = candlesByTimeframe[CANDLE_CLOSE_TICKER_TIMEFRAME] ?? [];
|
|
116049
|
+
const reference = preferred.length > 0 ? preferred : Object.values(candlesByTimeframe).find((rows) => rows.length > 0) ?? [];
|
|
116050
|
+
const latest = reference.reduce((current, candle) => current === null || toEpochSeconds(candle.timestamp) > toEpochSeconds(current.timestamp) ? candle : current, null);
|
|
116051
|
+
const close = toPositiveFinite3(latest?.close);
|
|
116052
|
+
return close === null ? null : { symbol: symbol2, price: close, timestamp: "", source: "recent_candle_close" };
|
|
116053
|
+
};
|
|
115504
116054
|
buildPromptCandlesPayload = (input) => {
|
|
115505
116055
|
const payload = {};
|
|
115506
116056
|
for (const symbol2 of input.symbols) {
|
|
115507
|
-
const
|
|
116057
|
+
const symbolTicker = input.tickersBySymbol[symbol2];
|
|
116058
|
+
const asOfTimestamp = (symbolTicker?.is_fresh === true ? toEpochSeconds(symbolTicker.timestamp) : 0) || Math.floor(Date.now() / MS_PER_SECOND);
|
|
115508
116059
|
const symbolData = {
|
|
115509
116060
|
data: {}
|
|
115510
116061
|
};
|
|
@@ -117449,10 +118000,6 @@ ${behaviorJson}
|
|
|
117449
118000
|
);
|
|
117450
118001
|
}
|
|
117451
118002
|
let requestTimeoutSeconds = clampNumber(settings.timeout_seconds, config2.default_timeout_seconds);
|
|
117452
|
-
let requestTimeoutMs = Math.max(CYCLE_TIMEOUT_FLOOR_MS, Math.round(requestTimeoutSeconds * MS_PER_SECOND));
|
|
117453
|
-
if (requestTimeoutMs !== defaultTimeoutMs) {
|
|
117454
|
-
armCycleDeadline(requestTimeoutMs, "Runtime request timeout reached.");
|
|
117455
|
-
}
|
|
117456
118003
|
const {
|
|
117457
118004
|
symbols,
|
|
117458
118005
|
timeframes,
|
|
@@ -117563,6 +118110,7 @@ ${behaviorJson}
|
|
|
117563
118110
|
const getLatestTotalUnrealizedPnl = () => _latestTotalUnrealizedPnl;
|
|
117564
118111
|
const getAccountStateResolvedAtMs = () => _accountStateResolvedAtMs;
|
|
117565
118112
|
const accountStateStartedAtMs = Date.now();
|
|
118113
|
+
let promptRescueSequence = 0;
|
|
117566
118114
|
observeRuntimeCycle(input, { stage: "market_context" });
|
|
117567
118115
|
const browserAccountStateTask = fetchBrowserAccountState2({
|
|
117568
118116
|
publicRequestPriority: "trading_analysis",
|
|
@@ -117572,7 +118120,7 @@ ${behaviorJson}
|
|
|
117572
118120
|
tickerPrice: 0,
|
|
117573
118121
|
leverage: resolveRuntimeLeveragePreference(settings, config2),
|
|
117574
118122
|
aggregatePerpDexs: true,
|
|
117575
|
-
perpDexScope:
|
|
118123
|
+
perpDexScope: perpDexScopeForSymbols(symbols),
|
|
117576
118124
|
feeSymbols: symbols,
|
|
117577
118125
|
includeEffectiveTakerRate: true,
|
|
117578
118126
|
// A Server bot's cycle reads the account authoritatively, as the Python
|
|
@@ -117580,6 +118128,36 @@ ${behaviorJson}
|
|
|
117580
118128
|
forceRefresh: input.executionMode === "server",
|
|
117581
118129
|
sessionId,
|
|
117582
118130
|
signal: timeoutController.signal
|
|
118131
|
+
}).catch(async (error48) => {
|
|
118132
|
+
if (input.executionMode !== "server" || !(error48 instanceof HyperliquidPublicReadError)) throw error48;
|
|
118133
|
+
promptRescueSequence += 1;
|
|
118134
|
+
try {
|
|
118135
|
+
const rescued = await requestServerHostPromptRescue(profileId, {
|
|
118136
|
+
sessionId,
|
|
118137
|
+
deviceId,
|
|
118138
|
+
schedulerInstanceId: String(input.schedulerInstanceId || "").trim(),
|
|
118139
|
+
mode: input.mode,
|
|
118140
|
+
analysisRunId: String(input.analysisRunId || "").trim() || cycleId,
|
|
118141
|
+
cycleId,
|
|
118142
|
+
symbol: localFallbackSymbol,
|
|
118143
|
+
symbols,
|
|
118144
|
+
requestSequence: promptRescueSequence,
|
|
118145
|
+
serverReason: error48.code
|
|
118146
|
+
}, {
|
|
118147
|
+
schedulerInstanceId: String(input.schedulerInstanceId || "").trim(),
|
|
118148
|
+
signal: timeoutController.signal
|
|
118149
|
+
});
|
|
118150
|
+
appendRuntimeDebugEvent({ label: "account_state_prompt_rescued", note: `job=${rescued.job_id} reason=${error48.code}` });
|
|
118151
|
+
return accountStateFromServerPromptRescueSnapshot(rescued.snapshot, localFallbackSymbol);
|
|
118152
|
+
} catch (rescueError) {
|
|
118153
|
+
if (timeoutController.signal.aborted) throw rescueError;
|
|
118154
|
+
appendRuntimeDebugEvent({
|
|
118155
|
+
label: "account_state_prompt_rescue_unavailable",
|
|
118156
|
+
note: rescueError instanceof Error ? rescueError.message : String(rescueError),
|
|
118157
|
+
outcome: "error"
|
|
118158
|
+
});
|
|
118159
|
+
throw error48;
|
|
118160
|
+
}
|
|
117583
118161
|
}).then((state2) => {
|
|
117584
118162
|
observeAccountState(input, state2);
|
|
117585
118163
|
latestPositions = state2.positions;
|
|
@@ -117671,8 +118249,13 @@ ${behaviorJson}
|
|
|
117671
118249
|
const marketDataStartedAtMs = Date.now();
|
|
117672
118250
|
const candlesTickerPromise = Promise.all(
|
|
117673
118251
|
symbols.map(async (marketSymbol) => {
|
|
118252
|
+
let tickerError = null;
|
|
117674
118253
|
const [loadedTicker, loadedCandles] = await Promise.all([
|
|
117675
|
-
getLiveTicker(marketSymbol, "hyperliquid", timeoutController.signal)
|
|
118254
|
+
getLiveTicker(marketSymbol, "hyperliquid", timeoutController.signal).catch((error48) => {
|
|
118255
|
+
if (timeoutController.signal.aborted || isAbortLikeError(error48)) throw error48;
|
|
118256
|
+
tickerError = error48;
|
|
118257
|
+
return null;
|
|
118258
|
+
}),
|
|
117676
118259
|
Promise.all(
|
|
117677
118260
|
sortedTimeframes.map(async (marketTimeframe) => [
|
|
117678
118261
|
marketTimeframe,
|
|
@@ -117693,11 +118276,17 @@ ${behaviorJson}
|
|
|
117693
118276
|
])
|
|
117694
118277
|
)
|
|
117695
118278
|
]);
|
|
117696
|
-
|
|
117697
|
-
|
|
117698
|
-
|
|
117699
|
-
|
|
117700
|
-
|
|
118279
|
+
const candles = Object.fromEntries(loadedCandles);
|
|
118280
|
+
const ticker2 = loadedTicker?.is_fresh === true && toPositiveFinite3(loadedTicker.price) !== null ? loadedTicker : candleCloseTicker(marketSymbol, candles) ?? loadedTicker;
|
|
118281
|
+
if (ticker2 === null) throw tickerError;
|
|
118282
|
+
if (loadedTicker === null) {
|
|
118283
|
+
appendRuntimeDebugEvent({
|
|
118284
|
+
label: "live_ticker_unavailable",
|
|
118285
|
+
note: `symbol=${marketSymbol} price_source=recent_candle_close detail=${tickerError instanceof Error ? tickerError.message : String(tickerError)}`,
|
|
118286
|
+
outcome: "error"
|
|
118287
|
+
});
|
|
118288
|
+
}
|
|
118289
|
+
return { symbol: marketSymbol, ticker: ticker2, candles };
|
|
117701
118290
|
})
|
|
117702
118291
|
).then((result) => {
|
|
117703
118292
|
const primaryTicker = result.find((entry) => entry.symbol === localFallbackSymbol)?.ticker ?? result[0]?.ticker;
|
|
@@ -117830,7 +118419,7 @@ ${behaviorJson}
|
|
|
117830
118419
|
const clientExchangeSnapshot = buildClientExchangeSnapshot({
|
|
117831
118420
|
walletAddress,
|
|
117832
118421
|
symbol: symbol2,
|
|
117833
|
-
capturedAt: (
|
|
118422
|
+
capturedAt: accountSnapshotCapturedAt(input.executionMode, browserAccountState.evidence?.fetchedAtMs),
|
|
117834
118423
|
markPrice: toPositiveFinite3(availableToTrade.mark_price) ?? toPositiveFinite3(ticker.price),
|
|
117835
118424
|
accountSummary,
|
|
117836
118425
|
positions,
|
|
@@ -117864,8 +118453,8 @@ ${behaviorJson}
|
|
|
117864
118453
|
const maxTradesPerExchange = Math.round(clampNumber(promptKnobs.max_trades_per_exchange, maxTradesGlobal));
|
|
117865
118454
|
const metadataTradeSize = clampNumber(promptKnobs.trade_size, config2.default_ai_trade_amount);
|
|
117866
118455
|
const metadataLeverage = clampNumber(promptKnobs.leverage, config2.default_leverage);
|
|
117867
|
-
const metricsWindowHours =
|
|
117868
|
-
const metricsSecondaryWindowHours =
|
|
118456
|
+
const metricsWindowHours = clampNumber(promptKnobs.metrics_window_hours, 0);
|
|
118457
|
+
const metricsSecondaryWindowHours = clampNumber(promptKnobs.metrics_secondary_window_hours, 0);
|
|
117869
118458
|
const promptSymbols = Array.isArray(promptKnobs.active_symbols) && promptKnobs.active_symbols.length > 0 ? promptKnobs.active_symbols.map((item) => String(item || "").trim()).filter(Boolean) : symbols;
|
|
117870
118459
|
const promptTimeframes = Array.isArray(promptKnobs.active_timeframes) && promptKnobs.active_timeframes.length > 0 ? sortTradingTimeframes(promptKnobs.active_timeframes.map((item) => String(item || "").trim()).filter(Boolean)) : sortedTimeframes;
|
|
117871
118460
|
const executionFreshnessMaxAgeSeconds = requirePositiveIntegerField(
|
|
@@ -118042,7 +118631,7 @@ ${behaviorJson}
|
|
|
118042
118631
|
throw new Error(message);
|
|
118043
118632
|
}
|
|
118044
118633
|
} catch (error48) {
|
|
118045
|
-
if (!(error48 instanceof Error) ||
|
|
118634
|
+
if (!(error48 instanceof Error) || normalizeModelFallbacks(settings.model_fallbacks).main.length === 0) throw error48;
|
|
118046
118635
|
primaryAvailabilityError = Object.assign(error48, { modelFallbackSafe: true });
|
|
118047
118636
|
}
|
|
118048
118637
|
const localAcceptanceConstraints = {
|
|
@@ -118514,8 +119103,10 @@ ${stringifyPromptJson(candlesPayload)}
|
|
|
118514
119103
|
config2,
|
|
118515
119104
|
requestTimeoutSeconds
|
|
118516
119105
|
);
|
|
118517
|
-
|
|
118518
|
-
|
|
119106
|
+
armCycleDeadline(
|
|
119107
|
+
Math.max(CYCLE_TIMEOUT_FLOOR_MS, Math.round(requestTimeoutSeconds * MS_PER_SECOND)),
|
|
119108
|
+
"Runtime request timeout reached."
|
|
119109
|
+
);
|
|
118519
119110
|
appendRuntimeDebugEvent({
|
|
118520
119111
|
label: "external_inference_timeout_extended",
|
|
118521
119112
|
note: `lane=main seconds=${requestTimeoutSeconds}`
|
|
@@ -118605,7 +119196,12 @@ ${stringifyPromptJson(candlesPayload)}
|
|
|
118605
119196
|
systemPrompt,
|
|
118606
119197
|
userPrompt,
|
|
118607
119198
|
temperature: entryParameters?.temperature ?? temperature,
|
|
118608
|
-
|
|
119199
|
+
// Every Main model gets at least the configured output budget, as in
|
|
119200
|
+
// the Server loop (ai_trading_service.py _execute_llm_request).
|
|
119201
|
+
maxTokens: Math.max(
|
|
119202
|
+
entryParameters?.max_tokens ?? maxTokens,
|
|
119203
|
+
requirePositiveIntegerField(config2.max_tokens_min, "max_tokens_min")
|
|
119204
|
+
),
|
|
118609
119205
|
reasoningPayload: modelIndex === 0 ? reasoningPayload : buildRuntimeReasoningPayload(controls, extractRuntimeReasoningSelection({ runtime_reasoning: entryParameters?.runtime_reasoning }, controls.control_type, controls.control_type === "toggle" ? controls.toggle_behavior : "disable_reasoning")),
|
|
118610
119206
|
nativeRequestParameters: entryConfig?.native_request_parameters,
|
|
118611
119207
|
nativeRequestParameterValues: modelIndex === 0 ? nativeRequestParameterValues : filterNativeRequestParameterValues(entryConfig?.native_request_parameters, entryParameters?.native_request_parameter_values),
|
|
@@ -118747,6 +119343,7 @@ ${stringifyPromptJson(candlesPayload)}
|
|
|
118747
119343
|
let finalTradability = selectedPrimaryPlan?.tradability ?? parsed.tradability;
|
|
118748
119344
|
let reviewTradability = null;
|
|
118749
119345
|
let finalAnalysis = primaryDecisionContent;
|
|
119346
|
+
let reviewedCycle = null;
|
|
118750
119347
|
let finalModel = primaryDisplayModel;
|
|
118751
119348
|
let finalProvider = providerResponse.provider;
|
|
118752
119349
|
let finalSystemPrompt = systemPrompt;
|
|
@@ -119053,7 +119650,11 @@ ${reviewOutputContract}`;
|
|
|
119053
119650
|
finalReasoning = selectedReviewedPlan?.reasoning ?? reviewed.reasoning;
|
|
119054
119651
|
reviewTradability = selectedReviewedPlan?.tradability ?? reviewed.tradability;
|
|
119055
119652
|
finalTradability = reviewTradability;
|
|
119056
|
-
finalAnalysis = reviewDecisionContent;
|
|
119653
|
+
finalAnalysis = finalDecisionPlans.length > 1 ? JSON.stringify(decisionRecordsBySymbol(finalDecisionPlans)) : reviewDecisionContent;
|
|
119654
|
+
reviewedCycle = {
|
|
119655
|
+
originalModel: primaryDisplayModel,
|
|
119656
|
+
originalDecisions: decisionRecordsBySymbol(primaryDecisionPlans)
|
|
119657
|
+
};
|
|
119057
119658
|
const reviewDisplayModel = isExternalRuntimeProviderResult(reviewResponse) ? String(reviewResponse.model || reviewModel).trim() || reviewModel : projectInvocationStageModelLabel({
|
|
119058
119659
|
requestedModel: requestedReviewModel,
|
|
119059
119660
|
displayModel: String(reviewResponse.model || reviewModel).trim() || reviewModel,
|
|
@@ -119105,6 +119706,7 @@ ${reviewOutputContract}`;
|
|
|
119105
119706
|
...entry,
|
|
119106
119707
|
...reviewedSymbolKeys.has(normalizeRuntimeSymbol(entry.symbol)) ? { decision: "HOLD", units: 0, reasoning: finalReasoning } : {}
|
|
119107
119708
|
}));
|
|
119709
|
+
if (finalDecisionPlans.length > 1) finalAnalysis = JSON.stringify(decisionRecordsBySymbol(finalDecisionPlans));
|
|
119108
119710
|
const failedSelectedPlan = finalDecisionPlans.find((entry) => normalizeRuntimeSymbol(entry.symbol) === normalizeRuntimeSymbol(symbol2)) ?? finalDecisionPlans[0];
|
|
119109
119711
|
finalDecision = failedSelectedPlan?.decision ?? "HOLD";
|
|
119110
119712
|
finalUnits = failedSelectedPlan?.units ?? 0;
|
|
@@ -119161,7 +119763,7 @@ ${reviewOutputContract}`;
|
|
|
119161
119763
|
Math.round(Number(settings.tradability_increase_minimum ?? config2.default_tradability_increase_minimum))
|
|
119162
119764
|
)
|
|
119163
119765
|
);
|
|
119164
|
-
const
|
|
119766
|
+
const acceptExecutionPlan = (entry) => {
|
|
119165
119767
|
const planSymbol = normalizeRuntimeSymbol(entry.symbol);
|
|
119166
119768
|
const isPrimaryPlanSymbol = planSymbol === normalizeRuntimeSymbol(symbol2);
|
|
119167
119769
|
const planSignedUnits = computePlanSignedUnits(entry.symbol);
|
|
@@ -119202,9 +119804,11 @@ ${reviewOutputContract}`;
|
|
|
119202
119804
|
const planConstraints = {
|
|
119203
119805
|
...localAcceptanceConstraints,
|
|
119204
119806
|
max_trades_per_prompt: remainingPromptUnits,
|
|
119205
|
-
|
|
119206
|
-
|
|
119207
|
-
|
|
119807
|
+
...acceptancePositionCaps(input.executionMode, {
|
|
119808
|
+
remaining_global_units: remainingGlobalUnits,
|
|
119809
|
+
remaining_exchange_units: Math.max(0, maxTradesPerExchange - (exchangeUnitsUsed.get(getHyperliquidMarketDex(entry.symbol)) ?? 0)),
|
|
119810
|
+
remaining_asset_units: remainingAssetUnits
|
|
119811
|
+
}),
|
|
119208
119812
|
current_symbol_signed_units: planSignedUnits
|
|
119209
119813
|
};
|
|
119210
119814
|
const planAcceptance = evaluateRuntimeDecisionAcceptance({
|
|
@@ -119277,7 +119881,16 @@ ${reviewOutputContract}`;
|
|
|
119277
119881
|
reasoning: entry.reasoning,
|
|
119278
119882
|
executionContext: buildExecutionContextForSymbol(entry.symbol)
|
|
119279
119883
|
};
|
|
119280
|
-
}
|
|
119884
|
+
};
|
|
119885
|
+
const acceptedBySlot = /* @__PURE__ */ new Map();
|
|
119886
|
+
for (const slot of reductionFirstOrder(finalDecisionPlans.map((entry) => ({
|
|
119887
|
+
decision: entry.decision,
|
|
119888
|
+
units: entry.units,
|
|
119889
|
+
signedUnits: computePlanSignedUnits(entry.symbol)
|
|
119890
|
+
})))) {
|
|
119891
|
+
acceptedBySlot.set(slot, acceptExecutionPlan(finalDecisionPlans[slot]));
|
|
119892
|
+
}
|
|
119893
|
+
const acceptedExecutionPlans = finalDecisionPlans.map((_, slot) => acceptedBySlot.get(slot));
|
|
119281
119894
|
const selectedAcceptedPlan = acceptedExecutionPlans.find((entry) => normalizeRuntimeSymbol(entry.symbol) === normalizeRuntimeSymbol(symbol2)) ?? acceptedExecutionPlans[0];
|
|
119282
119895
|
const acceptance = {
|
|
119283
119896
|
accepted: true,
|
|
@@ -119439,6 +120052,7 @@ ${reviewOutputContract}`;
|
|
|
119439
120052
|
completedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
119440
120053
|
settingsFallbackUsed,
|
|
119441
120054
|
settingsSnapshot: settingsSnapshotWithContext,
|
|
120055
|
+
reviewedCycle,
|
|
119442
120056
|
clientExchangeSnapshot,
|
|
119443
120057
|
executionContext: selectedAcceptedPlan?.executionContext ?? buildExecutionContextForSymbol(symbol2),
|
|
119444
120058
|
executionPlans: acceptedExecutionPlans
|
|
@@ -119540,6 +120154,7 @@ var init_engine = __esm({
|
|
|
119540
120154
|
init_hyperliquid_account_state_adapter();
|
|
119541
120155
|
init_hyperliquid_market_symbol();
|
|
119542
120156
|
init_client_killswitch();
|
|
120157
|
+
init_perp_dex_scope();
|
|
119543
120158
|
init_api2();
|
|
119544
120159
|
init_history_evidence();
|
|
119545
120160
|
init_portfolio_evidence();
|
|
@@ -119934,24 +120549,16 @@ var init_engine = __esm({
|
|
|
119934
120549
|
withServerPositionEvents = (result) => result.executionReports.map((report) => {
|
|
119935
120550
|
const action = String(report.action ?? "").toUpperCase();
|
|
119936
120551
|
if (report.status !== "executed" || !["BUY", "SELL", "FLIP_OPEN"].includes(action)) return report;
|
|
119937
|
-
const
|
|
119938
|
-
|
|
119939
|
-
|
|
119940
|
-
|
|
119941
|
-
|
|
119942
|
-
|
|
119943
|
-
|
|
119944
|
-
|
|
119945
|
-
|
|
119946
|
-
|
|
119947
|
-
event = "close";
|
|
119948
|
-
direction = action === "SELL" ? "LONG" : "SHORT";
|
|
119949
|
-
} else if (result.intent === "flip" && (result.side === "buy" || result.side === "sell")) {
|
|
119950
|
-
const [closeLeg, entryLeg] = flipExecutionLegs(result.side, "executed");
|
|
119951
|
-
const leg = report.execution_metadata?.decision_leg === "entry" || action === "FLIP_OPEN" ? entryLeg : closeLeg;
|
|
119952
|
-
event = leg.positionEvent;
|
|
119953
|
-
direction = leg.positionDirection;
|
|
119954
|
-
}
|
|
120552
|
+
const side = result.intent === "flip" || action === "FLIP_OPEN" ? result.side : action === "BUY" ? "buy" : "sell";
|
|
120553
|
+
if (side !== "buy" && side !== "sell") return report;
|
|
120554
|
+
const leg = report.execution_metadata?.decision_leg === "entry" || action === "FLIP_OPEN" ? "entry" : "flip_close";
|
|
120555
|
+
const { positionEvent: intentEvent, positionDirection: direction } = executedOrderPositionEvent(
|
|
120556
|
+
String(result.intent ?? ""),
|
|
120557
|
+
side,
|
|
120558
|
+
leg
|
|
120559
|
+
);
|
|
120560
|
+
const beganFlat = report.execution_metadata?.entry_began_flat;
|
|
120561
|
+
const event = (result.intent === "open" || result.intent === "add") && typeof beganFlat === "boolean" ? beganFlat ? "open" : "add" : result.intent === "close" && result.reasonCode === "close_fill_unresolved" ? "reduce" : intentEvent;
|
|
119955
120562
|
if (!event || !direction) return report;
|
|
119956
120563
|
return { ...report, execution_metadata: { ...report.execution_metadata, position_event: event, position_direction: direction } };
|
|
119957
120564
|
});
|
|
@@ -120182,6 +120789,8 @@ var init_engine = __esm({
|
|
|
120182
120789
|
this._stopPromise = null;
|
|
120183
120790
|
this._scheduledSuspendPromise = null;
|
|
120184
120791
|
this._loopIntervalMs = null;
|
|
120792
|
+
// When this runtime last checked in for Copy Trading (_processClientCopyTrading).
|
|
120793
|
+
this._lastClientCopyCheckInAtMs = null;
|
|
120185
120794
|
this._heartbeatIntervalMs = null;
|
|
120186
120795
|
this._leaseStaleAfterMs = null;
|
|
120187
120796
|
this._heartbeatOfflineAfterMs = null;
|
|
@@ -120236,6 +120845,8 @@ var init_engine = __esm({
|
|
|
120236
120845
|
this._settleUnreportedModelCalls = null;
|
|
120237
120846
|
// How many of an error's model calls its last error report carried.
|
|
120238
120847
|
this._lastErrorReportCalls = null;
|
|
120848
|
+
// The retry wait the API returned for this runtime's latest error report.
|
|
120849
|
+
this._reportedProviderRetryAfterSeconds = null;
|
|
120239
120850
|
this._activeRuntimeContractIdentity = null;
|
|
120240
120851
|
this._contractRebindInFlight = false;
|
|
120241
120852
|
this._contractRebindExhausted = false;
|
|
@@ -120424,6 +121035,7 @@ var init_engine = __esm({
|
|
|
120424
121035
|
await this._trailingMaintenancePromise;
|
|
120425
121036
|
await this._pendingProtectionRecoveryPromise;
|
|
120426
121037
|
await waitForBrowserExchangeMutationSettlement(profileId);
|
|
121038
|
+
const stopCloseVenues = profileEquityVenues(paused.settings.trading_symbols, paused.config.default_trading_symbols);
|
|
120427
121039
|
const { positions } = await fetchBrowserAccountState2({
|
|
120428
121040
|
publicRequestPriority: "trading_reduce",
|
|
120429
121041
|
config: paused.config,
|
|
@@ -120432,6 +121044,8 @@ var init_engine = __esm({
|
|
|
120432
121044
|
tickerPrice: 0,
|
|
120433
121045
|
leverage: 1,
|
|
120434
121046
|
aggregatePerpDexs: true,
|
|
121047
|
+
// Only the bot's exchanges: positions elsewhere are not the bot's to close.
|
|
121048
|
+
perpDexScope: stopCloseVenues?.filter(Boolean),
|
|
120435
121049
|
forceRefresh: true,
|
|
120436
121050
|
sessionId: this._sessionId ?? void 0
|
|
120437
121051
|
});
|
|
@@ -120444,7 +121058,8 @@ var init_engine = __esm({
|
|
|
120444
121058
|
positions,
|
|
120445
121059
|
config: paused.config,
|
|
120446
121060
|
signingKey,
|
|
120447
|
-
timeoutSeconds
|
|
121061
|
+
timeoutSeconds,
|
|
121062
|
+
venues: stopCloseVenues
|
|
120448
121063
|
});
|
|
120449
121064
|
if (summary.positionCloseFailures > 0) {
|
|
120450
121065
|
throw new Error(`${summary.positionCloseFailures} position(s) could not be closed`);
|
|
@@ -122577,6 +123192,18 @@ var init_engine = __esm({
|
|
|
122577
123192
|
this._analysisAbortReason = null;
|
|
122578
123193
|
const analysisAbortController = new AbortController();
|
|
122579
123194
|
this._analysisAbortController = analysisAbortController;
|
|
123195
|
+
let copyTradingCheckedIn = false;
|
|
123196
|
+
const checkInCopyTrading = async (config2) => {
|
|
123197
|
+
copyTradingCheckedIn = true;
|
|
123198
|
+
this._lastClientCopyCheckInAtMs = Date.now();
|
|
123199
|
+
await this._processClientCopyTrading({
|
|
123200
|
+
profileId,
|
|
123201
|
+
runtimeSessionId: sessionId,
|
|
123202
|
+
runtimeDeviceId: deviceId,
|
|
123203
|
+
config: config2,
|
|
123204
|
+
signal: analysisAbortController.signal
|
|
123205
|
+
});
|
|
123206
|
+
};
|
|
122580
123207
|
let decisionSubmitted = false;
|
|
122581
123208
|
let cycleModelCalls = [];
|
|
122582
123209
|
let cycleModelCallsReported = false;
|
|
@@ -122850,13 +123477,7 @@ var init_engine = __esm({
|
|
|
122850
123477
|
}
|
|
122851
123478
|
if (runtimeMode === "trader" && !cancelled()) {
|
|
122852
123479
|
try {
|
|
122853
|
-
await this.
|
|
122854
|
-
profileId,
|
|
122855
|
-
runtimeSessionId: sessionId,
|
|
122856
|
-
runtimeDeviceId: deviceId,
|
|
122857
|
-
config: await this.getExecutionConfig(profileId),
|
|
122858
|
-
signal: analysisAbortController.signal
|
|
122859
|
-
});
|
|
123480
|
+
await checkInCopyTrading(await this.getExecutionConfig(profileId));
|
|
122860
123481
|
} catch (copyTradingError) {
|
|
122861
123482
|
appendRuntimeDebugEvent({
|
|
122862
123483
|
label: "ai_schedule_paused_copy_poll_failed",
|
|
@@ -123040,14 +123661,7 @@ var init_engine = __esm({
|
|
|
123040
123661
|
if (this._primaryAnalysisDisabled) {
|
|
123041
123662
|
this._nextRunAtMs = null;
|
|
123042
123663
|
}
|
|
123043
|
-
|
|
123044
|
-
await this._processClientCopyTrading({
|
|
123045
|
-
profileId,
|
|
123046
|
-
runtimeSessionId: sessionId,
|
|
123047
|
-
runtimeDeviceId: deviceId,
|
|
123048
|
-
config: config2,
|
|
123049
|
-
signal: analysisAbortController.signal
|
|
123050
|
-
});
|
|
123664
|
+
await checkInCopyTrading(await this.getExecutionConfig(profileId));
|
|
123051
123665
|
}
|
|
123052
123666
|
this._lastError = null;
|
|
123053
123667
|
this._notifyListeners();
|
|
@@ -123101,7 +123715,17 @@ var init_engine = __esm({
|
|
|
123101
123715
|
// A Server bot's row records what started its cycle, as the
|
|
123102
123716
|
// Python Server loop's does (a Client row never has, and the key
|
|
123103
123717
|
// is part of a row's Insights settings epoch).
|
|
123104
|
-
settingsSnapshot:
|
|
123718
|
+
settingsSnapshot: {
|
|
123719
|
+
...result.settingsSnapshot,
|
|
123720
|
+
...this._expectedExecutionMode === "server" ? { analysis_trigger_origin: ignoreAiSchedule ? "manual" : "scheduled" } : {},
|
|
123721
|
+
// A cycle Review changed keeps the Main model and its own
|
|
123722
|
+
// decisions, as the Server loop's row does; the decision route
|
|
123723
|
+
// also records them as per-symbol rows.
|
|
123724
|
+
...result.reviewedCycle ? {
|
|
123725
|
+
original_model: result.reviewedCycle.originalModel,
|
|
123726
|
+
original_decisions: result.reviewedCycle.originalDecisions
|
|
123727
|
+
} : {}
|
|
123728
|
+
},
|
|
123105
123729
|
clientExchangeSnapshot: result.clientExchangeSnapshot ?? null,
|
|
123106
123730
|
// The server refuses a report with more attempts than one cycle can make.
|
|
123107
123731
|
invocations: boundRuntimeReportAttempts(
|
|
@@ -123209,7 +123833,7 @@ var init_engine = __esm({
|
|
|
123209
123833
|
symbol: plan.executionContext.symbol,
|
|
123210
123834
|
decision,
|
|
123211
123835
|
units: Math.trunc(Number(plan.units))
|
|
123212
|
-
})));
|
|
123836
|
+
})), capacityPlans[0]?.plan.executionContext.decisionSnapshotCapturedAt);
|
|
123213
123837
|
capacityPlans.forEach(({ planIndex }, index) => serverCapacityByPlan.set(planIndex, allocations[index]));
|
|
123214
123838
|
}
|
|
123215
123839
|
const runPlan = async (plan, planIndex) => {
|
|
@@ -123413,23 +124037,43 @@ var init_engine = __esm({
|
|
|
123413
124037
|
}
|
|
123414
124038
|
};
|
|
123415
124039
|
const cycleSupersededWithoutExecution = () => !this._executionFinalizationRequired && (analysisAbortController.signal.aborted || this._isStopping || this._analysisRequestId !== requestId);
|
|
123416
|
-
|
|
123417
|
-
|
|
124040
|
+
const advisorySignedUnits = (context) => {
|
|
124041
|
+
try {
|
|
124042
|
+
return signedUnitsFromEntryPosition(
|
|
124043
|
+
context.currentPositionSize,
|
|
124044
|
+
context.currentPositionEntryPrice,
|
|
124045
|
+
context.unitSizeUsdc
|
|
124046
|
+
);
|
|
124047
|
+
} catch {
|
|
124048
|
+
return 0;
|
|
124049
|
+
}
|
|
124050
|
+
};
|
|
124051
|
+
const dispatchOrder = reductionFirstOrder(executionPlans.map((plan) => ({
|
|
124052
|
+
decision: plan.decision,
|
|
124053
|
+
units: plan.units,
|
|
124054
|
+
signedUnits: advisorySignedUnits(plan.executionContext)
|
|
124055
|
+
})));
|
|
124056
|
+
const dispatchedPlanIndexes = [];
|
|
124057
|
+
for (const [dispatched, planIndex] of dispatchOrder.entries()) {
|
|
124058
|
+
if (dispatched > 0 && this._windowHandoffRequested) {
|
|
123418
124059
|
break;
|
|
123419
124060
|
}
|
|
123420
124061
|
const outcome = await runPlan(executionPlans[planIndex], planIndex);
|
|
123421
124062
|
if (outcome.control === "return") {
|
|
123422
124063
|
return;
|
|
123423
124064
|
}
|
|
124065
|
+
if (outcome.result) {
|
|
124066
|
+
recordPlanResult(outcome.result);
|
|
124067
|
+
dispatchedPlanIndexes.push(planIndex);
|
|
124068
|
+
}
|
|
123424
124069
|
if (outcome.control === "break") {
|
|
123425
|
-
if (outcome.result) recordPlanResult(outcome.result);
|
|
123426
124070
|
break;
|
|
123427
124071
|
}
|
|
123428
|
-
recordPlanResult(outcome.result);
|
|
123429
124072
|
if (cycleSupersededWithoutExecution()) {
|
|
123430
124073
|
return;
|
|
123431
124074
|
}
|
|
123432
124075
|
}
|
|
124076
|
+
executionResults.splice(0, executionResults.length, ...executionResults.map((executionResult, position) => ({ executionResult, planIndex: dispatchedPlanIndexes[position] })).sort((left, right) => left.planIndex - right.planIndex).map(({ executionResult }) => executionResult));
|
|
123433
124077
|
const executionReports = executionResults.flatMap((executionResult) => Array.isArray(executionResult.executionReports) ? this._expectedExecutionMode === "server" ? withServerPositionEvents(executionResult) : executionResult.executionReports : []);
|
|
123434
124078
|
const executedOrderReports = executionReports.filter((report) => report.status === "executed" && String(report.order_id || "").trim().length > 0);
|
|
123435
124079
|
const handoffCleanups = executionResults.flatMap((executionResult) => executionResult.handoffCleanup ? [executionResult.handoffCleanup] : []);
|
|
@@ -123574,13 +124218,7 @@ var init_engine = __esm({
|
|
|
123574
124218
|
if (this._windowHandoffRequested) {
|
|
123575
124219
|
return;
|
|
123576
124220
|
}
|
|
123577
|
-
await
|
|
123578
|
-
profileId,
|
|
123579
|
-
runtimeSessionId: sessionId,
|
|
123580
|
-
runtimeDeviceId: deviceId,
|
|
123581
|
-
config: config2,
|
|
123582
|
-
signal: analysisAbortController.signal
|
|
123583
|
-
});
|
|
124221
|
+
await checkInCopyTrading(config2);
|
|
123584
124222
|
this._executionModeMismatchConsecutiveCount = 0;
|
|
123585
124223
|
if (executionFailures.length > 0) {
|
|
123586
124224
|
cycleOutcome = "failed";
|
|
@@ -123734,9 +124372,8 @@ var init_engine = __esm({
|
|
|
123734
124372
|
});
|
|
123735
124373
|
return;
|
|
123736
124374
|
}
|
|
123737
|
-
if (
|
|
123738
|
-
|
|
123739
|
-
if (Number.isFinite(backoffSeconds) && backoffSeconds > 0) providerRetryDelayMs = backoffSeconds * MS_PER_SECOND;
|
|
124375
|
+
if (this._expectedExecutionMode === "server" && this._reportedProviderRetryAfterSeconds !== null) {
|
|
124376
|
+
providerRetryDelayMs = this._reportedProviderRetryAfterSeconds * MS_PER_SECOND;
|
|
123740
124377
|
}
|
|
123741
124378
|
if (hasEventBoundProviderFailureEvidence(error48)) {
|
|
123742
124379
|
this.scheduleProviderFailureDiagnosticsTelemetry({
|
|
@@ -123781,6 +124418,17 @@ var init_engine = __esm({
|
|
|
123781
124418
|
if (this._isExecuting) {
|
|
123782
124419
|
this._isExecuting = false;
|
|
123783
124420
|
}
|
|
124421
|
+
if (runtimeMode === "trader" && this._expectedExecutionMode !== "server" && !copyTradingCheckedIn && this._state === "running" && !this._isStopping && !this._windowHandoffRequested && !this._killswitchLatched && !this._executionFinalizationRequired && !this._scheduledSuspendPromise && !analysisAbortController.signal.aborted && this._profileId === profileId && this._sessionId === sessionId && this._deviceId === deviceId && (this._lastClientCopyCheckInAtMs === null || this._loopIntervalMs === null || Date.now() - this._lastClientCopyCheckInAtMs >= this._loopIntervalMs)) {
|
|
124422
|
+
try {
|
|
124423
|
+
await checkInCopyTrading(await this.getExecutionConfig(profileId));
|
|
124424
|
+
} catch (copyTradingError) {
|
|
124425
|
+
appendRuntimeDebugEvent({
|
|
124426
|
+
label: "copy_trading_cycle_end_check_in_failed",
|
|
124427
|
+
note: getSanitizedRuntimeErrorMessage(copyTradingError) || "Copy Trading check-in failed.",
|
|
124428
|
+
outcome: "error"
|
|
124429
|
+
});
|
|
124430
|
+
}
|
|
124431
|
+
}
|
|
123784
124432
|
if (this._analysisAbortController === analysisAbortController) {
|
|
123785
124433
|
this._analysisAbortController = null;
|
|
123786
124434
|
}
|
|
@@ -123819,7 +124467,7 @@ var init_engine = __esm({
|
|
|
123819
124467
|
primary_analysis_disabled: this._primaryAnalysisDisabled,
|
|
123820
124468
|
agent_poll_retry_ms: agentPollDelayMs
|
|
123821
124469
|
});
|
|
123822
|
-
const providerRetryWake = providerRetryDelayMs !== null && aiSchedulePauseMs === null && agentPollDelayMs === null
|
|
124470
|
+
const providerRetryWake = providerRetryDelayMs !== null && aiSchedulePauseMs === null && agentPollDelayMs === null ? providerRetryDelayMs : null;
|
|
123823
124471
|
if (providerRetryWake !== null) this._nextRunAtMs = Date.now() + providerRetryWake;
|
|
123824
124472
|
const windowEndsAtMs = this._aiScheduleWindowEndsAtMs;
|
|
123825
124473
|
const nextWorkAtMs = this._primaryAnalysisDisabled && this._loopIntervalMs != null ? Date.now() + this._loopIntervalMs : this._nextRunAtMs;
|
|
@@ -124046,6 +124694,7 @@ var init_engine = __esm({
|
|
|
124046
124694
|
}
|
|
124047
124695
|
}
|
|
124048
124696
|
async reportError(reason, options) {
|
|
124697
|
+
this._reportedProviderRetryAfterSeconds = null;
|
|
124049
124698
|
if (this._isStopping) {
|
|
124050
124699
|
this._lastError = null;
|
|
124051
124700
|
return null;
|
|
@@ -124124,6 +124773,8 @@ var init_engine = __esm({
|
|
|
124124
124773
|
}
|
|
124125
124774
|
);
|
|
124126
124775
|
const accepted = this._setRuntimeStatus(response.runtime, "error_report");
|
|
124776
|
+
const retryAfterSeconds = Number(response.provider_retry_after_seconds);
|
|
124777
|
+
this._reportedProviderRetryAfterSeconds = accepted && response.provider_retry_after_seconds != null && Number.isFinite(retryAfterSeconds) && retryAfterSeconds >= 0 ? retryAfterSeconds : null;
|
|
124127
124778
|
this._lastError = persistedError;
|
|
124128
124779
|
this._notifyListeners();
|
|
124129
124780
|
return accepted ? response.runtime ?? null : null;
|
|
@@ -124663,7 +125314,7 @@ var init_engine = __esm({
|
|
|
124663
125314
|
positionCloseFailures: 0
|
|
124664
125315
|
};
|
|
124665
125316
|
if (context.close_positions) {
|
|
124666
|
-
const stalePositions = evaluation.accountState?.positions ?? [];
|
|
125317
|
+
const stalePositions = positionsOnVenues(evaluation.accountState?.positions ?? [], evaluation.equityVenues);
|
|
124667
125318
|
try {
|
|
124668
125319
|
const signingKey = String(
|
|
124669
125320
|
this._deviceSecrets?.hyperliquidSigningKey || ""
|
|
@@ -124692,6 +125343,8 @@ var init_engine = __esm({
|
|
|
124692
125343
|
tickerPrice: 0,
|
|
124693
125344
|
leverage: 1,
|
|
124694
125345
|
aggregatePerpDexs: true,
|
|
125346
|
+
// The exchanges the check read: positions elsewhere are not the bot's to close.
|
|
125347
|
+
perpDexScope: evaluation.equityVenues?.filter(Boolean),
|
|
124695
125348
|
forceRefresh: true,
|
|
124696
125349
|
sessionId: this._sessionId ?? void 0,
|
|
124697
125350
|
signal: refreshController.signal
|
|
@@ -124714,7 +125367,8 @@ var init_engine = __esm({
|
|
|
124714
125367
|
positions: freshPositions,
|
|
124715
125368
|
config: config2,
|
|
124716
125369
|
signingKey,
|
|
124717
|
-
timeoutSeconds: closeTimeoutSeconds
|
|
125370
|
+
timeoutSeconds: closeTimeoutSeconds,
|
|
125371
|
+
venues: evaluation.equityVenues
|
|
124718
125372
|
});
|
|
124719
125373
|
} else {
|
|
124720
125374
|
closeSummary = {
|