@vtxmacro/cli 2026.10.68 → 2026.10.70
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 -1
- package/bin/vtx-mcp.js +3 -2
- package/bin/vtx-service-bootstrap.js +3 -2
- package/bin/vtx-service-launcher.js +2 -1
- package/bin/vtx.js +537 -389
- package/package.json +1 -1
package/bin/vtx.js
CHANGED
|
@@ -122,7 +122,7 @@ var init_routing = __esm({
|
|
|
122
122
|
var agent_cli_release_default;
|
|
123
123
|
var init_agent_cli_release = __esm({
|
|
124
124
|
"agent-cli-release.json"() {
|
|
125
|
-
agent_cli_release_default = { package_name: "@vtxmacro/cli", package_version: "2026.10.
|
|
125
|
+
agent_cli_release_default = { package_name: "@vtxmacro/cli", package_version: "2026.10.70", codex_package_name: "@openai/codex", codex_version: "0.155.0", copilot_sdk_package_name: "@github/copilot-sdk", copilot_sdk_version: "1.0.0-beta.8", copilot_cli_package_name: "@github/copilot", copilot_cli_version: "1.0.80", deepseek_harness_version: "0.1.1-rc.2", deepseek_harness_packages: ["@deepseek-ai/dsh-agent", "@deepseek-ai/dsh-agent-instructions", "@deepseek-ai/dsh-agent-loop", "@deepseek-ai/dsh-agent-spine-demo", "@deepseek-ai/dsh-anonymous-user-id", "@deepseek-ai/dsh-atomic-write", "@deepseek-ai/dsh-attachment", "@deepseek-ai/dsh-brand", "@deepseek-ai/dsh-code-runtime", "@deepseek-ai/dsh-credentials", "@deepseek-ai/dsh-fs", "@deepseek-ai/dsh-goal", "@deepseek-ai/dsh-goal-round-driver", "@deepseek-ai/dsh-home-paths", "@deepseek-ai/dsh-invariants", "@deepseek-ai/dsh-jobs", "@deepseek-ai/dsh-jobs-local", "@deepseek-ai/dsh-launch-environment", "@deepseek-ai/dsh-llm", "@deepseek-ai/dsh-llm-deepseek", "@deepseek-ai/dsh-llm-retry", "@deepseek-ai/dsh-output-retention", "@deepseek-ai/dsh-sandbox", "@deepseek-ai/dsh-sandbox-policy", "@deepseek-ai/dsh-scope", "@deepseek-ai/dsh-session", "@deepseek-ai/dsh-session-checkpoint-policy", "@deepseek-ai/dsh-session-persistence", "@deepseek-ai/dsh-session-persistence-jsonl", "@deepseek-ai/dsh-session-projection", "@deepseek-ai/dsh-session-title", "@deepseek-ai/dsh-settings", "@deepseek-ai/dsh-shell", "@deepseek-ai/dsh-shell-env", "@deepseek-ai/dsh-skill", "@deepseek-ai/dsh-skill-filesystem", "@deepseek-ai/dsh-subprocess", "@deepseek-ai/dsh-system-prompt", "@deepseek-ai/dsh-timeout", "@deepseek-ai/dsh-tool-bash", "@deepseek-ai/dsh-tool-goal", "@deepseek-ai/dsh-tool-jobs", "@deepseek-ai/dsh-tool-skill", "@deepseek-ai/dsh-tools", "@deepseek-ai/dsh-typert-protocol", "@deepseek-ai/dsh-user-approval"], deepseek_cordis_package_name: "@deepseek-ai/cordis", deepseek_cordis_version: "4.0.1", deepseek_support_packages: { "@deepseek-ai/cordis-plugin-timer": "1.1.3" }, platforms: { "linux-x64": { package_name: "@openai/codex-linux-x64", target: "x86_64-unknown-linux-musl", binary_name: "codex", sha256: "660e159a49e823ac8e5986cb238f73158ce4b957d40d9292f8de90862644b501" }, "win32-x64": { package_name: "@openai/codex-win32-x64", target: "x86_64-pc-windows-msvc", binary_name: "codex.exe", sha256: "e4c11374bd9de8ad5c3b7617fd4654bb7839901edb0863f9930666863c7a021b" } }, pi_coding_agent_package_name: "@earendil-works/pi-coding-agent", pi_ai_package_name: "@earendil-works/pi-ai", pi_version: "0.85.1", pi_support_packages: ["@earendil-works/pi-agent-core", "@earendil-works/pi-telemetry", "@earendil-works/pi-tui", "@earendil-works/chord"], grok_version: "1.0.30", grok_platforms: { "linux-x64": { package_name: "@xai-official/grok-linux-x64", binary_name: "grok", sha256: "504dd6546ab991b75d36698242875ce461489cd1f8cd84285873cb55bd5c7d54" }, "win32-x64": { package_name: "@xai-official/grok-win32-x64", binary_name: "grok.exe", sha256: "48736d1a4342a801ea26d0ecde4c516b653f791399065adaa55973f83abd8867" } } };
|
|
126
126
|
}
|
|
127
127
|
});
|
|
128
128
|
|
|
@@ -999,7 +999,8 @@ var init_runtime_policy_generated = __esm({
|
|
|
999
999
|
base_delay_milliseconds: 300,
|
|
1000
1000
|
max_delay_milliseconds: 8e3,
|
|
1001
1001
|
min_retry_after_milliseconds: 250,
|
|
1002
|
-
deadline_attempt_spacing_milliseconds: 250
|
|
1002
|
+
deadline_attempt_spacing_milliseconds: 250,
|
|
1003
|
+
market_data_max_attempts: 2
|
|
1003
1004
|
}
|
|
1004
1005
|
},
|
|
1005
1006
|
server_runtime: {
|
|
@@ -3233,7 +3234,7 @@ var init_shared_contracts_generated = __esm({
|
|
|
3233
3234
|
});
|
|
3234
3235
|
|
|
3235
3236
|
// lib/constants.ts
|
|
3236
|
-
var MS_PER_SECOND, MICROSECONDS_PER_MS, MICROSECONDS_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, FNV1A_32_OFFSET_BASIS, FNV1A_32_PRIME, JSON_INDENT_SPACES, INT32_MIN, INT32_MAX, SET_TIMEOUT_MAX_DELAY_MS,
|
|
3237
|
+
var MS_PER_SECOND, MICROSECONDS_PER_MS, MICROSECONDS_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, FNV1A_32_OFFSET_BASIS, FNV1A_32_PRIME, JSON_INDENT_SPACES, INT32_MIN, INT32_MAX, SET_TIMEOUT_MAX_DELAY_MS, POSITION_SIZE_EPSILON, HYPERLIQUID_WEBSOCKET_MAX_USERS_PER_IP, HTTP_STATUS, HTTP_STATUS_MIN, HTTP_STATUS_MAX, HTTP_CLIENT_ERROR_MIN, HTTP_SERVER_ERROR_MIN, PROMPT_RESCUE_ASKS_PER_CYCLE_BUILD, AI_COST_ESTIMATE_PERIOD_DAYS, SECONDS_PER_AI_COST_ESTIMATE_PERIOD, DATE_FIELD_DIGITS, NODE_ARGV_COMMAND_ARGS_START, EXIT_CODE_TEMPFAIL, SHA256_INITIAL_STATE, SHA256_ROUND_CONSTANTS, SHA256, UINT64_HIGH_WORD_DIVISOR, CANONICAL_BASE64URL, INFERENCE_ENVELOPE_CRYPTO, JSON_RPC_ERROR_CODES, INFERENCE_MCP_SCHEMA_PROBE_MAX_DEPTH, INFERENCE_HOST_PROCESS_LOCK_RECORD_SCHEMA_VERSION, NATIVE_PROTECTION_RECORD_WITH_LOTS_VERSION, INFERENCE_HOST_RECLAIM_GUARD_CREATE_PASSES, LINUX_PROC_STAT_COMM_TERMINATOR_CHARS, INFERENCE_HOST_RANDOM_BYTES, INFERENCE_OAUTH_TOKEN_MAX_LENGTH, INFERENCE_CREDENTIAL_WINDOWS_NOT_FOUND_EXIT_CODE, MACOS_SECURITY_ITEM_NOT_FOUND_EXIT_CODE, INFERENCE_CREDENTIAL_LABEL_ACCOUNT_KEY_CHARS, INFERENCE_HOST_STABLE_OPERATION_ID_HASH_CHARS, INFERENCE_HOST_DRAIN_PRIORITY, INFERENCE_JOB_CLAIM_SCHEMA_VERSION, INFERENCE_HOST_WINDOWS_TASK_IDENTITY_MAX_CHARS, INFERENCE_HOST_OWNER_ONLY_EXECUTABLE_MODE, WINDOWS_TASKKILL_PROCESS_NOT_FOUND_EXIT_CODE, INFERENCE_HOST_CLI_MAX_SERVICE_POSITIONALS, INFERENCE_HOST_CLI_MAX_COMMAND_POSITIONALS, INFERENCE_HOST_DISPLAY_NAME_MAX_CHARS, INFERENCE_HOST_REVOCATION_CHECKPOINT_MAX_CHARS, INFERENCE_HOST_MODEL_ID_MAX_CHARS, CODEX_RECOVERY_RECEIPT_MAX_CHARS, CODEX_HOSTED_ATTEMPT_PATH_SEGMENTS, INFERENCE_HOST_TEMP_FOLDERS, INFERENCE_HOST_FAILURE_CAUSE_MAX_DEPTH, CODEX_GUARDIAN_PROCESS_TOKEN_BYTES, CODEX_RATE_LIMIT_EXHAUSTED_PERCENT, INFERENCE_HOST_PROXY_TOKEN_BYTES, AGENT_TOOL_SERVER_TOKEN_BYTES, GROK_NATIVE_SESSION_GROUP_NAME_MAX_CHARS, GROK_POLICY_TRANSPORT_MAX_BYTES, EXO_POLICY_MAX_TOOL_ROUNDS, EXO_POLICY_MAX_MODELS, EXO_POLICY_MODEL_NAME_MAX_CHARS, CLAUDE_CODE_POLICY_MAX_MODELS, CLAUDE_CODE_POLICY_MODEL_NAME_MAX_CHARS, CLAUDE_CODE_POLICY_MAX_TURNS, ANTHROPIC_SCHEMA_PROPERTY_NAME_MAX_CHARS, EXO_RUNTIME_VERSION_COMMIT_CHARS, PI_QUALIFIED_MODEL_ID_MAX_CHARS, PI_STRUCTURED_OUTPUT_MAX_DEPTH, PI_STRUCTURED_OUTPUT_MAX_PROPERTIES, INFERENCE_HOST_API_KEY_MIN_CHARS, INFERENCE_HOST_API_KEY_MAX_BYTES, INFERENCE_HOST_API_KEY_IDENTITY_HEX_CHARS, DEEPSEEK_HARNESS_NODE_LTS_MAJOR, DEEPSEEK_HARNESS_NODE_LTS_MIN_MINOR, DEEPSEEK_HARNESS_NODE_CURRENT_MAJOR, PROMPT_FIXED_DIGITS, PROMPT_SIGNIFICANT_DIGITS, PROMPT_NUMBER_MAX_DIGITS, PROMPT_RELATIVE_VOLUME_DIGITS, BINARY_RADIX, PROMPT_PRICE_INTEGER_THRESHOLD, PROMPT_MARGIN_UTILIZATION_DECIMALS, PROMPT_SYMBOL_MAX_CHARS, HALF_UP_ROUNDING_OFFSET, PROMPT_ENTRY_PRICE_MATCH_ABS_TOLERANCE, PROMPT_ENTRY_PRICE_MATCH_REL_TOLERANCE, DECISION_OUTPUT_EXAMPLE_TRADABILITY, IEEE754_MANTISSA_BITS, IEEE754_EXPONENT_BIAS, IEEE754_EXPONENT_MASK, IEEE754_HIGH_MANTISSA_MASK, IEEE754_HIGH_WORD_EXPONENT_SHIFT, IEEE754_SIGN_BIT_SHIFT, UINT32_RANGE, PYTHON_SQRT_BIT_WIDTH, PYTHON_REPR_EXPONENT_MIN_DECPT, PYTHON_REPR_EXPONENT_MAX_DECPT, PYTHON_REPR_MIN_EXPONENT_DIGITS, TO_FIXED_MAX_MAGNITUDE, UNICODE_DEFAULT_IGNORABLE_RANGES_OUTSIDE_CATEGORIES, CALENDAR_FIELD_MAX_CHARS, 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, PROMPT_METRIC_DECIMALS, CENT_DECIMALS, REGIME_ADX_CHOP_DECIMALS, FILL_SIZE_MATCH_TOLERANCE, PERFORMANCE_HOLD_MINUTES_DECIMALS, SERIES_CHANGE_MIN_POINTS, INDICATOR_ADX_PERIOD, INDICATOR_CHOP_PERIOD, ADX_WARMUP_PERIODS, WINDOW_FEATURES_MIN_CANDLES, WINDOW_FEATURES_PIVOT_NEIGHBOR_DISTANCE, FRACTAL_SIDES, REGRESSION_MIN_POINTS, SAMPLE_STDEV_MIN_POINTS, WINDOW_FEATURES_SLOPE_DECIMALS, WINDOW_FEATURES_R_SQUARED_DECIMALS, WINDOW_FEATURES_Z_SCORE_DECIMALS, WINDOW_FEATURES_GREEN_RATIO_DECIMALS, WINDOW_FEATURES_ATR_PERCENT_DECIMALS, EMA_SMOOTHING_NUMERATOR, PROMPT_EMA_PERIODS, JSON_UNICODE_ESCAPE_PREFIX_LENGTH, JSON_UNICODE_ESCAPE_HEX_DIGITS, ASCII_FIRST_PRINTABLE_CODE, ASCII_LAST_PRINTABLE_CODE, JSON_CONTROL_CHARACTER_MAX, RUNTIME_DEBUG_SNIPPET_CHARS, RUNTIME_DEBUG_PROMPT_SNIPPET_CHARS, RUNTIME_DEBUG_TOKEN_PREFIX_CHARS, RUNTIME_DEBUG_USD_DECIMALS, 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_TIF_GTC, HYPERLIQUID_TPSL_BATCH_MIN_ORDERS, HYPERLIQUID_USER_FILLS_PROVIDER_PAGE_CAP, HYPERLIQUID_CANDLE_SNAPSHOT_BASE_WEIGHT, HYPERLIQUID_CANDLE_SNAPSHOT_ROWS_PER_WEIGHT, HYPERLIQUID_CANDLE_SNAPSHOT_MAX_ROWS, HYPERLIQUID_ROW_WEIGHTED_INFO_REQUESTS, HYPERLIQUID_ROW_WEIGHTED_INFO_BASE_WEIGHT, HYPERLIQUID_INFO_ROWS_PER_EXTRA_WEIGHT, HYPERLIQUID_PUBLIC_READ_WINDOWS_KEPT, CLIENT_RUNTIME_NOTE_GAP_MAX_LOOPS, HYPERLIQUID_META_AND_ASSET_CTXS_PARTS, HYPERLIQUID_SIDE_PAIR_LENGTH, HYPERLIQUID_SIGNED_SIZE_MATCH_EXTRA_DECIMALS, HYPERLIQUID_OPEN_ORDERS_MAX_NESTING_DEPTH, ACCOUNT_PAYLOAD_MODE_SEARCH_MAX_DEPTH, HYPERLIQUID_ACCOUNT_ROUNDING_DECIMALS, HYPERLIQUID_UNREALIZED_PNL_ZERO_TOLERANCE, HYPERLIQUID_MAX_DEPLOYER_FEE_SCALE, HYPERLIQUID_DEPLOYER_FEE_SCALE_MULTIPLIER, HYPERLIQUID_GROWTH_MODE_FEE_FACTOR, HYPERLIQUID_ALIGNED_QUOTE_NON_DEPLOYER_FEE_FACTOR, HYPERLIQUID_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_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, AI_SNAPSHOT_COMPACT_TRANSPORT_VERSION, AI_SNAPSHOT_PACKED_FIELDS, AI_SNAPSHOT_PACKED_ENTRY_FIELDS, TOKENS_PER_MILLION, RENDER_DEBUG_ID_RANDOM_CHARS, BASE32_BITS_PER_CHARACTER, MT5_CLIENT_ID_MAX_LENGTH, MT5_SYNTHETIC_LEG_ID_BASE, MT5_SYNTHETIC_LEG_KINDS, MT5_SYNTHETIC_LEG_KEY_BITS, FNV1A_64_BITS, FNV1A_64_OFFSET_BASIS, FNV1A_64_PRIME, MT5_GRID_TOLERANCE;
|
|
3237
3238
|
var init_constants = __esm({
|
|
3238
3239
|
"lib/constants.ts"() {
|
|
3239
3240
|
"use strict";
|
|
@@ -3282,7 +3283,6 @@ var init_constants = __esm({
|
|
|
3282
3283
|
INT32_MIN = -(2 ** 31);
|
|
3283
3284
|
INT32_MAX = 2 ** 31 - 1;
|
|
3284
3285
|
SET_TIMEOUT_MAX_DELAY_MS = INT32_MAX;
|
|
3285
|
-
FLOAT_EQUALITY_EPSILON = 1e-12;
|
|
3286
3286
|
POSITION_SIZE_EPSILON = 1e-5;
|
|
3287
3287
|
HYPERLIQUID_WEBSOCKET_MAX_USERS_PER_IP = 10;
|
|
3288
3288
|
HTTP_STATUS = {
|
|
@@ -22839,7 +22839,8 @@ var init_runtime_policy_generated2 = __esm({
|
|
|
22839
22839
|
base_delay_milliseconds: 300,
|
|
22840
22840
|
max_delay_milliseconds: 8e3,
|
|
22841
22841
|
min_retry_after_milliseconds: 250,
|
|
22842
|
-
deadline_attempt_spacing_milliseconds: 250
|
|
22842
|
+
deadline_attempt_spacing_milliseconds: 250,
|
|
22843
|
+
market_data_max_attempts: 2
|
|
22843
22844
|
}
|
|
22844
22845
|
},
|
|
22845
22846
|
server_runtime: {
|
|
@@ -60005,6 +60006,28 @@ var init_runtime_error_wording = __esm({
|
|
|
60005
60006
|
}
|
|
60006
60007
|
});
|
|
60007
60008
|
|
|
60009
|
+
// lib/rate-limit-text.ts
|
|
60010
|
+
var RATE_LIMIT_TEXT, COOLDOWN_SECONDS, RETRY_IN_SECONDS, APP_RATE_LIMIT_WORDING, isRateLimitErrorText, rateLimitMessage;
|
|
60011
|
+
var init_rate_limit_text = __esm({
|
|
60012
|
+
"lib/rate-limit-text.ts"() {
|
|
60013
|
+
"use strict";
|
|
60014
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
60015
|
+
init_define_VTX_EXO_POLICY();
|
|
60016
|
+
init_define_VTX_GROK_POLICY();
|
|
60017
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
60018
|
+
RATE_LIMIT_TEXT = /rate\s*limit|(?:^|[^\w.]|[^\d.]\.)429(?![\w]|\.\d)|cooling\s*down/i;
|
|
60019
|
+
COOLDOWN_SECONDS = /cooling\s*down\s*for\s*([0-9]+(?:\.[0-9]+)?)s/i;
|
|
60020
|
+
RETRY_IN_SECONDS = /retry\s*in\s*~?\s*([0-9]+(?:\.[0-9]+)?)s/i;
|
|
60021
|
+
APP_RATE_LIMIT_WORDING = "Hyperliquid is rate-limited.";
|
|
60022
|
+
isRateLimitErrorText = (text2) => RATE_LIMIT_TEXT.test(String(text2 || ""));
|
|
60023
|
+
rateLimitMessage = (raw) => {
|
|
60024
|
+
const text2 = String(raw || "");
|
|
60025
|
+
const match = text2.match(COOLDOWN_SECONDS) ?? text2.match(RETRY_IN_SECONDS);
|
|
60026
|
+
return match ? `${APP_RATE_LIMIT_WORDING} Please retry in ~${match[1]}s.` : `${APP_RATE_LIMIT_WORDING} Please wait a moment and retry.`;
|
|
60027
|
+
};
|
|
60028
|
+
}
|
|
60029
|
+
});
|
|
60030
|
+
|
|
60008
60031
|
// lib/api/shared.ts
|
|
60009
60032
|
function configureApiTransport(transport) {
|
|
60010
60033
|
if (transport === null) {
|
|
@@ -60032,7 +60055,7 @@ function getProfileHeaders(baseHeaders = {}, explicitProfileId) {
|
|
|
60032
60055
|
if (profileId) headers["x-profile-id"] = profileId.toString();
|
|
60033
60056
|
return headers;
|
|
60034
60057
|
}
|
|
60035
|
-
var configuredApiTransport, getApiUrl, withoutContentType, browserRequestInit, sendApiRequest, apiFetch, sleep, DEVICE_CLOCK_HEADER, deviceClockHeader, API_NO_ROUTE_DETAIL, isMissingApiRoute, sendExchangeMutationReport, inFlightClientGetRequests, recentClientGetResponses, clientGetRequestGenerations, initializedClientGetRequestKeys, CLIENT_GET_DEDUPE_TTL_MS, CLIENT_RUNTIME_STATUSES_DEDUPE_TTL_MS, CLIENT_LLM_CONFIG_PRIME_TTL_MS, AUTH_BOOTSTRAP_GET_MAX_ATTEMPTS, AUTH_BOOTSTRAP_RETRY_JITTER_MS, singleUserHostCache, canUseClientGetRequestCache, clientGetRequestCacheActive, invalidateClientGetRequestCache, raceWithAbortSignal, shareClientGetRequest, clientGetRequestKey, clientPreferencesRequestKey, invalidateClientPreferencesCache, parseRetryAfterMs2, resolveAuthBootstrapRetryDelayMs, fetchAuthBootstrapGetWithRetry, annotateMarketDataRequestError, buildMarketDataFetchError, buildMarketDataNetworkError, buildMarketDataResponseBodyError, NODE_FETCH_NETWORK_CAUSE_CODES, isTransientNetworkFetchError, createIdempotencyKey, getErrorMessage, getErrorPayloadOrEmpty, getErrorPayloadOrFallbackDetail, getErrorMessageFromResponse, throwUnauthorizedIfNeeded, activeProfileId, PROFILE_STORAGE_KEY;
|
|
60058
|
+
var configuredApiTransport, getApiUrl, withoutContentType, browserRequestInit, sendApiRequest, apiFetch, sleep, DEVICE_CLOCK_HEADER, deviceClockHeader, API_NO_ROUTE_DETAIL, isMissingApiRoute, sendExchangeMutationReport, inFlightClientGetRequests, recentClientGetResponses, clientGetRequestGenerations, initializedClientGetRequestKeys, CLIENT_GET_DEDUPE_TTL_MS, CLIENT_RUNTIME_STATUSES_DEDUPE_TTL_MS, CLIENT_LLM_CONFIG_PRIME_TTL_MS, AUTH_BOOTSTRAP_GET_MAX_ATTEMPTS, AUTH_BOOTSTRAP_RETRY_JITTER_MS, singleUserHostCache, canUseClientGetRequestCache, clientGetRequestCacheActive, invalidateClientGetRequestCache, raceWithAbortSignal, shareClientGetRequest, clientGetRequestKey, clientPreferencesRequestKey, invalidateClientPreferencesCache, parseRetryAfterMs2, resolveClientRuntimeRetryDelayMs, resolveAuthBootstrapRetryDelayMs, fetchAuthBootstrapGetWithRetry, annotateMarketDataRequestError, readMarketDataWithRetry, buildMarketDataFetchError, buildMarketDataNetworkError, buildMarketDataResponseBodyError, NODE_FETCH_NETWORK_CAUSE_CODES, isTransientNetworkFetchError, createIdempotencyKey, getErrorMessage, getErrorPayloadOrEmpty, getErrorPayloadOrFallbackDetail, getErrorMessageFromResponse, throwUnauthorizedIfNeeded, activeProfileId, PROFILE_STORAGE_KEY;
|
|
60036
60059
|
var init_shared = __esm({
|
|
60037
60060
|
"lib/api/shared.ts"() {
|
|
60038
60061
|
"use strict";
|
|
@@ -60048,6 +60071,7 @@ var init_shared = __esm({
|
|
|
60048
60071
|
init_abort();
|
|
60049
60072
|
init_runtime_redaction();
|
|
60050
60073
|
init_runtime_error_wording();
|
|
60074
|
+
init_rate_limit_text();
|
|
60051
60075
|
configuredApiTransport = null;
|
|
60052
60076
|
getApiUrl = () => {
|
|
60053
60077
|
if (configuredApiTransport) return configuredApiTransport.baseUrl;
|
|
@@ -60201,6 +60225,14 @@ var init_shared = __esm({
|
|
|
60201
60225
|
if (Number.isFinite(retryAtMs)) return Math.max(0, retryAtMs - Date.now());
|
|
60202
60226
|
return null;
|
|
60203
60227
|
};
|
|
60228
|
+
resolveClientRuntimeRetryDelayMs = (attempt2, retryAfterHeader) => {
|
|
60229
|
+
const policy3 = runtime_policy_generated_default2.trading.engine.client_runtime.request_retry;
|
|
60230
|
+
const retryAfterMs = parseRetryAfterMs2(retryAfterHeader);
|
|
60231
|
+
if (retryAfterMs != null) {
|
|
60232
|
+
return Math.min(policy3.max_delay_milliseconds, Math.max(policy3.min_retry_after_milliseconds, retryAfterMs));
|
|
60233
|
+
}
|
|
60234
|
+
return Math.min(policy3.max_delay_milliseconds, policy3.base_delay_milliseconds * BACKOFF_GROWTH_FACTOR ** (attempt2 - 1));
|
|
60235
|
+
};
|
|
60204
60236
|
resolveAuthBootstrapRetryDelayMs = (response, attempt2) => {
|
|
60205
60237
|
const retryAfterMs = parseRetryAfterMs2(response.headers.get("Retry-After"));
|
|
60206
60238
|
const baseDelayMs = retryAfterMs ?? runtime_policy_generated_default2.ui.auth_bootstrap_retry.base_delay_milliseconds * BACKOFF_GROWTH_FACTOR ** (attempt2 - 1);
|
|
@@ -60224,8 +60256,26 @@ var init_shared = __esm({
|
|
|
60224
60256
|
runtimeRequestMaxAttempts: 1,
|
|
60225
60257
|
runtimeRequestStatus: status,
|
|
60226
60258
|
runtimeRequestErrorKind: kind,
|
|
60227
|
-
runtimeRequestTransientNetwork: kind === "network" && isTransientNetworkFetchError(error48)
|
|
60259
|
+
runtimeRequestTransientNetwork: kind === "network" && isTransientNetworkFetchError(error48) || kind === "response_body" && isTransientNetworkFetchError(error48.cause)
|
|
60228
60260
|
});
|
|
60261
|
+
readMarketDataWithRetry = async (signal, read) => {
|
|
60262
|
+
const maxAttempts = runtime_policy_generated_default2.trading.engine.client_runtime.request_retry.market_data_max_attempts;
|
|
60263
|
+
for (let attempt2 = 1; ; attempt2 += 1) {
|
|
60264
|
+
try {
|
|
60265
|
+
return await read();
|
|
60266
|
+
} catch (error48) {
|
|
60267
|
+
const transient = error48?.runtimeRequestTransientNetwork === true;
|
|
60268
|
+
if (transient && attempt2 < maxAttempts) {
|
|
60269
|
+
await abortableSleep(resolveClientRuntimeRetryDelayMs(attempt2, null), signal);
|
|
60270
|
+
continue;
|
|
60271
|
+
}
|
|
60272
|
+
if (error48 instanceof Error && "runtimeRequestPath" in error48) {
|
|
60273
|
+
Object.assign(error48, { runtimeRequestAttempt: attempt2, runtimeRequestMaxAttempts: maxAttempts });
|
|
60274
|
+
}
|
|
60275
|
+
throw error48;
|
|
60276
|
+
}
|
|
60277
|
+
}
|
|
60278
|
+
};
|
|
60229
60279
|
buildMarketDataFetchError = async (response, label2, path) => {
|
|
60230
60280
|
let responseText = "";
|
|
60231
60281
|
try {
|
|
@@ -60280,11 +60330,7 @@ var init_shared = __esm({
|
|
|
60280
60330
|
};
|
|
60281
60331
|
getErrorMessage = (error48, defaultMessage) => {
|
|
60282
60332
|
if (typeof error48?.detail_in_android_app === "string" && isAndroidAppPage()) return error48.detail_in_android_app;
|
|
60283
|
-
const extractRateLimitMessage = (raw) =>
|
|
60284
|
-
if (!/rate\s*limit|429|cooling\s*down/i.test(raw)) return null;
|
|
60285
|
-
const match = raw.match(/cooling\s*down\s*for\s*([0-9]+(?:\.[0-9]+)?)s/i);
|
|
60286
|
-
return match ? `Hyperliquid is rate-limited. Please retry in ~${match[1]}s.` : "Hyperliquid is rate-limited. Please wait a moment and retry.";
|
|
60287
|
-
};
|
|
60333
|
+
const extractRateLimitMessage = (raw) => isRateLimitErrorText(raw) ? rateLimitMessage(raw) : null;
|
|
60288
60334
|
if (isTransientNetworkFetchError(error48 instanceof Error ? error48 : error48?.message)) {
|
|
60289
60335
|
return "Network error. Please check your connection.";
|
|
60290
60336
|
}
|
|
@@ -61879,7 +61925,7 @@ async function getRecentCandlesForProfile(profileId, limit, exchange, symbol2, t
|
|
|
61879
61925
|
}
|
|
61880
61926
|
async function getLiveTicker(symbol2 = "PI_XBTUSD", exchange = "kraken", signal) {
|
|
61881
61927
|
const requestKey = `live-ticker:${symbol2}:${exchange}`;
|
|
61882
|
-
return shareClientGetRequest(requestKey, async (
|
|
61928
|
+
return shareClientGetRequest(requestKey, (requestSignal) => readMarketDataWithRetry(requestSignal, async () => {
|
|
61883
61929
|
const requestUrl2 = `${getApiUrl()}/ticker/live?symbol=${encodeURIComponent(symbol2)}&exchange=${encodeURIComponent(exchange)}`;
|
|
61884
61930
|
const trace = startRuntimeNetworkDebugTrace({
|
|
61885
61931
|
kind: "runtime",
|
|
@@ -61912,7 +61958,7 @@ async function getLiveTicker(symbol2 = "PI_XBTUSD", exchange = "kraken", signal)
|
|
|
61912
61958
|
if (isAbortLikeError(error48)) throw error48;
|
|
61913
61959
|
throw buildMarketDataNetworkError(error48, "live ticker", "/ticker/live");
|
|
61914
61960
|
}
|
|
61915
|
-
}, { signal });
|
|
61961
|
+
}), { signal });
|
|
61916
61962
|
}
|
|
61917
61963
|
async function getExecutionAssetMetadata(exchange, symbol2, options) {
|
|
61918
61964
|
const params = new URLSearchParams();
|
|
@@ -61971,7 +62017,7 @@ var init_market_data = __esm({
|
|
|
61971
62017
|
const params = new URLSearchParams({ limit: limit.toString(), exchange, symbol: symbol2, timeframe });
|
|
61972
62018
|
const requestUrl2 = `${getApiUrl()}/candles/recent?${params.toString()}`;
|
|
61973
62019
|
const forProfile = profileId === null ? {} : { credentials: "include", headers: getProfileHeaders(persistedRuntimeLeaseHeaders(profileId), profileId) };
|
|
61974
|
-
return shareClientGetRequest(`recent-candles:${profileId ?? "none"}:${params.toString()}`, async (
|
|
62020
|
+
return shareClientGetRequest(`recent-candles:${profileId ?? "none"}:${params.toString()}`, (requestSignal) => readMarketDataWithRetry(requestSignal, async () => {
|
|
61975
62021
|
const trace = startRuntimeNetworkDebugTrace({
|
|
61976
62022
|
kind: "runtime",
|
|
61977
62023
|
label: "market_data_api:candles_recent",
|
|
@@ -62013,7 +62059,7 @@ var init_market_data = __esm({
|
|
|
62013
62059
|
if (isAbortLikeError(error48)) throw error48;
|
|
62014
62060
|
throw buildMarketDataNetworkError(error48, "recent candles", "/candles/recent");
|
|
62015
62061
|
}
|
|
62016
|
-
}, { signal, shareAbortScoped: true });
|
|
62062
|
+
}), { signal, shareAbortScoped: true });
|
|
62017
62063
|
};
|
|
62018
62064
|
ExecutionAssetMetadataRequestError = class extends Error {
|
|
62019
62065
|
constructor(message, status, retryAfterMs, code = null) {
|
|
@@ -64126,6 +64172,11 @@ var init_hyperliquid_public_read = __esm({
|
|
|
64126
64172
|
checkAbort(signal);
|
|
64127
64173
|
if (options.reservation?.closed) throw new DOMException("Hyperliquid account read was cancelled.", "AbortError");
|
|
64128
64174
|
hostTransport?.onPublicInfoSent?.(body);
|
|
64175
|
+
} else {
|
|
64176
|
+
try {
|
|
64177
|
+
hostTransport?.onPrivateInfoSent?.(body);
|
|
64178
|
+
} catch {
|
|
64179
|
+
}
|
|
64129
64180
|
}
|
|
64130
64181
|
outcome = "failure";
|
|
64131
64182
|
let transportAborted;
|
|
@@ -100051,7 +100102,8 @@ async function fetchClientRuntimePromptMetadata(profileId, payload, options) {
|
|
|
100051
100102
|
return postClientRuntime(
|
|
100052
100103
|
"/runtime/prompt-contract/metadata",
|
|
100053
100104
|
profileId,
|
|
100054
|
-
buildClientRuntimeBody(payload),
|
|
100105
|
+
buildClientRuntimeBody(payload, { renders_prompt_field_legends: true }),
|
|
100106
|
+
// builds each {<block>_legend} line
|
|
100055
100107
|
options
|
|
100056
100108
|
);
|
|
100057
100109
|
}
|
|
@@ -100059,8 +100111,8 @@ async function fetchClientRuntimePromptDerivedContext(profileId, payload, option
|
|
|
100059
100111
|
return postClientRuntime(
|
|
100060
100112
|
"/runtime/prompt-contract/derived-context",
|
|
100061
100113
|
profileId,
|
|
100062
|
-
|
|
100063
|
-
|
|
100114
|
+
// The engine renders the blocks (prompt_inputs) and builds each {<block>_legend} line.
|
|
100115
|
+
buildClientRuntimeBody(payload, { renders_derived_prompts: true, renders_prompt_field_legends: true }),
|
|
100064
100116
|
options
|
|
100065
100117
|
);
|
|
100066
100118
|
}
|
|
@@ -100268,7 +100320,7 @@ async function getClientRuntimeStatuses(profileIds, signal, options) {
|
|
|
100268
100320
|
ttlMs: viewer.requestKey ? 0 : CLIENT_RUNTIME_STATUSES_DEDUPE_TTL_MS
|
|
100269
100321
|
});
|
|
100270
100322
|
}
|
|
100271
|
-
var clientRuntimeSecretHeaders, preferencesWriteQueue, getCopyTradingRuntimeLeaseToken, getCopyTradingSchedulerInstanceId, AI_TRADE_HISTORY_BY_ORDER_IDS_MAX_BATCH, AI_TRADE_HISTORY_BY_ORDER_IDS_MAX_CONCURRENCY, resolveClientRuntimeStatusViewerHeaders, CLIENT_SUPPORTED_PROMPT_CONTRACT_VERSION, completedDeferredClientRuntimeStops, rememberCompletedDeferredClientRuntimeStop, consumeCompletedDeferredClientRuntimeStop, toNumericProfileId, buildClientRuntimeBody, shouldAttachRuntimeIdempotencyKey, attachRuntimeLeaseHeader, attachRuntimeSchedulerInstanceHeader, resolveRuntimeLeaseToken, resolveSchedulerBoundRuntimeLeaseToken, persistRuntimeLeaseFromPayload, persistRuntimeLeaseStatusMetadata, shouldClearPersistedRuntimeLeaseOnError, readRetryableRuntimeRefusalDelayMs, createRuntimeRequestError, parseClientRuntimeRequestContext, recordRuntimeAuthFailureBreadcrumb, classifyRuntimeRequestError, annotateRuntimeRequestError, CLIENT_RUNTIME_RETRYABLE_STATUSES, isRetryableClientRuntimeStatus, shouldRetryClientRuntimeHttpStatus, isRuntimeIdempotencyInProgressError, isRetryableRuntimeConflictError,
|
|
100323
|
+
var clientRuntimeSecretHeaders, preferencesWriteQueue, getCopyTradingRuntimeLeaseToken, getCopyTradingSchedulerInstanceId, AI_TRADE_HISTORY_BY_ORDER_IDS_MAX_BATCH, AI_TRADE_HISTORY_BY_ORDER_IDS_MAX_CONCURRENCY, resolveClientRuntimeStatusViewerHeaders, CLIENT_SUPPORTED_PROMPT_CONTRACT_VERSION, completedDeferredClientRuntimeStops, rememberCompletedDeferredClientRuntimeStop, consumeCompletedDeferredClientRuntimeStop, toNumericProfileId, buildClientRuntimeBody, shouldAttachRuntimeIdempotencyKey, attachRuntimeLeaseHeader, attachRuntimeSchedulerInstanceHeader, resolveRuntimeLeaseToken, resolveSchedulerBoundRuntimeLeaseToken, persistRuntimeLeaseFromPayload, persistRuntimeLeaseStatusMetadata, shouldClearPersistedRuntimeLeaseOnError, readRetryableRuntimeRefusalDelayMs, createRuntimeRequestError, parseClientRuntimeRequestContext, recordRuntimeAuthFailureBreadcrumb, classifyRuntimeRequestError, annotateRuntimeRequestError, CLIENT_RUNTIME_RETRYABLE_STATUSES, isRetryableClientRuntimeStatus, shouldRetryClientRuntimeHttpStatus, isRuntimeIdempotencyInProgressError, isRetryableRuntimeConflictError, reconcilePendingClientExchangeMutation, CLIENT_RUNTIME_CLAIM_EXCHANGE_MUTATION_WAIT_CODES, resolveClientExchangeMutationAuthority, pinClientExchangeMutationAuthority, CLIENT_EXCHANGE_MUTATION_AUTHORITY_MISMATCH, isClientExchangeMutationAuthorityConflict, handOffClientExchangeMutationToReconciliation, clientExchangeMutationAuthorityBody, isPendingClientExchangeMutationError, isMissingActiveClientExchangeMutationError, clientExchangeMutationReconciliationTimers, ClientExchangeMutationRebuildRequiredError, isTerminalClientExchangeMutation, clientExchangeMutationReconciliationKey, clearScheduledClientExchangeMutationReconciliation, snapshotClientExchangeMutationReconciliationAuthority, completeClientExchangeMutationReconciliation, postClientExchangeMutationReconciliation, scheduleClientExchangeMutationReconciliation, postClientDeviceReport, reportClientTradeMarketRead;
|
|
100272
100324
|
var init_api2 = __esm({
|
|
100273
100325
|
"lib/api.ts"() {
|
|
100274
100326
|
"use strict";
|
|
@@ -100670,14 +100722,6 @@ var init_api2 = __esm({
|
|
|
100670
100722
|
};
|
|
100671
100723
|
isRuntimeIdempotencyInProgressError = (status, message) => status === HTTP_STATUS.CONFLICT && (message.toLowerCase().includes("duplicate request already in progress") || message.toLowerCase().includes("duplicate request in-flight"));
|
|
100672
100724
|
isRetryableRuntimeConflictError = (status, error48) => status === HTTP_STATUS.CONFLICT && error48.retryable === true && (error48.code === "profile_runtime_contract_busy" || error48.code === "runtime_decision_finalizing" || error48.code === "runtime_trade_sync_finalizing" || error48.code === "runtime_decision_unconfirmed");
|
|
100673
|
-
resolveClientRuntimeRetryDelayMs = (attempt2, retryAfterHeader) => {
|
|
100674
|
-
const policy3 = runtime_policy_generated_default2.trading.engine.client_runtime.request_retry;
|
|
100675
|
-
const retryAfterMs = parseRetryAfterMs2(retryAfterHeader);
|
|
100676
|
-
if (retryAfterMs != null) {
|
|
100677
|
-
return Math.min(policy3.max_delay_milliseconds, Math.max(policy3.min_retry_after_milliseconds, retryAfterMs));
|
|
100678
|
-
}
|
|
100679
|
-
return Math.min(policy3.max_delay_milliseconds, policy3.base_delay_milliseconds * BACKOFF_GROWTH_FACTOR ** (attempt2 - 1));
|
|
100680
|
-
};
|
|
100681
100725
|
reconcilePendingClientExchangeMutation = async (profileId, requestOptions) => {
|
|
100682
100726
|
let reconciliation;
|
|
100683
100727
|
try {
|
|
@@ -104523,6 +104567,7 @@ var init_hyperliquid_account_state_adapter = __esm({
|
|
|
104523
104567
|
init_hyperliquid_perp_dex_config();
|
|
104524
104568
|
init_device_account_state_store();
|
|
104525
104569
|
init_runtime_policy_generated2();
|
|
104570
|
+
init_rate_limit_text();
|
|
104526
104571
|
init_constants();
|
|
104527
104572
|
init_hyperliquid_clearinghouse_state();
|
|
104528
104573
|
browserUserFillsCache = /* @__PURE__ */ new Map();
|
|
@@ -104811,7 +104856,7 @@ var init_hyperliquid_account_state_adapter = __esm({
|
|
|
104811
104856
|
return true;
|
|
104812
104857
|
}
|
|
104813
104858
|
const detail = normalizeHyperliquidErrorDetail(error48).toLowerCase();
|
|
104814
|
-
return
|
|
104859
|
+
return isRateLimitErrorText(detail) || detail.includes("rate-limited") || detail.includes("cooldown");
|
|
104815
104860
|
};
|
|
104816
104861
|
servesStaleObservation = (error48, priority) => isRateLimitError(error48) || isHyperliquidReadRefusal(error48) && isHeldBackHyperliquidPriority(priority);
|
|
104817
104862
|
createAbortError = (message) => {
|
|
@@ -118660,7 +118705,7 @@ var init_browser_observability = __esm({
|
|
|
118660
118705
|
init_define_VTX_GROK_POLICY();
|
|
118661
118706
|
init_define_VTX_PI_MODEL_POLICY();
|
|
118662
118707
|
init_runtime_policy_generated2();
|
|
118663
|
-
CLIENT_SOURCE_VERSION = typeof process !== "undefined" && true && "
|
|
118708
|
+
CLIENT_SOURCE_VERSION = typeof process !== "undefined" && true && "68890025dbd4546782da81b71404334ad74799f8".trim() && "68890025dbd4546782da81b71404334ad74799f8".trim() !== "unstamped" ? "68890025dbd4546782da81b71404334ad74799f8".trim() : null;
|
|
118664
118709
|
listenersInstalled = false;
|
|
118665
118710
|
state = {
|
|
118666
118711
|
loadedAtMs: Date.now(),
|
|
@@ -120703,6 +120748,7 @@ async function fetchCopyReviewPromptContract(profileId, payload, options) {
|
|
|
120703
120748
|
profileId,
|
|
120704
120749
|
buildClientRuntimeBody(payload, {
|
|
120705
120750
|
renders_derived_prompts: true,
|
|
120751
|
+
renders_prompt_field_legends: true,
|
|
120706
120752
|
copy_review_symbol: payload.copyReviewSymbol,
|
|
120707
120753
|
copy_review_symbols: payload.copyReviewSymbols
|
|
120708
120754
|
}),
|
|
@@ -123650,6 +123696,57 @@ var init_prompt_json_contract = __esm({
|
|
|
123650
123696
|
}
|
|
123651
123697
|
});
|
|
123652
123698
|
|
|
123699
|
+
// lib/runtime/prompt-field-visibility.ts
|
|
123700
|
+
var NO_FIELDS, LEGEND_TOKEN, isRecord7, readHidden, resolveHiddenPromptFields, hiddenFieldsOf, withoutHiddenFields, renderBlockLegend, renderPromptFieldLegends;
|
|
123701
|
+
var init_prompt_field_visibility = __esm({
|
|
123702
|
+
"lib/runtime/prompt-field-visibility.ts"() {
|
|
123703
|
+
"use strict";
|
|
123704
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
123705
|
+
init_define_VTX_EXO_POLICY();
|
|
123706
|
+
init_define_VTX_GROK_POLICY();
|
|
123707
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
123708
|
+
init_runtime_error_reason_rules();
|
|
123709
|
+
NO_FIELDS = /* @__PURE__ */ new Set();
|
|
123710
|
+
LEGEND_TOKEN = /\{([a-z_]+)_legend\}/g;
|
|
123711
|
+
isRecord7 = (value) => !!value && typeof value === "object" && !Array.isArray(value);
|
|
123712
|
+
readHidden = (value, source) => Object.fromEntries(Object.entries(value).map(([block, fields]) => {
|
|
123713
|
+
if (!Array.isArray(fields) || fields.some((field) => typeof field !== "string")) {
|
|
123714
|
+
throw new RuntimeReasonError(`Invalid ${source}.${block}: must be a list of field names.`, "internal_data_error");
|
|
123715
|
+
}
|
|
123716
|
+
return [block, new Set(fields)];
|
|
123717
|
+
}));
|
|
123718
|
+
resolveHiddenPromptFields = (defaults, setting2) => {
|
|
123719
|
+
if (isRecord7(setting2)) return readHidden(setting2, "hidden_prompt_fields");
|
|
123720
|
+
if (defaults === void 0) return {};
|
|
123721
|
+
if (!isRecord7(defaults)) {
|
|
123722
|
+
throw new RuntimeReasonError("Invalid client runtime config: default_hidden_prompt_fields must be an object.", "runtime_config_missing");
|
|
123723
|
+
}
|
|
123724
|
+
return readHidden(defaults, "default_hidden_prompt_fields");
|
|
123725
|
+
};
|
|
123726
|
+
hiddenFieldsOf = (hidden, block) => hidden?.[block] ?? NO_FIELDS;
|
|
123727
|
+
withoutHiddenFields = (record6, hidden) => hidden.size === 0 ? record6 : Object.fromEntries(Object.entries(record6).filter(([key]) => !hidden.has(key)));
|
|
123728
|
+
renderBlockLegend = (block, catalog, hidden) => {
|
|
123729
|
+
if (!Array.isArray(catalog.keys) || !Array.isArray(catalog.legend)) {
|
|
123730
|
+
throw new RuntimeReasonError(`Missing prompts config key: instructions.data_format.fields.${block}`, "runtime_config_missing");
|
|
123731
|
+
}
|
|
123732
|
+
const keys = catalog.keys.filter((key) => !hidden.has(key)).map((key) => catalog.shapes?.[key] ?? key).join(",");
|
|
123733
|
+
return catalog.legend.map((part) => {
|
|
123734
|
+
const fields = part.fields ?? [];
|
|
123735
|
+
const visible = fields.filter((field) => !hidden.has(field));
|
|
123736
|
+
if (fields.length > 0 && visible.length === 0) return "";
|
|
123737
|
+
return part.text.replaceAll("{keys}", keys).replaceAll("{visible}", visible.join(","));
|
|
123738
|
+
}).join("");
|
|
123739
|
+
};
|
|
123740
|
+
renderPromptFieldLegends = (legend, catalogs, hidden) => legend.replace(LEGEND_TOKEN, (_token, block) => {
|
|
123741
|
+
const catalog = isRecord7(catalogs) ? catalogs[block] : void 0;
|
|
123742
|
+
if (!isRecord7(catalog)) {
|
|
123743
|
+
throw new RuntimeReasonError(`Missing prompts config key: instructions.data_format.fields.${block}`, "runtime_config_missing");
|
|
123744
|
+
}
|
|
123745
|
+
return renderBlockLegend(block, catalog, hiddenFieldsOf(hidden, block));
|
|
123746
|
+
});
|
|
123747
|
+
}
|
|
123748
|
+
});
|
|
123749
|
+
|
|
123653
123750
|
// lib/runtime/derived-context/guidance.ts
|
|
123654
123751
|
var FIELD_NAME, FIXED_SPEC, formatField, formatGuidanceTemplate, requireTemplates, requireTemplate, pythonFloatOrNull, threshold, pythonTruthy, enabled, finiteOrNull3, thresholdState, PERFORMANCE_CHECKS, REGIME_CHECKS, stateMessage, assemble, performanceGuidanceMessage, marketRegimeGuidanceMessage;
|
|
123655
123752
|
var init_guidance = __esm({
|
|
@@ -123918,6 +124015,7 @@ var init_calendar = __esm({
|
|
|
123918
124015
|
init_define_VTX_PI_MODEL_POLICY();
|
|
123919
124016
|
init_constants();
|
|
123920
124017
|
init_prompt_json_contract();
|
|
124018
|
+
init_prompt_field_visibility();
|
|
123921
124019
|
init_guidance();
|
|
123922
124020
|
init_python_text();
|
|
123923
124021
|
init_runtime_error_reason_rules();
|
|
@@ -124024,7 +124122,8 @@ var init_calendar = __esm({
|
|
|
124024
124122
|
if (activeEvents.length === 0) {
|
|
124025
124123
|
return "";
|
|
124026
124124
|
}
|
|
124027
|
-
const
|
|
124125
|
+
const hiddenFields = input.hiddenFields ?? /* @__PURE__ */ new Set();
|
|
124126
|
+
const block = `<calendar>${stringifyPromptJson(activeEvents.map((event) => withoutHiddenFields(event, hiddenFields)))}</calendar>`;
|
|
124028
124127
|
const header = output3.header;
|
|
124029
124128
|
const scope = output3.scope;
|
|
124030
124129
|
if (typeof header !== "string" || !header.trim() || typeof scope !== "string" || !scope.trim()) {
|
|
@@ -124073,7 +124172,7 @@ var init_interval = __esm({
|
|
|
124073
124172
|
});
|
|
124074
124173
|
|
|
124075
124174
|
// lib/runtime/derived-context/market-context.ts
|
|
124076
|
-
var calculateSlopeR2, calculateZScore, countPivots, formatCandleSpan, extractWindowFeatures, calculateRelativeVolumeRatio, buildMarketContext, marketCandleFromRow, marketContextInputFromPayload;
|
|
124175
|
+
var calculateSlopeR2, calculateZScore, countPivots, formatCandleSpan, extractWindowFeatures, calculateRelativeVolumeRatio, shownStats, buildMarketContext, marketCandleFromRow, marketContextInputFromPayload;
|
|
124077
124176
|
var init_market_context = __esm({
|
|
124078
124177
|
"lib/runtime/derived-context/market-context.ts"() {
|
|
124079
124178
|
"use strict";
|
|
@@ -124089,6 +124188,7 @@ var init_market_context = __esm({
|
|
|
124089
124188
|
init_python_numbers();
|
|
124090
124189
|
init_python_text();
|
|
124091
124190
|
init_runtime_error_reason_rules();
|
|
124191
|
+
init_prompt_field_visibility();
|
|
124092
124192
|
calculateSlopeR2 = (values) => {
|
|
124093
124193
|
const count5 = values.length;
|
|
124094
124194
|
if (count5 < REGRESSION_MIN_POINTS) {
|
|
@@ -124181,7 +124281,7 @@ var init_market_context = __esm({
|
|
|
124181
124281
|
const volatility = lastAtr !== null && lastAtr !== void 0 && lastClose > 0 ? lastAtr / lastClose * PERCENT_SCALE : null;
|
|
124182
124282
|
return {
|
|
124183
124283
|
n: window2.length,
|
|
124184
|
-
|
|
124284
|
+
sp: formatCandleSpan(window2.length * timeframeSeconds),
|
|
124185
124285
|
s: pythonRound(slope ?? 0, WINDOW_FEATURES_SLOPE_DECIMALS),
|
|
124186
124286
|
r: pythonRound(rSquared ?? 0, WINDOW_FEATURES_R_SQUARED_DECIMALS),
|
|
124187
124287
|
z: pythonRound(zScore ?? 0, WINDOW_FEATURES_Z_SCORE_DECIMALS),
|
|
@@ -124205,6 +124305,13 @@ var init_market_context = __esm({
|
|
|
124205
124305
|
}
|
|
124206
124306
|
return recentDollarVolume / baselineDollarVolume;
|
|
124207
124307
|
};
|
|
124308
|
+
shownStats = (stats, hidden) => hidden && hidden.size > 0 ? Object.fromEntries(Object.entries(stats).map(([symbol2, byTimeframe]) => [
|
|
124309
|
+
symbol2,
|
|
124310
|
+
Object.fromEntries(Object.entries(byTimeframe).map(([timeframe, features]) => [
|
|
124311
|
+
timeframe,
|
|
124312
|
+
withoutHiddenFields(features, hidden)
|
|
124313
|
+
]))
|
|
124314
|
+
])) : stats;
|
|
124208
124315
|
buildMarketContext = (input) => {
|
|
124209
124316
|
const timeframes = [...new Set(input.timeframes)].sort(compareCandleTimeframes);
|
|
124210
124317
|
const stats = {};
|
|
@@ -124258,7 +124365,7 @@ var init_market_context = __esm({
|
|
|
124258
124365
|
}
|
|
124259
124366
|
const cleanStats = Object.fromEntries(Object.entries(stats).filter(([, value]) => Object.keys(value).length > 0));
|
|
124260
124367
|
const marketStats = Object.keys(cleanStats).length > 0 ? `<market_stats>
|
|
124261
|
-
${stringifyPromptJson(cleanStats)}
|
|
124368
|
+
${stringifyPromptJson(shownStats(cleanStats, input.hiddenStatFields))}
|
|
124262
124369
|
</market_stats>` : "";
|
|
124263
124370
|
const expected = input.symbols.flatMap((rawSymbol) => {
|
|
124264
124371
|
const symbol2 = String(rawSymbol).trim();
|
|
@@ -124311,6 +124418,7 @@ var init_market_regime = __esm({
|
|
|
124311
124418
|
init_constants();
|
|
124312
124419
|
init_candle_timeframes();
|
|
124313
124420
|
init_prompt_json_contract();
|
|
124421
|
+
init_prompt_field_visibility();
|
|
124314
124422
|
init_prompt_number_contract();
|
|
124315
124423
|
init_guidance();
|
|
124316
124424
|
init_python_numbers();
|
|
@@ -124385,13 +124493,13 @@ var init_market_regime = __esm({
|
|
|
124385
124493
|
for (const timeframe of Object.keys(activeMap).sort(compareCandleTimeframes)) {
|
|
124386
124494
|
const values = activeMap[timeframe];
|
|
124387
124495
|
const relativeVolume = roundPromptRelativeVolume(values.relative_volume);
|
|
124388
|
-
symbolRegime[timeframe] = {
|
|
124496
|
+
symbolRegime[timeframe] = withoutHiddenFields({
|
|
124389
124497
|
adx: values.adx === null || values.adx === void 0 ? "-" : pythonRound(values.adx, REGIME_ADX_CHOP_DECIMALS),
|
|
124390
124498
|
chop: values.chop === null || values.chop === void 0 ? "-" : pythonRound(values.chop, REGIME_ADX_CHOP_DECIMALS),
|
|
124391
124499
|
atr: values.atr_pct === null || values.atr_pct === void 0 ? "-" : pythonRound(values.atr_pct, PROMPT_METRIC_DECIMALS),
|
|
124392
124500
|
// The candle-row rv column shows the same value with the same rounding.
|
|
124393
124501
|
rv: relativeVolume === null ? "-" : relativeVolume
|
|
124394
|
-
};
|
|
124502
|
+
}, input.hiddenFields ?? /* @__PURE__ */ new Set());
|
|
124395
124503
|
}
|
|
124396
124504
|
guidance[symbol2] = symbolRegime;
|
|
124397
124505
|
}
|
|
@@ -124503,6 +124611,7 @@ var init_performance = __esm({
|
|
|
124503
124611
|
init_define_VTX_PI_MODEL_POLICY();
|
|
124504
124612
|
init_constants();
|
|
124505
124613
|
init_prompt_json_contract();
|
|
124614
|
+
init_prompt_field_visibility();
|
|
124506
124615
|
init_guidance();
|
|
124507
124616
|
init_python_numbers();
|
|
124508
124617
|
init_runtime_error_reason_rules();
|
|
@@ -124760,8 +124869,9 @@ var init_performance = __esm({
|
|
|
124760
124869
|
mlc: pair((metrics) => Math.trunc(metrics.lossCount))
|
|
124761
124870
|
};
|
|
124762
124871
|
const performanceStructured = { global: globalSummary };
|
|
124872
|
+
const shownGlobal = withoutHiddenFields(globalSummary, input.hiddenFields ?? /* @__PURE__ */ new Set());
|
|
124763
124873
|
let performance2 = `<performance>
|
|
124764
|
-
${stringifyPromptJson(
|
|
124874
|
+
${stringifyPromptJson({ global: shownGlobal })}
|
|
124765
124875
|
</performance>`;
|
|
124766
124876
|
const shortLabel = `${pythonFloatRepr(shortWindowHours)}h`;
|
|
124767
124877
|
const longLabel = `${pythonFloatRepr(longWindowHours)}h`;
|
|
@@ -124877,7 +124987,7 @@ ${stringifyPromptJson(structure)}
|
|
|
124877
124987
|
});
|
|
124878
124988
|
|
|
124879
124989
|
// lib/runtime/derived-context/render.ts
|
|
124880
|
-
var CLIENT_RUNTIME_LIVE_MARKET_STATS_UNAVAILABLE_ERROR, CLIENT_RUNTIME_LIVE_PERFORMANCE_UNAVAILABLE_ERROR, CLIENT_RUNTIME_LIVE_MARKET_REGIME_UNAVAILABLE_ERROR, CLIENT_RUNTIME_LIVE_CALENDAR_UNAVAILABLE_ERROR, UNAVAILABLE_REASON_CODES, DerivedPromptContextUnavailableError, renderPerformanceInputs, renderMarketRegime, renderCalendarInputs, renderNewsInputs, requireInput, renderDerivedPromptContext;
|
|
124990
|
+
var CLIENT_RUNTIME_LIVE_MARKET_STATS_UNAVAILABLE_ERROR, CLIENT_RUNTIME_LIVE_PERFORMANCE_UNAVAILABLE_ERROR, CLIENT_RUNTIME_LIVE_MARKET_REGIME_UNAVAILABLE_ERROR, CLIENT_RUNTIME_LIVE_CALENDAR_UNAVAILABLE_ERROR, UNAVAILABLE_REASON_CODES, DerivedPromptContextUnavailableError, renderPerformanceInputs, renderMarketRegime, renderCalendarInputs, renderNewsInputs, requireInput, requireDerivedPromptInputs, renderDerivedPromptContext;
|
|
124881
124991
|
var init_render = __esm({
|
|
124882
124992
|
"lib/runtime/derived-context/render.ts"() {
|
|
124883
124993
|
"use strict";
|
|
@@ -124893,6 +125003,7 @@ var init_render = __esm({
|
|
|
124893
125003
|
init_performance();
|
|
124894
125004
|
init_reference_candles();
|
|
124895
125005
|
init_runtime_error_reason_rules();
|
|
125006
|
+
init_prompt_field_visibility();
|
|
124896
125007
|
CLIENT_RUNTIME_LIVE_MARKET_STATS_UNAVAILABLE_ERROR = "Live market stats unavailable for client runtime contract";
|
|
124897
125008
|
CLIENT_RUNTIME_LIVE_PERFORMANCE_UNAVAILABLE_ERROR = "Live performance context unavailable for client runtime contract";
|
|
124898
125009
|
CLIENT_RUNTIME_LIVE_MARKET_REGIME_UNAVAILABLE_ERROR = "Live market regime context unavailable for client runtime contract";
|
|
@@ -124909,31 +125020,34 @@ var init_render = __esm({
|
|
|
124909
125020
|
this.name = "DerivedPromptContextUnavailableError";
|
|
124910
125021
|
}
|
|
124911
125022
|
};
|
|
124912
|
-
renderPerformanceInputs = (performance2, templates) => buildPerformanceContext({
|
|
125023
|
+
renderPerformanceInputs = (performance2, templates, hiddenFields) => buildPerformanceContext({
|
|
124913
125024
|
fillRecords: performance2.fill_records,
|
|
124914
125025
|
equityHistory: performance2.equity_history,
|
|
124915
125026
|
accountBalance: performance2.account_balance,
|
|
124916
125027
|
nowMs: performance2.now_ms,
|
|
124917
125028
|
config: performance2.config,
|
|
124918
125029
|
breakevenToleranceUsd: performance2.breakeven_tolerance_usd,
|
|
124919
|
-
templates
|
|
125030
|
+
templates,
|
|
125031
|
+
hiddenFields
|
|
124920
125032
|
});
|
|
124921
|
-
renderMarketRegime = (regimeIndicators, scope, thresholds, templates) => buildMarketRegimeContext({
|
|
125033
|
+
renderMarketRegime = (regimeIndicators, scope, thresholds, templates, hiddenFields) => buildMarketRegimeContext({
|
|
124922
125034
|
regimeIndicators,
|
|
124923
125035
|
symbols: scope.symbols,
|
|
124924
125036
|
primarySymbol: scope.primary_symbol,
|
|
124925
125037
|
activeTimeframes: scope.timeframes,
|
|
124926
125038
|
fallbackTimeframes: scope.fallback_timeframes,
|
|
124927
125039
|
thresholds,
|
|
124928
|
-
templates
|
|
125040
|
+
templates,
|
|
125041
|
+
hiddenFields
|
|
124929
125042
|
});
|
|
124930
|
-
renderCalendarInputs = (calendar, templates) => buildCalendarContext({
|
|
125043
|
+
renderCalendarInputs = (calendar, templates, hiddenFields) => buildCalendarContext({
|
|
124931
125044
|
events: calendar.events,
|
|
124932
125045
|
unavailable: calendar.unavailable,
|
|
124933
125046
|
settings: calendar.settings,
|
|
124934
125047
|
defaults: calendar.defaults,
|
|
124935
125048
|
templates: templates.calendar,
|
|
124936
|
-
nowSeconds: calendar.now_seconds
|
|
125049
|
+
nowSeconds: calendar.now_seconds,
|
|
125050
|
+
hiddenFields
|
|
124937
125051
|
});
|
|
124938
125052
|
renderNewsInputs = (news) => Object.fromEntries(
|
|
124939
125053
|
Object.entries(news ?? {}).map(([variable, item]) => [variable, buildNewsContext({
|
|
@@ -124953,12 +125067,23 @@ var init_render = __esm({
|
|
|
124953
125067
|
}
|
|
124954
125068
|
return value;
|
|
124955
125069
|
};
|
|
125070
|
+
requireDerivedPromptInputs = (derivedContext) => {
|
|
125071
|
+
const inputs = derivedContext.prompt_inputs;
|
|
125072
|
+
if (!inputs || typeof inputs !== "object" || Array.isArray(inputs)) {
|
|
125073
|
+
throw new RuntimeReasonError("Prompt derived context missing required field: prompt_inputs", "live_derived_context_build_failed");
|
|
125074
|
+
}
|
|
125075
|
+
return inputs;
|
|
125076
|
+
};
|
|
124956
125077
|
renderDerivedPromptContext = (input) => {
|
|
124957
125078
|
const { inputs } = input;
|
|
124958
125079
|
const uses = (variable) => input.placeholders.includes(variable);
|
|
124959
125080
|
const templates = requireInput(inputs.guidance_templates, "guidance_templates");
|
|
124960
125081
|
const values = {};
|
|
124961
|
-
const
|
|
125082
|
+
const hidden = input.hiddenPromptFields;
|
|
125083
|
+
const market = buildMarketContext({
|
|
125084
|
+
...marketContextInputFromPayload(requireInput(inputs.market, "market"), input.deviceMarket),
|
|
125085
|
+
hiddenStatFields: hiddenFieldsOf(hidden, "market_stats")
|
|
125086
|
+
});
|
|
124962
125087
|
if (uses("market_stats")) {
|
|
124963
125088
|
if (!market.marketStats || !market.marketStatsComplete) {
|
|
124964
125089
|
throw new DerivedPromptContextUnavailableError(CLIENT_RUNTIME_LIVE_MARKET_STATS_UNAVAILABLE_ERROR);
|
|
@@ -124968,8 +125093,14 @@ var init_render = __esm({
|
|
|
124968
125093
|
const performanceInputs = requireInput(inputs.performance, "performance");
|
|
124969
125094
|
let performanceStructured = null;
|
|
124970
125095
|
try {
|
|
124971
|
-
const performance2 = renderPerformanceInputs(performanceInputs, templates);
|
|
124972
|
-
const marketRegime = renderMarketRegime(
|
|
125096
|
+
const performance2 = renderPerformanceInputs(performanceInputs, templates, hiddenFieldsOf(hidden, "performance"));
|
|
125097
|
+
const marketRegime = renderMarketRegime(
|
|
125098
|
+
market.regimeIndicators,
|
|
125099
|
+
performanceInputs,
|
|
125100
|
+
performanceInputs.config.thresholds,
|
|
125101
|
+
templates,
|
|
125102
|
+
hiddenFieldsOf(hidden, "market_regime")
|
|
125103
|
+
);
|
|
124973
125104
|
if (performance2.performance) values.performance = performance2.performance;
|
|
124974
125105
|
if (marketRegime) values.market_regime = marketRegime;
|
|
124975
125106
|
performanceStructured = performance2.performanceStructured;
|
|
@@ -124982,7 +125113,7 @@ var init_render = __esm({
|
|
|
124982
125113
|
if (uses("market_regime") && !String(values.market_regime ?? "").trim()) {
|
|
124983
125114
|
throw new DerivedPromptContextUnavailableError(CLIENT_RUNTIME_LIVE_MARKET_REGIME_UNAVAILABLE_ERROR);
|
|
124984
125115
|
}
|
|
124985
|
-
values.calendar = renderCalendarInputs(requireInput(inputs.calendar, "calendar"), templates);
|
|
125116
|
+
values.calendar = renderCalendarInputs(requireInput(inputs.calendar, "calendar"), templates, hiddenFieldsOf(hidden, "calendar"));
|
|
124986
125117
|
Object.assign(values, renderNewsInputs(inputs.news));
|
|
124987
125118
|
let referenceIndicators;
|
|
124988
125119
|
if (inputs.reference_candles) {
|
|
@@ -128938,7 +129069,7 @@ var init_provider_client = __esm({
|
|
|
128938
129069
|
});
|
|
128939
129070
|
|
|
128940
129071
|
// lib/runtime/runtime-prompt-steps.ts
|
|
128941
|
-
var buildRuntimePromptParityContext, cycleMarketTicker, readRuntimePromptMarketData, invokeRuntimeReviewModel, resolveRuntimePromptKnobs, buildRuntimePromptCandles, requireRuntimePromptTemplates, resolveRuntimeBehaviorMemoryCutoff, buildRuntimeBehaviorStateArtifacts, buildRuntimePromptContextParts, runtimePromptArtifactInput;
|
|
129072
|
+
var buildRuntimePromptParityContext, cycleMarketTicker, readRuntimePromptMarketData, invokeRuntimeReviewModel, resolveRuntimePromptKnobs, buildRuntimePromptCandles, requireRuntimePromptTemplates, resolveRuntimeBehaviorMemoryCutoff, requireServerBehaviorStateInputs, buildRuntimeBehaviorStateArtifacts, buildRuntimePromptContextParts, runtimePromptArtifactInput;
|
|
128942
129073
|
var init_runtime_prompt_steps = __esm({
|
|
128943
129074
|
"lib/runtime/runtime-prompt-steps.ts"() {
|
|
128944
129075
|
"use strict";
|
|
@@ -128956,6 +129087,8 @@ var init_runtime_prompt_steps = __esm({
|
|
|
128956
129087
|
init_provider_client();
|
|
128957
129088
|
init_native_request_parameters();
|
|
128958
129089
|
init_constants();
|
|
129090
|
+
init_prompt_field_visibility();
|
|
129091
|
+
init_runtime_error_reason_rules();
|
|
128959
129092
|
init_local_analysis();
|
|
128960
129093
|
buildRuntimePromptParityContext = (input) => {
|
|
128961
129094
|
const parityContext = {};
|
|
@@ -129206,11 +129339,20 @@ var init_runtime_prompt_steps = __esm({
|
|
|
129206
129339
|
).trim();
|
|
129207
129340
|
return { backendStatus, cutoff, cutoffMs: Date.parse(cutoff) };
|
|
129208
129341
|
};
|
|
129342
|
+
requireServerBehaviorStateInputs = (derivedContext) => {
|
|
129343
|
+
const inputs = derivedContext.behavior_state_inputs;
|
|
129344
|
+
if (!inputs || typeof inputs !== "object" || Array.isArray(inputs)) {
|
|
129345
|
+
throw new RuntimeReasonError("Prompt derived context missing required field: behavior_state_inputs", "live_derived_context_build_failed");
|
|
129346
|
+
}
|
|
129347
|
+
return inputs;
|
|
129348
|
+
};
|
|
129209
129349
|
buildRuntimeBehaviorStateArtifacts = (input) => {
|
|
129350
|
+
const hiddenFields = hiddenFieldsOf(input.hiddenPromptFields, "behavior_state");
|
|
129210
129351
|
if (input.serverOwnsBehaviorState) {
|
|
129211
|
-
return
|
|
129352
|
+
return buildServerBehaviorStateArtifacts(requireServerBehaviorStateInputs(input.derivedContext), {
|
|
129212
129353
|
behaviorInstructions: input.behaviorInstructions,
|
|
129213
|
-
maxFillsPerSymbol: input.config.behavior_memory_max_fills_per_symbol
|
|
129354
|
+
maxFillsPerSymbol: input.config.behavior_memory_max_fills_per_symbol,
|
|
129355
|
+
hiddenFields
|
|
129214
129356
|
});
|
|
129215
129357
|
}
|
|
129216
129358
|
const behaviorFillCoverage = input.fillEvidence?.source === "live" && input.fillEvidence.exactTerminalFillEvidenceComplete === true ? "complete" : "capped";
|
|
@@ -129225,7 +129367,8 @@ var init_runtime_prompt_steps = __esm({
|
|
|
129225
129367
|
maxFillsPerSymbol: input.config.behavior_memory_max_fills_per_symbol,
|
|
129226
129368
|
decisionMemory: asRecord(input.derivedContext.behavior_decision_memory),
|
|
129227
129369
|
cycleCutoffMs: input.cutoffMs,
|
|
129228
|
-
fillHistoryCoverage: behaviorFillCoverage
|
|
129370
|
+
fillHistoryCoverage: behaviorFillCoverage,
|
|
129371
|
+
hiddenFields
|
|
129229
129372
|
});
|
|
129230
129373
|
};
|
|
129231
129374
|
buildRuntimePromptContextParts = (input) => ({
|
|
@@ -129254,8 +129397,9 @@ var init_runtime_prompt_steps = __esm({
|
|
|
129254
129397
|
},
|
|
129255
129398
|
size: input.size,
|
|
129256
129399
|
leverage: input.leverage,
|
|
129257
|
-
//
|
|
129258
|
-
interval: input.derivedBlocks.intervalContext
|
|
129400
|
+
// {interval}, rendered from the contract's loop interval.
|
|
129401
|
+
interval: input.derivedBlocks.intervalContext,
|
|
129402
|
+
hiddenPromptFields: input.hiddenPromptFields
|
|
129259
129403
|
});
|
|
129260
129404
|
runtimePromptArtifactInput = (input) => ({
|
|
129261
129405
|
systemTemplate: input.systemTemplate,
|
|
@@ -129266,7 +129410,8 @@ var init_runtime_prompt_steps = __esm({
|
|
|
129266
129410
|
maxTradesPerPrompt: input.maxTradesPerPrompt,
|
|
129267
129411
|
metricsWindowHours: input.metricsWindowHours,
|
|
129268
129412
|
metricsSecondaryWindowHours: input.metricsSecondaryWindowHours,
|
|
129269
|
-
userTemplate: input.userTemplate
|
|
129413
|
+
userTemplate: input.userTemplate,
|
|
129414
|
+
hiddenPromptFields: input.hiddenPromptFields
|
|
129270
129415
|
});
|
|
129271
129416
|
}
|
|
129272
129417
|
});
|
|
@@ -129285,6 +129430,7 @@ var init_prompt_contract = __esm({
|
|
|
129285
129430
|
init_candle_prompt_contract();
|
|
129286
129431
|
init_constants();
|
|
129287
129432
|
init_python_text();
|
|
129433
|
+
init_prompt_field_visibility();
|
|
129288
129434
|
PROMPT_PLACEHOLDER_MAP = {};
|
|
129289
129435
|
DATA_FORMAT_TAG_ALIASES = {};
|
|
129290
129436
|
buildDecisionInstructionVariables = (rawSymbols, maxTrades) => {
|
|
@@ -129423,7 +129569,7 @@ var init_prompt_contract = __esm({
|
|
|
129423
129569
|
};
|
|
129424
129570
|
const metricsWindowLabel = formatWindowHours(options.metricsWindowHours);
|
|
129425
129571
|
const metricsSecondaryWindowLabel = formatWindowHours(options.metricsSecondaryWindowHours);
|
|
129426
|
-
let legend = String(legendTemplate ?? "").replaceAll("{metrics_window_hours}", metricsWindowLabel).replaceAll("{metrics_secondary_window_hours}", metricsSecondaryWindowLabel).replaceAll("{metrics_window}", metricsWindowLabel).replaceAll("{metrics_secondary_window}", metricsSecondaryWindowLabel).trim();
|
|
129572
|
+
let legend = renderPromptFieldLegends(String(legendTemplate ?? ""), options.fieldCatalogs, options.hiddenPromptFields).replaceAll("{metrics_window_hours}", metricsWindowLabel).replaceAll("{metrics_secondary_window_hours}", metricsSecondaryWindowLabel).replaceAll("{metrics_window}", metricsWindowLabel).replaceAll("{metrics_secondary_window}", metricsSecondaryWindowLabel).trim();
|
|
129427
129573
|
if (!legend) return "";
|
|
129428
129574
|
const candleLiveFieldToken = "{candle_live_field}";
|
|
129429
129575
|
const candleLiveGuidanceToken = "{candle_live_guidance}";
|
|
@@ -129727,7 +129873,9 @@ ${jsonInstruction}`.trim();
|
|
|
129727
129873
|
behaviorEntryTradeSchema: instructions.data_format?.behavior_entry_trade,
|
|
129728
129874
|
candleIndicatorSchemas: instructions.data_format?.candle_indicators,
|
|
129729
129875
|
referenceCandlesSummary: options.referenceCandlesSummary,
|
|
129730
|
-
referenceIndicatorFlags: options.referenceIndicatorFlags
|
|
129876
|
+
referenceIndicatorFlags: options.referenceIndicatorFlags,
|
|
129877
|
+
fieldCatalogs: instructions.data_format?.fields,
|
|
129878
|
+
hiddenPromptFields: options.hiddenPromptFields
|
|
129731
129879
|
});
|
|
129732
129880
|
const hasDataFormatInstructions = /^[ \t]*DATA FORMAT(?: INSTRUCTIONS)?:/m.test(template);
|
|
129733
129881
|
if (legend && !hasDataFormatInstructions) {
|
|
@@ -129746,7 +129894,8 @@ ${legend}`.trim();
|
|
|
129746
129894
|
behaviorEntryTradeSchema: instructions.data_format?.behavior_entry_trade,
|
|
129747
129895
|
candleIndicatorSchemas: instructions.data_format?.candle_indicators,
|
|
129748
129896
|
referenceCandlesSummary: options.referenceCandlesSummary,
|
|
129749
|
-
referenceIndicatorFlags: options.referenceIndicatorFlags
|
|
129897
|
+
referenceIndicatorFlags: options.referenceIndicatorFlags,
|
|
129898
|
+
fieldCatalogs: instructions.data_format?.fields
|
|
129750
129899
|
});
|
|
129751
129900
|
template = replaceEmbeddedDataFormatLegend(template, canonicalLegend, legend);
|
|
129752
129901
|
}
|
|
@@ -129757,7 +129906,7 @@ ${legend}`.trim();
|
|
|
129757
129906
|
});
|
|
129758
129907
|
|
|
129759
129908
|
// lib/runtime/behavior-memory-prompt-observability.ts
|
|
129760
|
-
var BODY_FREE_STATUS_FIELDS,
|
|
129909
|
+
var BODY_FREE_STATUS_FIELDS, isRecord8, isBodyFreeScalar, sanitizeBehaviorMemoryStatus, sha256Hex3, renderBehaviorMemoryPromptSeam;
|
|
129761
129910
|
var init_behavior_memory_prompt_observability = __esm({
|
|
129762
129911
|
"lib/runtime/behavior-memory-prompt-observability.ts"() {
|
|
129763
129912
|
"use strict";
|
|
@@ -129786,10 +129935,10 @@ var init_behavior_memory_prompt_observability = __esm({
|
|
|
129786
129935
|
"duration_ms",
|
|
129787
129936
|
"loader_outcome"
|
|
129788
129937
|
];
|
|
129789
|
-
|
|
129938
|
+
isRecord8 = (value) => Boolean(value) && typeof value === "object" && !Array.isArray(value);
|
|
129790
129939
|
isBodyFreeScalar = (value) => value === null || typeof value === "string" || typeof value === "number" || typeof value === "boolean";
|
|
129791
129940
|
sanitizeBehaviorMemoryStatus = (value) => {
|
|
129792
|
-
if (!
|
|
129941
|
+
if (!isRecord8(value)) {
|
|
129793
129942
|
return {};
|
|
129794
129943
|
}
|
|
129795
129944
|
const sanitized = {};
|
|
@@ -129799,16 +129948,16 @@ var init_behavior_memory_prompt_observability = __esm({
|
|
|
129799
129948
|
sanitized[key] = fieldValue;
|
|
129800
129949
|
}
|
|
129801
129950
|
}
|
|
129802
|
-
if (
|
|
129951
|
+
if (isRecord8(value.symbols)) {
|
|
129803
129952
|
const symbols = {};
|
|
129804
129953
|
for (const [symbol2, rawSymbolStatus] of Object.entries(value.symbols)) {
|
|
129805
|
-
if (!
|
|
129954
|
+
if (!isRecord8(rawSymbolStatus)) {
|
|
129806
129955
|
continue;
|
|
129807
129956
|
}
|
|
129808
129957
|
const symbolStatus = {};
|
|
129809
129958
|
for (const itemKey of ["pd", "pc", "et"]) {
|
|
129810
129959
|
const rawItemStatus = rawSymbolStatus[itemKey];
|
|
129811
|
-
if (!
|
|
129960
|
+
if (!isRecord8(rawItemStatus)) {
|
|
129812
129961
|
continue;
|
|
129813
129962
|
}
|
|
129814
129963
|
const itemStatus = {};
|
|
@@ -129900,6 +130049,93 @@ var init_behavior_memory_prompt_observability = __esm({
|
|
|
129900
130049
|
}
|
|
129901
130050
|
});
|
|
129902
130051
|
|
|
130052
|
+
// lib/runtime/prompt-collateral-contract.ts
|
|
130053
|
+
var orderPromptSymbols, buildPromptCollateralPools, poolEquityForSymbol, buildPromptFeeMap;
|
|
130054
|
+
var init_prompt_collateral_contract = __esm({
|
|
130055
|
+
"lib/runtime/prompt-collateral-contract.ts"() {
|
|
130056
|
+
"use strict";
|
|
130057
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
130058
|
+
init_define_VTX_EXO_POLICY();
|
|
130059
|
+
init_define_VTX_GROK_POLICY();
|
|
130060
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
130061
|
+
init_hyperliquid_market_symbol();
|
|
130062
|
+
init_prompt_number_contract();
|
|
130063
|
+
init_constants();
|
|
130064
|
+
orderPromptSymbols = (selected, held = []) => {
|
|
130065
|
+
const ordered = new Set(selected.map(normalizeHyperliquidMarketSymbol).filter(Boolean));
|
|
130066
|
+
const heldOnly = [...new Set(held.map(normalizeHyperliquidMarketSymbol).filter(Boolean))].filter((symbol2) => !ordered.has(symbol2)).sort();
|
|
130067
|
+
return [...ordered, ...heldOnly];
|
|
130068
|
+
};
|
|
130069
|
+
buildPromptCollateralPools = (accounts, symbols) => {
|
|
130070
|
+
const byDex = /* @__PURE__ */ new Map();
|
|
130071
|
+
const duplicateDexes = /* @__PURE__ */ new Set();
|
|
130072
|
+
for (const account of Array.isArray(accounts) ? accounts : []) {
|
|
130073
|
+
if (!account || typeof account !== "object" || typeof account.dex !== "string") continue;
|
|
130074
|
+
const dex = account.dex.trim().toLowerCase();
|
|
130075
|
+
if (byDex.has(dex)) duplicateDexes.add(dex);
|
|
130076
|
+
byDex.set(dex, account);
|
|
130077
|
+
}
|
|
130078
|
+
const symbolsByDex = /* @__PURE__ */ new Map();
|
|
130079
|
+
for (const raw of symbols) {
|
|
130080
|
+
const symbol2 = normalizeHyperliquidMarketSymbol(raw);
|
|
130081
|
+
if (!symbol2) continue;
|
|
130082
|
+
const dex = getHyperliquidMarketDex(symbol2);
|
|
130083
|
+
if (!symbolsByDex.has(dex)) symbolsByDex.set(dex, /* @__PURE__ */ new Set());
|
|
130084
|
+
symbolsByDex.get(dex).add(symbol2);
|
|
130085
|
+
}
|
|
130086
|
+
const number6 = (account, field) => {
|
|
130087
|
+
const raw = account[field];
|
|
130088
|
+
if (typeof raw !== "number" && typeof raw !== "string" || typeof raw === "string" && !raw.trim()) return null;
|
|
130089
|
+
const value = Number(raw);
|
|
130090
|
+
return Number.isFinite(value) ? value : null;
|
|
130091
|
+
};
|
|
130092
|
+
return [...symbolsByDex.keys()].map((dex) => {
|
|
130093
|
+
const account = duplicateDexes.has(dex) ? {} : byDex.get(dex) ?? {};
|
|
130094
|
+
const e = number6(account, "account_value");
|
|
130095
|
+
const u = number6(account, "total_unrealized_pnl");
|
|
130096
|
+
const m = number6(account, "maintenance_margin");
|
|
130097
|
+
const metrics = {
|
|
130098
|
+
e,
|
|
130099
|
+
b: e !== null && u !== null ? e - u : null,
|
|
130100
|
+
u,
|
|
130101
|
+
l: number6(account, "cross_account_leverage"),
|
|
130102
|
+
ut: e !== null && e > 0 && m !== null ? PERCENT_SCALE * m / e : null,
|
|
130103
|
+
a: number6(account, "available_margin"),
|
|
130104
|
+
m,
|
|
130105
|
+
lb: e !== null && m !== null ? e - m : null,
|
|
130106
|
+
mu: number6(account, "total_margin_used")
|
|
130107
|
+
};
|
|
130108
|
+
return {
|
|
130109
|
+
dex,
|
|
130110
|
+
symbols: [...symbolsByDex.get(dex)],
|
|
130111
|
+
...Object.fromEntries(Object.entries(metrics).map(([key, value]) => [
|
|
130112
|
+
key,
|
|
130113
|
+
value === null ? null : roundPromptFixed(value, key === "ut" ? PROMPT_MARGIN_UTILIZATION_DECIMALS : PROMPT_FIXED_DIGITS)
|
|
130114
|
+
]))
|
|
130115
|
+
};
|
|
130116
|
+
});
|
|
130117
|
+
};
|
|
130118
|
+
poolEquityForSymbol = (accounts, symbol2) => {
|
|
130119
|
+
const pool = buildPromptCollateralPools(accounts, [symbol2])[0];
|
|
130120
|
+
const dex = getHyperliquidMarketDex(symbol2);
|
|
130121
|
+
const matches = (Array.isArray(accounts) ? accounts : []).filter((account) => account && typeof account.dex === "string" && account.dex.trim().toLowerCase() === dex);
|
|
130122
|
+
if (!pool || matches.length !== 1 || matches[0].account_value == null) return null;
|
|
130123
|
+
const raw = matches[0].account_value;
|
|
130124
|
+
if (typeof raw !== "number" && typeof raw !== "string" || typeof raw === "string" && !raw.trim()) return null;
|
|
130125
|
+
const value = Number(raw);
|
|
130126
|
+
return Number.isFinite(value) ? value : null;
|
|
130127
|
+
};
|
|
130128
|
+
buildPromptFeeMap = (rates, symbols) => {
|
|
130129
|
+
const source = rates && typeof rates === "object" && !Array.isArray(rates) ? rates : {};
|
|
130130
|
+
return Object.fromEntries(orderPromptSymbols(symbols).map((symbol2) => {
|
|
130131
|
+
const raw = source[symbol2];
|
|
130132
|
+
const value = typeof raw === "number" && Number.isFinite(raw) && raw >= 0 && raw < 1 ? raw : null;
|
|
130133
|
+
return [symbol2, value];
|
|
130134
|
+
}));
|
|
130135
|
+
};
|
|
130136
|
+
}
|
|
130137
|
+
});
|
|
130138
|
+
|
|
129903
130139
|
// lib/runtime/position-prompt-contract.ts
|
|
129904
130140
|
var promptPercent, projectPositionPromptNormalization, projectPositionPromptExcursions;
|
|
129905
130141
|
var init_position_prompt_contract = __esm({
|
|
@@ -129974,89 +130210,151 @@ var init_position_prompt_contract = __esm({
|
|
|
129974
130210
|
}
|
|
129975
130211
|
});
|
|
129976
130212
|
|
|
129977
|
-
// lib/runtime/prompt-
|
|
129978
|
-
var
|
|
129979
|
-
var
|
|
129980
|
-
"lib/runtime/prompt-
|
|
130213
|
+
// lib/runtime/prompt-positions-block.ts
|
|
130214
|
+
var formatPromptPrice, buildPromptAccountStatusValue, buildPromptPositionsValue;
|
|
130215
|
+
var init_prompt_positions_block = __esm({
|
|
130216
|
+
"lib/runtime/prompt-positions-block.ts"() {
|
|
129981
130217
|
"use strict";
|
|
129982
130218
|
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
129983
130219
|
init_define_VTX_EXO_POLICY();
|
|
129984
130220
|
init_define_VTX_GROK_POLICY();
|
|
129985
130221
|
init_define_VTX_PI_MODEL_POLICY();
|
|
130222
|
+
init_constants();
|
|
130223
|
+
init_execution_capacity();
|
|
129986
130224
|
init_hyperliquid_market_symbol();
|
|
130225
|
+
init_position_prompt_contract();
|
|
130226
|
+
init_prompt_collateral_contract();
|
|
130227
|
+
init_prompt_field_visibility();
|
|
130228
|
+
init_prompt_json_contract();
|
|
129987
130229
|
init_prompt_number_contract();
|
|
129988
|
-
|
|
129989
|
-
|
|
129990
|
-
|
|
129991
|
-
const
|
|
129992
|
-
|
|
129993
|
-
|
|
129994
|
-
buildPromptCollateralPools = (accounts, symbols) => {
|
|
129995
|
-
const byDex = /* @__PURE__ */ new Map();
|
|
129996
|
-
const duplicateDexes = /* @__PURE__ */ new Set();
|
|
129997
|
-
for (const account of Array.isArray(accounts) ? accounts : []) {
|
|
129998
|
-
if (!account || typeof account !== "object" || typeof account.dex !== "string") continue;
|
|
129999
|
-
const dex = account.dex.trim().toLowerCase();
|
|
130000
|
-
if (byDex.has(dex)) duplicateDexes.add(dex);
|
|
130001
|
-
byDex.set(dex, account);
|
|
130230
|
+
init_prompt_variable_validation_contract();
|
|
130231
|
+
init_runtime_error_reason_rules();
|
|
130232
|
+
formatPromptPrice = (value) => {
|
|
130233
|
+
const numeric2 = Number(value);
|
|
130234
|
+
if (!Number.isFinite(numeric2) || numeric2 === 0) {
|
|
130235
|
+
return 0;
|
|
130002
130236
|
}
|
|
130003
|
-
|
|
130004
|
-
|
|
130005
|
-
const symbol2 = normalizeHyperliquidMarketSymbol(raw);
|
|
130006
|
-
if (!symbol2) continue;
|
|
130007
|
-
const dex = getHyperliquidMarketDex(symbol2);
|
|
130008
|
-
if (!symbolsByDex.has(dex)) symbolsByDex.set(dex, /* @__PURE__ */ new Set());
|
|
130009
|
-
symbolsByDex.get(dex).add(symbol2);
|
|
130237
|
+
if (Math.abs(numeric2) >= PROMPT_PRICE_INTEGER_THRESHOLD) {
|
|
130238
|
+
return Number(Math.trunc(numeric2));
|
|
130010
130239
|
}
|
|
130011
|
-
|
|
130012
|
-
|
|
130013
|
-
|
|
130014
|
-
|
|
130015
|
-
|
|
130240
|
+
return roundPromptSignificant(numeric2, PROMPT_SIGNIFICANT_DIGITS);
|
|
130241
|
+
};
|
|
130242
|
+
buildPromptAccountStatusValue = (accountSummary, marginNote, effectiveTakerRates, symbols, hiddenFields) => [
|
|
130243
|
+
"<account_status>",
|
|
130244
|
+
stringifyPromptJson(withoutHiddenFields({
|
|
130245
|
+
pools: buildPromptCollateralPools(accountSummary.perp_dex_accounts, symbols).map((pool) => withoutHiddenFields(pool, hiddenFields)),
|
|
130246
|
+
fees: buildPromptFeeMap(effectiveTakerRates, symbols)
|
|
130247
|
+
}, hiddenFields)),
|
|
130248
|
+
"</account_status>",
|
|
130249
|
+
"",
|
|
130250
|
+
marginNote
|
|
130251
|
+
].join("\n");
|
|
130252
|
+
buildPromptPositionsValue = (input) => {
|
|
130253
|
+
const validateInstructionTemplate = (template, allowedKeys) => {
|
|
130254
|
+
formatInstructionTemplate(
|
|
130255
|
+
template,
|
|
130256
|
+
Object.fromEntries(allowedKeys.map((key) => [key, ""])),
|
|
130257
|
+
"positions instruction template"
|
|
130258
|
+
);
|
|
130016
130259
|
};
|
|
130017
|
-
|
|
130018
|
-
|
|
130019
|
-
|
|
130020
|
-
|
|
130021
|
-
|
|
130022
|
-
|
|
130023
|
-
|
|
130024
|
-
|
|
130025
|
-
|
|
130026
|
-
|
|
130027
|
-
|
|
130028
|
-
|
|
130029
|
-
|
|
130030
|
-
|
|
130031
|
-
|
|
130032
|
-
|
|
130260
|
+
validateInstructionTemplate(input.positionsInstructions.close_reduce, []);
|
|
130261
|
+
validateInstructionTemplate(input.positionsInstructions.capacity_flat, []);
|
|
130262
|
+
validateInstructionTemplate(input.positionsInstructions.capacity_full, []);
|
|
130263
|
+
validateInstructionTemplate(input.positionsInstructions.capacity_low, ["remaining"]);
|
|
130264
|
+
const activePositions = input.positions.filter((position) => Number(position.size) !== 0);
|
|
130265
|
+
const orderedSymbols = orderPromptSymbols(input.symbols, activePositions.map((position) => position.symbol));
|
|
130266
|
+
const symbolRanks = new Map(orderedSymbols.map((symbol2, index) => [symbol2, index]));
|
|
130267
|
+
activePositions.sort((left, right) => symbolRanks.get(normalizeHyperliquidMarketSymbol(left.symbol)) - symbolRanks.get(normalizeHyperliquidMarketSymbol(right.symbol)));
|
|
130268
|
+
const assetUsage = /* @__PURE__ */ new Map();
|
|
130269
|
+
const exchangeUsage = /* @__PURE__ */ new Map();
|
|
130270
|
+
let globalUnitsUsed = 0;
|
|
130271
|
+
const promptPositions = activePositions.map((position) => {
|
|
130272
|
+
const entryPrice = Number(position.entry_price);
|
|
130273
|
+
const size = Number(position.size);
|
|
130274
|
+
const unrealizedPnl = Number(position.unrealized_pnl);
|
|
130275
|
+
if (!Number.isFinite(entryPrice) || entryPrice <= 0 || !Number.isFinite(size) || size === 0) {
|
|
130276
|
+
throw new RuntimeReasonError(`Active position identity/economics are invalid for ${position.symbol}`, "internal_data_error");
|
|
130277
|
+
}
|
|
130278
|
+
if (!Number.isFinite(unrealizedPnl)) {
|
|
130279
|
+
throw new RuntimeReasonError(`Active position PnL is unavailable for ${position.symbol}`, "internal_data_error");
|
|
130280
|
+
}
|
|
130281
|
+
const notionalValue = Math.abs(size * entryPrice);
|
|
130282
|
+
const unitsUsed = capacityUnitsUsedForPosition(size, entryPrice, input.unitSize);
|
|
130283
|
+
globalUnitsUsed += unitsUsed;
|
|
130284
|
+
assetUsage.set(position.symbol, unitsUsed);
|
|
130285
|
+
const venue = getHyperliquidMarketDex(position.symbol);
|
|
130286
|
+
exchangeUsage.set(venue, (exchangeUsage.get(venue) ?? 0) + unitsUsed);
|
|
130287
|
+
const currentValue = Math.abs(size > 0 ? notionalValue + unrealizedPnl : notionalValue - unrealizedPnl);
|
|
130288
|
+
const takerRate = buildPromptFeeMap(input.effectiveTakerRates, [position.symbol])[normalizeHyperliquidMarketSymbol(position.symbol)];
|
|
130289
|
+
const totalFees = takerRate == null ? null : (notionalValue + currentValue) * takerRate;
|
|
130290
|
+
const pnlAfterFees = totalFees == null ? null : unrealizedPnl - totalFees;
|
|
130291
|
+
let breakeven = null;
|
|
130292
|
+
if (entryPrice > 0 && takerRate != null) {
|
|
130293
|
+
if (size > 0) {
|
|
130294
|
+
breakeven = entryPrice * (1 + takerRate) / (1 - takerRate);
|
|
130295
|
+
} else if (size < 0) {
|
|
130296
|
+
breakeven = entryPrice * (1 - takerRate) / (1 + takerRate);
|
|
130297
|
+
}
|
|
130298
|
+
}
|
|
130033
130299
|
return {
|
|
130034
|
-
|
|
130035
|
-
|
|
130036
|
-
|
|
130037
|
-
|
|
130038
|
-
|
|
130039
|
-
|
|
130300
|
+
s: position.symbol,
|
|
130301
|
+
sd: size > 0 ? "LONG" : "SHORT",
|
|
130302
|
+
v: roundPromptFixed(notionalValue),
|
|
130303
|
+
cv: roundPromptFixed(currentValue),
|
|
130304
|
+
ep: entryPrice ? formatPromptPrice(entryPrice) : 0,
|
|
130305
|
+
be: breakeven == null ? null : formatPromptPrice(breakeven),
|
|
130306
|
+
liq: position.liquidation_price ? formatPromptPrice(position.liquidation_price) : "-",
|
|
130307
|
+
u: unitsUsed,
|
|
130308
|
+
up: roundPromptFixed(unrealizedPnl),
|
|
130309
|
+
f: totalFees == null ? null : roundPromptFixed(totalFees),
|
|
130310
|
+
n: pnlAfterFees == null ? null : roundPromptFixed(pnlAfterFees),
|
|
130311
|
+
...projectPositionPromptNormalization({
|
|
130312
|
+
entryValue: notionalValue,
|
|
130313
|
+
currentValue,
|
|
130314
|
+
unrealizedPnl,
|
|
130315
|
+
netPnl: pnlAfterFees,
|
|
130316
|
+
accountEquity: poolEquityForSymbol(input.perpDexAccounts, position.symbol)
|
|
130317
|
+
}),
|
|
130318
|
+
...projectPositionPromptExcursions({
|
|
130319
|
+
projection: input.positionExcursions[normalizeHyperliquidMarketSymbol(position.symbol)],
|
|
130320
|
+
size,
|
|
130321
|
+
entryPrice,
|
|
130322
|
+
unrealizedPnl,
|
|
130323
|
+
accountEquity: poolEquityForSymbol(input.perpDexAccounts, position.symbol),
|
|
130324
|
+
cutoffMs: input.cutoffMs
|
|
130325
|
+
})
|
|
130040
130326
|
};
|
|
130041
130327
|
});
|
|
130042
|
-
|
|
130043
|
-
|
|
130044
|
-
|
|
130045
|
-
|
|
130046
|
-
|
|
130047
|
-
|
|
130048
|
-
|
|
130049
|
-
|
|
130050
|
-
|
|
130051
|
-
|
|
130052
|
-
|
|
130053
|
-
|
|
130054
|
-
|
|
130055
|
-
|
|
130056
|
-
|
|
130057
|
-
|
|
130058
|
-
|
|
130059
|
-
|
|
130328
|
+
const remainingGlobal = Math.max(0, input.maxTradesGlobal - globalUnitsUsed);
|
|
130329
|
+
const parts = [
|
|
130330
|
+
"<positions>",
|
|
130331
|
+
stringifyPromptJson(promptPositions.map((position) => withoutHiddenFields(position, input.hiddenFields))),
|
|
130332
|
+
"</positions>",
|
|
130333
|
+
...activePositions.length === 0 ? ["", input.positionsInstructions.capacity_flat] : [],
|
|
130334
|
+
"",
|
|
130335
|
+
"--- Capacity & Limits --- ",
|
|
130336
|
+
`Global: ${globalUnitsUsed}/${input.maxTradesGlobal} exposure units used. (Additional capacity: ${remainingGlobal}) `
|
|
130337
|
+
];
|
|
130338
|
+
for (const venue of new Set(orderedSymbols.map(getHyperliquidMarketDex))) {
|
|
130339
|
+
const used = exchangeUsage.get(venue) ?? 0;
|
|
130340
|
+
const remaining = Math.max(0, input.maxTradesPerExchange - used);
|
|
130341
|
+
parts.push(`Exchange '${venue || "native"}': ${used}/${input.maxTradesPerExchange} exposure units used. (Additional capacity: ${remaining}) `);
|
|
130342
|
+
}
|
|
130343
|
+
for (const symbol2 of input.symbols) {
|
|
130344
|
+
const used = assetUsage.get(symbol2) ?? 0;
|
|
130345
|
+
const remaining = Math.max(0, input.maxTradesPerAsset - used);
|
|
130346
|
+
parts.push(`Asset '${symbol2}': ${used}/${input.maxTradesPerAsset} exposure units used. (Additional capacity: ${remaining}) `);
|
|
130347
|
+
}
|
|
130348
|
+
parts.push("");
|
|
130349
|
+
parts.push(...input.positionsInstructions.close_reduce.split("\n"));
|
|
130350
|
+
if (remainingGlobal <= 0) {
|
|
130351
|
+
parts.push(`${input.positionsInstructions.capacity_full} `);
|
|
130352
|
+
} else if (input.maxTradesPerPrompt < input.maxTradesGlobal && remainingGlobal < input.maxTradesPerPrompt) {
|
|
130353
|
+
parts.push(`${formatInstructionTemplate(input.positionsInstructions.capacity_low, {
|
|
130354
|
+
remaining: remainingGlobal
|
|
130355
|
+
}, "positions instruction template")} `);
|
|
130356
|
+
}
|
|
130357
|
+
return parts.join("\n");
|
|
130060
130358
|
};
|
|
130061
130359
|
}
|
|
130062
130360
|
});
|
|
@@ -130569,13 +130867,12 @@ __export(local_analysis_exports, {
|
|
|
130569
130867
|
resolveRuntimeReasoningControlsForModel: () => resolveRuntimeReasoningControlsForModel,
|
|
130570
130868
|
resolveRuntimeTradingScope: () => resolveRuntimeTradingScope,
|
|
130571
130869
|
runLocalRuntimeCycle: () => runLocalRuntimeCycle,
|
|
130572
|
-
serverBehaviorStateArtifacts: () => serverBehaviorStateArtifacts,
|
|
130573
130870
|
settleRuntimeCyclePromise: () => settleRuntimeCyclePromise,
|
|
130574
130871
|
sortTradingTimeframes: () => sortTradingTimeframes,
|
|
130575
130872
|
toPositiveFinite: () => toPositiveFinite2,
|
|
130576
130873
|
unwrapRuntimeCycleSettledResult: () => unwrapRuntimeCycleSettledResult
|
|
130577
130874
|
});
|
|
130578
|
-
var cycleCandles, CYCLE_TIMEOUT_FLOOR_MS, DECISION_SETTLEMENT_RESERVE_MAX_BUDGET_DIVISOR, MIN_AGENT_INSTRUCTION_RETRY_AFTER_MS, PROMPT_PARITY_ERROR_DETAIL_MAX_CHARS, EXTERNAL_INFERENCE_RUNTIME_POLL_INTERVAL_MS, EXTERNAL_INFERENCE_RESULT_WAIT_MS, assertPromptModelController, resolveRuntimeReasoningControlsForModel, observeRuntimeCycle, observeAccountState, aiOrderSlippageFraction, buildServerBehaviorStateArtifacts,
|
|
130875
|
+
var cycleCandles, CYCLE_TIMEOUT_FLOOR_MS, DECISION_SETTLEMENT_RESERVE_MAX_BUDGET_DIVISOR, MIN_AGENT_INSTRUCTION_RETRY_AFTER_MS, PROMPT_PARITY_ERROR_DETAIL_MAX_CHARS, EXTERNAL_INFERENCE_RUNTIME_POLL_INTERVAL_MS, EXTERNAL_INFERENCE_RESULT_WAIT_MS, assertPromptModelController, resolveRuntimeReasoningControlsForModel, observeRuntimeCycle, observeAccountState, aiOrderSlippageFraction, buildServerBehaviorStateArtifacts, ClientRuntimeAgentInstructionEmpty, isClientRuntimeAgentInstructionEmpty, ClientRuntimeAiSchedulePaused, ClientRuntimeAiScheduleStillActive, isClientRuntimeAiScheduleStillActive, ServerDispatchAccountStateStale, isServerDispatchAccountStateStale, isClientRuntimeAiSchedulePaused, judgesPositionCaps, NO_POSITION_CAPS, POSITION_CAP_REFUSALS, judgeCyclePlans, capacityTrimOf, tradabilityExecutionBlock, accountSnapshotCapturedAt, buildClaimedAgentRuntimeCycleResult, resolveRuntimeMarginModePreference, resolveRuntimeLeveragePreference, resolveBooleanSetting, CLIENT_RUNTIME_LIVE_CONTEXT_UNAVAILABLE_ERRORS, BEHAVIOR_STATE_UNAVAILABLE_ERROR, CriticalBehaviorStateError, BEHAVIOR_MEMORY_UNAVAILABLE_ERROR, BehaviorMemoryUnavailableError, clampNumber, resolveExternalInferenceRuntimeTimeoutSeconds, toPositiveFinite2, 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, CLIENT_REVIEW_PROMPT_RENDERER, resolveEffectivePromptRuntimeProvenance, canonicalManifestValue, canonicalManifestJson, sha256ManifestHex, effectiveInputComponent, buildEffectiveInputManifest, MANIFEST_COMPONENT_NAME, derivePromptVisibleSections, decodeDecisionTracePayload, extractDecisionSymbolTrace, formatDecisionSymbolTrace, formatActionableDecisionSymbols, decisionRecordsBySymbol, SERVER_UNREADABLE_REPLY_HOLD_REASONING, buildMissingDecisionHold, buildDecisionPlansFromResponse, buildReviewCandidatePlansFromResponse, forceUnavailableSymbolsToHold, extractTemplatePlaceholders, requireReviewPrimaryUserPromptTemplate, containsCompetingBehaviorStateMarkup, containsCompetingMainBehaviorStateMarkup, requireStrategyReviewTemplates, preflightStrategyReviewPromptContract, extractRuntimeReasoningSelection, isAbortError, isRuntimeTimeoutAbortReason, 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, AI_INDICATOR_KEYS_NEWER_THAN_SOME_SERVERS, sortTradingTimeframes, normalizePromptIdentityTimestamp, resolveCompletedCandleBoundary, normalizeAiIndicatorFlags, getPromptLookback, resolvePromptRelativeVolumeContext, promptRelativeVolumeBaseline, CANDLE_CLOSE_TICKER_TIMEFRAME, candleCloseTicker, promptMarketAsOfTimestamp, deviceMarketReads, buildPromptCandlesPayload, formatUtcTimestampWithWeekday, formatUtcNowWithWeekday, capacityUnitSize, 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, buildReviewSystemPrompt, formatReviewUserPrompt, assemblePromptContextVars, buildPromptBehaviorStateValue, buildLocalRuntimePromptArtifacts2, createRuntimeId2, asRecord, buildRuntimeConstraintRejectionMessage, hasDeviceProviderSecret, requireNonEmptyStringField, requirePositiveIntegerField, compareContractVersion, parsePromptContractTimestamp, assertPromptContractCompatibility, assertPromptContractTemporalBounds, sleepWithAbort, requireAgentPollRetryAfterMs, materializeClaimedClientRuntimeAgentInstruction, attachClientRuntimeErrorProvenance, isExternalRuntimeProviderResult, invokeClientExternalInference, assertPromptContractBindingTupleEqual, assertPromptContractScopeMatch, fetchBoundPromptContracts, carryReturnedModelCalls, requireRuntimePositionsInstructions2, resolveRuntimePromptDerivedBlocks, requireRuntimePromptLane, requireRuntimeAccountMarginNote, runLocalRuntimeCycle;
|
|
130579
130876
|
var init_local_analysis = __esm({
|
|
130580
130877
|
"lib/runtime/local-analysis.ts"() {
|
|
130581
130878
|
"use strict";
|
|
@@ -130622,10 +130919,10 @@ var init_local_analysis = __esm({
|
|
|
130622
130919
|
init_prompt_contract();
|
|
130623
130920
|
init_behavior_memory_prompt_observability();
|
|
130624
130921
|
init_prompt_variable_validation_contract();
|
|
130625
|
-
init_position_prompt_contract();
|
|
130626
130922
|
init_prompt_json_contract();
|
|
130627
130923
|
init_prompt_collateral_contract();
|
|
130628
|
-
|
|
130924
|
+
init_prompt_positions_block();
|
|
130925
|
+
init_prompt_field_visibility();
|
|
130629
130926
|
init_local_ai();
|
|
130630
130927
|
init_reasoning_controls();
|
|
130631
130928
|
init_native_request_parameters();
|
|
@@ -130712,24 +131009,9 @@ var init_local_analysis = __esm({
|
|
|
130712
131009
|
cycleCutoffMs: inputs.now_ms ?? void 0,
|
|
130713
131010
|
nowMs: inputs.now_ms ?? options.nowMs,
|
|
130714
131011
|
fillHistoryCoverage: inputs.fill_history_coverage,
|
|
130715
|
-
positionStates: inputs.position_states
|
|
131012
|
+
positionStates: inputs.position_states,
|
|
131013
|
+
hiddenFields: options.hiddenFields
|
|
130716
131014
|
});
|
|
130717
|
-
serverBehaviorStateArtifacts = (derived, options) => {
|
|
130718
|
-
const inputs = derived.behavior_state_inputs;
|
|
130719
|
-
if (derived.behavior_state_owner === "server" && inputs && typeof inputs === "object" && !Array.isArray(inputs)) {
|
|
130720
|
-
return buildServerBehaviorStateArtifacts(inputs, options);
|
|
130721
|
-
}
|
|
130722
|
-
const rendered = derived.behavior_state;
|
|
130723
|
-
if (derived.behavior_state_owner !== "server" || typeof rendered !== "string" || !rendered.trim()) {
|
|
130724
|
-
throw new Error("The server did not build this Server bot's behavior state.");
|
|
130725
|
-
}
|
|
130726
|
-
const preMemory = derived.behavior_state_pre_memory;
|
|
130727
|
-
return {
|
|
130728
|
-
rendered,
|
|
130729
|
-
preMemoryRendered: typeof preMemory === "string" && preMemory.trim() ? preMemory : rendered,
|
|
130730
|
-
policyState: asRecord(derived.behavior_policy_state)
|
|
130731
|
-
};
|
|
130732
|
-
};
|
|
130733
131015
|
ClientRuntimeAgentInstructionEmpty = class extends Error {
|
|
130734
131016
|
constructor(retryAfterMs) {
|
|
130735
131017
|
super("No Agent instruction is currently queued for this Client runtime.");
|
|
@@ -131224,9 +131506,9 @@ var init_local_analysis = __esm({
|
|
|
131224
131506
|
RUNTIME_SOURCE_DEFINITION_VERSION = "runtime-source-v1";
|
|
131225
131507
|
DECISION_INPUT_DEFINITION_VERSION = "decision-input-v1";
|
|
131226
131508
|
CONTEXT_ENVELOPE_DEFINITION_VERSION = "context-envelope-v2.1";
|
|
131227
|
-
CLIENT_RUNTIME_SOURCE_VERSION = typeof process !== "undefined" && true && "
|
|
131228
|
-
"
|
|
131229
|
-
) ? "
|
|
131509
|
+
CLIENT_RUNTIME_SOURCE_VERSION = typeof process !== "undefined" && true && "68890025dbd4546782da81b71404334ad74799f8".trim() && !["unknown", "unstamped", "development"].includes(
|
|
131510
|
+
"68890025dbd4546782da81b71404334ad74799f8".trim().toLowerCase()
|
|
131511
|
+
) ? "68890025dbd4546782da81b71404334ad74799f8".trim() : null;
|
|
131230
131512
|
CLIENT_MAIN_PROMPT_RENDERER = "client_runtime.buildLocalRuntimePromptArtifacts:v1";
|
|
131231
131513
|
CLIENT_REVIEW_PROMPT_RENDERER = "client_runtime.review_prompt_assembly:v1";
|
|
131232
131514
|
resolveEffectivePromptRuntimeProvenance = (input) => ({
|
|
@@ -132295,16 +132577,6 @@ ${reviewOutputContract}`;
|
|
|
132295
132577
|
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds} UTC (${weekday})`;
|
|
132296
132578
|
};
|
|
132297
132579
|
formatUtcNowWithWeekday = () => formatUtcTimestampWithWeekday(Date.now());
|
|
132298
|
-
formatPromptPrice = (value) => {
|
|
132299
|
-
const numeric2 = Number(value);
|
|
132300
|
-
if (!Number.isFinite(numeric2) || numeric2 === 0) {
|
|
132301
|
-
return 0;
|
|
132302
|
-
}
|
|
132303
|
-
if (Math.abs(numeric2) >= PROMPT_PRICE_INTEGER_THRESHOLD) {
|
|
132304
|
-
return Number(Math.trunc(numeric2));
|
|
132305
|
-
}
|
|
132306
|
-
return roundPromptSignificant(numeric2, PROMPT_SIGNIFICANT_DIGITS);
|
|
132307
|
-
};
|
|
132308
132580
|
capacityUnitSize = (tradeSize, configuredTradeAmount) => {
|
|
132309
132581
|
if (Number.isFinite(tradeSize) && tradeSize > 0) return tradeSize;
|
|
132310
132582
|
const configured2 = Number(configuredTradeAmount);
|
|
@@ -132313,123 +132585,6 @@ ${reviewOutputContract}`;
|
|
|
132313
132585
|
}
|
|
132314
132586
|
return configured2;
|
|
132315
132587
|
};
|
|
132316
|
-
buildPromptAccountStatusValue = (accountSummary, marginNote, effectiveTakerRates, symbols) => [
|
|
132317
|
-
"<account_status>",
|
|
132318
|
-
stringifyPromptJson({
|
|
132319
|
-
pools: buildPromptCollateralPools(accountSummary.perp_dex_accounts, symbols),
|
|
132320
|
-
fees: buildPromptFeeMap(effectiveTakerRates, symbols)
|
|
132321
|
-
}),
|
|
132322
|
-
"</account_status>",
|
|
132323
|
-
"",
|
|
132324
|
-
marginNote
|
|
132325
|
-
].join("\n");
|
|
132326
|
-
buildPromptPositionsValue = (input) => {
|
|
132327
|
-
const validateInstructionTemplate = (template, allowedKeys) => {
|
|
132328
|
-
formatInstructionTemplate(
|
|
132329
|
-
template,
|
|
132330
|
-
Object.fromEntries(allowedKeys.map((key) => [key, ""])),
|
|
132331
|
-
"positions instruction template"
|
|
132332
|
-
);
|
|
132333
|
-
};
|
|
132334
|
-
validateInstructionTemplate(input.positionsInstructions.close_reduce, []);
|
|
132335
|
-
validateInstructionTemplate(input.positionsInstructions.capacity_flat, []);
|
|
132336
|
-
validateInstructionTemplate(input.positionsInstructions.capacity_full, []);
|
|
132337
|
-
validateInstructionTemplate(input.positionsInstructions.capacity_low, ["remaining"]);
|
|
132338
|
-
const activePositions = input.positions.filter((position) => Number(position.size) !== 0);
|
|
132339
|
-
const orderedSymbols = orderPromptSymbols(input.symbols, activePositions.map((position) => position.symbol));
|
|
132340
|
-
const symbolRanks = new Map(orderedSymbols.map((symbol2, index) => [symbol2, index]));
|
|
132341
|
-
activePositions.sort((left, right) => symbolRanks.get(normalizeHyperliquidMarketSymbol(left.symbol)) - symbolRanks.get(normalizeHyperliquidMarketSymbol(right.symbol)));
|
|
132342
|
-
const assetUsage = /* @__PURE__ */ new Map();
|
|
132343
|
-
const exchangeUsage = /* @__PURE__ */ new Map();
|
|
132344
|
-
let globalUnitsUsed = 0;
|
|
132345
|
-
const promptPositions = activePositions.map((position) => {
|
|
132346
|
-
const entryPrice = Number(position.entry_price);
|
|
132347
|
-
const size = Number(position.size);
|
|
132348
|
-
const unrealizedPnl = Number(position.unrealized_pnl);
|
|
132349
|
-
if (!Number.isFinite(entryPrice) || entryPrice <= 0 || !Number.isFinite(size) || size === 0) {
|
|
132350
|
-
throw new Error(`Active position identity/economics are invalid for ${position.symbol}`);
|
|
132351
|
-
}
|
|
132352
|
-
if (!Number.isFinite(unrealizedPnl)) {
|
|
132353
|
-
throw new Error(`Active position PnL is unavailable for ${position.symbol}`);
|
|
132354
|
-
}
|
|
132355
|
-
const notionalValue = Math.abs(size * entryPrice);
|
|
132356
|
-
const unitsUsed = capacityUnitsUsedForPosition(size, entryPrice, input.unitSize);
|
|
132357
|
-
globalUnitsUsed += unitsUsed;
|
|
132358
|
-
assetUsage.set(position.symbol, unitsUsed);
|
|
132359
|
-
const venue = getHyperliquidMarketDex(position.symbol);
|
|
132360
|
-
exchangeUsage.set(venue, (exchangeUsage.get(venue) ?? 0) + unitsUsed);
|
|
132361
|
-
const currentValue = Math.abs(size > 0 ? notionalValue + unrealizedPnl : notionalValue - unrealizedPnl);
|
|
132362
|
-
const takerRate = buildPromptFeeMap(input.effectiveTakerRates, [position.symbol])[normalizeHyperliquidMarketSymbol(position.symbol)];
|
|
132363
|
-
const totalFees = takerRate == null ? null : (notionalValue + currentValue) * takerRate;
|
|
132364
|
-
const pnlAfterFees = totalFees == null ? null : unrealizedPnl - totalFees;
|
|
132365
|
-
let breakeven = null;
|
|
132366
|
-
if (entryPrice > 0 && takerRate != null) {
|
|
132367
|
-
if (size > 0) {
|
|
132368
|
-
breakeven = entryPrice * (1 + takerRate) / (1 - takerRate);
|
|
132369
|
-
} else if (size < 0) {
|
|
132370
|
-
breakeven = entryPrice * (1 - takerRate) / (1 + takerRate);
|
|
132371
|
-
}
|
|
132372
|
-
}
|
|
132373
|
-
return {
|
|
132374
|
-
s: position.symbol,
|
|
132375
|
-
sd: size > 0 ? "LONG" : "SHORT",
|
|
132376
|
-
v: roundPromptFixed(notionalValue),
|
|
132377
|
-
cv: roundPromptFixed(currentValue),
|
|
132378
|
-
ep: entryPrice ? formatPromptPrice(entryPrice) : 0,
|
|
132379
|
-
be: breakeven == null ? null : formatPromptPrice(breakeven),
|
|
132380
|
-
liq: position.liquidation_price ? formatPromptPrice(position.liquidation_price) : "-",
|
|
132381
|
-
u: unitsUsed,
|
|
132382
|
-
up: roundPromptFixed(unrealizedPnl),
|
|
132383
|
-
f: totalFees == null ? null : roundPromptFixed(totalFees),
|
|
132384
|
-
n: pnlAfterFees == null ? null : roundPromptFixed(pnlAfterFees),
|
|
132385
|
-
...projectPositionPromptNormalization({
|
|
132386
|
-
entryValue: notionalValue,
|
|
132387
|
-
currentValue,
|
|
132388
|
-
unrealizedPnl,
|
|
132389
|
-
netPnl: pnlAfterFees,
|
|
132390
|
-
accountEquity: poolEquityForSymbol(input.perpDexAccounts, position.symbol)
|
|
132391
|
-
}),
|
|
132392
|
-
...projectPositionPromptExcursions({
|
|
132393
|
-
projection: input.positionExcursions[normalizeHyperliquidMarketSymbol(position.symbol)],
|
|
132394
|
-
size,
|
|
132395
|
-
entryPrice,
|
|
132396
|
-
unrealizedPnl,
|
|
132397
|
-
accountEquity: poolEquityForSymbol(input.perpDexAccounts, position.symbol),
|
|
132398
|
-
cutoffMs: input.cutoffMs
|
|
132399
|
-
})
|
|
132400
|
-
};
|
|
132401
|
-
});
|
|
132402
|
-
const remainingGlobal = Math.max(0, input.maxTradesGlobal - globalUnitsUsed);
|
|
132403
|
-
const parts = [
|
|
132404
|
-
"<positions>",
|
|
132405
|
-
stringifyPromptJson(promptPositions),
|
|
132406
|
-
"</positions>",
|
|
132407
|
-
...activePositions.length === 0 ? ["", input.positionsInstructions.capacity_flat] : [],
|
|
132408
|
-
"",
|
|
132409
|
-
"--- Capacity & Limits --- ",
|
|
132410
|
-
`Global: ${globalUnitsUsed}/${input.maxTradesGlobal} exposure units used. (Additional capacity: ${remainingGlobal}) `
|
|
132411
|
-
];
|
|
132412
|
-
for (const venue of new Set(orderedSymbols.map(getHyperliquidMarketDex))) {
|
|
132413
|
-
const used = exchangeUsage.get(venue) ?? 0;
|
|
132414
|
-
const remaining = Math.max(0, input.maxTradesPerExchange - used);
|
|
132415
|
-
parts.push(`Exchange '${venue || "native"}': ${used}/${input.maxTradesPerExchange} exposure units used. (Additional capacity: ${remaining}) `);
|
|
132416
|
-
}
|
|
132417
|
-
for (const symbol2 of input.symbols) {
|
|
132418
|
-
const used = assetUsage.get(symbol2) ?? 0;
|
|
132419
|
-
const remaining = Math.max(0, input.maxTradesPerAsset - used);
|
|
132420
|
-
parts.push(`Asset '${symbol2}': ${used}/${input.maxTradesPerAsset} exposure units used. (Additional capacity: ${remaining}) `);
|
|
132421
|
-
}
|
|
132422
|
-
parts.push("");
|
|
132423
|
-
parts.push(...input.positionsInstructions.close_reduce.split("\n"));
|
|
132424
|
-
if (remainingGlobal <= 0) {
|
|
132425
|
-
parts.push(`${input.positionsInstructions.capacity_full} `);
|
|
132426
|
-
} else if (input.maxTradesPerPrompt < input.maxTradesGlobal && remainingGlobal < input.maxTradesPerPrompt) {
|
|
132427
|
-
parts.push(`${formatInstructionTemplate(input.positionsInstructions.capacity_low, {
|
|
132428
|
-
remaining: remainingGlobal
|
|
132429
|
-
}, "positions instruction template")} `);
|
|
132430
|
-
}
|
|
132431
|
-
return parts.join("\n");
|
|
132432
|
-
};
|
|
132433
132588
|
sanitizePromptSymbol = (value) => String(value ?? "").replace(/<[^>]*>/g, "").slice(0, PROMPT_SYMBOL_MAX_CHARS);
|
|
132434
132589
|
fillTimeMs = (fill) => {
|
|
132435
132590
|
const value = Number(fill.time ?? fill.time_ms ?? 0);
|
|
@@ -133181,7 +133336,9 @@ ${reviewOutputContract}`;
|
|
|
133181
133336
|
return text2.startsWith("- ") ? text2 : `- ${text2}`;
|
|
133182
133337
|
};
|
|
133183
133338
|
const renderBehaviorData = (entries) => {
|
|
133184
|
-
const behaviorJson = stringifyPromptJson(
|
|
133339
|
+
const behaviorJson = stringifyPromptJson(Object.fromEntries(Object.entries(entries).map(
|
|
133340
|
+
([symbol2, entry]) => [symbol2, withoutHiddenFields(entry, input.hiddenFields ?? /* @__PURE__ */ new Set())]
|
|
133341
|
+
))).replace(/&/g, "\\u0026").replace(/</g, "\\u003c").replace(/>/g, "\\u003e");
|
|
133185
133342
|
const lines = [
|
|
133186
133343
|
`<behavior_state>
|
|
133187
133344
|
${behaviorJson}
|
|
@@ -133247,11 +133404,12 @@ ${stringifyPromptJson(parts.candlesPayload)}
|
|
|
133247
133404
|
orderPromptSymbols(
|
|
133248
133405
|
parts.positions.symbols,
|
|
133249
133406
|
parts.positions.positions.filter((position) => Number(position.size) !== 0).map((position) => position.symbol)
|
|
133250
|
-
)
|
|
133407
|
+
),
|
|
133408
|
+
hiddenFieldsOf(parts.hiddenPromptFields, "account_status")
|
|
133251
133409
|
),
|
|
133252
133410
|
calendar: parts.calendar,
|
|
133253
133411
|
behavior_state: parts.behaviorState,
|
|
133254
|
-
positions: buildPromptPositionsValue(parts.positions),
|
|
133412
|
+
positions: buildPromptPositionsValue({ ...parts.positions, hiddenFields: hiddenFieldsOf(parts.hiddenPromptFields, "positions") }),
|
|
133255
133413
|
performance: String(parts.derivedValues.performance ?? ""),
|
|
133256
133414
|
market_regime: String(parts.derivedValues.market_regime ?? ""),
|
|
133257
133415
|
...Object.fromEntries(
|
|
@@ -133278,7 +133436,8 @@ ${stringifyPromptJson(parts.candlesPayload)}
|
|
|
133278
133436
|
calendarSummary: String(input.contextVars.calendar ?? ""),
|
|
133279
133437
|
behaviorStateSummary: String(input.contextVars.behavior_state ?? ""),
|
|
133280
133438
|
referenceCandlesSummary: String(input.contextVars[REFERENCE_CANDLES_PROMPT_VARIABLE] ?? ""),
|
|
133281
|
-
referenceIndicatorFlags: input.referenceIndicators
|
|
133439
|
+
referenceIndicatorFlags: input.referenceIndicators,
|
|
133440
|
+
hiddenPromptFields: input.hiddenPromptFields
|
|
133282
133441
|
});
|
|
133283
133442
|
const templateContextVars = Object.fromEntries(
|
|
133284
133443
|
Object.entries(input.contextVars).filter(([key]) => activePlaceholders.has(key))
|
|
@@ -133990,27 +134149,24 @@ ${stringifyPromptJson(parts.candlesPayload)}
|
|
|
133990
134149
|
"market_regime",
|
|
133991
134150
|
...NEWS_PROMPT_VARIABLES,
|
|
133992
134151
|
"calendar",
|
|
133993
|
-
// The
|
|
134152
|
+
// The whole <reference_candles> block, rendered from its inputs; it is
|
|
133994
134153
|
// present, possibly blank, whenever the template uses the variable.
|
|
133995
134154
|
REFERENCE_CANDLES_PROMPT_VARIABLE,
|
|
133996
134155
|
"interval"
|
|
133997
134156
|
].includes(key));
|
|
133998
|
-
const derivedValues = input.renderedDerivedContext
|
|
134157
|
+
const derivedValues = input.renderedDerivedContext.values;
|
|
133999
134158
|
for (const key of requiredDerivedKeys) {
|
|
134000
134159
|
if (!Object.prototype.hasOwnProperty.call(derivedValues, key)) {
|
|
134001
|
-
throw new
|
|
134160
|
+
throw new RuntimeReasonError(`Prompt derived context missing required field: ${key}`, "live_derived_context_build_failed");
|
|
134002
134161
|
}
|
|
134003
134162
|
}
|
|
134004
|
-
const rawReferenceIndicators = input.renderedDerivedContext ? input.renderedDerivedContext.referenceIndicators : input.derivedContext.reference_candles_indicators;
|
|
134005
134163
|
return {
|
|
134006
134164
|
derivedValues,
|
|
134007
134165
|
intervalContext: String(derivedValues.interval ?? "").trim(),
|
|
134008
134166
|
calendarContext: String(derivedValues.calendar ?? ""),
|
|
134009
134167
|
// The block, its unavailable form, or blank.
|
|
134010
134168
|
referenceCandlesContext: String(derivedValues[REFERENCE_CANDLES_PROMPT_VARIABLE] ?? ""),
|
|
134011
|
-
referenceIndicators:
|
|
134012
|
-
Object.entries(rawReferenceIndicators).map(([key, value]) => [key, Boolean(value)])
|
|
134013
|
-
) : void 0
|
|
134169
|
+
referenceIndicators: input.renderedDerivedContext.referenceIndicators
|
|
134014
134170
|
};
|
|
134015
134171
|
};
|
|
134016
134172
|
requireRuntimePromptLane = (promptKnobs, expectedPromptLane) => {
|
|
@@ -134288,6 +134444,7 @@ ${stringifyPromptJson(parts.candlesPayload)}
|
|
|
134288
134444
|
} = resolveRuntimeTradingScope(settings, config2);
|
|
134289
134445
|
const sortedTimeframes = sortTradingTimeframes(timeframes);
|
|
134290
134446
|
const activeIndicators = normalizeAiIndicatorFlags(config2.default_ai_indicators, settings.ai_indicators);
|
|
134447
|
+
const hiddenPromptFields = resolveHiddenPromptFields(config2.default_hidden_prompt_fields, settings.hidden_prompt_fields);
|
|
134291
134448
|
const lookbackSettings = settings.analysis_lookback;
|
|
134292
134449
|
const effectiveDefaultLookbacks = config2.default_analysis_lookback_fallbacks;
|
|
134293
134450
|
const indicatorCandleCount = Number(config2.indicator_candle_count);
|
|
@@ -134661,22 +134818,20 @@ ${stringifyPromptJson(parts.candlesPayload)}
|
|
|
134661
134818
|
throw error48;
|
|
134662
134819
|
}
|
|
134663
134820
|
const { metadata: promptMetadata, derived: promptDerivedContext } = promptContracts;
|
|
134664
|
-
let renderedDerivedContext
|
|
134665
|
-
|
|
134666
|
-
|
|
134667
|
-
|
|
134668
|
-
|
|
134669
|
-
|
|
134670
|
-
|
|
134671
|
-
|
|
134672
|
-
|
|
134673
|
-
|
|
134674
|
-
|
|
134675
|
-
|
|
134676
|
-
return liveContextUnavailableResult(promptMetadata, error48.message);
|
|
134677
|
-
}
|
|
134678
|
-
throw error48;
|
|
134821
|
+
let renderedDerivedContext;
|
|
134822
|
+
try {
|
|
134823
|
+
renderedDerivedContext = renderDerivedPromptContext({
|
|
134824
|
+
inputs: requireDerivedPromptInputs(asRecord(promptDerivedContext.derived_context)),
|
|
134825
|
+
placeholders: extractTemplatePlaceholders(String(promptMetadata.user_template ?? "")),
|
|
134826
|
+
loopIntervalSeconds: Number(asRecord(promptMetadata.prompt_knobs).loop_interval_seconds),
|
|
134827
|
+
deviceMarket: deviceMarketReads({ candlesBySymbol, tickersBySymbol, indicatorCandleCount }),
|
|
134828
|
+
hiddenPromptFields
|
|
134829
|
+
});
|
|
134830
|
+
} catch (error48) {
|
|
134831
|
+
if (input.mode === "trader" && error48 instanceof DerivedPromptContextUnavailableError) {
|
|
134832
|
+
return liveContextUnavailableResult(promptMetadata, error48.message);
|
|
134679
134833
|
}
|
|
134834
|
+
throw error48;
|
|
134680
134835
|
}
|
|
134681
134836
|
if (input.mode === "trader" && promptMetadata.main_model_enabled === false) {
|
|
134682
134837
|
return buildMainModelDisabledResult(promptMetadata);
|
|
@@ -134935,7 +135090,7 @@ ${stringifyPromptJson(parts.candlesPayload)}
|
|
|
134935
135090
|
calendarContext,
|
|
134936
135091
|
referenceCandlesContext,
|
|
134937
135092
|
referenceIndicators
|
|
134938
|
-
} = resolveRuntimePromptDerivedBlocks({ templatePlaceholders, renderedDerivedContext
|
|
135093
|
+
} = resolveRuntimePromptDerivedBlocks({ templatePlaceholders, renderedDerivedContext });
|
|
134939
135094
|
const expectedPromptLane = input.mode === "trader" ? "strategy" : "assistant";
|
|
134940
135095
|
requireRuntimePromptLane(promptKnobs, expectedPromptLane);
|
|
134941
135096
|
if (input.mode === "trader" && promptMetadata.review_enabled) {
|
|
@@ -134972,7 +135127,8 @@ ${stringifyPromptJson(parts.candlesPayload)}
|
|
|
134972
135127
|
promptSymbols,
|
|
134973
135128
|
promptTimeframes,
|
|
134974
135129
|
behaviorMemoryEnabled,
|
|
134975
|
-
cutoffMs: behaviorMemoryCutoffMs
|
|
135130
|
+
cutoffMs: behaviorMemoryCutoffMs,
|
|
135131
|
+
hiddenPromptFields
|
|
134976
135132
|
});
|
|
134977
135133
|
} catch (error48) {
|
|
134978
135134
|
throw new BehaviorMemoryUnavailableError(error48);
|
|
@@ -134995,7 +135151,8 @@ ${stringifyPromptJson(parts.candlesPayload)}
|
|
|
134995
135151
|
knobs: { maxTradesGlobal, maxTradesPerExchange, maxTradesPerAsset, maxTradesPerPrompt, tradeSize: metadataTradeSize },
|
|
134996
135152
|
positionsInstructions,
|
|
134997
135153
|
size: metadataTradeSize,
|
|
134998
|
-
leverage: metadataLeverage
|
|
135154
|
+
leverage: metadataLeverage,
|
|
135155
|
+
hiddenPromptFields
|
|
134999
135156
|
}));
|
|
135000
135157
|
} catch (error48) {
|
|
135001
135158
|
const detail = error48 instanceof Error ? error48.message : String(error48);
|
|
@@ -135044,7 +135201,6 @@ ${stringifyPromptJson(parts.candlesPayload)}
|
|
|
135044
135201
|
`calendar_source=${calendarContext ? "derived_context" : "missing"}`,
|
|
135045
135202
|
...NEWS_PROMPT_VARIABLES.map((key) => `${key}_source=${Object.prototype.hasOwnProperty.call(derivedValues, key) ? "derived_context" : "missing"}`),
|
|
135046
135203
|
`${REFERENCE_CANDLES_PROMPT_VARIABLE}_source=${Object.prototype.hasOwnProperty.call(derivedValues, REFERENCE_CANDLES_PROMPT_VARIABLE) ? "derived_context" : "missing"}`,
|
|
135047
|
-
`derived_blocks=${renderedDerivedContext ? "rendered_here" : "server"}`,
|
|
135048
135204
|
...activeIndicators.rv ? [`relative_volume_baselines_source=${relativeVolumeContext ? "derived_context" : "missing"}`] : []
|
|
135049
135205
|
].join(" ")
|
|
135050
135206
|
});
|
|
@@ -135053,9 +135209,8 @@ ${stringifyPromptJson(parts.candlesPayload)}
|
|
|
135053
135209
|
policy_state: behaviorPolicyState
|
|
135054
135210
|
};
|
|
135055
135211
|
let effectivePromptContextVars = { ...contextVars };
|
|
135056
|
-
|
|
135057
|
-
|
|
135058
|
-
contextSnapshots.performance_structured = performanceStructured;
|
|
135212
|
+
if (renderedDerivedContext.performanceStructured) {
|
|
135213
|
+
contextSnapshots.performance_structured = renderedDerivedContext.performanceStructured;
|
|
135059
135214
|
}
|
|
135060
135215
|
let settingsSnapshotWithContext = {
|
|
135061
135216
|
...settings,
|
|
@@ -135118,7 +135273,8 @@ ${stringifyPromptJson(parts.candlesPayload)}
|
|
|
135118
135273
|
promptSymbols,
|
|
135119
135274
|
maxTradesPerPrompt,
|
|
135120
135275
|
metricsWindowHours,
|
|
135121
|
-
metricsSecondaryWindowHours
|
|
135276
|
+
metricsSecondaryWindowHours,
|
|
135277
|
+
hiddenPromptFields
|
|
135122
135278
|
}),
|
|
135123
135279
|
contextVars: renderContextVars
|
|
135124
135280
|
})
|
|
@@ -136277,7 +136433,7 @@ ${indentText.repeat(depth)}${brackets[1]}`;
|
|
|
136277
136433
|
});
|
|
136278
136434
|
|
|
136279
136435
|
// lib/runtime/copy-review-prompt.ts
|
|
136280
|
-
var COPY_REVIEW_PRIMARY_MODEL, COPY_TRADE_PROPOSAL, COPY_POSITION_REPAIR, metadataOf, copyReviewIsGapRepair,
|
|
136436
|
+
var COPY_REVIEW_DECISIONS, COPY_REVIEW_INTENTS, COPY_REVIEW_PRIMARY_MODEL, COPY_TRADE_PROPOSAL, COPY_POSITION_REPAIR, metadataOf, copyReviewIsGapRepair, isOneOf, copyReviewSentProposal, copyReviewObserved, copyReviewProposedTrade, text, gapRepairTemplates, copyReviewPromptContext, copyReviewPrimaryReasoning, copyReviewPromptSymbols, copyReviewPromptSize, promptJsonValue, renderCopyReviewPrompts;
|
|
136281
136437
|
var init_copy_review_prompt = __esm({
|
|
136282
136438
|
"lib/runtime/copy-review-prompt.ts"() {
|
|
136283
136439
|
"use strict";
|
|
@@ -136294,40 +136450,24 @@ var init_copy_review_prompt = __esm({
|
|
|
136294
136450
|
init_local_analysis();
|
|
136295
136451
|
init_python_json();
|
|
136296
136452
|
init_runtime_error_reason_rules();
|
|
136453
|
+
COPY_REVIEW_DECISIONS = ["BUY", "SELL", "HOLD"];
|
|
136454
|
+
COPY_REVIEW_INTENTS = ["open", "add", "reduce", "close", "flip", "unknown"];
|
|
136297
136455
|
COPY_REVIEW_PRIMARY_MODEL = "Copy Trading";
|
|
136298
136456
|
COPY_TRADE_PROPOSAL = "copy_trade_proposal";
|
|
136299
136457
|
COPY_POSITION_REPAIR = "copy_position_repair";
|
|
136300
136458
|
metadataOf = (event) => event.sanitized_metadata && typeof event.sanitized_metadata === "object" && !Array.isArray(event.sanitized_metadata) ? event.sanitized_metadata : {};
|
|
136301
136459
|
copyReviewIsGapRepair = (event) => metadataOf(event).source_fill_gap_reconciliation === true;
|
|
136302
|
-
|
|
136303
|
-
|
|
136304
|
-
|
|
136305
|
-
|
|
136306
|
-
|
|
136307
|
-
|
|
136308
|
-
|
|
136309
|
-
|
|
136310
|
-
|
|
136311
|
-
|
|
136312
|
-
|
|
136313
|
-
if (Math.abs(next) > Math.abs(previous)) return "add";
|
|
136314
|
-
return "reduce";
|
|
136315
|
-
};
|
|
136316
|
-
pythonFloatOf = (value) => {
|
|
136317
|
-
if (typeof value === "boolean") return value ? 1 : 0;
|
|
136318
|
-
if (typeof value === "number") return value;
|
|
136319
|
-
if (typeof value !== "string" || !value.trim()) return null;
|
|
136320
|
-
const parsed = Number(value.trim());
|
|
136321
|
-
return Number.isNaN(parsed) ? null : parsed;
|
|
136322
|
-
};
|
|
136323
|
-
copyReviewDestinationIntent = (event) => {
|
|
136324
|
-
const reconciliation = metadataOf(event).position_reconciliation;
|
|
136325
|
-
if (!reconciliation || typeof reconciliation !== "object" || Array.isArray(reconciliation)) return "unknown";
|
|
136326
|
-
const previous = pythonFloatOf(reconciliation.destination_position_before);
|
|
136327
|
-
const size = event.destination_size || 0;
|
|
136328
|
-
if (previous === null) return "unknown";
|
|
136329
|
-
const delta = String(event.destination_side || "").trim().toLowerCase() === "buy" ? size : -size;
|
|
136330
|
-
return inferIntentFromPositionDelta(previous, previous + delta);
|
|
136460
|
+
isOneOf = (values, value) => values.includes(value);
|
|
136461
|
+
copyReviewSentProposal = (event) => {
|
|
136462
|
+
const decision = event.proposed_decision;
|
|
136463
|
+
const intent = event.destination_intent;
|
|
136464
|
+
if (!isOneOf(COPY_REVIEW_DECISIONS, decision) || !isOneOf(COPY_REVIEW_INTENTS, intent)) {
|
|
136465
|
+
throw new RuntimeReasonError(
|
|
136466
|
+
"Missing copy review proposal: the server sent this copy without its proposed_decision and destination_intent.",
|
|
136467
|
+
"runtime_config_missing"
|
|
136468
|
+
);
|
|
136469
|
+
}
|
|
136470
|
+
return { decision, intent };
|
|
136331
136471
|
};
|
|
136332
136472
|
copyReviewObserved = (event) => copyReviewIsGapRepair(event) ? {
|
|
136333
136473
|
source_position: {
|
|
@@ -136346,32 +136486,35 @@ var init_copy_review_prompt = __esm({
|
|
|
136346
136486
|
fingerprint: event.source_event_fingerprint
|
|
136347
136487
|
}
|
|
136348
136488
|
};
|
|
136349
|
-
copyReviewProposedTrade = (event, source) =>
|
|
136350
|
-
|
|
136351
|
-
|
|
136352
|
-
type:
|
|
136353
|
-
|
|
136354
|
-
|
|
136355
|
-
|
|
136356
|
-
|
|
136357
|
-
|
|
136358
|
-
|
|
136359
|
-
|
|
136360
|
-
|
|
136361
|
-
|
|
136362
|
-
|
|
136363
|
-
|
|
136364
|
-
|
|
136365
|
-
|
|
136366
|
-
|
|
136367
|
-
|
|
136368
|
-
|
|
136369
|
-
|
|
136370
|
-
|
|
136371
|
-
|
|
136372
|
-
|
|
136373
|
-
|
|
136374
|
-
|
|
136489
|
+
copyReviewProposedTrade = (event, source) => {
|
|
136490
|
+
const proposal = copyReviewSentProposal(event);
|
|
136491
|
+
return {
|
|
136492
|
+
type: copyReviewIsGapRepair(event) ? COPY_POSITION_REPAIR : COPY_TRADE_PROPOSAL,
|
|
136493
|
+
source: {
|
|
136494
|
+
type: source.source_type,
|
|
136495
|
+
identifier: source.source_identifier,
|
|
136496
|
+
display_name: source.source_display_name,
|
|
136497
|
+
wallet_address: source.source_wallet_address
|
|
136498
|
+
},
|
|
136499
|
+
symbol: event.symbol,
|
|
136500
|
+
decision: proposal.decision,
|
|
136501
|
+
...copyReviewObserved(event),
|
|
136502
|
+
destination_order: {
|
|
136503
|
+
side: event.destination_side,
|
|
136504
|
+
size: pythonFloat(event.destination_size),
|
|
136505
|
+
notional: pythonFloat(event.destination_notional),
|
|
136506
|
+
reduce_only: Boolean(event.reduce_only),
|
|
136507
|
+
runtime_mode: event.runtime_mode,
|
|
136508
|
+
idempotency_key: event.idempotency_key
|
|
136509
|
+
},
|
|
136510
|
+
copy_intent: {
|
|
136511
|
+
source_intent: event.inferred_intent,
|
|
136512
|
+
destination_intent: proposal.intent,
|
|
136513
|
+
scaling_mode: event.scaling_mode,
|
|
136514
|
+
scale_factor: pythonFloat(event.scale_factor)
|
|
136515
|
+
}
|
|
136516
|
+
};
|
|
136517
|
+
};
|
|
136375
136518
|
text = (value) => ({ kind: "str", value });
|
|
136376
136519
|
gapRepairTemplates = (templates) => {
|
|
136377
136520
|
if (!templates.gap_repair) {
|
|
@@ -136410,7 +136553,7 @@ var init_copy_review_prompt = __esm({
|
|
|
136410
136553
|
return value;
|
|
136411
136554
|
};
|
|
136412
136555
|
renderCopyReviewPrompts = (input) => {
|
|
136413
|
-
const proposedDecision =
|
|
136556
|
+
const proposedDecision = copyReviewSentProposal(input.event).decision;
|
|
136414
136557
|
const proposedTrade = copyReviewProposedTrade(input.event, input.source);
|
|
136415
136558
|
const { context, ...primary } = input.primary;
|
|
136416
136559
|
const main = buildLocalRuntimePromptArtifacts2({ ...primary, contextVars: assemblePromptContextVars(context) });
|
|
@@ -136455,7 +136598,6 @@ ${copyReviewPromptContext(proposedTrade, input.templates)}`;
|
|
|
136455
136598
|
primaryDecisionJson
|
|
136456
136599
|
});
|
|
136457
136600
|
return {
|
|
136458
|
-
proposedDecision,
|
|
136459
136601
|
primaryDecision,
|
|
136460
136602
|
primarySystemPrompt,
|
|
136461
136603
|
primaryUserPrompt,
|
|
@@ -136480,6 +136622,7 @@ var init_copy_review_render_inputs = __esm({
|
|
|
136480
136622
|
init_client_account_report();
|
|
136481
136623
|
init_copy_review_prompt();
|
|
136482
136624
|
init_render();
|
|
136625
|
+
init_prompt_field_visibility();
|
|
136483
136626
|
init_local_analysis();
|
|
136484
136627
|
init_runtime_error_reason_rules();
|
|
136485
136628
|
init_runtime_prompt_steps();
|
|
@@ -136551,18 +136694,19 @@ var init_copy_review_render_inputs = __esm({
|
|
|
136551
136694
|
const { config: config2, contract: derived, marketData, fills, accountState } = input;
|
|
136552
136695
|
const { settings, symbols, sortedTimeframes, indicatorCandleCount } = input.scope;
|
|
136553
136696
|
const activeIndicators = normalizeAiIndicatorFlags(config2.default_ai_indicators, settings.ai_indicators);
|
|
136697
|
+
const hiddenPromptFields = resolveHiddenPromptFields(config2.default_hidden_prompt_fields, settings.hidden_prompt_fields);
|
|
136554
136698
|
const accountSummary = copyReviewAccountSummary(accountState);
|
|
136555
136699
|
const promptMetadata = requireCopyReviewContractReady(derived);
|
|
136556
136700
|
const tickersBySymbol = Object.fromEntries(marketData.map((entry) => [entry.symbol, entry.ticker]));
|
|
136557
136701
|
const candlesBySymbol = Object.fromEntries(marketData.map((entry) => [entry.symbol, entry.candles]));
|
|
136558
136702
|
const derivedContext = asRecord(derived.derived_context);
|
|
136559
|
-
const
|
|
136560
|
-
|
|
136561
|
-
inputs: derivedPromptInputs,
|
|
136703
|
+
const renderedDerivedContext = renderDerivedPromptContext({
|
|
136704
|
+
inputs: requireDerivedPromptInputs(derivedContext),
|
|
136562
136705
|
placeholders: extractTemplatePlaceholders(String(promptMetadata.user_template ?? "")),
|
|
136563
136706
|
loopIntervalSeconds: Number(asRecord(promptMetadata.prompt_knobs).loop_interval_seconds),
|
|
136564
|
-
deviceMarket: deviceMarketReads({ candlesBySymbol, tickersBySymbol, indicatorCandleCount })
|
|
136565
|
-
|
|
136707
|
+
deviceMarket: deviceMarketReads({ candlesBySymbol, tickersBySymbol, indicatorCandleCount }),
|
|
136708
|
+
hiddenPromptFields
|
|
136709
|
+
});
|
|
136566
136710
|
const promptKnobs = asRecord(promptMetadata.prompt_knobs);
|
|
136567
136711
|
const promptInstructions = asRecord(promptMetadata.prompt_instructions);
|
|
136568
136712
|
const knobs = resolveRuntimePromptKnobs(promptKnobs, config2, symbols, sortedTimeframes);
|
|
@@ -136584,7 +136728,7 @@ var init_copy_review_render_inputs = __esm({
|
|
|
136584
136728
|
});
|
|
136585
136729
|
const positionsInstructions = requireRuntimePositionsInstructions2(asRecord(promptInstructions.positions));
|
|
136586
136730
|
const { systemTemplate, userTemplate, templatePlaceholders } = requireRuntimePromptTemplates(promptMetadata);
|
|
136587
|
-
const derivedBlocks = resolveRuntimePromptDerivedBlocks({ templatePlaceholders, renderedDerivedContext
|
|
136731
|
+
const derivedBlocks = resolveRuntimePromptDerivedBlocks({ templatePlaceholders, renderedDerivedContext });
|
|
136588
136732
|
requireRuntimePromptLane(promptKnobs, "copy_review");
|
|
136589
136733
|
const behaviorMemoryEnabled = promptKnobs.behavior_memory_enabled;
|
|
136590
136734
|
const { cutoffMs } = resolveRuntimeBehaviorMemoryCutoff(derivedContext, derived.derived_context_generated_at);
|
|
@@ -136600,7 +136744,8 @@ var init_copy_review_render_inputs = __esm({
|
|
|
136600
136744
|
promptSymbols: knobs.promptSymbols,
|
|
136601
136745
|
promptTimeframes: knobs.promptTimeframes,
|
|
136602
136746
|
behaviorMemoryEnabled,
|
|
136603
|
-
cutoffMs
|
|
136747
|
+
cutoffMs,
|
|
136748
|
+
hiddenPromptFields
|
|
136604
136749
|
}).rendered;
|
|
136605
136750
|
const context = buildRuntimePromptContextParts({
|
|
136606
136751
|
config: config2,
|
|
@@ -136618,7 +136763,8 @@ var init_copy_review_render_inputs = __esm({
|
|
|
136618
136763
|
knobs,
|
|
136619
136764
|
positionsInstructions,
|
|
136620
136765
|
size: input.promptSize(copyReviewSizes),
|
|
136621
|
-
leverage: knobs.leverage
|
|
136766
|
+
leverage: knobs.leverage,
|
|
136767
|
+
hiddenPromptFields
|
|
136622
136768
|
});
|
|
136623
136769
|
const reviewInstructions = asRecord(promptMetadata.review_instructions);
|
|
136624
136770
|
return {
|
|
@@ -136632,7 +136778,8 @@ var init_copy_review_render_inputs = __esm({
|
|
|
136632
136778
|
promptSymbols: knobs.promptSymbols,
|
|
136633
136779
|
maxTradesPerPrompt: knobs.maxTradesPerPrompt,
|
|
136634
136780
|
metricsWindowHours: knobs.metricsWindowHours,
|
|
136635
|
-
metricsSecondaryWindowHours: knobs.metricsSecondaryWindowHours
|
|
136781
|
+
metricsSecondaryWindowHours: knobs.metricsSecondaryWindowHours,
|
|
136782
|
+
hiddenPromptFields
|
|
136636
136783
|
}),
|
|
136637
136784
|
context
|
|
136638
136785
|
},
|
|
@@ -136779,6 +136926,7 @@ var init_copy_review_runtime = __esm({
|
|
|
136779
136926
|
});
|
|
136780
136927
|
};
|
|
136781
136928
|
renderRuntimeCopyReview = async (input) => {
|
|
136929
|
+
copyReviewSentProposal(input.event);
|
|
136782
136930
|
const prepared = await prepareRuntimeCopyReviewPrimary({
|
|
136783
136931
|
profileId: input.profileId,
|
|
136784
136932
|
payload: input.payload,
|
|
@@ -138820,7 +138968,7 @@ var init_client_killswitch = __esm({
|
|
|
138820
138968
|
});
|
|
138821
138969
|
|
|
138822
138970
|
// lib/runtime/portfolio-evidence.ts
|
|
138823
|
-
var PORTFOLIO_RETRY_MS, PORTFOLIO_READ_PRIORITY, PortfolioBodyError, portfolioRequestBody,
|
|
138971
|
+
var PORTFOLIO_RETRY_MS, PORTFOLIO_READ_PRIORITY, PortfolioBodyError, portfolioRequestBody, isRecord9, checkPortfolioBody, runningProfiles2, portfolioBackoffUntil, errorCode2, runClientPortfolioReport;
|
|
138824
138972
|
var init_portfolio_evidence = __esm({
|
|
138825
138973
|
"lib/runtime/portfolio-evidence.ts"() {
|
|
138826
138974
|
"use strict";
|
|
@@ -138842,7 +138990,7 @@ var init_portfolio_evidence = __esm({
|
|
|
138842
138990
|
}
|
|
138843
138991
|
};
|
|
138844
138992
|
portfolioRequestBody = (walletAddress) => ({ type: "portfolio", user: walletAddress });
|
|
138845
|
-
|
|
138993
|
+
isRecord9 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
|
|
138846
138994
|
checkPortfolioBody = (body) => {
|
|
138847
138995
|
if (typeof body !== "string") throw new PortfolioBodyError("The portfolio body must be the raw response text.");
|
|
138848
138996
|
let parsed;
|
|
@@ -138852,7 +139000,7 @@ var init_portfolio_evidence = __esm({
|
|
|
138852
139000
|
throw new PortfolioBodyError("The portfolio response is not JSON.");
|
|
138853
139001
|
}
|
|
138854
139002
|
const periods = Array.isArray(parsed) ? parsed : [];
|
|
138855
|
-
const valid = periods.some((item) => Array.isArray(item) && item.length === RUNTIME_PORTFOLIO_PERIOD_ENTRY_LENGTH && typeof item[0] === "string" &&
|
|
139003
|
+
const valid = periods.some((item) => Array.isArray(item) && item.length === RUNTIME_PORTFOLIO_PERIOD_ENTRY_LENGTH && typeof item[0] === "string" && isRecord9(item[1]) && Array.isArray(item[1].accountValueHistory) && Array.isArray(item[1].pnlHistory));
|
|
138856
139004
|
if (!valid) throw new PortfolioBodyError("The portfolio response has no period histories.");
|
|
138857
139005
|
};
|
|
138858
139006
|
runningProfiles2 = /* @__PURE__ */ new Set();
|