@vtxmacro/cli 2026.10.45 → 2026.10.46
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/exo-harness.ts +74 -4
- package/bin/vtx-mcp.js +20 -3
- package/bin/vtx-service-bootstrap.js +20 -3
- package/bin/vtx-service-launcher.js +19 -2
- package/bin/vtx.js +1079 -614
- 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.46", codex_package_name: "@openai/codex", codex_version: "0.155.0", copilot_sdk_package_name: "@github/copilot-sdk", copilot_sdk_version: "1.0.0-beta.8", copilot_cli_package_name: "@github/copilot", copilot_cli_version: "1.0.80", deepseek_harness_version: "0.1.1-rc.2", deepseek_harness_packages: ["@deepseek-ai/dsh-agent", "@deepseek-ai/dsh-agent-instructions", "@deepseek-ai/dsh-agent-loop", "@deepseek-ai/dsh-agent-spine-demo", "@deepseek-ai/dsh-anonymous-user-id", "@deepseek-ai/dsh-atomic-write", "@deepseek-ai/dsh-attachment", "@deepseek-ai/dsh-brand", "@deepseek-ai/dsh-code-runtime", "@deepseek-ai/dsh-credentials", "@deepseek-ai/dsh-fs", "@deepseek-ai/dsh-goal", "@deepseek-ai/dsh-goal-round-driver", "@deepseek-ai/dsh-home-paths", "@deepseek-ai/dsh-invariants", "@deepseek-ai/dsh-jobs", "@deepseek-ai/dsh-jobs-local", "@deepseek-ai/dsh-launch-environment", "@deepseek-ai/dsh-llm", "@deepseek-ai/dsh-llm-deepseek", "@deepseek-ai/dsh-llm-retry", "@deepseek-ai/dsh-output-retention", "@deepseek-ai/dsh-sandbox", "@deepseek-ai/dsh-sandbox-policy", "@deepseek-ai/dsh-scope", "@deepseek-ai/dsh-session", "@deepseek-ai/dsh-session-checkpoint-policy", "@deepseek-ai/dsh-session-persistence", "@deepseek-ai/dsh-session-persistence-jsonl", "@deepseek-ai/dsh-session-projection", "@deepseek-ai/dsh-session-title", "@deepseek-ai/dsh-settings", "@deepseek-ai/dsh-shell", "@deepseek-ai/dsh-shell-env", "@deepseek-ai/dsh-skill", "@deepseek-ai/dsh-skill-filesystem", "@deepseek-ai/dsh-subprocess", "@deepseek-ai/dsh-system-prompt", "@deepseek-ai/dsh-timeout", "@deepseek-ai/dsh-tool-bash", "@deepseek-ai/dsh-tool-goal", "@deepseek-ai/dsh-tool-jobs", "@deepseek-ai/dsh-tool-skill", "@deepseek-ai/dsh-tools", "@deepseek-ai/dsh-typert-protocol", "@deepseek-ai/dsh-user-approval"], deepseek_cordis_package_name: "@deepseek-ai/cordis", deepseek_cordis_version: "4.0.1", deepseek_support_packages: { "@deepseek-ai/cordis-plugin-timer": "1.1.3" }, platforms: { "linux-x64": { package_name: "@openai/codex-linux-x64", target: "x86_64-unknown-linux-musl", binary_name: "codex", sha256: "660e159a49e823ac8e5986cb238f73158ce4b957d40d9292f8de90862644b501" }, "win32-x64": { package_name: "@openai/codex-win32-x64", target: "x86_64-pc-windows-msvc", binary_name: "codex.exe", sha256: "e4c11374bd9de8ad5c3b7617fd4654bb7839901edb0863f9930666863c7a021b" } }, pi_coding_agent_package_name: "@earendil-works/pi-coding-agent", pi_ai_package_name: "@earendil-works/pi-ai", pi_version: "0.85.1", pi_support_packages: ["@earendil-works/pi-agent-core", "@earendil-works/pi-telemetry", "@earendil-works/pi-tui", "@earendil-works/chord"], grok_version: "1.0.30", grok_platforms: { "linux-x64": { package_name: "@xai-official/grok-linux-x64", binary_name: "grok", sha256: "504dd6546ab991b75d36698242875ce461489cd1f8cd84285873cb55bd5c7d54" }, "win32-x64": { package_name: "@xai-official/grok-win32-x64", binary_name: "grok.exe", sha256: "48736d1a4342a801ea26d0ecde4c516b653f791399065adaa55973f83abd8867" } } };
|
|
126
126
|
}
|
|
127
127
|
});
|
|
128
128
|
|
|
@@ -929,6 +929,10 @@ var init_runtime_policy_generated = __esm({
|
|
|
929
929
|
auto_resume_failure_detail_chars: 500,
|
|
930
930
|
vault_migration_error_chars: 200
|
|
931
931
|
},
|
|
932
|
+
event_batch: {
|
|
933
|
+
window_milliseconds: 1e3,
|
|
934
|
+
max_events: 32
|
|
935
|
+
},
|
|
932
936
|
request_retry: {
|
|
933
937
|
max_attempts: 3,
|
|
934
938
|
base_delay_milliseconds: 300,
|
|
@@ -1378,13 +1382,22 @@ var init_runtime_policy_generated = __esm({
|
|
|
1378
1382
|
page_start_wait_seconds: 45,
|
|
1379
1383
|
page_start_poll_seconds: 1,
|
|
1380
1384
|
profiles_read_timeout_seconds: 30,
|
|
1381
|
-
command_notice_reconnect_max_seconds: 60
|
|
1385
|
+
command_notice_reconnect_max_seconds: 60,
|
|
1386
|
+
sleep_quiet_milliseconds: 3e3,
|
|
1387
|
+
sleep_max_seconds: 60,
|
|
1388
|
+
sleep_min_seconds: 10,
|
|
1389
|
+
sleep_alarm_grace_seconds: 15,
|
|
1390
|
+
sleep_elastic_below_milliseconds: 1e3,
|
|
1391
|
+
sleep_request_wait_milliseconds: 4e3,
|
|
1392
|
+
sleep_defer_seconds: 30
|
|
1382
1393
|
}
|
|
1383
1394
|
},
|
|
1384
1395
|
websocket: {
|
|
1385
1396
|
client_connection: {
|
|
1386
1397
|
reconnect_delay_ms: 3e3,
|
|
1387
1398
|
ping_interval_ms: 3e4,
|
|
1399
|
+
pong_timeout_ms: 5e3,
|
|
1400
|
+
max_unanswered_pings: 2,
|
|
1388
1401
|
message_flush_interval_ms: 16,
|
|
1389
1402
|
price_change_highlight_ms: 1e3,
|
|
1390
1403
|
debug_recent_channel_limit: 24
|
|
@@ -1403,6 +1416,9 @@ var init_runtime_policy_generated = __esm({
|
|
|
1403
1416
|
min_length: 3,
|
|
1404
1417
|
max_length: 20,
|
|
1405
1418
|
update_confirmation_ms: 3e3
|
|
1419
|
+
},
|
|
1420
|
+
passkey_names: {
|
|
1421
|
+
max_length: 100
|
|
1406
1422
|
}
|
|
1407
1423
|
},
|
|
1408
1424
|
profiles: {
|
|
@@ -1466,7 +1482,8 @@ var init_runtime_policy_generated = __esm({
|
|
|
1466
1482
|
full_history_default_limit: 20,
|
|
1467
1483
|
default_page_size: 50,
|
|
1468
1484
|
trade_lookup_max_order_ids: 200,
|
|
1469
|
-
decision_batch_default_limit: 50
|
|
1485
|
+
decision_batch_default_limit: 50,
|
|
1486
|
+
non_admin_lookback_days: 30
|
|
1470
1487
|
},
|
|
1471
1488
|
updates: {
|
|
1472
1489
|
posts: {
|
|
@@ -21036,6 +21053,10 @@ var init_runtime_policy_generated2 = __esm({
|
|
|
21036
21053
|
auto_resume_failure_detail_chars: 500,
|
|
21037
21054
|
vault_migration_error_chars: 200
|
|
21038
21055
|
},
|
|
21056
|
+
event_batch: {
|
|
21057
|
+
window_milliseconds: 1e3,
|
|
21058
|
+
max_events: 32
|
|
21059
|
+
},
|
|
21039
21060
|
request_retry: {
|
|
21040
21061
|
max_attempts: 3,
|
|
21041
21062
|
base_delay_milliseconds: 300,
|
|
@@ -21485,13 +21506,22 @@ var init_runtime_policy_generated2 = __esm({
|
|
|
21485
21506
|
page_start_wait_seconds: 45,
|
|
21486
21507
|
page_start_poll_seconds: 1,
|
|
21487
21508
|
profiles_read_timeout_seconds: 30,
|
|
21488
|
-
command_notice_reconnect_max_seconds: 60
|
|
21509
|
+
command_notice_reconnect_max_seconds: 60,
|
|
21510
|
+
sleep_quiet_milliseconds: 3e3,
|
|
21511
|
+
sleep_max_seconds: 60,
|
|
21512
|
+
sleep_min_seconds: 10,
|
|
21513
|
+
sleep_alarm_grace_seconds: 15,
|
|
21514
|
+
sleep_elastic_below_milliseconds: 1e3,
|
|
21515
|
+
sleep_request_wait_milliseconds: 4e3,
|
|
21516
|
+
sleep_defer_seconds: 30
|
|
21489
21517
|
}
|
|
21490
21518
|
},
|
|
21491
21519
|
websocket: {
|
|
21492
21520
|
client_connection: {
|
|
21493
21521
|
reconnect_delay_ms: 3e3,
|
|
21494
21522
|
ping_interval_ms: 3e4,
|
|
21523
|
+
pong_timeout_ms: 5e3,
|
|
21524
|
+
max_unanswered_pings: 2,
|
|
21495
21525
|
message_flush_interval_ms: 16,
|
|
21496
21526
|
price_change_highlight_ms: 1e3,
|
|
21497
21527
|
debug_recent_channel_limit: 24
|
|
@@ -21510,6 +21540,9 @@ var init_runtime_policy_generated2 = __esm({
|
|
|
21510
21540
|
min_length: 3,
|
|
21511
21541
|
max_length: 20,
|
|
21512
21542
|
update_confirmation_ms: 3e3
|
|
21543
|
+
},
|
|
21544
|
+
passkey_names: {
|
|
21545
|
+
max_length: 100
|
|
21513
21546
|
}
|
|
21514
21547
|
},
|
|
21515
21548
|
profiles: {
|
|
@@ -21573,7 +21606,8 @@ var init_runtime_policy_generated2 = __esm({
|
|
|
21573
21606
|
full_history_default_limit: 20,
|
|
21574
21607
|
default_page_size: 50,
|
|
21575
21608
|
trade_lookup_max_order_ids: 200,
|
|
21576
|
-
decision_batch_default_limit: 50
|
|
21609
|
+
decision_batch_default_limit: 50,
|
|
21610
|
+
non_admin_lookback_days: 30
|
|
21577
21611
|
},
|
|
21578
21612
|
updates: {
|
|
21579
21613
|
posts: {
|
|
@@ -25625,16 +25659,16 @@ var init_mcp_client = __esm({
|
|
|
25625
25659
|
MAX_REJECTION_REASON_CHARS = runtime_policy_generated_default2.external_inference.host_core.mcp_rejection_reason_max_chars;
|
|
25626
25660
|
CONTROL_CHARACTERS = /[\u0000-\u001f\u007f]/gu;
|
|
25627
25661
|
publicRejectionReason = (text) => {
|
|
25628
|
-
const
|
|
25629
|
-
const [firstLine = ""] = (
|
|
25662
|
+
const marker2 = text.indexOf(PUBLIC_TOOL_ERROR_PREFIX);
|
|
25663
|
+
const [firstLine = ""] = (marker2 < 0 ? text : text.slice(0, marker2)).split("\n");
|
|
25630
25664
|
const reason = sanitizeRuntimeDiagnosticValue(firstLine.replace(CONTROL_CHARACTERS, " ")).trim();
|
|
25631
25665
|
if (!reason) return null;
|
|
25632
25666
|
return reason.length > MAX_REJECTION_REASON_CHARS ? `${reason.slice(0, MAX_REJECTION_REASON_CHARS)}\u2026` : reason;
|
|
25633
25667
|
};
|
|
25634
25668
|
parsePublicToolError = (text) => {
|
|
25635
|
-
const
|
|
25636
|
-
if (
|
|
25637
|
-
const raw = text.slice(
|
|
25669
|
+
const marker2 = text.lastIndexOf(PUBLIC_TOOL_ERROR_PREFIX);
|
|
25670
|
+
if (marker2 < 0) return null;
|
|
25671
|
+
const raw = text.slice(marker2 + PUBLIC_TOOL_ERROR_PREFIX.length).trim();
|
|
25638
25672
|
try {
|
|
25639
25673
|
const parsed = publicToolErrorSchema.safeParse(JSON.parse(raw));
|
|
25640
25674
|
return parsed.success ? parsed.data : null;
|
|
@@ -25977,7 +26011,7 @@ var init_mcp_client = __esm({
|
|
|
25977
26011
|
parseSseDocuments = (body) => {
|
|
25978
26012
|
const documents = [];
|
|
25979
26013
|
let dataLines = [];
|
|
25980
|
-
const
|
|
26014
|
+
const flush2 = () => {
|
|
25981
26015
|
if (dataLines.length === 0) return;
|
|
25982
26016
|
const data4 = dataLines.join("\n");
|
|
25983
26017
|
dataLines = [];
|
|
@@ -25985,7 +26019,7 @@ var init_mcp_client = __esm({
|
|
|
25985
26019
|
};
|
|
25986
26020
|
for (const rawLine of body.replace(/\r\n/g, "\n").split("\n")) {
|
|
25987
26021
|
if (!rawLine) {
|
|
25988
|
-
|
|
26022
|
+
flush2();
|
|
25989
26023
|
continue;
|
|
25990
26024
|
}
|
|
25991
26025
|
if (rawLine.startsWith(":")) continue;
|
|
@@ -25997,7 +26031,7 @@ var init_mcp_client = __esm({
|
|
|
25997
26031
|
dataLines.push(rawLine.slice(SSE_DATA_FIELD_PREFIX.length).replace(/^ /, ""));
|
|
25998
26032
|
}
|
|
25999
26033
|
}
|
|
26000
|
-
|
|
26034
|
+
flush2();
|
|
26001
26035
|
if (documents.length === 0) {
|
|
26002
26036
|
throw new ExternalInferenceMcpError(
|
|
26003
26037
|
"invalid_response",
|
|
@@ -35998,6 +36032,68 @@ var init_agent_state = __esm({
|
|
|
35998
36032
|
}
|
|
35999
36033
|
});
|
|
36000
36034
|
|
|
36035
|
+
// lib/inference-host/agent-answer.ts
|
|
36036
|
+
var CODE_FENCE, OBJECT_ON_OWN_LINE, closingJsonFenceDocument, scanObject, closingJsonObjectDocument, agentAnswerJsonDocument;
|
|
36037
|
+
var init_agent_answer = __esm({
|
|
36038
|
+
"lib/inference-host/agent-answer.ts"() {
|
|
36039
|
+
"use strict";
|
|
36040
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
36041
|
+
init_define_VTX_EXO_POLICY();
|
|
36042
|
+
init_define_VTX_GROK_POLICY();
|
|
36043
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
36044
|
+
CODE_FENCE = "```";
|
|
36045
|
+
OBJECT_ON_OWN_LINE = /(?:^|\n)[ \t]*(?=\{)/gu;
|
|
36046
|
+
closingJsonFenceDocument = (text) => {
|
|
36047
|
+
const trimmed = text.trim();
|
|
36048
|
+
const open4 = trimmed.indexOf(CODE_FENCE);
|
|
36049
|
+
const close = trimmed.lastIndexOf(CODE_FENCE);
|
|
36050
|
+
if (open4 < 0 || close === open4 || trimmed.indexOf(CODE_FENCE, open4 + CODE_FENCE.length) !== close) return null;
|
|
36051
|
+
const match = /```json[ \t]*\r?\n([\s\S]*?)\r?\n?```$/iu.exec(trimmed);
|
|
36052
|
+
return match ? match[1] : null;
|
|
36053
|
+
};
|
|
36054
|
+
scanObject = (text, start) => {
|
|
36055
|
+
let depth = 0;
|
|
36056
|
+
let inString = false;
|
|
36057
|
+
for (let index = start; index < text.length; index += 1) {
|
|
36058
|
+
const char = text[index];
|
|
36059
|
+
if (inString) {
|
|
36060
|
+
if (char === "\\") index += 1;
|
|
36061
|
+
else if (char === '"') inString = false;
|
|
36062
|
+
else if (char === "\n") return { close: null, stop: index };
|
|
36063
|
+
} else if (char === '"') inString = true;
|
|
36064
|
+
else if (char === "{" || char === "[") depth += 1;
|
|
36065
|
+
else if (char === "}" || char === "]") {
|
|
36066
|
+
depth -= 1;
|
|
36067
|
+
if (depth === 0) return { close: char === "}" ? index : null, stop: index };
|
|
36068
|
+
}
|
|
36069
|
+
}
|
|
36070
|
+
return { close: null, stop: text.length };
|
|
36071
|
+
};
|
|
36072
|
+
closingJsonObjectDocument = (text) => {
|
|
36073
|
+
const trimmed = text.trim();
|
|
36074
|
+
if (!trimmed.endsWith("}") || trimmed.includes(CODE_FENCE)) return null;
|
|
36075
|
+
const objects = [];
|
|
36076
|
+
let resumeAt = 0;
|
|
36077
|
+
for (const match of trimmed.matchAll(OBJECT_ON_OWN_LINE)) {
|
|
36078
|
+
const start = match.index + match[0].length;
|
|
36079
|
+
if (start < resumeAt) continue;
|
|
36080
|
+
const { close, stop } = scanObject(trimmed, start);
|
|
36081
|
+
resumeAt = stop + 1;
|
|
36082
|
+
if (close === null) continue;
|
|
36083
|
+
try {
|
|
36084
|
+
JSON.parse(trimmed.slice(start, close + 1));
|
|
36085
|
+
} catch {
|
|
36086
|
+
continue;
|
|
36087
|
+
}
|
|
36088
|
+
objects.push({ start, close });
|
|
36089
|
+
}
|
|
36090
|
+
if (objects.length !== 1 || objects[0].close !== trimmed.length - 1) return null;
|
|
36091
|
+
return trimmed.slice(objects[0].start);
|
|
36092
|
+
};
|
|
36093
|
+
agentAnswerJsonDocument = (text) => closingJsonFenceDocument(text) ?? closingJsonObjectDocument(text);
|
|
36094
|
+
}
|
|
36095
|
+
});
|
|
36096
|
+
|
|
36001
36097
|
// lib/inference-host/runner.ts
|
|
36002
36098
|
import { createHash as createHash5, randomUUID as randomUUID2 } from "node:crypto";
|
|
36003
36099
|
function createDefaultInferenceHostRunnerDependencies(options) {
|
|
@@ -36053,6 +36149,7 @@ var init_runner = __esm({
|
|
|
36053
36149
|
init_agent_state();
|
|
36054
36150
|
init_crypto();
|
|
36055
36151
|
init_mcp_client();
|
|
36152
|
+
init_agent_answer();
|
|
36056
36153
|
init_config2();
|
|
36057
36154
|
init_oauth();
|
|
36058
36155
|
providerHttpStatus = (error48) => {
|
|
@@ -38386,7 +38483,8 @@ var init_runner = __esm({
|
|
|
38386
38483
|
0,
|
|
38387
38484
|
claimCallRoundTripMs - (serverProcessingMs ?? 0)
|
|
38388
38485
|
);
|
|
38389
|
-
const
|
|
38486
|
+
const serverDeadlineClockOffsetMs = claim.schema_version === "external_inference_job_claim_result_v4" ? claimCallStartedAtMs + claim.server_processing_ms - Date.parse(claim.server_time_at) : 0;
|
|
38487
|
+
const serverReportClockOffsetMs = claim.schema_version === "external_inference_job_claim_result_v4" ? claimResponseReceivedAtMs - Date.parse(claim.server_time_at) : 0;
|
|
38390
38488
|
emitDiagnostic("claim_batch_received", {
|
|
38391
38489
|
claim_request_id: request.claim_request_id,
|
|
38392
38490
|
jobs: claim.claims.map((item) => ({
|
|
@@ -38399,7 +38497,8 @@ var init_runner = __esm({
|
|
|
38399
38497
|
claim_count: claim.claims.length,
|
|
38400
38498
|
round_trip_ms: claimCallRoundTripMs,
|
|
38401
38499
|
server_processing_ms: serverProcessingMs,
|
|
38402
|
-
server_clock_offset_ms:
|
|
38500
|
+
server_clock_offset_ms: serverDeadlineClockOffsetMs,
|
|
38501
|
+
server_report_clock_offset_ms: serverReportClockOffsetMs,
|
|
38403
38502
|
transport_residual_ms: claimTransportResidualMs,
|
|
38404
38503
|
minimum_freshness_remaining_ms: claim.claims.length ? Math.min(...claim.claims.map((item) => item.provider_dispatch_freshness_remaining_ms)) : null,
|
|
38405
38504
|
active_attempts: active.size
|
|
@@ -38489,7 +38588,8 @@ var init_runner = __esm({
|
|
|
38489
38588
|
roundTripMs: claimTransportResidualMs,
|
|
38490
38589
|
claimResponseReceivedAtMs,
|
|
38491
38590
|
receiptDurability: batchReceiptDurability,
|
|
38492
|
-
|
|
38591
|
+
serverDeadlineClockOffsetMs,
|
|
38592
|
+
serverReportClockOffsetMs
|
|
38493
38593
|
});
|
|
38494
38594
|
}
|
|
38495
38595
|
if (this.options.once) requestDrain("once_complete");
|
|
@@ -38634,9 +38734,10 @@ var init_runner = __esm({
|
|
|
38634
38734
|
signal,
|
|
38635
38735
|
now
|
|
38636
38736
|
} = options;
|
|
38637
|
-
const
|
|
38638
|
-
const hostClockMs = (serverTimestamp) => Date.parse(serverTimestamp) +
|
|
38639
|
-
const
|
|
38737
|
+
const serverDeadlineClockOffsetMs = options.prestarted?.serverDeadlineClockOffsetMs ?? 0;
|
|
38738
|
+
const hostClockMs = (serverTimestamp) => Date.parse(serverTimestamp) + serverDeadlineClockOffsetMs;
|
|
38739
|
+
const serverReportClockOffsetMs = options.prestarted?.serverReportClockOffsetMs ?? 0;
|
|
38740
|
+
const serverIsoAt = (hostMs) => isoAt(hostMs - serverReportClockOffsetMs);
|
|
38640
38741
|
const adapterId = this.options.adapterId ?? "codex";
|
|
38641
38742
|
const usageSource = this.options.usageSource ?? (adapterId === "codex" ? "codex_app_server" : adapterId);
|
|
38642
38743
|
const sameAttemptRecovery = this.options.sameAttemptRecovery ?? adapterId === "codex";
|
|
@@ -39635,10 +39736,16 @@ var init_runner = __esm({
|
|
|
39635
39736
|
try {
|
|
39636
39737
|
value = JSON.parse(text);
|
|
39637
39738
|
} catch {
|
|
39638
|
-
|
|
39639
|
-
|
|
39640
|
-
|
|
39641
|
-
|
|
39739
|
+
const fenced = agentAnswerJsonDocument(text);
|
|
39740
|
+
try {
|
|
39741
|
+
if (fenced === null) throw new Error("unfenced");
|
|
39742
|
+
value = JSON.parse(fenced);
|
|
39743
|
+
} catch {
|
|
39744
|
+
throw new InferenceHostRunnerError(
|
|
39745
|
+
"invalid_agent_wake",
|
|
39746
|
+
"Inference Agent returned invalid wake JSON."
|
|
39747
|
+
);
|
|
39748
|
+
}
|
|
39642
39749
|
}
|
|
39643
39750
|
if (!value || typeof value !== "object" || Array.isArray(value)) {
|
|
39644
39751
|
throw new InferenceHostRunnerError("invalid_agent_wake", "Inference Agent wake is invalid.");
|
|
@@ -44544,10 +44651,10 @@ var init_pi_transport = __esm({
|
|
|
44544
44651
|
}
|
|
44545
44652
|
}
|
|
44546
44653
|
};
|
|
44547
|
-
const consume = (
|
|
44654
|
+
const consume = (flush2 = false) => {
|
|
44548
44655
|
if (pending3.length > HOST_RUNTIME_POLICY6.pi_receipt_event_max_chars) throw new Error("pi_receipt_event_too_large");
|
|
44549
44656
|
const events = pending3.split(/\r?\n\r?\n/u);
|
|
44550
|
-
pending3 =
|
|
44657
|
+
pending3 = flush2 ? "" : events.pop();
|
|
44551
44658
|
for (const event of events) {
|
|
44552
44659
|
const data4 = event.split(/\r?\n/u).filter((line) => line.startsWith(SSE_DATA_PREFIX2)).map((line) => line.slice(SSE_DATA_PREFIX2.length).trimStart()).join("\n");
|
|
44553
44660
|
if (data4) inspect3(data4);
|
|
@@ -46217,23 +46324,23 @@ var init_grok_state = __esm({
|
|
|
46217
46324
|
throw error48;
|
|
46218
46325
|
}
|
|
46219
46326
|
const encoded = encodedCwd(value.workspace);
|
|
46220
|
-
let
|
|
46221
|
-
if (encoded.length <= GROK_NATIVE_SESSION_GROUP_NAME_MAX_CHARS)
|
|
46327
|
+
let groups2;
|
|
46328
|
+
if (encoded.length <= GROK_NATIVE_SESSION_GROUP_NAME_MAX_CHARS) groups2 = [join12(sessions, encoded)];
|
|
46222
46329
|
else {
|
|
46223
|
-
|
|
46330
|
+
groups2 = [];
|
|
46224
46331
|
for (const entry of await readdir6(sessions, { withFileTypes: true })) {
|
|
46225
46332
|
if (!entry.isDirectory() || entry.isSymbolicLink()) continue;
|
|
46226
46333
|
const group = join12(sessions, entry.name);
|
|
46227
46334
|
if (await realpath7(group) !== resolve7(group)) throw invalid();
|
|
46228
46335
|
try {
|
|
46229
|
-
if ((await nativeFile(join12(group, ".cwd"), HOST_RUNTIME_POLICY9.grok_cwd_marker_max_bytes)).trim() === value.workspace)
|
|
46336
|
+
if ((await nativeFile(join12(group, ".cwd"), HOST_RUNTIME_POLICY9.grok_cwd_marker_max_bytes)).trim() === value.workspace) groups2.push(group);
|
|
46230
46337
|
} catch (error48) {
|
|
46231
46338
|
if (!missing(error48)) throw error48;
|
|
46232
46339
|
}
|
|
46233
46340
|
}
|
|
46234
|
-
if (
|
|
46341
|
+
if (groups2.length > 1) throw invalid();
|
|
46235
46342
|
}
|
|
46236
|
-
for (const group of
|
|
46343
|
+
for (const group of groups2) {
|
|
46237
46344
|
const session = join12(group, value.sessionId);
|
|
46238
46345
|
try {
|
|
46239
46346
|
await nativeDirectory(group);
|
|
@@ -47280,14 +47387,14 @@ var init_claude_code_runtime = __esm({
|
|
|
47280
47387
|
SESSION_ID = /^[0-9a-f-]{36}$/u;
|
|
47281
47388
|
claudeCodeSessionTranscriptExists = async (configDir, sessionId) => {
|
|
47282
47389
|
if (!SESSION_ID.test(sessionId)) return false;
|
|
47283
|
-
let
|
|
47390
|
+
let groups2;
|
|
47284
47391
|
try {
|
|
47285
|
-
|
|
47392
|
+
groups2 = await readdir7(join14(configDir, "projects"));
|
|
47286
47393
|
} catch (error48) {
|
|
47287
47394
|
if (error48.code === "ENOENT") return false;
|
|
47288
47395
|
throw error48;
|
|
47289
47396
|
}
|
|
47290
|
-
for (const group of
|
|
47397
|
+
for (const group of groups2) {
|
|
47291
47398
|
try {
|
|
47292
47399
|
if ((await lstat9(join14(configDir, "projects", group, `${sessionId}.jsonl`))).isFile()) return true;
|
|
47293
47400
|
} catch (error48) {
|
|
@@ -47299,14 +47406,14 @@ var init_claude_code_runtime = __esm({
|
|
|
47299
47406
|
removeClaudeCodeSessionTranscript = async (configDir, sessionId) => {
|
|
47300
47407
|
if (!SESSION_ID.test(sessionId)) return;
|
|
47301
47408
|
const projects = join14(configDir, "projects");
|
|
47302
|
-
let
|
|
47409
|
+
let groups2;
|
|
47303
47410
|
try {
|
|
47304
|
-
|
|
47411
|
+
groups2 = await readdir7(projects);
|
|
47305
47412
|
} catch (error48) {
|
|
47306
47413
|
if (error48.code === "ENOENT") return;
|
|
47307
47414
|
throw error48;
|
|
47308
47415
|
}
|
|
47309
|
-
for (const group of
|
|
47416
|
+
for (const group of groups2) {
|
|
47310
47417
|
await rm12(join14(projects, group, `${sessionId}.jsonl`), { force: true });
|
|
47311
47418
|
}
|
|
47312
47419
|
};
|
|
@@ -50367,12 +50474,12 @@ ${result.stderr}`)) {
|
|
|
50367
50474
|
let cooperativeStopTimedOut = false;
|
|
50368
50475
|
let cooperativeStopTimer = null;
|
|
50369
50476
|
const pending3 = { stdout: "", stderr: "" };
|
|
50370
|
-
const writeTaggedOutput = (stream, text,
|
|
50477
|
+
const writeTaggedOutput = (stream, text, flush2 = false) => {
|
|
50371
50478
|
const lines = `${pending3[stream]}${text}`.split(/\r?\n/u);
|
|
50372
50479
|
const remainder = lines.pop() ?? "";
|
|
50373
|
-
pending3[stream] =
|
|
50374
|
-
if (
|
|
50375
|
-
if (
|
|
50480
|
+
pending3[stream] = flush2 ? "" : remainder;
|
|
50481
|
+
if (flush2 && remainder) lines.push(remainder);
|
|
50482
|
+
if (flush2 && lines.at(-1) === "") lines.pop();
|
|
50376
50483
|
for (const line of lines) {
|
|
50377
50484
|
if (!line) continue;
|
|
50378
50485
|
try {
|
|
@@ -54826,7 +54933,7 @@ var init_protection_storage = __esm({
|
|
|
54826
54933
|
});
|
|
54827
54934
|
|
|
54828
54935
|
// lib/android-app.ts
|
|
54829
|
-
var ANDROID_APP_PACKAGES, ANDROID_APP_REFERRER_SCHEME, ANDROID_APP_LAUNCH_STORAGE_KEY, ANDROID_APP_HOST_FRAGMENT_PARAM, knownLaunch, storedLaunch, referrerPackage, HOST_FRAGMENT_PAIR_PREFIX, fragmentParts, hostFragment, freshNavigation, remember, followAppReopens, androidAppLaunch, isAndroidAppPage;
|
|
54936
|
+
var ANDROID_APP_PACKAGES, ANDROID_APP_REFERRER_SCHEME, ANDROID_APP_LAUNCH_STORAGE_KEY, ANDROID_APP_HOST_FRAGMENT_PARAM, knownLaunch, storedLaunch, referrerPackage, HOST_FRAGMENT_PAIR_PREFIX, fragmentParts, hostFragment, freshNavigation, remember, hostNamedListeners, followAppReopens, androidAppLaunch, isAndroidAppPage;
|
|
54830
54937
|
var init_android_app = __esm({
|
|
54831
54938
|
"lib/android-app.ts"() {
|
|
54832
54939
|
"use strict";
|
|
@@ -54882,11 +54989,13 @@ var init_android_app = __esm({
|
|
|
54882
54989
|
}
|
|
54883
54990
|
return launch;
|
|
54884
54991
|
};
|
|
54992
|
+
hostNamedListeners = /* @__PURE__ */ new Set();
|
|
54885
54993
|
followAppReopens = () => {
|
|
54886
54994
|
window.addEventListener("hashchange", () => {
|
|
54887
54995
|
if (!knownLaunch) return;
|
|
54888
54996
|
const named = knownLaunch.hostDeviceId ? null : hostFragment();
|
|
54889
54997
|
remember(named ? { ...knownLaunch, hostDeviceId: named } : knownLaunch);
|
|
54998
|
+
if (named) hostNamedListeners.forEach((listener) => listener());
|
|
54890
54999
|
});
|
|
54891
55000
|
};
|
|
54892
55001
|
androidAppLaunch = () => {
|
|
@@ -56295,7 +56404,7 @@ var init_esm = __esm({
|
|
|
56295
56404
|
strm.flush(ev.data[1]);
|
|
56296
56405
|
};
|
|
56297
56406
|
};
|
|
56298
|
-
astrmify = function(fns, strm, opts, init2, id2,
|
|
56407
|
+
astrmify = function(fns, strm, opts, init2, id2, flush2, ext) {
|
|
56299
56408
|
var t;
|
|
56300
56409
|
var w = wrkr(fns, init2, id2, function(err2, dat) {
|
|
56301
56410
|
if (err2)
|
|
@@ -56325,7 +56434,7 @@ var init_esm = __esm({
|
|
|
56325
56434
|
strm.terminate = function() {
|
|
56326
56435
|
w.terminate();
|
|
56327
56436
|
};
|
|
56328
|
-
if (
|
|
56437
|
+
if (flush2) {
|
|
56329
56438
|
strm.flush = function(sync) {
|
|
56330
56439
|
w.postMessage([0, sync]);
|
|
56331
56440
|
};
|
|
@@ -57389,7 +57498,7 @@ function getProfileHeaders(baseHeaders = {}, explicitProfileId) {
|
|
|
57389
57498
|
if (profileId) headers["x-profile-id"] = profileId.toString();
|
|
57390
57499
|
return headers;
|
|
57391
57500
|
}
|
|
57392
|
-
var configuredApiTransport, getApiUrl, sendApiRequest, apiFetch, sleep, DEVICE_CLOCK_HEADER, deviceClockHeader, inFlightClientGetRequests, recentClientGetResponses, clientGetRequestGenerations, initializedClientGetRequestKeys, CLIENT_GET_DEDUPE_TTL_MS, CLIENT_RUNTIME_STATUSES_DEDUPE_TTL_MS, CLIENT_LLM_CONFIG_PRIME_TTL_MS, AUTH_BOOTSTRAP_GET_MAX_ATTEMPTS, AUTH_BOOTSTRAP_RETRY_JITTER_MS, canUseClientGetRequestCache, invalidateClientGetRequestCache, raceWithAbortSignal, shareClientGetRequest, clientGetRequestKey, clientPreferencesRequestKey, invalidateClientPreferencesCache, parseRetryAfterMs2, resolveAuthBootstrapRetryDelayMs, fetchAuthBootstrapGetWithRetry, annotateMarketDataRequestError, buildMarketDataFetchError, buildMarketDataNetworkError, buildMarketDataResponseBodyError, isTransientNetworkFetchError, createIdempotencyKey, getErrorMessage, getErrorPayloadOrEmpty, getErrorPayloadOrFallbackDetail, getErrorMessageFromResponse, throwUnauthorizedIfNeeded, activeProfileId, PROFILE_STORAGE_KEY;
|
|
57501
|
+
var configuredApiTransport, getApiUrl, sendApiRequest, apiFetch, sleep, DEVICE_CLOCK_HEADER, deviceClockHeader, inFlightClientGetRequests, recentClientGetResponses, clientGetRequestGenerations, initializedClientGetRequestKeys, CLIENT_GET_DEDUPE_TTL_MS, CLIENT_RUNTIME_STATUSES_DEDUPE_TTL_MS, CLIENT_LLM_CONFIG_PRIME_TTL_MS, AUTH_BOOTSTRAP_GET_MAX_ATTEMPTS, AUTH_BOOTSTRAP_RETRY_JITTER_MS, singleUserHostCache, canUseClientGetRequestCache, clientGetRequestCacheActive, invalidateClientGetRequestCache, raceWithAbortSignal, shareClientGetRequest, clientGetRequestKey, clientPreferencesRequestKey, invalidateClientPreferencesCache, parseRetryAfterMs2, resolveAuthBootstrapRetryDelayMs, fetchAuthBootstrapGetWithRetry, annotateMarketDataRequestError, buildMarketDataFetchError, buildMarketDataNetworkError, buildMarketDataResponseBodyError, isTransientNetworkFetchError, createIdempotencyKey, getErrorMessage, getErrorPayloadOrEmpty, getErrorPayloadOrFallbackDetail, getErrorMessageFromResponse, throwUnauthorizedIfNeeded, activeProfileId, PROFILE_STORAGE_KEY;
|
|
57393
57502
|
var init_shared = __esm({
|
|
57394
57503
|
"lib/api/shared.ts"() {
|
|
57395
57504
|
"use strict";
|
|
@@ -57449,7 +57558,9 @@ var init_shared = __esm({
|
|
|
57449
57558
|
CLIENT_LLM_CONFIG_PRIME_TTL_MS = runtime_policy_generated_default2.ui.api_client.llm_config_prime_ttl_ms;
|
|
57450
57559
|
AUTH_BOOTSTRAP_GET_MAX_ATTEMPTS = runtime_policy_generated_default2.ui.auth_bootstrap_retry.max_attempts;
|
|
57451
57560
|
AUTH_BOOTSTRAP_RETRY_JITTER_MS = runtime_policy_generated_default2.ui.auth_bootstrap_retry.jitter_milliseconds;
|
|
57452
|
-
|
|
57561
|
+
singleUserHostCache = false;
|
|
57562
|
+
canUseClientGetRequestCache = (cookie) => (typeof window !== "undefined" || singleUserHostCache) && !cookie;
|
|
57563
|
+
clientGetRequestCacheActive = () => canUseClientGetRequestCache();
|
|
57453
57564
|
invalidateClientGetRequestCache = (key) => {
|
|
57454
57565
|
initializedClientGetRequestKeys.add(key);
|
|
57455
57566
|
clientGetRequestGenerations.set(key, (clientGetRequestGenerations.get(key) ?? 0) + 1);
|
|
@@ -57499,7 +57610,7 @@ var init_shared = __esm({
|
|
|
57499
57610
|
clientGetRequestKey = (name, profileId) => `${name}:${profileId ?? "none"}`;
|
|
57500
57611
|
clientPreferencesRequestKey = (profileId, includeTradeLayouts) => `${clientGetRequestKey("preferences", profileId)}:trade-layouts:${includeTradeLayouts ? "full" : "lite"}`;
|
|
57501
57612
|
invalidateClientPreferencesCache = (profileId) => {
|
|
57502
|
-
if (
|
|
57613
|
+
if (!clientGetRequestCacheActive()) return;
|
|
57503
57614
|
for (const includeTradeLayouts of [false, true]) {
|
|
57504
57615
|
const baseKey = clientPreferencesRequestKey(profileId, includeTradeLayouts);
|
|
57505
57616
|
invalidateClientGetRequestCache(baseKey);
|
|
@@ -57576,7 +57687,7 @@ var init_shared = __esm({
|
|
|
57576
57687
|
isTransientNetworkFetchError = (error48) => {
|
|
57577
57688
|
const message = error48 instanceof Error ? error48.message : String(error48 || "");
|
|
57578
57689
|
const normalized = message.toLowerCase();
|
|
57579
|
-
return message === "Failed to fetch" || message === "TypeError: Failed to fetch" || normalized.includes("network error") || normalized.includes("failed to fetch");
|
|
57690
|
+
return message === "Failed to fetch" || message === "TypeError: Failed to fetch" || normalized.includes("network error") || normalized.includes("failed to fetch") || normalized === "fetch failed";
|
|
57580
57691
|
};
|
|
57581
57692
|
createIdempotencyKey = (action) => {
|
|
57582
57693
|
const suffix = typeof crypto !== "undefined" && typeof crypto.randomUUID === "function" ? crypto.randomUUID() : `${Date.now()}-${Math.random().toString(HEX_RADIX).slice(RANDOM_FRACTION_PREFIX_LENGTH)}`;
|
|
@@ -58623,6 +58734,413 @@ var init_network_debug = __esm({
|
|
|
58623
58734
|
}
|
|
58624
58735
|
});
|
|
58625
58736
|
|
|
58737
|
+
// lib/runtime/runtime-error-reason-rules.json
|
|
58738
|
+
var runtime_error_reason_rules_default;
|
|
58739
|
+
var init_runtime_error_reason_rules = __esm({
|
|
58740
|
+
"lib/runtime/runtime-error-reason-rules.json"() {
|
|
58741
|
+
runtime_error_reason_rules_default = {
|
|
58742
|
+
about: "The one owner of runtime error reason codes, loaded by the web runtime (runtime-error-reason-rules.ts) and the API (runtime_error_reason_rules.py). Rules are tried in order on the normalized message without its warning prefix or its AI panel history wrapper (Analysis unavailable:), lowercased, so a stored row and the bare message get the same code; the first match names the code. A condition is equals, starts_with, contains, all, any, or a named predicate each runtime implements. reason_codes classifies every code: transient codes clear on their own; WARN codes record a skipped cycle, not a failure. A code not listed is ERROR and needs the owner's attention.",
|
|
58743
|
+
unclassified_messages: [
|
|
58744
|
+
"unknown runtime error.",
|
|
58745
|
+
"vtx did not receive error details for this runtime failure."
|
|
58746
|
+
],
|
|
58747
|
+
rules: [
|
|
58748
|
+
{ reason_code: "ai_service_rate_limit", when: { predicate: "provider_attempt_summary_http_429" } },
|
|
58749
|
+
{ reason_code: "ai_service_unavailable", when: { predicate: "provider_attempt_summary_unavailable" } },
|
|
58750
|
+
{ reason_code: "hyperliquid_request_capacity", when: { starts_with: "vtx could not obtain hyperliquid request capacity" } },
|
|
58751
|
+
{ reason_code: "http_request_capacity", when: { starts_with: "vtx could not obtain http request capacity" } },
|
|
58752
|
+
{ reason_code: "live_market_stats_unavailable", when: { equals: "live market stats unavailable for client runtime contract" } },
|
|
58753
|
+
{ reason_code: "live_performance_unavailable", when: { equals: "live performance context unavailable for client runtime contract" } },
|
|
58754
|
+
{ reason_code: "live_market_regime_unavailable", when: { equals: "live market regime context unavailable for client runtime contract" } },
|
|
58755
|
+
{ reason_code: "live_calendar_unavailable", when: { equals: "live calendar context unavailable for client runtime contract" } },
|
|
58756
|
+
{ reason_code: "live_derived_context_timeout", when: { equals: "timed out while building live derived context for client runtime contract" } },
|
|
58757
|
+
{ reason_code: "live_derived_context_build_failed", when: { equals: "failed to build live derived context for client runtime contract" } },
|
|
58758
|
+
{ reason_code: "internal_data_error", when: { any: [
|
|
58759
|
+
{ equals: "internal data error. please try again." },
|
|
58760
|
+
{ equals: "vtx could not read the required app data. please try again." }
|
|
58761
|
+
] } },
|
|
58762
|
+
{ reason_code: "private_node_stale", when: { all: [
|
|
58763
|
+
{ contains: "order was not sent" },
|
|
58764
|
+
{ any: [
|
|
58765
|
+
{ contains: "too stale to validate the signing key" },
|
|
58766
|
+
{ contains: "required hyperliquid account data was stale" }
|
|
58767
|
+
] }
|
|
58768
|
+
] } },
|
|
58769
|
+
{ reason_code: "signer_validation_unavailable", when: { all: [
|
|
58770
|
+
{ contains: "order was not sent" },
|
|
58771
|
+
{ any: [
|
|
58772
|
+
{ contains: "private account service could not validate the signing key" },
|
|
58773
|
+
{ contains: "required hyperliquid account data was temporarily unavailable" }
|
|
58774
|
+
] }
|
|
58775
|
+
] } },
|
|
58776
|
+
{ reason_code: "wallet_not_authorized", when: { all: [
|
|
58777
|
+
{ contains: "order was not sent" },
|
|
58778
|
+
{ any: [
|
|
58779
|
+
{ contains: "signing key is not authorized for the configured wallet" },
|
|
58780
|
+
{ contains: "hyperliquid confirmed that the signing key is not authorized" },
|
|
58781
|
+
{ contains: "hyperliquid has not approved this key for this profile's wallet" }
|
|
58782
|
+
] }
|
|
58783
|
+
] } },
|
|
58784
|
+
{ reason_code: "credentials_missing", when: { all: [
|
|
58785
|
+
{ contains: "order was not sent" },
|
|
58786
|
+
{ contains: "authorized signing key are required for trading" }
|
|
58787
|
+
] } },
|
|
58788
|
+
{ reason_code: "local_safety_block", when: { contains: "order was not sent before exchange dispatch" } },
|
|
58789
|
+
{ reason_code: "redis_unavailable", when: { contains: "order was not sent because execution coordination was unavailable" } },
|
|
58790
|
+
{ reason_code: "exchange_rejected", when: { all: [
|
|
58791
|
+
{ starts_with: "hyperliquid rejected the " },
|
|
58792
|
+
{ contains: " order:" }
|
|
58793
|
+
] } },
|
|
58794
|
+
{ reason_code: "outcome_unknown", when: { all: [
|
|
58795
|
+
{ contains: "vtx could not confirm whether the " },
|
|
58796
|
+
{ contains: " order was applied" }
|
|
58797
|
+
] } },
|
|
58798
|
+
{ reason_code: "internal_execution_error", when: { all: [
|
|
58799
|
+
{ starts_with: "vtx could not complete the " },
|
|
58800
|
+
{ contains: " order:" }
|
|
58801
|
+
] } },
|
|
58802
|
+
{ reason_code: "hyperliquid_rate_limit", when: { any: [
|
|
58803
|
+
{ contains: "hyperliquid returned 429" },
|
|
58804
|
+
{ contains: "hyperliquid returned http 429" },
|
|
58805
|
+
{ contains: "public reads are waiting for a rate-limit cooldown" },
|
|
58806
|
+
{ contains: "public reads are waiting after a hyperliquid rate limit" },
|
|
58807
|
+
{ contains: "recovery queue before its deadline" },
|
|
58808
|
+
{ contains: "hyperliquid info endpoint returned 429" },
|
|
58809
|
+
{ contains: "hyperliquid rate limit (429)" },
|
|
58810
|
+
{ contains: "hyperliquid public api returned http 429" },
|
|
58811
|
+
{ contains: "hyperliquid public info cooldown is active" },
|
|
58812
|
+
{ contains: "hyperliquid public request cooldown is active" },
|
|
58813
|
+
{ contains: "hyperliquid public recovery is waiting after an observed http 429" },
|
|
58814
|
+
{ contains: "hyperliquid provider recovery could not dispatch before the request deadline" }
|
|
58815
|
+
] } },
|
|
58816
|
+
{ reason_code: "hyperliquid_read_budget_exhausted", when: { any: [
|
|
58817
|
+
{ all: [
|
|
58818
|
+
{ contains: "fresh hyperliquid data" },
|
|
58819
|
+
{ contains: "current read budget" }
|
|
58820
|
+
] },
|
|
58821
|
+
{ contains: "server's public-read budget is full" },
|
|
58822
|
+
{ contains: "app's shared public-read budget is also full" },
|
|
58823
|
+
{ all: [
|
|
58824
|
+
{ contains: "hyperliquid" },
|
|
58825
|
+
{ contains: "budget exhausted" }
|
|
58826
|
+
] },
|
|
58827
|
+
{ contains: "hyperliquid execution preflight is waiting for its fair public-read turn" },
|
|
58828
|
+
{ contains: "hyperliquid local public request allowance is exhausted" }
|
|
58829
|
+
] } },
|
|
58830
|
+
{ reason_code: "hyperliquid_data_unavailable", when: { any: [
|
|
58831
|
+
{ contains: "fresh private hyperliquid data is unavailable" },
|
|
58832
|
+
{ contains: "private hyperliquid node is stale" },
|
|
58833
|
+
{ contains: "private hyperliquid info circuit is open" },
|
|
58834
|
+
{ contains: "private hyperliquid freshness probe failed" },
|
|
58835
|
+
{ contains: "hyperliquid info endpoint is stale for" },
|
|
58836
|
+
{ contains: "hyperliquid fresh public read returned non-json" },
|
|
58837
|
+
{ contains: "hyperliquid public freshness bracket moved backwards" }
|
|
58838
|
+
] } },
|
|
58839
|
+
{ reason_code: "behavior_state_unavailable", when: { any: [
|
|
58840
|
+
{ all: [
|
|
58841
|
+
{ contains: "your prompt on the ai page contains something vtx can't use" },
|
|
58842
|
+
{ contains: "next scheduled cycle" }
|
|
58843
|
+
] },
|
|
58844
|
+
{ all: [
|
|
58845
|
+
{ contains: "critical behavior context could not be constructed" },
|
|
58846
|
+
{ contains: "next scheduled cycle" }
|
|
58847
|
+
] }
|
|
58848
|
+
] } },
|
|
58849
|
+
{ reason_code: "hyperliquid_wallet_not_authorized", when: { any: [
|
|
58850
|
+
{ contains: "hyperliquid api wallet is not authorized" },
|
|
58851
|
+
{ contains: "hyperliquid signing key is not authorized for this wallet" },
|
|
58852
|
+
{ contains: "hyperliquid has not approved this key for this profile's wallet" }
|
|
58853
|
+
] } },
|
|
58854
|
+
{ reason_code: "ai_service_rate_limit", when: { any: [
|
|
58855
|
+
{ all: [
|
|
58856
|
+
{ contains: "exhausted fallback chain" },
|
|
58857
|
+
{ contains: "(429)" }
|
|
58858
|
+
] },
|
|
58859
|
+
{ contains: "ai provider returned 429" },
|
|
58860
|
+
{ contains: "ai provider and fallback model returned 429" },
|
|
58861
|
+
{ contains: "ai service rate limit (429)" },
|
|
58862
|
+
{ contains: "external ai account has reached its current usage limit" }
|
|
58863
|
+
] } },
|
|
58864
|
+
{ reason_code: "ai_service_unavailable", when: { any: [
|
|
58865
|
+
{ contains: "ai provider returned 503" },
|
|
58866
|
+
{ contains: "ai provider returned 500" },
|
|
58867
|
+
{ contains: "ai provider returned 502" },
|
|
58868
|
+
{ contains: "ai provider returned 504" },
|
|
58869
|
+
{ contains: "ai provider and fallback model returned 503" },
|
|
58870
|
+
{ contains: "service unavailable" },
|
|
58871
|
+
{ contains: "ai service unavailable (503)" },
|
|
58872
|
+
{ contains: "ai provider is temporarily unavailable" },
|
|
58873
|
+
{ contains: "codex reported server overload" },
|
|
58874
|
+
{ contains: "external inference host heartbeat is stale" },
|
|
58875
|
+
{ contains: "external inference host is finishing or recovering outstanding work" },
|
|
58876
|
+
{ contains: "external ai membership is currently available. at least one is cooling down" },
|
|
58877
|
+
{ contains: "external inference current advertisement is stale" },
|
|
58878
|
+
{ predicate: "provider_retry_status" }
|
|
58879
|
+
] } },
|
|
58880
|
+
{ reason_code: "app_bootstrap_unavailable", when: { any: [
|
|
58881
|
+
{ contains: "vtx could not load this profile's runtime settings" },
|
|
58882
|
+
{ contains: "vtx runtime settings temporarily unavailable due to server load" }
|
|
58883
|
+
] } },
|
|
58884
|
+
{ reason_code: "runtime_config_missing", when: { contains: "vtx is missing required runtime configuration" } },
|
|
58885
|
+
{ reason_code: "provider_not_configured", when: { any: [
|
|
58886
|
+
{ contains: "client runtime provider setup error" },
|
|
58887
|
+
{ contains: "is not configured for this profile" },
|
|
58888
|
+
{ contains: "is not account-synced for this profile" }
|
|
58889
|
+
] } },
|
|
58890
|
+
{ reason_code: "provider_unavailable", when: { contains: "client runtime provider error" } },
|
|
58891
|
+
{ reason_code: "browser_cors_failure", when: { any: [
|
|
58892
|
+
{ contains: "the browser blocked the ai provider request" },
|
|
58893
|
+
{ contains: "request was blocked" },
|
|
58894
|
+
{ contains: "failed in browser (network/cors)" }
|
|
58895
|
+
] } },
|
|
58896
|
+
{ reason_code: "market_data_browser_failure", when: { any: [
|
|
58897
|
+
{ contains: "market data did not load" },
|
|
58898
|
+
{ contains: "market data request failed in browser" }
|
|
58899
|
+
] } },
|
|
58900
|
+
{ reason_code: "browser_network_failure", when: { any: [
|
|
58901
|
+
{ contains: "browser could not complete a vtx runtime request" },
|
|
58902
|
+
{ contains: "hyperliquid public request network failure" },
|
|
58903
|
+
{ contains: "a browser network request failed" },
|
|
58904
|
+
{ contains: "browser could not reach the ai provider" },
|
|
58905
|
+
{ contains: "failed in browser (network request failed)" }
|
|
58906
|
+
] } },
|
|
58907
|
+
{ reason_code: "provider_network_failure", when: { contains: "vtx could not reach the ai provider" } },
|
|
58908
|
+
{ reason_code: "runtime_timeout", when: { any: [
|
|
58909
|
+
{ contains: "ai run took too long" },
|
|
58910
|
+
{ contains: "cycle deadline was reached" },
|
|
58911
|
+
{ contains: "this analysis timed out" },
|
|
58912
|
+
{ contains: "hyperliquid request exceeded its total read deadline" }
|
|
58913
|
+
] } },
|
|
58914
|
+
{ reason_code: "snapshot_stale", when: { any: [
|
|
58915
|
+
{ contains: "decision skipped: account data was" },
|
|
58916
|
+
{ contains: "couldn't refresh this bot's hyperliquid account data in time" },
|
|
58917
|
+
{ contains: "server account context could not be rebuilt inside the dispatch freshness window" }
|
|
58918
|
+
] } },
|
|
58919
|
+
{ reason_code: "model_output_schema_invalid", when: { any: [
|
|
58920
|
+
{ starts_with: "model_output_schema_invalid:" },
|
|
58921
|
+
{ contains: "model's reply could not be read" },
|
|
58922
|
+
{ contains: "the agent's instruction could not be read" }
|
|
58923
|
+
] } },
|
|
58924
|
+
{ reason_code: "ai_service_rate_limit", when: { contains: "provider request failed (http 429)" } },
|
|
58925
|
+
{ reason_code: "external_inference_window_missed", when: { any: [
|
|
58926
|
+
{ contains: "external inference host claimed the server prompt but did not dispatch it" },
|
|
58927
|
+
{ contains: "external inference host did not claim the server prompt inside its account-state freshness window" }
|
|
58928
|
+
] } },
|
|
58929
|
+
{ reason_code: "runtime_timeout", when: { contains: "failure code: runtime_timeout" } },
|
|
58930
|
+
{ reason_code: "account_state_changing", when: { any: [
|
|
58931
|
+
{ contains: "account state is changing while preparing prompt context" },
|
|
58932
|
+
{ contains: "server account state changed" }
|
|
58933
|
+
] } },
|
|
58934
|
+
{ reason_code: "runtime_contract_changed", when: { any: [
|
|
58935
|
+
{ contains: "rejected by contract: contract_identity_mismatch" },
|
|
58936
|
+
{ contains: "rejected by contract: contract_binding_mismatch" }
|
|
58937
|
+
] } },
|
|
58938
|
+
{ reason_code: "decision_persistence_timeout", when: { contains: "could not confirm that its decision was saved before the cycle deadline" } },
|
|
58939
|
+
{ reason_code: "model_unavailable", when: { any: [
|
|
58940
|
+
{ contains: "this model is not available from the selected provider" },
|
|
58941
|
+
{ contains: "model is not available on the selected provider" },
|
|
58942
|
+
{ contains: "client runtime model error" },
|
|
58943
|
+
{ contains: " is not available on " },
|
|
58944
|
+
{ starts_with: "unknown model" }
|
|
58945
|
+
] } },
|
|
58946
|
+
{ reason_code: "runtime_contract_changed", when: { any: [
|
|
58947
|
+
{ contains: "the bot's run changed while this analysis was waiting" },
|
|
58948
|
+
{ equals: "runtime_fence_stale" },
|
|
58949
|
+
{ equals: "settings_superseded" },
|
|
58950
|
+
{ contains: "terminal code: runtime_fence_" },
|
|
58951
|
+
{ contains: "failure code: runtime_fence_" }
|
|
58952
|
+
] } },
|
|
58953
|
+
{ reason_code: "runtime_timeout", when: { any: [
|
|
58954
|
+
{ contains: "terminal code: deadline_exceeded" },
|
|
58955
|
+
{ equals: "the operation was aborted." },
|
|
58956
|
+
{ contains: "encountered timeouterror without additional error details" }
|
|
58957
|
+
] } },
|
|
58958
|
+
{ reason_code: "ai_service_rate_limit", when: { any: [
|
|
58959
|
+
{ contains: "terminal code: codex_rate_limited." },
|
|
58960
|
+
{ contains: "terminal code: provider_rate_limited." }
|
|
58961
|
+
] } },
|
|
58962
|
+
{ reason_code: "ai_service_unavailable", when: { any: [
|
|
58963
|
+
{ contains: "terminal code: codex_server_overloaded." },
|
|
58964
|
+
{ contains: "terminal code: codex_internal_error." },
|
|
58965
|
+
{ contains: "terminal code: codex_http_connection_failed." },
|
|
58966
|
+
{ contains: "terminal code: codex_response_stream_connection_failed." },
|
|
58967
|
+
{ contains: "terminal code: codex_response_stream_disconnected." },
|
|
58968
|
+
{ contains: "terminal code: codex_provider_retry_exhausted." },
|
|
58969
|
+
{ contains: "terminal code: model_unavailable." },
|
|
58970
|
+
{ contains: "terminal code: reasoning_effort_unavailable." }
|
|
58971
|
+
] } },
|
|
58972
|
+
{ reason_code: "external_inference_failed", when: { any: [
|
|
58973
|
+
{ contains: "terminal code: " },
|
|
58974
|
+
{ contains: "external ai recovery checkpoint failed" }
|
|
58975
|
+
] } },
|
|
58976
|
+
{ reason_code: "vtx_api_request_failed", when: { contains: "client runtime inference job read failed" } },
|
|
58977
|
+
{ reason_code: "hyperliquid_data_unavailable", when: { any: [
|
|
58978
|
+
{ starts_with: "hyperliquid didn't answer vtx's request" },
|
|
58979
|
+
{ starts_with: "hyperliquid info request failed (5" }
|
|
58980
|
+
] } },
|
|
58981
|
+
{ reason_code: "hyperliquid_request_rejected", when: { any: [
|
|
58982
|
+
{ starts_with: "hyperliquid refused vtx's request" },
|
|
58983
|
+
{ starts_with: "hyperliquid info request failed (4" }
|
|
58984
|
+
] } },
|
|
58985
|
+
{ reason_code: "hyperliquid_read_budget_exhausted", when: { contains: "hyperliquid public read capacity is in use by higher-priority reads" } },
|
|
58986
|
+
{ reason_code: "cycle_ended_without_decision", when: { any: [
|
|
58987
|
+
{ contains: "this analysis ended before it reached a decision" },
|
|
58988
|
+
{ starts_with: "client_runtime_no_decision_cycle" }
|
|
58989
|
+
] } },
|
|
58990
|
+
{ reason_code: "provider_credentials_refreshing", when: { contains: "client provider credentials changed; account refresh is pending" } },
|
|
58991
|
+
{ reason_code: "browser_network_failure", when: { any: [
|
|
58992
|
+
{ equals: "fetch failed" },
|
|
58993
|
+
{ equals: "terminated" },
|
|
58994
|
+
{ contains: "content-length header of network response exceeds response body" }
|
|
58995
|
+
] } },
|
|
58996
|
+
{ reason_code: "provider_not_configured", when: { any: [
|
|
58997
|
+
{ contains: "no profile api key was provided for source" },
|
|
58998
|
+
{ contains: "no configured external inference host currently supports the selected model" }
|
|
58999
|
+
] } },
|
|
59000
|
+
{ reason_code: "provider_access_denied", when: { any: [
|
|
59001
|
+
{ starts_with: "provider request failed (http 401" },
|
|
59002
|
+
{ starts_with: "provider request failed (http 402" },
|
|
59003
|
+
{ starts_with: "provider request failed (http 403" },
|
|
59004
|
+
{ contains: "user location is not supported for the api use" }
|
|
59005
|
+
] } },
|
|
59006
|
+
{ reason_code: "model_output_schema_invalid", when: { contains: "rejected by constraints: symbol_mismatch" } },
|
|
59007
|
+
{ reason_code: "internal_data_error", when: { any: [
|
|
59008
|
+
{ contains: "external inference delivery identity did not match" },
|
|
59009
|
+
{ contains: "external inference idempotency key conflicts with another job" },
|
|
59010
|
+
{ contains: "external inference advertisement evidence is inconsistent" }
|
|
59011
|
+
] } },
|
|
59012
|
+
{ reason_code: "ai_service_rate_limit", when: { equals: "rate limit (paused)" } },
|
|
59013
|
+
{ reason_code: "profile_wallet_unavailable", when: { equals: "profile_wallet_unavailable" } },
|
|
59014
|
+
{ reason_code: "provider_access_denied", when: { all: [
|
|
59015
|
+
{ starts_with: "ai provider attempts failed:" },
|
|
59016
|
+
{ any: [{ contains: ": http 401" }, { contains: ": http 402" }, { contains: ": http 403" }] }
|
|
59017
|
+
] } },
|
|
59018
|
+
{ reason_code: "runtime_contract_changed", when: { any: [
|
|
59019
|
+
{ contains: "the external agent setting changed while this cycle was starting" },
|
|
59020
|
+
{ contains: "external inference job creation runtime fence is stale" }
|
|
59021
|
+
] } },
|
|
59022
|
+
{ reason_code: "account_state_changing", when: { contains: "server account state reconciliation is pending" } },
|
|
59023
|
+
{ reason_code: "snapshot_stale", when: { contains: "rejected by constraints: snapshot_stale" } },
|
|
59024
|
+
{ reason_code: "provider_not_configured", when: { any: [
|
|
59025
|
+
{ starts_with: "missing device-local api key for" },
|
|
59026
|
+
{ contains: "codex host runtime must be upgraded" }
|
|
59027
|
+
] } },
|
|
59028
|
+
{ reason_code: "model_output_schema_invalid", when: { any: [
|
|
59029
|
+
{ contains: "did not include any message content" },
|
|
59030
|
+
{ contains: "did not include any text content" }
|
|
59031
|
+
] } },
|
|
59032
|
+
{ reason_code: "browser_network_failure", when: { equals: "load failed" } },
|
|
59033
|
+
{ reason_code: "ai_service_unavailable", when: { starts_with: "ai provider recovery cooldown" } },
|
|
59034
|
+
{ reason_code: "hyperliquid_credentials_missing", when: { contains: "has no hyperliquid credentials configured" } },
|
|
59035
|
+
{ reason_code: "external_inference_window_missed", when: { contains: "external inference admission deadline expired while refreshing account context" } }
|
|
59036
|
+
],
|
|
59037
|
+
reason_codes: {
|
|
59038
|
+
account_state_changing: { transient: true, severity: "ERROR" },
|
|
59039
|
+
ai_service_rate_limit: { transient: true, severity: "ERROR" },
|
|
59040
|
+
ai_service_unavailable: { transient: true, severity: "ERROR" },
|
|
59041
|
+
app_bootstrap_unavailable: { transient: true, severity: "ERROR" },
|
|
59042
|
+
behavior_state_unavailable: { transient: true, severity: "WARN" },
|
|
59043
|
+
browser_cors_failure: { transient: true, severity: "ERROR" },
|
|
59044
|
+
browser_network_failure: { transient: true, severity: "ERROR" },
|
|
59045
|
+
credentials_missing: { transient: false, severity: "ERROR" },
|
|
59046
|
+
cycle_ended_without_decision: { transient: true, severity: "ERROR" },
|
|
59047
|
+
decision_persistence_timeout: { transient: true, severity: "ERROR" },
|
|
59048
|
+
device_signing_key_invalid: { transient: false, severity: "ERROR" },
|
|
59049
|
+
device_signing_key_unauthorized: { transient: false, severity: "ERROR" },
|
|
59050
|
+
exchange_rejected: { transient: false, severity: "ERROR" },
|
|
59051
|
+
external_inference_failed: { transient: false, severity: "ERROR" },
|
|
59052
|
+
external_inference_window_missed: { transient: true, severity: "ERROR" },
|
|
59053
|
+
http_request_capacity: { transient: true, severity: "ERROR" },
|
|
59054
|
+
hyperliquid_credentials_missing: { transient: false, severity: "ERROR" },
|
|
59055
|
+
hyperliquid_data_unavailable: { transient: true, severity: "ERROR" },
|
|
59056
|
+
hyperliquid_rate_limit: { transient: true, severity: "ERROR" },
|
|
59057
|
+
hyperliquid_read_budget_exhausted: { transient: true, severity: "WARN" },
|
|
59058
|
+
hyperliquid_request_capacity: { transient: true, severity: "ERROR" },
|
|
59059
|
+
hyperliquid_request_rejected: { transient: false, severity: "ERROR" },
|
|
59060
|
+
hyperliquid_wallet_not_authorized: { transient: false, severity: "ERROR" },
|
|
59061
|
+
internal_data_error: { transient: false, severity: "ERROR" },
|
|
59062
|
+
internal_execution_error: { transient: false, severity: "ERROR" },
|
|
59063
|
+
live_calendar_unavailable: { transient: true, severity: "ERROR" },
|
|
59064
|
+
live_derived_context_build_failed: { transient: true, severity: "ERROR" },
|
|
59065
|
+
live_derived_context_timeout: { transient: true, severity: "ERROR" },
|
|
59066
|
+
live_market_regime_unavailable: { transient: true, severity: "ERROR" },
|
|
59067
|
+
live_market_stats_unavailable: { transient: true, severity: "ERROR" },
|
|
59068
|
+
live_performance_unavailable: { transient: true, severity: "ERROR" },
|
|
59069
|
+
local_safety_block: { transient: false, severity: "ERROR" },
|
|
59070
|
+
market_data_browser_failure: { transient: true, severity: "ERROR" },
|
|
59071
|
+
model_output_schema_invalid: { transient: true, severity: "ERROR" },
|
|
59072
|
+
model_unavailable: { transient: false, severity: "ERROR" },
|
|
59073
|
+
outcome_unknown: { transient: true, severity: "ERROR" },
|
|
59074
|
+
private_node_stale: { transient: true, severity: "ERROR" },
|
|
59075
|
+
profile_wallet_unavailable: { transient: false, severity: "ERROR" },
|
|
59076
|
+
protective_order_not_placed: { transient: false, severity: "WARN" },
|
|
59077
|
+
protective_order_unmanaged: { transient: false, severity: "WARN" },
|
|
59078
|
+
provider_access_denied: { transient: false, severity: "ERROR" },
|
|
59079
|
+
provider_credentials_refreshing: { transient: true, severity: "ERROR" },
|
|
59080
|
+
provider_network_failure: { transient: true, severity: "ERROR" },
|
|
59081
|
+
provider_not_configured: { transient: false, severity: "ERROR" },
|
|
59082
|
+
provider_unavailable: { transient: true, severity: "ERROR" },
|
|
59083
|
+
redis_unavailable: { transient: true, severity: "ERROR" },
|
|
59084
|
+
runtime_config_missing: { transient: false, severity: "ERROR" },
|
|
59085
|
+
runtime_contract_changed: { transient: true, severity: "ERROR" },
|
|
59086
|
+
runtime_timeout: { transient: true, severity: "ERROR" },
|
|
59087
|
+
signer_validation_unavailable: { transient: false, severity: "ERROR" },
|
|
59088
|
+
snapshot_stale: { transient: true, severity: "ERROR" },
|
|
59089
|
+
vtx_api_request_failed: { transient: true, severity: "ERROR" },
|
|
59090
|
+
wallet_not_authorized: { transient: false, severity: "ERROR" }
|
|
59091
|
+
}
|
|
59092
|
+
};
|
|
59093
|
+
}
|
|
59094
|
+
});
|
|
59095
|
+
|
|
59096
|
+
// lib/runtime/runtime-error-reason-rules.ts
|
|
59097
|
+
var RuntimeReasonError, runtimeRequestFailure, raisedRuntimeErrorReasonCode, HISTORY_WRAPPER, runtimeErrorReasonSubject, RULES, matches, matchRuntimeErrorReasonCode;
|
|
59098
|
+
var init_runtime_error_reason_rules2 = __esm({
|
|
59099
|
+
"lib/runtime/runtime-error-reason-rules.ts"() {
|
|
59100
|
+
"use strict";
|
|
59101
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
59102
|
+
init_define_VTX_EXO_POLICY();
|
|
59103
|
+
init_define_VTX_GROK_POLICY();
|
|
59104
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
59105
|
+
init_runtime_error_reason_rules();
|
|
59106
|
+
init_constants();
|
|
59107
|
+
RuntimeReasonError = class extends Error {
|
|
59108
|
+
constructor(message, runtimeReasonCode, options) {
|
|
59109
|
+
super(message, options);
|
|
59110
|
+
this.name = "RuntimeReasonError";
|
|
59111
|
+
this.runtimeReasonCode = runtimeReasonCode;
|
|
59112
|
+
}
|
|
59113
|
+
};
|
|
59114
|
+
runtimeRequestFailure = (message, status, unexplained) => unexplained && (status >= HTTP_SERVER_ERROR_MIN || status === HTTP_STATUS.TOO_MANY_REQUESTS) ? new RuntimeReasonError(message, "vtx_api_request_failed") : new Error(message);
|
|
59115
|
+
raisedRuntimeErrorReasonCode = (error48) => error48 instanceof RuntimeReasonError ? error48.runtimeReasonCode : null;
|
|
59116
|
+
HISTORY_WRAPPER = /^analysis unavailable:\s*(?:\u26a0\ufe0f?\s*)?/iu;
|
|
59117
|
+
runtimeErrorReasonSubject = (normalizedWithoutWarning) => normalizedWithoutWarning.replace(HISTORY_WRAPPER, "").trim();
|
|
59118
|
+
RULES = runtime_error_reason_rules_default;
|
|
59119
|
+
matches = (condition, lowered, texts, predicates) => {
|
|
59120
|
+
if ("equals" in condition) return lowered === condition.equals;
|
|
59121
|
+
if ("starts_with" in condition) return lowered.startsWith(condition.starts_with);
|
|
59122
|
+
if ("contains" in condition) return lowered.includes(condition.contains);
|
|
59123
|
+
if ("all" in condition) return condition.all.every((item) => matches(item, lowered, texts, predicates));
|
|
59124
|
+
if ("any" in condition) return condition.any.some((item) => matches(item, lowered, texts, predicates));
|
|
59125
|
+
return predicates[condition.predicate](...texts);
|
|
59126
|
+
};
|
|
59127
|
+
matchRuntimeErrorReasonCode = (normalized, normalizedWithoutWarning, predicates) => {
|
|
59128
|
+
const subject = runtimeErrorReasonSubject(normalizedWithoutWarning);
|
|
59129
|
+
const lowered = subject.toLowerCase();
|
|
59130
|
+
if (!normalized || RULES.unclassified_messages.includes(lowered)) {
|
|
59131
|
+
return null;
|
|
59132
|
+
}
|
|
59133
|
+
const texts = [normalized, subject];
|
|
59134
|
+
for (const rule of RULES.rules) {
|
|
59135
|
+
if (matches(rule.when, lowered, texts, predicates)) {
|
|
59136
|
+
return rule.reason_code;
|
|
59137
|
+
}
|
|
59138
|
+
}
|
|
59139
|
+
return null;
|
|
59140
|
+
};
|
|
59141
|
+
}
|
|
59142
|
+
});
|
|
59143
|
+
|
|
58626
59144
|
// lib/runtime/monotonic-clock.ts
|
|
58627
59145
|
var monotonicNowMs, monotonicAgeMs;
|
|
58628
59146
|
var init_monotonic_clock = __esm({
|
|
@@ -58954,27 +59472,35 @@ var init_local_breadcrumbs = __esm({
|
|
|
58954
59472
|
if (pending3.length === 0) {
|
|
58955
59473
|
return 0;
|
|
58956
59474
|
}
|
|
59475
|
+
const report = (entry) => options.reporter(normalizedProfileId, {
|
|
59476
|
+
// Authenticate delivery with the current owner after recovery/reload.
|
|
59477
|
+
// Historical ownership remains unchanged inside the breadcrumb.
|
|
59478
|
+
sessionId: sanitizeOptionalString(options.sessionId) ?? sanitizeOptionalString(entry.sessionId),
|
|
59479
|
+
deviceId: sanitizeOptionalString(options.deviceId) ?? sanitizeOptionalString(entry.deviceId),
|
|
59480
|
+
mode: entry.mode ?? (options.mode === "assistant" ? "assistant" : options.mode === "trader" ? "trader" : null),
|
|
59481
|
+
lastRunAt: sanitizeOptionalString(entry.lastRunAt) ?? sanitizeOptionalString(options.lastRunAt),
|
|
59482
|
+
eventType: "client_recovered_local_breadcrumb",
|
|
59483
|
+
detail: `Recovered local runtime breadcrumb: ${entry.kind}`,
|
|
59484
|
+
payload: {
|
|
59485
|
+
flush_reason: flushReason,
|
|
59486
|
+
recovered_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
59487
|
+
breadcrumb: entry
|
|
59488
|
+
}
|
|
59489
|
+
});
|
|
58957
59490
|
const flushedIds = [];
|
|
58958
|
-
|
|
58959
|
-
|
|
58960
|
-
|
|
58961
|
-
|
|
58962
|
-
|
|
58963
|
-
|
|
58964
|
-
|
|
58965
|
-
|
|
58966
|
-
|
|
58967
|
-
|
|
58968
|
-
|
|
58969
|
-
|
|
58970
|
-
|
|
58971
|
-
recovered_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
58972
|
-
breadcrumb: entry
|
|
58973
|
-
}
|
|
58974
|
-
});
|
|
58975
|
-
flushedIds.push(entry.id);
|
|
58976
|
-
} catch {
|
|
58977
|
-
break;
|
|
59491
|
+
if (options.together) {
|
|
59492
|
+
const settled2 = await Promise.allSettled(pending3.map((entry) => Promise.resolve().then(() => report(entry))));
|
|
59493
|
+
pending3.forEach((entry, index) => {
|
|
59494
|
+
if (settled2[index].status === "fulfilled") flushedIds.push(entry.id);
|
|
59495
|
+
});
|
|
59496
|
+
} else {
|
|
59497
|
+
for (const entry of pending3) {
|
|
59498
|
+
try {
|
|
59499
|
+
await report(entry);
|
|
59500
|
+
flushedIds.push(entry.id);
|
|
59501
|
+
} catch {
|
|
59502
|
+
break;
|
|
59503
|
+
}
|
|
58978
59504
|
}
|
|
58979
59505
|
}
|
|
58980
59506
|
if (flushedIds.length > 0) {
|
|
@@ -59557,6 +60083,109 @@ var init_llm_config = __esm({
|
|
|
59557
60083
|
}
|
|
59558
60084
|
});
|
|
59559
60085
|
|
|
60086
|
+
// lib/api/runtime-event-batch.ts
|
|
60087
|
+
var EVENT_BATCH, groups, batchRouteMissing, statusOf, sendSingly, flush, queueRuntimeEvent, eventBody, reportRuntimeEvent;
|
|
60088
|
+
var init_runtime_event_batch = __esm({
|
|
60089
|
+
"lib/api/runtime-event-batch.ts"() {
|
|
60090
|
+
"use strict";
|
|
60091
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
60092
|
+
init_define_VTX_EXO_POLICY();
|
|
60093
|
+
init_define_VTX_GROK_POLICY();
|
|
60094
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
60095
|
+
init_runtime_policy_generated2();
|
|
60096
|
+
init_constants();
|
|
60097
|
+
EVENT_BATCH = runtime_policy_generated_default2.trading.engine.client_runtime.event_batch;
|
|
60098
|
+
groups = /* @__PURE__ */ new Map();
|
|
60099
|
+
batchRouteMissing = false;
|
|
60100
|
+
statusOf = (error48) => {
|
|
60101
|
+
const value = Number(error48?.status);
|
|
60102
|
+
return Number.isFinite(value) ? value : null;
|
|
60103
|
+
};
|
|
60104
|
+
sendSingly = (events, sendOne) => {
|
|
60105
|
+
for (const event of events) sendOne(event.body).then(event.resolve, event.reject);
|
|
60106
|
+
};
|
|
60107
|
+
flush = (key) => {
|
|
60108
|
+
const group = groups.get(key);
|
|
60109
|
+
if (!group) return;
|
|
60110
|
+
groups.delete(key);
|
|
60111
|
+
if (group.timer) clearTimeout(group.timer);
|
|
60112
|
+
if (batchRouteMissing) {
|
|
60113
|
+
sendSingly(group.events, group.sendOne);
|
|
60114
|
+
return;
|
|
60115
|
+
}
|
|
60116
|
+
for (let start = 0; start < group.events.length; start += EVENT_BATCH.max_events) {
|
|
60117
|
+
const chunk = group.events.slice(start, start + EVENT_BATCH.max_events);
|
|
60118
|
+
group.sendBatch(chunk.map((event) => event.body)).then(
|
|
60119
|
+
(response) => {
|
|
60120
|
+
const results = response?.results;
|
|
60121
|
+
const unrecorded = chunk.filter((event, index) => {
|
|
60122
|
+
if (results?.[index]?.status === "not_recorded") return true;
|
|
60123
|
+
event.resolve({ status: "event_recorded" });
|
|
60124
|
+
return false;
|
|
60125
|
+
});
|
|
60126
|
+
sendSingly(unrecorded, group.sendOne);
|
|
60127
|
+
},
|
|
60128
|
+
(error48) => {
|
|
60129
|
+
const status = statusOf(error48);
|
|
60130
|
+
if (status === HTTP_STATUS.METHOD_NOT_ALLOWED) {
|
|
60131
|
+
batchRouteMissing = true;
|
|
60132
|
+
sendSingly(chunk, group.sendOne);
|
|
60133
|
+
return;
|
|
60134
|
+
}
|
|
60135
|
+
if (status === HTTP_STATUS.UNPROCESSABLE_CONTENT) {
|
|
60136
|
+
sendSingly(chunk, group.sendOne);
|
|
60137
|
+
return;
|
|
60138
|
+
}
|
|
60139
|
+
chunk.forEach((event) => event.reject(error48));
|
|
60140
|
+
}
|
|
60141
|
+
);
|
|
60142
|
+
}
|
|
60143
|
+
};
|
|
60144
|
+
queueRuntimeEvent = (key, body, send) => new Promise((resolve16, reject) => {
|
|
60145
|
+
let group = groups.get(key);
|
|
60146
|
+
if (!group) {
|
|
60147
|
+
group = { events: [], timer: null, sendBatch: send.batch, sendOne: send.one };
|
|
60148
|
+
groups.set(key, group);
|
|
60149
|
+
group.timer = setTimeout(() => flush(key), EVENT_BATCH.window_milliseconds);
|
|
60150
|
+
}
|
|
60151
|
+
group.events.push({ body, resolve: resolve16, reject });
|
|
60152
|
+
if (group.events.length >= EVENT_BATCH.max_events) flush(key);
|
|
60153
|
+
});
|
|
60154
|
+
eventBody = (payload) => ({
|
|
60155
|
+
session_id: payload.sessionId ?? null,
|
|
60156
|
+
device_id: payload.deviceId ?? null,
|
|
60157
|
+
...String(payload.schedulerInstanceId ?? "").trim() ? { scheduler_instance_id: String(payload.schedulerInstanceId).trim() } : {},
|
|
60158
|
+
mode: payload.mode ?? null,
|
|
60159
|
+
last_run_at: payload.lastRunAt ?? null,
|
|
60160
|
+
event_type: payload.eventType,
|
|
60161
|
+
detail: payload.detail ?? null,
|
|
60162
|
+
payload: payload.payload ?? null
|
|
60163
|
+
});
|
|
60164
|
+
reportRuntimeEvent = (profileId, payload, options, post) => {
|
|
60165
|
+
const body = eventBody(payload);
|
|
60166
|
+
const sendOne = (event) => post("/runtime/event", profileId, JSON.stringify(event), options);
|
|
60167
|
+
if (options?.keepalive || options?.signal) return sendOne(body);
|
|
60168
|
+
const context = {
|
|
60169
|
+
session_id: body.session_id ?? null,
|
|
60170
|
+
device_id: body.device_id ?? null,
|
|
60171
|
+
mode: body.mode ?? null,
|
|
60172
|
+
...body.scheduler_instance_id ? { scheduler_instance_id: body.scheduler_instance_id } : {}
|
|
60173
|
+
};
|
|
60174
|
+
const key = [
|
|
60175
|
+
String(profileId).trim(),
|
|
60176
|
+
JSON.stringify(context),
|
|
60177
|
+
options?.runtimeLeaseToken ?? "",
|
|
60178
|
+
options?.omitRuntimeLeaseToken ? "omit" : "",
|
|
60179
|
+
options?.reconcileOnly ? "reconcile" : ""
|
|
60180
|
+
].join("|");
|
|
60181
|
+
return queueRuntimeEvent(key, body, {
|
|
60182
|
+
batch: (events) => post("/runtime/events", profileId, JSON.stringify({ ...context, events }), options),
|
|
60183
|
+
one: sendOne
|
|
60184
|
+
});
|
|
60185
|
+
};
|
|
60186
|
+
}
|
|
60187
|
+
});
|
|
60188
|
+
|
|
59560
60189
|
// lib/api/insights-access-center.ts
|
|
59561
60190
|
var init_insights_access_center = __esm({
|
|
59562
60191
|
"lib/api/insights-access-center.ts"() {
|
|
@@ -60332,7 +60961,7 @@ var init_hyperliquid_public_capacity = __esm({
|
|
|
60332
60961
|
});
|
|
60333
60962
|
|
|
60334
60963
|
// lib/runtime/hyperliquid-public-read.ts
|
|
60335
|
-
var policy, weights, recoveryPolicy, budgets, unpersistedBudgets, cache, pending2, PREFIX, priorityRank, createHyperliquidPublicPriorityScope, promoteHyperliquidPublicPriority, hostTransport, hyperliquidPrivateInfoHeldOff, abortError2, checkAbort, wait, waitUnlessPromoted, storage, loadBudget, saveBudget, withBudgetLock, HyperliquidPublicReadError, getHyperliquidPublicReadBudget, cooldownError, recoveryWaitError, ranks, mostUrgentRank, lastRank, capacityPolicy, READERS_KEY, memoryReaders, unwrittenReaders, validSchedule, readTradingReaders, noteTradingReader, noteHyperliquidTradingRuntime, noteHyperliquidUnscheduledTradingRead, noteHyperliquidTradingRuntimeAttach, hyperliquidDemandWindowMs, hyperliquidDemandHorizonMs, greatestCommonDivisor, heldDemand, ranTogether, isHeldBack, reservationRank, classBoundaries, everyone, slotOf, windowWeights, foldDemand, demandFor, heldBackDecision, fallbackDelayMs, admit, rowWeightedCharge, settleRowWeightedReservation, cooldown, finishHyperliquidRecoveryRequest, assertHyperliquidRecoveryDispatch, validateHyperliquidRecoveryDispatch, cacheTtlMs, eligibleCache, reserveHyperliquidPublicReads, releaseHyperliquidPublicReadReservation, admitHyperliquidExchangeRequest, recordHyperliquidExchangeResponse, readHyperliquidPublicInfo;
|
|
60964
|
+
var policy, weights, recoveryPolicy, budgets, unpersistedBudgets, cache, pending2, PREFIX, priorityRank, createHyperliquidPublicPriorityScope, promoteHyperliquidPublicPriority, hostTransport, hyperliquidPrivateInfoHeldOff, abortError2, checkAbort, wait, waitUnlessPromoted, storage, loadBudget, saveBudget, withBudgetLock, PUBLIC_READ_REASON_CODES, HyperliquidPublicReadError, getHyperliquidPublicReadBudget, cooldownError, recoveryWaitError, ranks, mostUrgentRank, lastRank, capacityPolicy, READERS_KEY, memoryReaders, unwrittenReaders, validSchedule, readTradingReaders, noteTradingReader, noteHyperliquidTradingRuntime, noteHyperliquidUnscheduledTradingRead, noteHyperliquidTradingRuntimeAttach, hyperliquidDemandWindowMs, hyperliquidDemandHorizonMs, greatestCommonDivisor, heldDemand, ranTogether, isHeldBack, reservationRank, classBoundaries, everyone, slotOf, windowWeights, unscheduledSlot, demandEntryLength, foldDemand, demandFor, heldBackDecision, fallbackDelayMs, admit, rowWeightedCharge, settleRowWeightedReservation, cooldown, finishHyperliquidRecoveryRequest, assertHyperliquidRecoveryDispatch, validateHyperliquidRecoveryDispatch, cacheTtlMs, eligibleCache, reserveHyperliquidPublicReads, releaseHyperliquidPublicReadReservation, admitHyperliquidExchangeRequest, recordHyperliquidExchangeResponse, readHyperliquidPublicInfo;
|
|
60336
60965
|
var init_hyperliquid_public_read = __esm({
|
|
60337
60966
|
"lib/runtime/hyperliquid-public-read.ts"() {
|
|
60338
60967
|
"use strict";
|
|
@@ -60342,6 +60971,7 @@ var init_hyperliquid_public_read = __esm({
|
|
|
60342
60971
|
init_define_VTX_PI_MODEL_POLICY();
|
|
60343
60972
|
init_runtime_redaction();
|
|
60344
60973
|
init_runtime_policy_generated2();
|
|
60974
|
+
init_runtime_error_reason_rules2();
|
|
60345
60975
|
init_constants();
|
|
60346
60976
|
init_hyperliquid_public_capacity();
|
|
60347
60977
|
policy = runtime_policy_generated_default2.exchange.hyperliquid.client_public_read_budget;
|
|
@@ -60353,7 +60983,7 @@ var init_hyperliquid_public_read = __esm({
|
|
|
60353
60983
|
pending2 = /* @__PURE__ */ new Map();
|
|
60354
60984
|
PREFIX = "vtx:hl-public-read-budget:v1:";
|
|
60355
60985
|
priorityRank = (priority) => runtime_policy_generated_default2.exchange.hyperliquid.public_request_priority[priority];
|
|
60356
|
-
createHyperliquidPublicPriorityScope = (priority) => ({ value: priority });
|
|
60986
|
+
createHyperliquidPublicPriorityScope = (priority, unscheduled = false) => ({ value: priority, ...unscheduled ? { unscheduled: true } : {} });
|
|
60357
60987
|
promoteHyperliquidPublicPriority = (scope, priority) => {
|
|
60358
60988
|
if (priorityRank(priority) >= priorityRank(scope.value)) return;
|
|
60359
60989
|
scope.value = priority;
|
|
@@ -60445,9 +61075,17 @@ var init_hyperliquid_public_read = __esm({
|
|
|
60445
61075
|
}
|
|
60446
61076
|
return work();
|
|
60447
61077
|
};
|
|
60448
|
-
|
|
61078
|
+
PUBLIC_READ_REASON_CODES = {
|
|
61079
|
+
public_budget_exhausted: "hyperliquid_read_budget_exhausted",
|
|
61080
|
+
public_recovery_wait: "hyperliquid_rate_limit",
|
|
61081
|
+
public_cooldown_active: "hyperliquid_rate_limit",
|
|
61082
|
+
public_rate_limited: "hyperliquid_rate_limit",
|
|
61083
|
+
public_network_error: "browser_network_failure",
|
|
61084
|
+
public_timeout: "runtime_timeout"
|
|
61085
|
+
};
|
|
61086
|
+
HyperliquidPublicReadError = class extends RuntimeReasonError {
|
|
60449
61087
|
constructor(code, message, requestType, status, retryAfterMs, requiredWeight, usedWeight, maxWeight) {
|
|
60450
|
-
super(message);
|
|
61088
|
+
super(message, PUBLIC_READ_REASON_CODES[code]);
|
|
60451
61089
|
this.code = code;
|
|
60452
61090
|
this.requestType = requestType;
|
|
60453
61091
|
this.status = status;
|
|
@@ -60503,7 +61141,7 @@ var init_hyperliquid_public_read = __esm({
|
|
|
60503
61141
|
let readers = memoryReaders;
|
|
60504
61142
|
try {
|
|
60505
61143
|
const stored = JSON.parse(storage()?.getItem(READERS_KEY) ?? "null");
|
|
60506
|
-
if (Array.isArray(stored) && stored.every((reader) => typeof reader?.id === "string" && Number.isFinite(reader.until) && Number.isFinite(reader.notedAt) && (reader.schedule === void 0 || typeof reader.schedule === "object" && reader.schedule !== null && validSchedule(reader.schedule)))) {
|
|
61144
|
+
if (Array.isArray(stored) && stored.every((reader) => typeof reader?.id === "string" && Number.isFinite(reader.until) && Number.isFinite(reader.notedAt) && (reader.schedule === void 0 || typeof reader.schedule === "object" && reader.schedule !== null && validSchedule(reader.schedule)) && (reader.unscheduled === void 0 || reader.unscheduled === true))) {
|
|
60507
61145
|
readers = stored.filter((reader) => {
|
|
60508
61146
|
const own = unwrittenReaders.get(reader.id);
|
|
60509
61147
|
return own === void 0 || own !== null && reader.notedAt > own.notedAt;
|
|
@@ -60557,16 +61195,20 @@ var init_hyperliquid_public_read = __esm({
|
|
|
60557
61195
|
while (b3 !== 0) [a, b3] = [b3, a % b3];
|
|
60558
61196
|
return a;
|
|
60559
61197
|
};
|
|
60560
|
-
heldDemand = (buckets, now,
|
|
61198
|
+
heldDemand = (buckets, now, allReaders) => {
|
|
61199
|
+
const isMeasured = (reader) => reader.unscheduled === true && !reader.schedule;
|
|
61200
|
+
const measured = allReaders.some(isMeasured);
|
|
61201
|
+
const readers = allReaders.filter((reader) => !isMeasured(reader));
|
|
60561
61202
|
const schedules = readers.flatMap((reader) => reader.schedule ? [reader.schedule] : []);
|
|
60562
|
-
|
|
61203
|
+
const all = { held: buckets, measuredRelease: false };
|
|
61204
|
+
if (schedules.length === 0 || schedules.length < readers.length) return all;
|
|
60563
61205
|
let linedUpMs = schedules[0].loopMs;
|
|
60564
61206
|
for (const { loopMs } of schedules) {
|
|
60565
61207
|
linedUpMs = linedUpMs / greatestCommonDivisor(linedUpMs, loopMs) * loopMs;
|
|
60566
|
-
if (linedUpMs >= capacityPolicy.horizonMs) return
|
|
61208
|
+
if (linedUpMs >= capacityPolicy.horizonMs) return all;
|
|
60567
61209
|
}
|
|
60568
61210
|
const releaseAfterMs = linedUpMs + Math.max(...schedules.map((schedule) => schedule.loopMs)) + Math.max(...schedules.map((schedule) => schedule.cycleMs)) + capacityPolicy.windowMs;
|
|
60569
|
-
if (releaseAfterMs >= capacityPolicy.horizonMs) return
|
|
61211
|
+
if (releaseAfterMs >= capacityPolicy.horizonMs) return all;
|
|
60570
61212
|
const phased = schedules.filter((schedule) => capacityPolicy.windowMs % schedule.loopMs !== 0);
|
|
60571
61213
|
const linesUpAnew = phased.length > 1;
|
|
60572
61214
|
const offCadenceAt = Math.max(
|
|
@@ -60584,12 +61226,13 @@ var init_hyperliquid_public_read = __esm({
|
|
|
60584
61226
|
now - Math.max(...schedules.map((schedule) => schedule.cycleMs)) - capacityPolicy.windowMs,
|
|
60585
61227
|
now
|
|
60586
61228
|
);
|
|
60587
|
-
|
|
61229
|
+
const held = buckets.filter((bucket) => {
|
|
60588
61230
|
const bucketStart = bucket.index * capacityPolicy.bucketMs;
|
|
60589
61231
|
const bucketEnd = bucketStart + capacityPolicy.bucketMs;
|
|
60590
61232
|
const startup = startups.some(({ from, to }) => from < bucketEnd && to > bucketStart - capacityPolicy.windowMs);
|
|
60591
61233
|
return !startup || !seenTogether || now < Math.max(bucketEnd, offCadenceAt) + releaseAfterMs;
|
|
60592
61234
|
});
|
|
61235
|
+
return { held, measuredRelease: measured && held.length < buckets.length };
|
|
60593
61236
|
};
|
|
60594
61237
|
ranTogether = (readers, startupsEnd, latestEnd, now) => {
|
|
60595
61238
|
const windowMs = capacityPolicy.windowMs;
|
|
@@ -60609,16 +61252,23 @@ var init_hyperliquid_public_read = __esm({
|
|
|
60609
61252
|
everyone = lastRank + 1;
|
|
60610
61253
|
slotOf = (boundary) => boundary - mostUrgentRank;
|
|
60611
61254
|
windowWeights = (reservations, endAt) => {
|
|
60612
|
-
const
|
|
61255
|
+
const classes = classBoundaries.length;
|
|
61256
|
+
const weights2 = Array.from({ length: classes + 1 + classes }, () => 0);
|
|
60613
61257
|
for (const entry of reservations) {
|
|
60614
61258
|
if (entry.at <= endAt - capacityPolicy.windowMs || entry.at > endAt) continue;
|
|
60615
61259
|
classBoundaries.forEach((boundary, slot) => {
|
|
60616
|
-
if (reservationRank(entry)
|
|
61260
|
+
if (reservationRank(entry) >= boundary) return;
|
|
61261
|
+
weights2[slot] += entry.weight;
|
|
61262
|
+
if (!entry.unscheduled) weights2[classes + 1 + slot] += entry.weight;
|
|
60617
61263
|
});
|
|
61264
|
+
if (entry.unscheduled) weights2[classes] += entry.weight;
|
|
60618
61265
|
}
|
|
60619
61266
|
return weights2;
|
|
60620
61267
|
};
|
|
61268
|
+
unscheduledSlot = 1 + classBoundaries.length;
|
|
61269
|
+
demandEntryLength = 1 + classBoundaries.length + 1 + classBoundaries.length;
|
|
60621
61270
|
foldDemand = (budget, now) => {
|
|
61271
|
+
if (budget.splitFolded !== void 0 && budget.folded !== budget.splitFolded) budget.olderTabFoldedAt = now;
|
|
60622
61272
|
const foldUpTo = now - capacityPolicy.windowMs;
|
|
60623
61273
|
const foldedUpTo = Math.min(budget.folded ?? 0, foldUpTo);
|
|
60624
61274
|
const oldest = publicDemandBucketIndex(now - capacityPolicy.horizonMs, capacityPolicy.bucketMs);
|
|
@@ -60629,21 +61279,30 @@ var init_hyperliquid_public_read = __esm({
|
|
|
60629
61279
|
if (index < oldest) continue;
|
|
60630
61280
|
let entry = demand.find((item) => item[0] === index);
|
|
60631
61281
|
if (!entry) {
|
|
60632
|
-
entry = [index, ...
|
|
61282
|
+
entry = [index, ...Array.from({ length: demandEntryLength - 1 }, () => 0)];
|
|
60633
61283
|
demand.push(entry);
|
|
60634
61284
|
}
|
|
60635
61285
|
const weights2 = windowWeights(budget.reservations, reservation.at);
|
|
60636
61286
|
const bucketPeaks = entry;
|
|
60637
|
-
|
|
60638
|
-
|
|
60639
|
-
});
|
|
61287
|
+
const slots = bucketPeaks.length >= demandEntryLength ? demandEntryLength - 1 : classBoundaries.length;
|
|
61288
|
+
for (let slot = 0; slot < slots; slot += 1) bucketPeaks[slot + 1] = Math.max(bucketPeaks[slot + 1], weights2[slot]);
|
|
60640
61289
|
}
|
|
60641
61290
|
budget.folded = foldUpTo;
|
|
61291
|
+
budget.splitFolded = foldUpTo;
|
|
60642
61292
|
budget.demand = demand;
|
|
60643
61293
|
budget.reservations = budget.reservations.filter((entry) => entry.at > now - HYPERLIQUID_PUBLIC_READ_WINDOWS_KEPT * capacityPolicy.windowMs);
|
|
60644
61294
|
};
|
|
60645
61295
|
demandFor = (budget, rank, now) => {
|
|
60646
|
-
const of = (entry) =>
|
|
61296
|
+
const of = (entry) => {
|
|
61297
|
+
const split3 = entry.length >= demandEntryLength;
|
|
61298
|
+
return {
|
|
61299
|
+
index: entry[0],
|
|
61300
|
+
higherPeak: entry[slotOf(rank)],
|
|
61301
|
+
totalPeak: entry[slotOf(everyone)],
|
|
61302
|
+
unscheduledPeak: split3 ? entry[unscheduledSlot] : entry[slotOf(rank)],
|
|
61303
|
+
otherHigherPeak: split3 ? entry[unscheduledSlot + slotOf(rank)] : entry[slotOf(rank)]
|
|
61304
|
+
};
|
|
61305
|
+
};
|
|
60647
61306
|
const unfolded = budget.reservations.filter((reservation) => reservation.at > (budget.folded ?? 0)).map((reservation) => [
|
|
60648
61307
|
publicDemandBucketIndex(Math.min(reservation.at, now), capacityPolicy.bucketMs),
|
|
60649
61308
|
...windowWeights(budget.reservations, reservation.at)
|
|
@@ -60659,8 +61318,16 @@ var init_hyperliquid_public_read = __esm({
|
|
|
60659
61318
|
const buckets = demandFor(budget, fromRank, now);
|
|
60660
61319
|
const lastFailureMs = budget.lastFailure ?? 0;
|
|
60661
61320
|
const computed = adaptivePublicCapacity({ nowMs: now, lastFailureMs, buckets, policy: capacityPolicy });
|
|
60662
|
-
const
|
|
60663
|
-
|
|
61321
|
+
const peakOf = (list2) => adaptivePublicCapacity({ nowMs: now, lastFailureMs, buckets: list2, policy: capacityPolicy }).peakHigher;
|
|
61322
|
+
const { held, measuredRelease } = heldDemand(buckets, now, readers);
|
|
61323
|
+
const olderTab = budget.olderTabFoldedAt !== void 0 && now - budget.olderTabFoldedAt < capacityPolicy.horizonMs;
|
|
61324
|
+
let peakHigher = peakOf(olderTab && measuredRelease ? buckets : held);
|
|
61325
|
+
if (measuredRelease && !olderTab) {
|
|
61326
|
+
const others = peakOf(held.map((bucket) => ({ ...bucket, higherPeak: bucket.otherHigherPeak })));
|
|
61327
|
+
const unscheduled = peakOf(buckets.map((bucket) => ({ ...bucket, higherPeak: bucket.unscheduledPeak })));
|
|
61328
|
+
peakHigher = Math.min(computed.peakHigher, Math.max(peakHigher, others + unscheduled));
|
|
61329
|
+
}
|
|
61330
|
+
return { capacity: Math.min(computed.capacity, policy.max_weight), peakHigher };
|
|
60664
61331
|
};
|
|
60665
61332
|
const own = above(rank);
|
|
60666
61333
|
const uiRank = priorityRank("ui");
|
|
@@ -60761,7 +61428,13 @@ var init_hyperliquid_public_read = __esm({
|
|
|
60761
61428
|
recovery.nextAt = now + recoveryPolicy.recovery_min_spacing_ms;
|
|
60762
61429
|
permit = { endpoint: apiUrl, id: ticket, generation: recovery.generation, expiresAt };
|
|
60763
61430
|
}
|
|
60764
|
-
budget.reservations.push({
|
|
61431
|
+
budget.reservations.push({
|
|
61432
|
+
at: now,
|
|
61433
|
+
weight,
|
|
61434
|
+
rank,
|
|
61435
|
+
...reservationId ? { id: reservationId } : {},
|
|
61436
|
+
...priority.unscheduled ? { unscheduled: true } : {}
|
|
61437
|
+
});
|
|
60765
61438
|
foldDemand(budget, now);
|
|
60766
61439
|
saveBudget(key, budget);
|
|
60767
61440
|
return { ready: true, permit, waitMs: 0 };
|
|
@@ -61052,7 +61725,8 @@ var init_hyperliquid_public_read = __esm({
|
|
|
61052
61725
|
}
|
|
61053
61726
|
if (!response.ok) {
|
|
61054
61727
|
const detail = sanitizeRuntimeDiagnosticValue(typeof payload?.response === "string" ? payload.response : typeof payload?.detail === "string" ? payload.detail : "");
|
|
61055
|
-
|
|
61728
|
+
const reasonCode = response.status >= HTTP_SERVER_ERROR_MIN ? "hyperliquid_data_unavailable" : "hyperliquid_request_rejected";
|
|
61729
|
+
throw Object.assign(new RuntimeReasonError(`Hyperliquid info request failed (${response.status}) request_type=${requestType}.${detail ? ` ${detail}` : ""}`, reasonCode), {
|
|
61056
61730
|
status: response.status,
|
|
61057
61731
|
requestType
|
|
61058
61732
|
});
|
|
@@ -61278,290 +61952,6 @@ var init_status_contract = __esm({
|
|
|
61278
61952
|
}
|
|
61279
61953
|
});
|
|
61280
61954
|
|
|
61281
|
-
// lib/runtime/runtime-error-reason-rules.json
|
|
61282
|
-
var runtime_error_reason_rules_default;
|
|
61283
|
-
var init_runtime_error_reason_rules = __esm({
|
|
61284
|
-
"lib/runtime/runtime-error-reason-rules.json"() {
|
|
61285
|
-
runtime_error_reason_rules_default = {
|
|
61286
|
-
about: "The one owner of runtime error reason codes, loaded by the web runtime (runtime-error-reason-rules.ts) and the API (runtime_error_reason_rules.py). Rules are tried in order on the normalized message without its warning prefix or its AI panel history wrapper (Analysis unavailable:), lowercased, so a stored row and the bare message get the same code; the first match names the code. A condition is equals, starts_with, contains, all, any, or a named predicate each runtime implements. reason_codes classifies every code: transient codes clear on their own; WARN codes record a skipped cycle, not a failure. A code not listed is ERROR and needs the owner's attention.",
|
|
61287
|
-
unclassified_messages: [
|
|
61288
|
-
"unknown runtime error.",
|
|
61289
|
-
"vtx did not receive error details for this runtime failure."
|
|
61290
|
-
],
|
|
61291
|
-
rules: [
|
|
61292
|
-
{ reason_code: "ai_service_rate_limit", when: { predicate: "provider_attempt_summary_http_429" } },
|
|
61293
|
-
{ reason_code: "ai_service_unavailable", when: { predicate: "provider_attempt_summary_unavailable" } },
|
|
61294
|
-
{ reason_code: "hyperliquid_request_capacity", when: { starts_with: "vtx could not obtain hyperliquid request capacity" } },
|
|
61295
|
-
{ reason_code: "http_request_capacity", when: { starts_with: "vtx could not obtain http request capacity" } },
|
|
61296
|
-
{ reason_code: "live_market_stats_unavailable", when: { equals: "live market stats unavailable for client runtime contract" } },
|
|
61297
|
-
{ reason_code: "live_performance_unavailable", when: { equals: "live performance context unavailable for client runtime contract" } },
|
|
61298
|
-
{ reason_code: "live_market_regime_unavailable", when: { equals: "live market regime context unavailable for client runtime contract" } },
|
|
61299
|
-
{ reason_code: "live_calendar_unavailable", when: { equals: "live calendar context unavailable for client runtime contract" } },
|
|
61300
|
-
{ reason_code: "live_derived_context_timeout", when: { equals: "timed out while building live derived context for client runtime contract" } },
|
|
61301
|
-
{ reason_code: "live_derived_context_build_failed", when: { equals: "failed to build live derived context for client runtime contract" } },
|
|
61302
|
-
{ reason_code: "internal_data_error", when: { any: [
|
|
61303
|
-
{ equals: "internal data error. please try again." },
|
|
61304
|
-
{ equals: "vtx could not read the required app data. please try again." }
|
|
61305
|
-
] } },
|
|
61306
|
-
{ reason_code: "private_node_stale", when: { all: [
|
|
61307
|
-
{ contains: "order was not sent" },
|
|
61308
|
-
{ any: [
|
|
61309
|
-
{ contains: "too stale to validate the signing key" },
|
|
61310
|
-
{ contains: "required hyperliquid account data was stale" }
|
|
61311
|
-
] }
|
|
61312
|
-
] } },
|
|
61313
|
-
{ reason_code: "signer_validation_unavailable", when: { all: [
|
|
61314
|
-
{ contains: "order was not sent" },
|
|
61315
|
-
{ any: [
|
|
61316
|
-
{ contains: "private account service could not validate the signing key" },
|
|
61317
|
-
{ contains: "required hyperliquid account data was temporarily unavailable" }
|
|
61318
|
-
] }
|
|
61319
|
-
] } },
|
|
61320
|
-
{ reason_code: "wallet_not_authorized", when: { all: [
|
|
61321
|
-
{ contains: "order was not sent" },
|
|
61322
|
-
{ any: [
|
|
61323
|
-
{ contains: "signing key is not authorized for the configured wallet" },
|
|
61324
|
-
{ contains: "hyperliquid confirmed that the signing key is not authorized" },
|
|
61325
|
-
{ contains: "hyperliquid has not approved this key for this profile's wallet" }
|
|
61326
|
-
] }
|
|
61327
|
-
] } },
|
|
61328
|
-
{ reason_code: "credentials_missing", when: { all: [
|
|
61329
|
-
{ contains: "order was not sent" },
|
|
61330
|
-
{ contains: "authorized signing key are required for trading" }
|
|
61331
|
-
] } },
|
|
61332
|
-
{ reason_code: "local_safety_block", when: { contains: "order was not sent before exchange dispatch" } },
|
|
61333
|
-
{ reason_code: "redis_unavailable", when: { contains: "order was not sent because execution coordination was unavailable" } },
|
|
61334
|
-
{ reason_code: "exchange_rejected", when: { all: [
|
|
61335
|
-
{ starts_with: "hyperliquid rejected the " },
|
|
61336
|
-
{ contains: " order:" }
|
|
61337
|
-
] } },
|
|
61338
|
-
{ reason_code: "outcome_unknown", when: { all: [
|
|
61339
|
-
{ contains: "vtx could not confirm whether the " },
|
|
61340
|
-
{ contains: " order was applied" }
|
|
61341
|
-
] } },
|
|
61342
|
-
{ reason_code: "internal_execution_error", when: { all: [
|
|
61343
|
-
{ starts_with: "vtx could not complete the " },
|
|
61344
|
-
{ contains: " order:" }
|
|
61345
|
-
] } },
|
|
61346
|
-
{ reason_code: "hyperliquid_rate_limit", when: { any: [
|
|
61347
|
-
{ contains: "hyperliquid returned 429" },
|
|
61348
|
-
{ contains: "hyperliquid returned http 429" },
|
|
61349
|
-
{ contains: "public reads are waiting for a rate-limit cooldown" },
|
|
61350
|
-
{ contains: "public reads are waiting after a hyperliquid rate limit" },
|
|
61351
|
-
{ contains: "recovery queue before its deadline" },
|
|
61352
|
-
{ contains: "hyperliquid info endpoint returned 429" },
|
|
61353
|
-
{ contains: "hyperliquid rate limit (429)" },
|
|
61354
|
-
{ contains: "hyperliquid public api returned http 429" },
|
|
61355
|
-
{ contains: "hyperliquid public info cooldown is active" },
|
|
61356
|
-
{ contains: "hyperliquid public request cooldown is active" },
|
|
61357
|
-
{ contains: "hyperliquid public recovery is waiting after an observed http 429" },
|
|
61358
|
-
{ contains: "hyperliquid provider recovery could not dispatch before the request deadline" }
|
|
61359
|
-
] } },
|
|
61360
|
-
{ reason_code: "hyperliquid_read_budget_exhausted", when: { any: [
|
|
61361
|
-
{ all: [
|
|
61362
|
-
{ contains: "fresh hyperliquid data" },
|
|
61363
|
-
{ contains: "current read budget" }
|
|
61364
|
-
] },
|
|
61365
|
-
{ contains: "server's public-read budget is full" },
|
|
61366
|
-
{ contains: "app's shared public-read budget is also full" },
|
|
61367
|
-
{ all: [
|
|
61368
|
-
{ contains: "hyperliquid" },
|
|
61369
|
-
{ contains: "budget exhausted" }
|
|
61370
|
-
] },
|
|
61371
|
-
{ contains: "hyperliquid execution preflight is waiting for its fair public-read turn" },
|
|
61372
|
-
{ contains: "hyperliquid local public request allowance is exhausted" }
|
|
61373
|
-
] } },
|
|
61374
|
-
{ reason_code: "hyperliquid_data_unavailable", when: { any: [
|
|
61375
|
-
{ contains: "fresh private hyperliquid data is unavailable" },
|
|
61376
|
-
{ contains: "private hyperliquid node is stale" },
|
|
61377
|
-
{ contains: "private hyperliquid info circuit is open" },
|
|
61378
|
-
{ contains: "private hyperliquid freshness probe failed" },
|
|
61379
|
-
{ contains: "hyperliquid info endpoint is stale for" },
|
|
61380
|
-
{ contains: "hyperliquid fresh public read returned non-json" },
|
|
61381
|
-
{ contains: "hyperliquid public freshness bracket moved backwards" }
|
|
61382
|
-
] } },
|
|
61383
|
-
{ reason_code: "behavior_state_unavailable", when: { any: [
|
|
61384
|
-
{ all: [
|
|
61385
|
-
{ contains: "your prompt on the ai page contains something vtx can't use" },
|
|
61386
|
-
{ contains: "next scheduled cycle" }
|
|
61387
|
-
] },
|
|
61388
|
-
{ all: [
|
|
61389
|
-
{ contains: "critical behavior context could not be constructed" },
|
|
61390
|
-
{ contains: "next scheduled cycle" }
|
|
61391
|
-
] }
|
|
61392
|
-
] } },
|
|
61393
|
-
{ reason_code: "hyperliquid_wallet_not_authorized", when: { any: [
|
|
61394
|
-
{ contains: "hyperliquid api wallet is not authorized" },
|
|
61395
|
-
{ contains: "hyperliquid signing key is not authorized for this wallet" },
|
|
61396
|
-
{ contains: "hyperliquid has not approved this key for this profile's wallet" }
|
|
61397
|
-
] } },
|
|
61398
|
-
{ reason_code: "ai_service_rate_limit", when: { any: [
|
|
61399
|
-
{ all: [
|
|
61400
|
-
{ contains: "exhausted fallback chain" },
|
|
61401
|
-
{ contains: "(429)" }
|
|
61402
|
-
] },
|
|
61403
|
-
{ contains: "ai provider returned 429" },
|
|
61404
|
-
{ contains: "ai provider and fallback model returned 429" },
|
|
61405
|
-
{ contains: "ai service rate limit (429)" },
|
|
61406
|
-
{ contains: "external ai account has reached its current usage limit" }
|
|
61407
|
-
] } },
|
|
61408
|
-
{ reason_code: "ai_service_unavailable", when: { any: [
|
|
61409
|
-
{ contains: "ai provider returned 503" },
|
|
61410
|
-
{ contains: "ai provider returned 500" },
|
|
61411
|
-
{ contains: "ai provider returned 502" },
|
|
61412
|
-
{ contains: "ai provider returned 504" },
|
|
61413
|
-
{ contains: "ai provider and fallback model returned 503" },
|
|
61414
|
-
{ contains: "service unavailable" },
|
|
61415
|
-
{ contains: "ai service unavailable (503)" },
|
|
61416
|
-
{ contains: "ai provider is temporarily unavailable" },
|
|
61417
|
-
{ contains: "codex reported server overload" },
|
|
61418
|
-
{ contains: "external inference host heartbeat is stale" },
|
|
61419
|
-
{ contains: "external inference host is finishing or recovering outstanding work" },
|
|
61420
|
-
{ contains: "external ai membership is currently available. at least one is cooling down" },
|
|
61421
|
-
{ contains: "external inference current advertisement is stale" },
|
|
61422
|
-
{ predicate: "provider_retry_status" }
|
|
61423
|
-
] } },
|
|
61424
|
-
{ reason_code: "app_bootstrap_unavailable", when: { any: [
|
|
61425
|
-
{ contains: "vtx could not load this profile's runtime settings" },
|
|
61426
|
-
{ contains: "vtx runtime settings temporarily unavailable due to server load" }
|
|
61427
|
-
] } },
|
|
61428
|
-
{ reason_code: "runtime_config_missing", when: { contains: "vtx is missing required runtime configuration" } },
|
|
61429
|
-
{ reason_code: "provider_not_configured", when: { any: [
|
|
61430
|
-
{ contains: "client runtime provider setup error" },
|
|
61431
|
-
{ contains: "is not configured for this profile" },
|
|
61432
|
-
{ contains: "is not account-synced for this profile" }
|
|
61433
|
-
] } },
|
|
61434
|
-
{ reason_code: "provider_unavailable", when: { contains: "client runtime provider error" } },
|
|
61435
|
-
{ reason_code: "browser_cors_failure", when: { any: [
|
|
61436
|
-
{ contains: "the browser blocked the ai provider request" },
|
|
61437
|
-
{ contains: "request was blocked" },
|
|
61438
|
-
{ contains: "failed in browser (network/cors)" }
|
|
61439
|
-
] } },
|
|
61440
|
-
{ reason_code: "market_data_browser_failure", when: { any: [
|
|
61441
|
-
{ contains: "market data did not load" },
|
|
61442
|
-
{ contains: "market data request failed in browser" }
|
|
61443
|
-
] } },
|
|
61444
|
-
{ reason_code: "browser_network_failure", when: { any: [
|
|
61445
|
-
{ contains: "browser could not complete a vtx runtime request" },
|
|
61446
|
-
{ contains: "hyperliquid public request network failure" },
|
|
61447
|
-
{ contains: "a browser network request failed" },
|
|
61448
|
-
{ contains: "browser could not reach the ai provider" },
|
|
61449
|
-
{ contains: "failed in browser (network request failed)" }
|
|
61450
|
-
] } },
|
|
61451
|
-
{ reason_code: "provider_network_failure", when: { contains: "vtx could not reach the ai provider" } },
|
|
61452
|
-
{ reason_code: "runtime_timeout", when: { any: [
|
|
61453
|
-
{ contains: "ai run took too long" },
|
|
61454
|
-
{ contains: "cycle deadline was reached" },
|
|
61455
|
-
{ contains: "this analysis timed out" },
|
|
61456
|
-
{ contains: "hyperliquid request exceeded its total read deadline" }
|
|
61457
|
-
] } },
|
|
61458
|
-
{ reason_code: "snapshot_stale", when: { contains: "decision skipped: account data was" } },
|
|
61459
|
-
{ reason_code: "ai_service_rate_limit", when: { contains: "provider request failed (http 429)" } },
|
|
61460
|
-
{ reason_code: "external_inference_window_missed", when: { any: [
|
|
61461
|
-
{ contains: "external inference host claimed the server prompt but did not dispatch it" },
|
|
61462
|
-
{ contains: "external inference host did not claim the server prompt inside its account-state freshness window" }
|
|
61463
|
-
] } },
|
|
61464
|
-
{ reason_code: "runtime_timeout", when: { contains: "failure code: runtime_timeout" } },
|
|
61465
|
-
{ reason_code: "account_state_changing", when: { contains: "account state is changing while preparing prompt context" } },
|
|
61466
|
-
{ reason_code: "runtime_contract_changed", when: { any: [
|
|
61467
|
-
{ contains: "rejected by contract: contract_identity_mismatch" },
|
|
61468
|
-
{ contains: "rejected by contract: contract_binding_mismatch" }
|
|
61469
|
-
] } },
|
|
61470
|
-
{ reason_code: "decision_persistence_timeout", when: { contains: "could not confirm that its decision was saved before the cycle deadline" } },
|
|
61471
|
-
{ reason_code: "model_unavailable", when: { any: [
|
|
61472
|
-
{ contains: "this model is not available from the selected provider" },
|
|
61473
|
-
{ contains: "model is not available on the selected provider" },
|
|
61474
|
-
{ contains: "client runtime model error" },
|
|
61475
|
-
{ contains: " is not available on " },
|
|
61476
|
-
{ starts_with: "unknown model" }
|
|
61477
|
-
] } }
|
|
61478
|
-
],
|
|
61479
|
-
reason_codes: {
|
|
61480
|
-
account_state_changing: { transient: true, severity: "ERROR" },
|
|
61481
|
-
ai_service_rate_limit: { transient: true, severity: "ERROR" },
|
|
61482
|
-
ai_service_unavailable: { transient: true, severity: "ERROR" },
|
|
61483
|
-
app_bootstrap_unavailable: { transient: true, severity: "ERROR" },
|
|
61484
|
-
behavior_state_unavailable: { transient: true, severity: "WARN" },
|
|
61485
|
-
browser_cors_failure: { transient: true, severity: "ERROR" },
|
|
61486
|
-
browser_network_failure: { transient: true, severity: "ERROR" },
|
|
61487
|
-
credentials_missing: { transient: false, severity: "ERROR" },
|
|
61488
|
-
decision_persistence_timeout: { transient: true, severity: "ERROR" },
|
|
61489
|
-
exchange_rejected: { transient: false, severity: "ERROR" },
|
|
61490
|
-
external_inference_window_missed: { transient: true, severity: "ERROR" },
|
|
61491
|
-
http_request_capacity: { transient: true, severity: "ERROR" },
|
|
61492
|
-
hyperliquid_data_unavailable: { transient: true, severity: "ERROR" },
|
|
61493
|
-
hyperliquid_rate_limit: { transient: true, severity: "ERROR" },
|
|
61494
|
-
hyperliquid_read_budget_exhausted: { transient: true, severity: "WARN" },
|
|
61495
|
-
hyperliquid_request_capacity: { transient: true, severity: "ERROR" },
|
|
61496
|
-
hyperliquid_wallet_not_authorized: { transient: false, severity: "ERROR" },
|
|
61497
|
-
internal_data_error: { transient: false, severity: "ERROR" },
|
|
61498
|
-
internal_execution_error: { transient: false, severity: "ERROR" },
|
|
61499
|
-
live_calendar_unavailable: { transient: true, severity: "ERROR" },
|
|
61500
|
-
live_derived_context_build_failed: { transient: true, severity: "ERROR" },
|
|
61501
|
-
live_derived_context_timeout: { transient: true, severity: "ERROR" },
|
|
61502
|
-
live_market_regime_unavailable: { transient: true, severity: "ERROR" },
|
|
61503
|
-
live_market_stats_unavailable: { transient: true, severity: "ERROR" },
|
|
61504
|
-
live_performance_unavailable: { transient: true, severity: "ERROR" },
|
|
61505
|
-
local_safety_block: { transient: false, severity: "ERROR" },
|
|
61506
|
-
market_data_browser_failure: { transient: true, severity: "ERROR" },
|
|
61507
|
-
model_unavailable: { transient: false, severity: "ERROR" },
|
|
61508
|
-
outcome_unknown: { transient: true, severity: "ERROR" },
|
|
61509
|
-
private_node_stale: { transient: true, severity: "ERROR" },
|
|
61510
|
-
protective_order_not_placed: { transient: false, severity: "WARN" },
|
|
61511
|
-
protective_order_unmanaged: { transient: false, severity: "WARN" },
|
|
61512
|
-
provider_network_failure: { transient: true, severity: "ERROR" },
|
|
61513
|
-
provider_not_configured: { transient: false, severity: "ERROR" },
|
|
61514
|
-
provider_unavailable: { transient: true, severity: "ERROR" },
|
|
61515
|
-
redis_unavailable: { transient: true, severity: "ERROR" },
|
|
61516
|
-
runtime_config_missing: { transient: false, severity: "ERROR" },
|
|
61517
|
-
runtime_contract_changed: { transient: true, severity: "ERROR" },
|
|
61518
|
-
runtime_timeout: { transient: true, severity: "ERROR" },
|
|
61519
|
-
signer_validation_unavailable: { transient: false, severity: "ERROR" },
|
|
61520
|
-
snapshot_stale: { transient: true, severity: "ERROR" },
|
|
61521
|
-
wallet_not_authorized: { transient: false, severity: "ERROR" }
|
|
61522
|
-
}
|
|
61523
|
-
};
|
|
61524
|
-
}
|
|
61525
|
-
});
|
|
61526
|
-
|
|
61527
|
-
// lib/runtime/runtime-error-reason-rules.ts
|
|
61528
|
-
var HISTORY_WRAPPER, runtimeErrorReasonSubject, RULES, matches, matchRuntimeErrorReasonCode;
|
|
61529
|
-
var init_runtime_error_reason_rules2 = __esm({
|
|
61530
|
-
"lib/runtime/runtime-error-reason-rules.ts"() {
|
|
61531
|
-
"use strict";
|
|
61532
|
-
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
61533
|
-
init_define_VTX_EXO_POLICY();
|
|
61534
|
-
init_define_VTX_GROK_POLICY();
|
|
61535
|
-
init_define_VTX_PI_MODEL_POLICY();
|
|
61536
|
-
init_runtime_error_reason_rules();
|
|
61537
|
-
HISTORY_WRAPPER = /^analysis unavailable:\s*(?:\u26a0\ufe0f?\s*)?/iu;
|
|
61538
|
-
runtimeErrorReasonSubject = (normalizedWithoutWarning) => normalizedWithoutWarning.replace(HISTORY_WRAPPER, "").trim();
|
|
61539
|
-
RULES = runtime_error_reason_rules_default;
|
|
61540
|
-
matches = (condition, lowered, texts, predicates) => {
|
|
61541
|
-
if ("equals" in condition) return lowered === condition.equals;
|
|
61542
|
-
if ("starts_with" in condition) return lowered.startsWith(condition.starts_with);
|
|
61543
|
-
if ("contains" in condition) return lowered.includes(condition.contains);
|
|
61544
|
-
if ("all" in condition) return condition.all.every((item) => matches(item, lowered, texts, predicates));
|
|
61545
|
-
if ("any" in condition) return condition.any.some((item) => matches(item, lowered, texts, predicates));
|
|
61546
|
-
return predicates[condition.predicate](...texts);
|
|
61547
|
-
};
|
|
61548
|
-
matchRuntimeErrorReasonCode = (normalized, normalizedWithoutWarning, predicates) => {
|
|
61549
|
-
const subject = runtimeErrorReasonSubject(normalizedWithoutWarning);
|
|
61550
|
-
const lowered = subject.toLowerCase();
|
|
61551
|
-
if (!normalized || RULES.unclassified_messages.includes(lowered)) {
|
|
61552
|
-
return null;
|
|
61553
|
-
}
|
|
61554
|
-
const texts = [normalized, subject];
|
|
61555
|
-
for (const rule of RULES.rules) {
|
|
61556
|
-
if (matches(rule.when, lowered, texts, predicates)) {
|
|
61557
|
-
return rule.reason_code;
|
|
61558
|
-
}
|
|
61559
|
-
}
|
|
61560
|
-
return null;
|
|
61561
|
-
};
|
|
61562
|
-
}
|
|
61563
|
-
});
|
|
61564
|
-
|
|
61565
61955
|
// lib/runtime/signing-key-messages.ts
|
|
61566
61956
|
var SIGNING_KEY_NOT_APPROVED, SIGNING_KEY_INVALID, SIGNING_KEY_THEN_START, SIGNING_KEY_NOT_APPROVED_THEN_START;
|
|
61567
61957
|
var init_signing_key_messages = __esm({
|
|
@@ -61579,7 +61969,7 @@ var init_signing_key_messages = __esm({
|
|
|
61579
61969
|
});
|
|
61580
61970
|
|
|
61581
61971
|
// lib/runtime/error-surface-contract.ts
|
|
61582
|
-
var RUNTIME_SERVICE_UNAVAILABLE_TOKENS, RUNTIME_APP_BOOTSTRAP_UNAVAILABLE_TOKENS, RUNTIME_BROWSER_FETCH_FAILURE_TOKENS, SENSITIVE_DB_TOKENS, SCHEMA_DISCLOSURE_TOKENS, SQL_STATEMENT_PATTERN, TRACEBACK_PATTERN, DB_SESSION_STATE_PATTERNS, RUNTIME_MARKET_DATA_FAILURE_TOKENS, RUNTIME_CYCLE_DEADLINE_TOKENS, RUNTIME_TIMEOUT_TOKENS, RUNTIME_GENERIC_TIMEOUT_MESSAGE, LEGACY_RUNTIME_TIMEOUT_PATTERN, RUNTIME_PROVIDER_NETWORK_FAILURE_TOKENS, RUNTIME_EXPLICIT_CORS_TOKENS, RUNTIME_MODEL_UNAVAILABLE_TOKENS, RUNTIME_REASONING_CONTROL_REJECTION_TOKENS, RUNTIME_CANONICAL_PREFIX_TOKENS, RUNTIME_PROVIDER_RETRY_STATUS_PATTERN, RUNTIME_SERVICE_UNAVAILABLE_STATUSES, RUNTIME_MISSING_CONFIG_PATTERN, DEFAULT_RUNTIME_RETRY_SECONDS, normalizeRuntimeRetrySeconds, hasRuntimeRetrySeconds, runtimeRetryPhrase, applyRuntimeRetrySeconds, RUNTIME_PROVIDER_FAILURE_PATTERN, RUNTIME_HYPERLIQUID_RATE_LIMIT_PATTERN, RUNTIME_HYPERLIQUID_INFO_429_PATTERN, RUNTIME_HYPERLIQUID_REQUEST_TYPE_PATTERN, RUNTIME_HYPERLIQUID_WALLET_NOT_AUTHORIZED_PATTERN, runtimePausePrefix, ensureRuntimeWarningPrefix, stripRuntimeWarningPrefix, isRuntimeAppBootstrapUnavailableError, isSensitiveRuntimeErrorDetail, extractRuntimeProviderError, extractHttpStatusCode, formatHyperliquidRateLimitMessage, providerStatusLabel, PROVIDER_ATTEMPT_SUMMARY_ITEM, PROVIDER_ATTEMPT_SUMMARY_PATTERN, PROVIDER_ATTEMPT_STATUS_PATTERN, isCanonicalProviderAttemptSummary, providerAttemptSummaryStatuses, normalizeRuntimeErrorMessage, RUNTIME_ERROR_REASON_PREDICATES, deriveRuntimeErrorReasonCode, EXECUTION_DISPATCH_RISK_RANK, selectPrimaryExecutionFailure, EXECUTION_ERROR_DEFAULTS, isExecutionErrorReasonCode, RuntimeExecutionError, projectExecutionErrorContract, projectRuntimeErrorSurfaceContract;
|
|
61972
|
+
var RUNTIME_SERVICE_UNAVAILABLE_TOKENS, RUNTIME_APP_BOOTSTRAP_UNAVAILABLE_TOKENS, RUNTIME_BROWSER_FETCH_FAILURE_TOKENS, SENSITIVE_DB_TOKENS, SCHEMA_DISCLOSURE_TOKENS, SQL_STATEMENT_PATTERN, TRACEBACK_PATTERN, DB_SESSION_STATE_PATTERNS, RUNTIME_MARKET_DATA_FAILURE_TOKENS, RUNTIME_CYCLE_DEADLINE_TOKENS, RUNTIME_TIMEOUT_TOKENS, RUNTIME_GENERIC_TIMEOUT_MESSAGE, LEGACY_RUNTIME_TIMEOUT_PATTERN, RUNTIME_PROVIDER_NETWORK_FAILURE_TOKENS, RUNTIME_EXPLICIT_CORS_TOKENS, RUNTIME_MODEL_UNAVAILABLE_TOKENS, RUNTIME_REASONING_CONTROL_REJECTION_TOKENS, RUNTIME_CANONICAL_PREFIX_TOKENS, RUNTIME_PROVIDER_RETRY_STATUS_PATTERN, RUNTIME_SERVICE_UNAVAILABLE_STATUSES, RUNTIME_MISSING_CONFIG_PATTERN, DEFAULT_RUNTIME_RETRY_SECONDS, normalizeRuntimeRetrySeconds, hasRuntimeRetrySeconds, runtimeRetryPhrase, applyRuntimeRetrySeconds, RUNTIME_PROVIDER_FAILURE_PATTERN, RUNTIME_HYPERLIQUID_RATE_LIMIT_PATTERN, RUNTIME_HYPERLIQUID_INFO_429_PATTERN, RUNTIME_HYPERLIQUID_INFO_STATUS_PATTERN, formatHyperliquidReadFailureMessage, RUNTIME_HYPERLIQUID_REQUEST_TYPE_PATTERN, RUNTIME_HYPERLIQUID_WALLET_NOT_AUTHORIZED_PATTERN, runtimePausePrefix, ensureRuntimeWarningPrefix, stripRuntimeWarningPrefix, isRuntimeAppBootstrapUnavailableError, isSensitiveRuntimeErrorDetail, extractRuntimeProviderError, extractHttpStatusCode, formatHyperliquidRateLimitMessage, providerStatusLabel, PROVIDER_ATTEMPT_SUMMARY_ITEM, PROVIDER_ATTEMPT_SUMMARY_PATTERN, PROVIDER_ATTEMPT_STATUS_PATTERN, isCanonicalProviderAttemptSummary, providerAttemptSummaryStatuses, normalizeRuntimeErrorMessage, RUNTIME_ERROR_REASON_PREDICATES, deriveRuntimeErrorReasonCode, EXECUTION_DISPATCH_RISK_RANK, selectPrimaryExecutionFailure, EXECUTION_ERROR_DEFAULTS, isExecutionErrorReasonCode, RuntimeExecutionError, projectExecutionErrorContract, projectRuntimeErrorSurfaceContract;
|
|
61583
61973
|
var init_error_surface_contract = __esm({
|
|
61584
61974
|
"lib/runtime/error-surface-contract.ts"() {
|
|
61585
61975
|
"use strict";
|
|
@@ -61704,7 +62094,11 @@ var init_error_surface_contract = __esm({
|
|
|
61704
62094
|
RUNTIME_CANONICAL_PREFIX_TOKENS = [
|
|
61705
62095
|
"**ai trader paused**:",
|
|
61706
62096
|
"**ai assistant paused**:",
|
|
61707
|
-
"**rate limit**:"
|
|
62097
|
+
"**rate limit**:",
|
|
62098
|
+
// Already plain words (formatHyperliquidReadFailureMessage): a stored row read
|
|
62099
|
+
// back must not be reworded by the provider "503" or wallet rules.
|
|
62100
|
+
"hyperliquid didn't answer vtx's request",
|
|
62101
|
+
"hyperliquid refused vtx's request"
|
|
61708
62102
|
];
|
|
61709
62103
|
RUNTIME_PROVIDER_RETRY_STATUS_PATTERN = /^(ai provider temporarily unavailable(?:\s+\(http\s+(\d{3})(?:\s+[a-z_]+)?\))?|codex reported server overload);\s+retrying automatically(?:\s+in\s+(\d+)s)?$/i;
|
|
61710
62104
|
RUNTIME_SERVICE_UNAVAILABLE_STATUSES = /* @__PURE__ */ new Set([
|
|
@@ -61737,6 +62131,14 @@ var init_error_surface_contract = __esm({
|
|
|
61737
62131
|
RUNTIME_PROVIDER_FAILURE_PATTERN = /^provider request failed(?:\s*\(http\s*(\d{3})[^)]*\))?(?::\s*(.*))?$/i;
|
|
61738
62132
|
RUNTIME_HYPERLIQUID_RATE_LIMIT_PATTERN = /hyperliquid(?:\s+rate\s+limit\s*\(\s*429\s*\)|\s+info\s+request\s+failed\s*\(\s*429\s*\))/i;
|
|
61739
62133
|
RUNTIME_HYPERLIQUID_INFO_429_PATTERN = /hyperliquid\s+info\s+request\s+failed\s*\(\s*429\s*\)(.*)$/i;
|
|
62134
|
+
RUNTIME_HYPERLIQUID_INFO_STATUS_PATTERN = /hyperliquid\s+info\s+request\s+failed\s*\(\s*(\d{3})\s*\)\s*(?:request_type=[A-Za-z0-9_.:-]+\.?)?\s*(.*)$/i;
|
|
62135
|
+
formatHyperliquidReadFailureMessage = (status, detail) => {
|
|
62136
|
+
if (status >= HTTP_SERVER_ERROR_MIN) {
|
|
62137
|
+
return `Hyperliquid didn't answer VTX's request (HTTP ${status}). VTX tries again next cycle.`;
|
|
62138
|
+
}
|
|
62139
|
+
const reason = detail.trim().replace(/\.$/, "");
|
|
62140
|
+
return `Hyperliquid refused VTX's request (HTTP ${status})${reason ? `: ${reason}` : ""}. VTX tries again next cycle.`;
|
|
62141
|
+
};
|
|
61740
62142
|
RUNTIME_HYPERLIQUID_REQUEST_TYPE_PATTERN = /\brequest_type=([A-Za-z0-9_.:-]+)/i;
|
|
61741
62143
|
RUNTIME_HYPERLIQUID_WALLET_NOT_AUTHORIZED_PATTERN = /user\s+or\s+api\s+wallet\s+0x[a-f0-9]{40}\s+does\s+not\s+exist/i;
|
|
61742
62144
|
runtimePausePrefix = (isAssistantActive) => isAssistantActive ? "\u26A0\uFE0F **AI Assistant Paused**" : "\u26A0\uFE0F **AI Trader Paused**";
|
|
@@ -61893,6 +62295,13 @@ var init_error_surface_contract = __esm({
|
|
|
61893
62295
|
if (RUNTIME_HYPERLIQUID_RATE_LIMIT_PATTERN.test(message)) {
|
|
61894
62296
|
return formatHyperliquidRateLimitMessage({ message, pausePrefix, retrySeconds });
|
|
61895
62297
|
}
|
|
62298
|
+
const hyperliquidReadFailure = message.match(RUNTIME_HYPERLIQUID_INFO_STATUS_PATTERN);
|
|
62299
|
+
if (hyperliquidReadFailure) {
|
|
62300
|
+
return ensureRuntimeWarningPrefix(formatHyperliquidReadFailureMessage(
|
|
62301
|
+
Number(hyperliquidReadFailure[1]),
|
|
62302
|
+
hyperliquidReadFailure[2] ?? ""
|
|
62303
|
+
));
|
|
62304
|
+
}
|
|
61896
62305
|
if (RUNTIME_HYPERLIQUID_WALLET_NOT_AUTHORIZED_PATTERN.test(message)) {
|
|
61897
62306
|
return `${pausePrefix}: ${SIGNING_KEY_NOT_APPROVED_THEN_START}`;
|
|
61898
62307
|
}
|
|
@@ -62087,7 +62496,8 @@ var init_error_surface_contract = __esm({
|
|
|
62087
62496
|
isActive = true,
|
|
62088
62497
|
isAssistantActive = false,
|
|
62089
62498
|
retrySeconds = null,
|
|
62090
|
-
errorOrigin = null
|
|
62499
|
+
errorOrigin = null,
|
|
62500
|
+
reasonCode = null
|
|
62091
62501
|
}) => {
|
|
62092
62502
|
const errorMessage = normalizeRuntimeErrorMessage({
|
|
62093
62503
|
error: error48,
|
|
@@ -62095,7 +62505,7 @@ var init_error_surface_contract = __esm({
|
|
|
62095
62505
|
retrySeconds,
|
|
62096
62506
|
errorOrigin
|
|
62097
62507
|
});
|
|
62098
|
-
const errorReasonCode = deriveRuntimeErrorReasonCode({
|
|
62508
|
+
const errorReasonCode = reasonCode ?? deriveRuntimeErrorReasonCode({
|
|
62099
62509
|
error: errorMessage,
|
|
62100
62510
|
isAssistantActive
|
|
62101
62511
|
});
|
|
@@ -72421,20 +72831,20 @@ function check_whole(group, unique) {
|
|
|
72421
72831
|
}
|
|
72422
72832
|
}
|
|
72423
72833
|
function determine_group(unique) {
|
|
72424
|
-
let
|
|
72834
|
+
let groups2 = GROUPS;
|
|
72425
72835
|
for (let cp of unique) {
|
|
72426
|
-
let gs =
|
|
72836
|
+
let gs = groups2.filter((g) => group_has_cp(g, cp));
|
|
72427
72837
|
if (!gs.length) {
|
|
72428
72838
|
if (!GROUPS.some((g) => group_has_cp(g, cp))) {
|
|
72429
72839
|
throw error_disallowed(cp);
|
|
72430
72840
|
} else {
|
|
72431
|
-
throw error_group_member(
|
|
72841
|
+
throw error_group_member(groups2[0], cp);
|
|
72432
72842
|
}
|
|
72433
72843
|
}
|
|
72434
|
-
|
|
72844
|
+
groups2 = gs;
|
|
72435
72845
|
if (gs.length == 1) break;
|
|
72436
72846
|
}
|
|
72437
|
-
return
|
|
72847
|
+
return groups2;
|
|
72438
72848
|
}
|
|
72439
72849
|
function flatten(split3) {
|
|
72440
72850
|
return split3.map(({ input, error: error48, output: output3 }) => {
|
|
@@ -96652,21 +97062,7 @@ async function reportClientRuntimeError(profileId, payload, options) {
|
|
|
96652
97062
|
);
|
|
96653
97063
|
}
|
|
96654
97064
|
async function reportClientRuntimeLifecycleEvent(profileId, payload, options) {
|
|
96655
|
-
return postClientRuntime
|
|
96656
|
-
"/runtime/event",
|
|
96657
|
-
profileId,
|
|
96658
|
-
JSON.stringify({
|
|
96659
|
-
session_id: payload.sessionId ?? null,
|
|
96660
|
-
device_id: payload.deviceId ?? null,
|
|
96661
|
-
...String(payload.schedulerInstanceId ?? "").trim() ? { scheduler_instance_id: String(payload.schedulerInstanceId).trim() } : {},
|
|
96662
|
-
mode: payload.mode ?? null,
|
|
96663
|
-
last_run_at: payload.lastRunAt ?? null,
|
|
96664
|
-
event_type: payload.eventType,
|
|
96665
|
-
detail: payload.detail ?? null,
|
|
96666
|
-
payload: payload.payload ?? null
|
|
96667
|
-
}),
|
|
96668
|
-
options
|
|
96669
|
-
);
|
|
97065
|
+
return reportRuntimeEvent(profileId, payload, options, postClientRuntime);
|
|
96670
97066
|
}
|
|
96671
97067
|
async function reportClientRuntimeTradeSync(profileId, payload, options) {
|
|
96672
97068
|
const extras = {
|
|
@@ -96869,6 +97265,7 @@ var init_api2 = __esm({
|
|
|
96869
97265
|
init_client_runtime_provider_visibility_contract();
|
|
96870
97266
|
init_google_auth_url();
|
|
96871
97267
|
init_network_debug();
|
|
97268
|
+
init_runtime_error_reason_rules2();
|
|
96872
97269
|
init_monotonic_clock();
|
|
96873
97270
|
init_bot_exchanges();
|
|
96874
97271
|
init_local_breadcrumbs();
|
|
@@ -96885,6 +97282,7 @@ var init_api2 = __esm({
|
|
|
96885
97282
|
init_logout();
|
|
96886
97283
|
init_llm_config();
|
|
96887
97284
|
init_llm_config();
|
|
97285
|
+
init_runtime_event_batch();
|
|
96888
97286
|
init_insights_access_center();
|
|
96889
97287
|
init_updates();
|
|
96890
97288
|
init_profile_emoji();
|
|
@@ -97102,10 +97500,11 @@ var init_api2 = __esm({
|
|
|
97102
97500
|
profile_equity_venues_changed: "The bot's markets moved to another venue during this Client Mode cycle. The next cycle measures the new venue."
|
|
97103
97501
|
}[rawMessage.trim()] : void 0;
|
|
97104
97502
|
const message = walletCohortMessage ?? rawMessage;
|
|
97105
|
-
const error48 =
|
|
97106
|
-
|
|
97107
|
-
|
|
97108
|
-
|
|
97503
|
+
const error48 = Object.assign(runtimeRequestFailure(message, response.status, rawMessage === defaultMessage), {
|
|
97504
|
+
status: response.status,
|
|
97505
|
+
detail: payload.detail,
|
|
97506
|
+
modelFallbackSafe: nestedDetail?.model_fallback_safe === true
|
|
97507
|
+
});
|
|
97109
97508
|
const code = typeof payload.code === "string" ? payload.code.trim() : typeof nestedDetail?.code === "string" ? nestedDetail.code.trim() : "";
|
|
97110
97509
|
if (code) {
|
|
97111
97510
|
error48.code = code;
|
|
@@ -97235,7 +97634,7 @@ var init_api2 = __esm({
|
|
|
97235
97634
|
if (!isRetryableClientRuntimeStatus(status)) {
|
|
97236
97635
|
return false;
|
|
97237
97636
|
}
|
|
97238
|
-
if (path === "/runtime/event" || path === "/runtime/server-prompt-rescue") {
|
|
97637
|
+
if (path === "/runtime/event" || path === "/runtime/events" || path === "/runtime/server-prompt-rescue") {
|
|
97239
97638
|
return false;
|
|
97240
97639
|
}
|
|
97241
97640
|
return true;
|
|
@@ -98181,6 +98580,7 @@ var init_vault = __esm({
|
|
|
98181
98580
|
init_define_VTX_PI_MODEL_POLICY();
|
|
98182
98581
|
init_host_storage();
|
|
98183
98582
|
init_runtime_redaction();
|
|
98583
|
+
init_runtime_error_reason_rules2();
|
|
98184
98584
|
init_api2();
|
|
98185
98585
|
init_client_runtime_secret_contract();
|
|
98186
98586
|
init_client_runtime_provider_contract();
|
|
@@ -98192,9 +98592,9 @@ var init_vault = __esm({
|
|
|
98192
98592
|
init_byokProviderRegistry();
|
|
98193
98593
|
init_constants();
|
|
98194
98594
|
CLIENT_VAULT_CHANGED_EVENT = "vtx-client-vault-changed";
|
|
98195
|
-
ClientRuntimeSecretRefreshPendingError = class extends
|
|
98595
|
+
ClientRuntimeSecretRefreshPendingError = class extends RuntimeReasonError {
|
|
98196
98596
|
constructor(retryAfterSeconds) {
|
|
98197
|
-
super("Client provider credentials changed; account refresh is pending.");
|
|
98597
|
+
super("Client provider credentials changed; account refresh is pending.", "provider_credentials_refreshing");
|
|
98198
98598
|
this.code = "client_runtime_secret_refresh_pending";
|
|
98199
98599
|
this.retryAfterSeconds = retryAfterSeconds;
|
|
98200
98600
|
}
|
|
@@ -100132,7 +100532,7 @@ var init_hyperliquid_account_state_adapter = __esm({
|
|
|
100132
100532
|
return withAccountStateEvidence(cached2.result, "stale_if_429", cached2.fetchedAtMs, staleIf429MaxAgeMs);
|
|
100133
100533
|
}
|
|
100134
100534
|
const existingFlight = input.forceRefresh ? void 0 : browserAccountStateInFlight.get(cacheKey);
|
|
100135
|
-
const priority = existingFlight?.priority ?? createHyperliquidPublicPriorityScope(input.publicRequestPriority);
|
|
100535
|
+
const priority = existingFlight?.priority ?? createHyperliquidPublicPriorityScope(input.publicRequestPriority, input.unscheduledRead === true);
|
|
100136
100536
|
promoteHyperliquidPublicPriority(priority, input.publicRequestPriority);
|
|
100137
100537
|
input = { ...input, priorityScope: priority };
|
|
100138
100538
|
let inFlight = existingFlight?.promise;
|
|
@@ -104626,7 +105026,7 @@ var init_runtime_execution = __esm({
|
|
|
104626
105026
|
}
|
|
104627
105027
|
return parsed;
|
|
104628
105028
|
};
|
|
104629
|
-
writeClientProtectiveGroups = (profileId, symbol2,
|
|
105029
|
+
writeClientProtectiveGroups = (profileId, symbol2, groups2) => {
|
|
104630
105030
|
const key = protectiveGroupStorageKey(profileId, symbol2);
|
|
104631
105031
|
const storage3 = resolveClientRuntimeProtectionStorage();
|
|
104632
105032
|
if (!storage3) {
|
|
@@ -104635,7 +105035,7 @@ var init_runtime_execution = __esm({
|
|
|
104635
105035
|
return false;
|
|
104636
105036
|
}
|
|
104637
105037
|
try {
|
|
104638
|
-
if (
|
|
105038
|
+
if (groups2.length === 0) {
|
|
104639
105039
|
storage3.removeItem(key);
|
|
104640
105040
|
const removed = storage3.getItem(key) === null;
|
|
104641
105041
|
if (removed) {
|
|
@@ -104644,11 +105044,11 @@ var init_runtime_execution = __esm({
|
|
|
104644
105044
|
}
|
|
104645
105045
|
return removed;
|
|
104646
105046
|
} else {
|
|
104647
|
-
const serialized = JSON.stringify(
|
|
105047
|
+
const serialized = JSON.stringify(groups2);
|
|
104648
105048
|
storage3.setItem(key, serialized);
|
|
104649
105049
|
const persisted = storage3.getItem(key) === serialized;
|
|
104650
105050
|
if (persisted) {
|
|
104651
|
-
protectiveGroupMemory.set(key,
|
|
105051
|
+
protectiveGroupMemory.set(key, groups2);
|
|
104652
105052
|
protectiveGroupReadFailures.delete(key);
|
|
104653
105053
|
}
|
|
104654
105054
|
return persisted;
|
|
@@ -104692,25 +105092,25 @@ var init_runtime_execution = __esm({
|
|
|
104692
105092
|
}
|
|
104693
105093
|
}
|
|
104694
105094
|
});
|
|
104695
|
-
exactClientProtectiveGroupSetSnapshot = (
|
|
105095
|
+
exactClientProtectiveGroupSetSnapshot = (groups2) => stableProtectionSnapshot(groups2.map((group) => exactClientProtectiveGroupSnapshot(group)));
|
|
104696
105096
|
storableClientProtectiveGroup = (group) => group != null && group.legs.length === 0 && group.pendingEntry == null ? null : group;
|
|
104697
105097
|
replaceExactClientProtectiveGroup = (profileId, symbol2, expected, candidateReplacement) => {
|
|
104698
105098
|
const replacement = storableClientProtectiveGroup(candidateReplacement);
|
|
104699
|
-
const
|
|
105099
|
+
const groups2 = readFreshClientProtectiveGroups(profileId, symbol2);
|
|
104700
105100
|
if (hasClientProtectiveGroupReadFailure(profileId, symbol2)) return false;
|
|
104701
105101
|
const expectedSnapshot = exactClientProtectiveGroupSnapshot(expected);
|
|
104702
105102
|
const matches2 = (candidate) => exactClientProtectiveGroupSnapshot(candidate) === expectedSnapshot;
|
|
104703
|
-
if (
|
|
105103
|
+
if (groups2.filter(matches2).length !== 1) return false;
|
|
104704
105104
|
return writeClientProtectiveGroups(
|
|
104705
105105
|
profileId,
|
|
104706
105106
|
symbol2,
|
|
104707
|
-
|
|
105107
|
+
groups2.flatMap((candidate) => matches2(candidate) ? replacement == null ? [] : [replacement] : [candidate])
|
|
104708
105108
|
);
|
|
104709
105109
|
};
|
|
104710
105110
|
replaceExactClientProtectiveGroupSet = (profileId, symbol2, expected, replacement) => {
|
|
104711
|
-
const
|
|
105111
|
+
const groups2 = readFreshClientProtectiveGroups(profileId, symbol2);
|
|
104712
105112
|
if (hasClientProtectiveGroupReadFailure(profileId, symbol2)) return false;
|
|
104713
|
-
if (exactClientProtectiveGroupSetSnapshot(
|
|
105113
|
+
if (exactClientProtectiveGroupSetSnapshot(groups2) !== exactClientProtectiveGroupSetSnapshot(expected)) return false;
|
|
104714
105114
|
return writeClientProtectiveGroups(profileId, symbol2, replacement);
|
|
104715
105115
|
};
|
|
104716
105116
|
isClientRuntimeLeaseOwnershipError = (error48) => {
|
|
@@ -104741,12 +105141,12 @@ var init_runtime_execution = __esm({
|
|
|
104741
105141
|
if (provisionalSnapshot !== input.provisionalGroupSnapshot || restoredSnapshot !== input.restoredGroupSnapshot || provisionalGroup.profileId !== profileId || restoredGroup.profileId !== profileId || provisionalGroup.symbol !== symbol2.toUpperCase() || restoredGroup.symbol !== symbol2.toUpperCase() || provisionalGroup.entryOrderId !== input.provisionalEntryOrderId || restoredGroup.entryOrderId !== input.pendingEntryOrderId || provisionalGroup.walletAddress !== input.walletAddress || restoredGroup.walletAddress !== input.walletAddress || provisionalGroup.isLong !== input.isLong || restoredGroup.isLong !== input.isLong || !Array.isArray(provisionalGroup.legs) || !Array.isArray(restoredGroup.legs) || stableProtectionSnapshot(provisionalGroup.pendingEntry) !== stableProtectionSnapshot(input.pendingEntry) || stableProtectionSnapshot(restoredGroup.pendingEntry) !== stableProtectionSnapshot(input.pendingEntry) || provisionalGroup.legs.map((leg) => String(leg.orderId)).sort().join(",") !== [...input.provisionalClientOrderIds].sort().join(",")) {
|
|
104742
105142
|
return false;
|
|
104743
105143
|
}
|
|
104744
|
-
const
|
|
105144
|
+
const groups3 = readFreshClientProtectiveGroups(profileId, symbol2);
|
|
104745
105145
|
if (hasClientProtectiveGroupReadFailure(profileId, symbol2)) return false;
|
|
104746
105146
|
const matchesProvisional = (group) => exactClientProtectiveGroupSnapshot(group) === provisionalSnapshot;
|
|
104747
105147
|
const matchesRestored = (group) => exactClientProtectiveGroupSnapshot(group) === restoredSnapshot;
|
|
104748
|
-
const provisionalGroups =
|
|
104749
|
-
const restoredGroups =
|
|
105148
|
+
const provisionalGroups = groups3.filter(matchesProvisional);
|
|
105149
|
+
const restoredGroups = groups3.filter(matchesRestored);
|
|
104750
105150
|
if (provisionalGroups.length === 0 && restoredGroups.length === 1) {
|
|
104751
105151
|
windowHandoffCleanupAttempts.delete(cleanupAttemptKey);
|
|
104752
105152
|
return true;
|
|
@@ -104795,27 +105195,27 @@ var init_runtime_execution = __esm({
|
|
|
104795
105195
|
replacement
|
|
104796
105196
|
});
|
|
104797
105197
|
if (reservedSourceSnapshot !== input.reservedSourceGroupSnapshot || restoredSourceSnapshot !== input.restoredSourceGroupSnapshot || journalSnapshot !== input.journalGroupSnapshot || exactClientProtectiveGroupSnapshot(expectedRestoredGroup) !== restoredSourceSnapshot || exactClientProtectiveGroupSnapshot(expectedJournalGroup) !== journalSnapshot || reservedSourceGroup.profileId !== profileId || restoredSourceGroup.profileId !== profileId || journalGroup.profileId !== profileId || reservedSourceGroup.symbol !== symbol2.toUpperCase() || restoredSourceGroup.symbol !== symbol2.toUpperCase() || journalGroup.symbol !== symbol2.toUpperCase() || replacement.previousOrderId !== input.previousOrderId || replacement.mutationId !== input.mutationId) return false;
|
|
104798
|
-
const
|
|
105198
|
+
const groups3 = readFreshClientProtectiveGroups(profileId, symbol2);
|
|
104799
105199
|
if (hasClientProtectiveGroupReadFailure(profileId, symbol2)) return false;
|
|
104800
|
-
const reservedSourceMatches =
|
|
104801
|
-
const journalEntryMatches =
|
|
105200
|
+
const reservedSourceMatches = groups3.filter((group) => exactClientProtectiveGroupSnapshot(group) === reservedSourceSnapshot);
|
|
105201
|
+
const journalEntryMatches = groups3.filter((group) => group.entryOrderId === journalGroup.entryOrderId);
|
|
104802
105202
|
const exactJournalMatches = journalEntryMatches.filter((group) => exactClientProtectiveGroupSnapshot(group) === journalSnapshot);
|
|
104803
|
-
const conflictingMutationOwners =
|
|
104804
|
-
const sourceEntryMatches =
|
|
105203
|
+
const conflictingMutationOwners = groups3.flatMap((group) => group.legs.filter((leg) => leg.replacement?.mutationId === input.mutationId && exactClientProtectiveGroupSnapshot(group) !== reservedSourceSnapshot));
|
|
105204
|
+
const sourceEntryMatches = groups3.filter((group) => group.entryOrderId === reservedSourceGroup.entryOrderId);
|
|
104805
105205
|
if (reservedSourceMatches.length > 1 || journalEntryMatches.length !== exactJournalMatches.length || exactJournalMatches.length > 1 || conflictingMutationOwners.length > 0 || sourceEntryMatches.length > 1) return false;
|
|
104806
105206
|
if (reservedSourceMatches.length === 0 && exactJournalMatches.length === 0) {
|
|
104807
105207
|
return true;
|
|
104808
105208
|
}
|
|
104809
|
-
const nextGroups =
|
|
105209
|
+
const nextGroups = groups3.flatMap((group) => {
|
|
104810
105210
|
const snapshot = exactClientProtectiveGroupSnapshot(group);
|
|
104811
105211
|
if (snapshot === reservedSourceSnapshot) return [restoredSourceGroup];
|
|
104812
105212
|
if (snapshot === journalSnapshot) return [];
|
|
104813
105213
|
return [group];
|
|
104814
105214
|
});
|
|
104815
|
-
return replaceExactClientProtectiveGroupSet(profileId, symbol2,
|
|
105215
|
+
return replaceExactClientProtectiveGroupSet(profileId, symbol2, groups3, nextGroups);
|
|
104816
105216
|
}
|
|
104817
105217
|
const entryOrderId = String(input.entryOrderId).trim();
|
|
104818
|
-
const
|
|
105218
|
+
const groups2 = readFreshClientProtectiveGroups(profileId, symbol2);
|
|
104819
105219
|
if (hasClientProtectiveGroupReadFailure(profileId, symbol2)) {
|
|
104820
105220
|
return false;
|
|
104821
105221
|
}
|
|
@@ -104830,7 +105230,7 @@ var init_runtime_execution = __esm({
|
|
|
104830
105230
|
return false;
|
|
104831
105231
|
}
|
|
104832
105232
|
const matchingSnapshot = exactClientProtectiveGroupSnapshot(pendingGroup);
|
|
104833
|
-
const exactMatches =
|
|
105233
|
+
const exactMatches = groups2.filter((group) => exactClientProtectiveGroupSnapshot(group) === matchingSnapshot);
|
|
104834
105234
|
if (exactMatches.length === 0) {
|
|
104835
105235
|
windowHandoffCleanupAttempts.delete(cleanupAttemptKey);
|
|
104836
105236
|
return true;
|
|
@@ -104840,15 +105240,15 @@ var init_runtime_execution = __esm({
|
|
|
104840
105240
|
const persisted2 = replaceExactClientProtectiveGroupSet(
|
|
104841
105241
|
profileId,
|
|
104842
105242
|
symbol2,
|
|
104843
|
-
|
|
104844
|
-
|
|
105243
|
+
groups2,
|
|
105244
|
+
groups2.filter((group) => exactClientProtectiveGroupSnapshot(group) !== matchingSnapshot)
|
|
104845
105245
|
);
|
|
104846
105246
|
if (persisted2) {
|
|
104847
105247
|
windowHandoffCleanupAttempts.delete(cleanupAttemptKey);
|
|
104848
105248
|
}
|
|
104849
105249
|
return persisted2;
|
|
104850
105250
|
}
|
|
104851
|
-
const matchingGroups =
|
|
105251
|
+
const matchingGroups = groups2.filter((group) => group.entryOrderId === entryOrderId);
|
|
104852
105252
|
if (matchingGroups.length === 0 && windowHandoffCleanupAttempts.has(cleanupAttemptKey)) {
|
|
104853
105253
|
windowHandoffCleanupAttempts.delete(cleanupAttemptKey);
|
|
104854
105254
|
return true;
|
|
@@ -104911,9 +105311,9 @@ var init_runtime_execution = __esm({
|
|
|
104911
105311
|
);
|
|
104912
105312
|
};
|
|
104913
105313
|
replaceProtectiveLeg = (profileId, symbol2, previousOrderId, replacement) => {
|
|
104914
|
-
const
|
|
105314
|
+
const groups2 = readFreshClientProtectiveGroups(profileId, symbol2);
|
|
104915
105315
|
if (hasClientProtectiveGroupReadFailure(profileId, symbol2)) return false;
|
|
104916
|
-
const matches2 =
|
|
105316
|
+
const matches2 = groups2.flatMap((group2) => group2.legs.some((leg) => leg.orderId === previousOrderId) ? [group2] : []);
|
|
104917
105317
|
if (matches2.length !== 1) return false;
|
|
104918
105318
|
const [group] = matches2;
|
|
104919
105319
|
if (group.legs.filter((leg) => leg.orderId === previousOrderId).length !== 1) return false;
|
|
@@ -104981,25 +105381,25 @@ var init_runtime_execution = __esm({
|
|
|
104981
105381
|
};
|
|
104982
105382
|
};
|
|
104983
105383
|
ensureProtectiveReplacementJournalCompanion = (input) => {
|
|
104984
|
-
const
|
|
105384
|
+
const groups2 = readFreshClientProtectiveGroups(input.profileId, input.symbol);
|
|
104985
105385
|
if (hasClientProtectiveGroupReadFailure(input.profileId, input.symbol)) return null;
|
|
104986
105386
|
const sourceSnapshot = exactClientProtectiveGroupSnapshot(input.sourceGroup);
|
|
104987
|
-
const sourceMatches =
|
|
105387
|
+
const sourceMatches = groups2.filter((group) => exactClientProtectiveGroupSnapshot(group) === sourceSnapshot);
|
|
104988
105388
|
const sourceLegSnapshot = stableProtectionSnapshot(input.sourceLeg);
|
|
104989
|
-
if (sourceMatches.length !== 1 || sourceMatches[0].legs.filter((leg) => stableProtectionSnapshot(leg) === sourceLegSnapshot).length !== 1 || stableProtectionSnapshot(input.sourceLeg.replacement) !== stableProtectionSnapshot(input.replacement) ||
|
|
105389
|
+
if (sourceMatches.length !== 1 || sourceMatches[0].legs.filter((leg) => stableProtectionSnapshot(leg) === sourceLegSnapshot).length !== 1 || stableProtectionSnapshot(input.sourceLeg.replacement) !== stableProtectionSnapshot(input.replacement) || groups2.flatMap((group) => group.legs.filter((leg) => leg.replacement?.mutationId === input.replacement.mutationId)).length !== 1) return null;
|
|
104990
105390
|
const journalGroup = buildProtectiveReplacementJournalGroup({
|
|
104991
105391
|
sourceGroup: input.sourceGroup,
|
|
104992
105392
|
sourceLeg: { ...input.sourceLeg, replacement: void 0 },
|
|
104993
105393
|
replacement: input.replacement
|
|
104994
105394
|
});
|
|
104995
105395
|
const journalSnapshot = exactClientProtectiveGroupSnapshot(journalGroup);
|
|
104996
|
-
const journalEntryMatches =
|
|
105396
|
+
const journalEntryMatches = groups2.filter((group) => group.entryOrderId === journalGroup.entryOrderId);
|
|
104997
105397
|
if (journalEntryMatches.length > 1 || journalEntryMatches.length === 1 && exactClientProtectiveGroupSnapshot(journalEntryMatches[0]) !== journalSnapshot) return null;
|
|
104998
|
-
const nextGroups = journalEntryMatches.length === 1 ?
|
|
105398
|
+
const nextGroups = journalEntryMatches.length === 1 ? groups2 : [...groups2, journalGroup];
|
|
104999
105399
|
if (!replaceExactClientProtectiveGroupSet(
|
|
105000
105400
|
input.profileId,
|
|
105001
105401
|
input.symbol,
|
|
105002
|
-
|
|
105402
|
+
groups2,
|
|
105003
105403
|
nextGroups
|
|
105004
105404
|
)) return null;
|
|
105005
105405
|
return {
|
|
@@ -105034,12 +105434,12 @@ var init_runtime_execution = __esm({
|
|
|
105034
105434
|
input.reservation.groups
|
|
105035
105435
|
);
|
|
105036
105436
|
transitionProtectiveReplacementAcknowledgement = (input) => {
|
|
105037
|
-
const
|
|
105437
|
+
const groups2 = readFreshClientProtectiveGroups(input.profileId, input.symbol);
|
|
105038
105438
|
if (hasClientProtectiveGroupReadFailure(input.profileId, input.symbol)) return null;
|
|
105039
105439
|
const sourceSnapshot = exactClientProtectiveGroupSnapshot(input.reservation.sourceGroup);
|
|
105040
105440
|
const journalSnapshot = exactClientProtectiveGroupSnapshot(input.reservation.journalGroup);
|
|
105041
|
-
const sourceMatches =
|
|
105042
|
-
const journalMatches =
|
|
105441
|
+
const sourceMatches = groups2.filter((group) => exactClientProtectiveGroupSnapshot(group) === sourceSnapshot);
|
|
105442
|
+
const journalMatches = groups2.filter((group) => exactClientProtectiveGroupSnapshot(group) === journalSnapshot);
|
|
105043
105443
|
if (journalMatches.length !== 1) return null;
|
|
105044
105444
|
const canonicalLeg = {
|
|
105045
105445
|
...input.replacementLeg ?? input.reservation.sourceLeg,
|
|
@@ -105054,7 +105454,7 @@ var init_runtime_execution = __esm({
|
|
|
105054
105454
|
...input.state === "fulfilled" ? { cleanupRequired: true } : {},
|
|
105055
105455
|
legs: input.reservation.sourceGroup.legs.map((leg) => stableProtectionSnapshot(leg) === stableProtectionSnapshot(input.reservation.sourceLeg) ? canonicalLeg : leg)
|
|
105056
105456
|
};
|
|
105057
|
-
const nextGroups2 =
|
|
105457
|
+
const nextGroups2 = groups2.flatMap((group) => {
|
|
105058
105458
|
const snapshot = exactClientProtectiveGroupSnapshot(group);
|
|
105059
105459
|
if (snapshot === sourceSnapshot) return [sourceGroup];
|
|
105060
105460
|
if (snapshot === journalSnapshot) return [];
|
|
@@ -105063,7 +105463,7 @@ var init_runtime_execution = __esm({
|
|
|
105063
105463
|
return replaceExactClientProtectiveGroupSet(
|
|
105064
105464
|
input.profileId,
|
|
105065
105465
|
input.symbol,
|
|
105066
|
-
|
|
105466
|
+
groups2,
|
|
105067
105467
|
nextGroups2
|
|
105068
105468
|
) ? { kind: "source_bound", groups: nextGroups2 } : null;
|
|
105069
105469
|
}
|
|
@@ -105071,27 +105471,27 @@ var init_runtime_execution = __esm({
|
|
|
105071
105471
|
...input.reservation.journalGroup,
|
|
105072
105472
|
legs: [canonicalLeg]
|
|
105073
105473
|
};
|
|
105074
|
-
const nextGroups =
|
|
105474
|
+
const nextGroups = groups2.map((group) => exactClientProtectiveGroupSnapshot(group) === journalSnapshot ? cleanupJournal : group);
|
|
105075
105475
|
return replaceExactClientProtectiveGroupSet(
|
|
105076
105476
|
input.profileId,
|
|
105077
105477
|
input.symbol,
|
|
105078
|
-
|
|
105478
|
+
groups2,
|
|
105079
105479
|
nextGroups
|
|
105080
105480
|
) ? { kind: "cleanup_retained", groups: nextGroups } : null;
|
|
105081
105481
|
};
|
|
105082
105482
|
transitionTerminalProtectiveReplacement = (input) => {
|
|
105083
|
-
const
|
|
105483
|
+
const groups2 = readFreshClientProtectiveGroups(input.profileId, input.symbol);
|
|
105084
105484
|
if (hasClientProtectiveGroupReadFailure(input.profileId, input.symbol)) return false;
|
|
105085
105485
|
const sourceSnapshot = exactClientProtectiveGroupSnapshot(input.sourceGroup);
|
|
105086
105486
|
const journalSnapshot = input.journalGroup == null ? null : exactClientProtectiveGroupSnapshot(input.journalGroup);
|
|
105087
|
-
if (
|
|
105088
|
-
if (journalSnapshot != null &&
|
|
105487
|
+
if (groups2.filter((group) => exactClientProtectiveGroupSnapshot(group) === sourceSnapshot).length !== 1) return false;
|
|
105488
|
+
if (journalSnapshot != null && groups2.filter((group) => exactClientProtectiveGroupSnapshot(group) === journalSnapshot).length !== 1) return false;
|
|
105089
105489
|
const clearedLeg = { ...input.sourceLeg, replacement: void 0 };
|
|
105090
105490
|
const clearedGroup = {
|
|
105091
105491
|
...input.sourceGroup,
|
|
105092
105492
|
legs: input.sourceGroup.legs.map((leg) => stableProtectionSnapshot(leg) === stableProtectionSnapshot(input.sourceLeg) ? clearedLeg : leg)
|
|
105093
105493
|
};
|
|
105094
|
-
const nextGroups =
|
|
105494
|
+
const nextGroups = groups2.flatMap((group) => {
|
|
105095
105495
|
const snapshot = exactClientProtectiveGroupSnapshot(group);
|
|
105096
105496
|
if (snapshot === sourceSnapshot) return [clearedGroup];
|
|
105097
105497
|
if (journalSnapshot != null && snapshot === journalSnapshot) return [];
|
|
@@ -105100,7 +105500,7 @@ var init_runtime_execution = __esm({
|
|
|
105100
105500
|
return replaceExactClientProtectiveGroupSet(
|
|
105101
105501
|
input.profileId,
|
|
105102
105502
|
input.symbol,
|
|
105103
|
-
|
|
105503
|
+
groups2,
|
|
105104
105504
|
nextGroups
|
|
105105
105505
|
);
|
|
105106
105506
|
};
|
|
@@ -105162,12 +105562,12 @@ var init_runtime_execution = __esm({
|
|
|
105162
105562
|
const symbol2 = request.executionContext.symbol;
|
|
105163
105563
|
try {
|
|
105164
105564
|
const profileId = String(request.profileId).trim();
|
|
105165
|
-
const
|
|
105565
|
+
const groups2 = readFreshClientProtectiveGroups(profileId, symbol2);
|
|
105166
105566
|
if (hasClientProtectiveGroupReadFailure(profileId, symbol2)) {
|
|
105167
105567
|
throw new Error("Protective cleanup authority could not be read durably.");
|
|
105168
105568
|
}
|
|
105169
|
-
const exactOwnerGroups =
|
|
105170
|
-
const acknowledgedOwnerMatches = exactOwnerGroups.length === 0 && acknowledgedAuthority != null ?
|
|
105569
|
+
const exactOwnerGroups = groups2.filter((group) => group.isLong === isLong && group.legs.some((candidate) => String(candidate.orderId) === String(leg.orderId)));
|
|
105570
|
+
const acknowledgedOwnerMatches = exactOwnerGroups.length === 0 && acknowledgedAuthority != null ? groups2.flatMap((group) => group.isLong === isLong ? group.legs.flatMap((candidate, legIndex) => {
|
|
105171
105571
|
if (String(candidate.orderId) !== String(acknowledgedAuthority.persistedOrderId)) {
|
|
105172
105572
|
return [];
|
|
105173
105573
|
}
|
|
@@ -105190,7 +105590,7 @@ var init_runtime_execution = __esm({
|
|
|
105190
105590
|
throw new Error("Acknowledged protective cleanup authority could not be bound durably.");
|
|
105191
105591
|
}
|
|
105192
105592
|
}
|
|
105193
|
-
const journalOwnerGroups = exactOwnerGroups.length === 0 && acknowledgedOwnerGroup == null ?
|
|
105593
|
+
const journalOwnerGroups = exactOwnerGroups.length === 0 && acknowledgedOwnerGroup == null ? groups2.filter((group) => group.isLong === isLong && group.cleanupRequired === true && group.attachmentJournal != null && group.legs.some((candidate) => candidate.kind === leg.kind && candidate.size === leg.size && candidate.triggerPrice === leg.triggerPrice && candidate.positionTpsl === true === (leg.positionTpsl === true))) : [];
|
|
105194
105594
|
const ownerGroups = exactOwnerGroups.length > 0 ? exactOwnerGroups : acknowledgedOwnerGroup != null ? [acknowledgedOwnerGroup] : journalOwnerGroups;
|
|
105195
105595
|
if (ownerGroups.length !== 1) {
|
|
105196
105596
|
throw new Error("Protective cleanup authority is not exact.");
|
|
@@ -105351,8 +105751,8 @@ var init_runtime_execution = __esm({
|
|
|
105351
105751
|
return { group, cleanup, persistedGroupSet: persistenceFailed ? null : nextGroups };
|
|
105352
105752
|
};
|
|
105353
105753
|
attachmentMemberNeverLanded = (group, leg) => group.attachmentJournal?.members.some((member) => member.clientOrderId === leg.orderId && member.neverLandedAtMs != null) === true;
|
|
105354
|
-
storedClientProtectiveCover = async (request, entryIsLong,
|
|
105355
|
-
const storedLegs =
|
|
105754
|
+
storedClientProtectiveCover = async (request, entryIsLong, groups2) => {
|
|
105755
|
+
const storedLegs = groups2.filter((group) => group.isLong === entryIsLong).flatMap((group) => group.legs.map((leg) => ({
|
|
105356
105756
|
isLong: group.isLong,
|
|
105357
105757
|
kind: leg.kind,
|
|
105358
105758
|
size: leg.size,
|
|
@@ -107041,11 +107441,11 @@ var init_runtime_execution = __esm({
|
|
|
107041
107441
|
}
|
|
107042
107442
|
return reports;
|
|
107043
107443
|
};
|
|
107044
|
-
recoverPendingProtectiveReplacements = async (request,
|
|
107444
|
+
recoverPendingProtectiveReplacements = async (request, groups2) => {
|
|
107045
107445
|
const reports = [];
|
|
107046
107446
|
const profileId = String(request.profileId).trim();
|
|
107047
107447
|
const symbol2 = request.executionContext.symbol;
|
|
107048
|
-
for (const group of
|
|
107448
|
+
for (const group of groups2) {
|
|
107049
107449
|
for (const leg of group.legs) {
|
|
107050
107450
|
const replacement = leg.replacement;
|
|
107051
107451
|
if (!replacement) continue;
|
|
@@ -107444,7 +107844,7 @@ var init_runtime_execution = __esm({
|
|
|
107444
107844
|
}
|
|
107445
107845
|
}
|
|
107446
107846
|
}
|
|
107447
|
-
for (const journalGroup of
|
|
107847
|
+
for (const journalGroup of groups2.filter(isProtectiveReplacementJournalGroup)) {
|
|
107448
107848
|
const mutationId = journalGroup.entryOrderId.slice("replacement-journal:".length);
|
|
107449
107849
|
const currentGroups = readFreshClientProtectiveGroups(profileId, symbol2);
|
|
107450
107850
|
if (hasClientProtectiveGroupReadFailure(profileId, symbol2)) {
|
|
@@ -107864,8 +108264,8 @@ var init_runtime_execution = __esm({
|
|
|
107864
108264
|
expectedGroupSet = expectedGroupSet.flatMap((candidate) => exactClientProtectiveGroupSnapshot(candidate) === expectedSnapshot ? replacement == null ? [] : [replacement] : [candidate]);
|
|
107865
108265
|
return true;
|
|
107866
108266
|
};
|
|
107867
|
-
const
|
|
107868
|
-
if (
|
|
108267
|
+
const groups2 = reconciliationGroupSet.filter((group) => group.pendingEntry == null && group.legs.length > 0 && !isProtectiveReplacementJournalGroup(group));
|
|
108268
|
+
if (groups2.length === 0) {
|
|
107869
108269
|
return reports;
|
|
107870
108270
|
}
|
|
107871
108271
|
let livePositionSize = Number(knownPositionSize);
|
|
@@ -107880,7 +108280,7 @@ var init_runtime_execution = __esm({
|
|
|
107880
108280
|
);
|
|
107881
108281
|
livePositionSize = Number(snapshot.size);
|
|
107882
108282
|
} catch (error48) {
|
|
107883
|
-
return
|
|
108283
|
+
return groups2.flatMap((group) => group.legs.map((leg) => ({
|
|
107884
108284
|
order_id: String(leg.orderId),
|
|
107885
108285
|
symbol: symbol2,
|
|
107886
108286
|
action: protectiveAction(leg),
|
|
@@ -107903,7 +108303,7 @@ var init_runtime_execution = __esm({
|
|
|
107903
108303
|
}
|
|
107904
108304
|
liveOrders = fetchedOrders;
|
|
107905
108305
|
} catch (error48) {
|
|
107906
|
-
return
|
|
108306
|
+
return groups2.flatMap((group) => group.legs.map((leg) => ({
|
|
107907
108307
|
order_id: String(leg.orderId),
|
|
107908
108308
|
symbol: symbol2,
|
|
107909
108309
|
action: protectiveAction(leg),
|
|
@@ -107964,7 +108364,7 @@ var init_runtime_execution = __esm({
|
|
|
107964
108364
|
};
|
|
107965
108365
|
const inspectedGroups = [];
|
|
107966
108366
|
const legsLiveSinceMs = protectiveReadStampMs();
|
|
107967
|
-
for (const observedGroup of
|
|
108367
|
+
for (const observedGroup of groups2) {
|
|
107968
108368
|
let group = observedGroup;
|
|
107969
108369
|
const standaloneGroup = observedStandaloneProtectiveGroup(group, liveOrders, symbol2);
|
|
107970
108370
|
if (standaloneGroup != null) {
|
|
@@ -108943,7 +109343,7 @@ var init_runtime_execution = __esm({
|
|
|
108943
109343
|
cancelAllClientProtectiveGroups = async (request, reasonCode) => {
|
|
108944
109344
|
const profileId = String(request.profileId).trim();
|
|
108945
109345
|
const symbol2 = request.executionContext.symbol;
|
|
108946
|
-
const
|
|
109346
|
+
const groups2 = readFreshClientProtectiveGroups(profileId, symbol2);
|
|
108947
109347
|
const reports = [];
|
|
108948
109348
|
if (hasClientProtectiveGroupReadFailure(profileId, symbol2)) {
|
|
108949
109349
|
return [{
|
|
@@ -108956,9 +109356,9 @@ var init_runtime_execution = __esm({
|
|
|
108956
109356
|
}
|
|
108957
109357
|
}];
|
|
108958
109358
|
}
|
|
108959
|
-
let expectedGroups =
|
|
109359
|
+
let expectedGroups = groups2;
|
|
108960
109360
|
const retainedGroups = [];
|
|
108961
|
-
for (const group of
|
|
109361
|
+
for (const group of groups2) {
|
|
108962
109362
|
if (group.pendingEntry != null || group.attachmentJournal != null || isProtectiveReplacementJournalGroup(group)) {
|
|
108963
109363
|
retainedGroups.push(group);
|
|
108964
109364
|
reports.push({
|
|
@@ -110000,12 +110400,12 @@ var init_runtime_execution = __esm({
|
|
|
110000
110400
|
const maxAge = Number(context.executionFreshnessMaxAgeSeconds) * MS_PER_SECOND;
|
|
110001
110401
|
const age = Date.now() - capturedAt;
|
|
110002
110402
|
if (!context.tpSlEnabled || context.stopLossEnabled === false || context.stopLossType !== "trailing" || !Number.isFinite(age) || age < 0 || !Number.isFinite(maxAge) || maxAge <= 0 || age > maxAge || !Number.isFinite(context.currentPositionSize) || context.currentPositionSize === 0 || !Number.isFinite(context.lastPrice) || context.lastPrice <= 0) return [];
|
|
110003
|
-
const
|
|
110004
|
-
if (hasClientProtectiveGroupReadFailure(String(request.profileId).trim(), context.symbol) ||
|
|
110005
|
-
if (!
|
|
110403
|
+
const groups2 = readFreshClientProtectiveGroups(String(request.profileId).trim(), context.symbol);
|
|
110404
|
+
if (hasClientProtectiveGroupReadFailure(String(request.profileId).trim(), context.symbol) || groups2.some((group) => group.walletAddress !== String(context.walletAddress ?? "").trim().toLowerCase() || group.pendingEntry || group.attachmentJournal || group.cleanupRequired || group.legs.some((leg) => leg.replacement))) return [];
|
|
110405
|
+
if (!groups2.some((group) => group.legs.some((leg) => leg.isTrailing && typeof leg.orderId === "number"))) return [];
|
|
110006
110406
|
const assetSizeDecimals = await resolveExchangeSizeDecimals(context.symbol, request.config ?? void 0, "trading_reduce");
|
|
110007
110407
|
const isLong = context.currentPositionSize > 0;
|
|
110008
|
-
const improves =
|
|
110408
|
+
const improves = groups2.some((group) => group.isLong === isLong && group.legs.some((leg) => {
|
|
110009
110409
|
if (!leg.isTrailing || typeof leg.orderId !== "number") return false;
|
|
110010
110410
|
const size = roundAssetSize(Math.min(leg.size, Math.abs(context.currentPositionSize)), assetSizeDecimals);
|
|
110011
110411
|
if (!(size > 0)) return false;
|
|
@@ -110069,20 +110469,20 @@ var init_runtime_execution = __esm({
|
|
|
110069
110469
|
}
|
|
110070
110470
|
return [...symbols].sort();
|
|
110071
110471
|
};
|
|
110072
|
-
hasUnresolvedClientProtectiveIdentity = (
|
|
110472
|
+
hasUnresolvedClientProtectiveIdentity = (groups2) => groups2.some((group) => isProtectiveReplacementJournalGroup(group) || group.legs.some((leg) => leg.replacement != null));
|
|
110073
110473
|
resolveClientProtectiveIdentitiesForAdoption = async (input) => {
|
|
110074
110474
|
const profileId = String(input.profileId ?? "").trim();
|
|
110075
110475
|
const walletAddress = String(input.walletAddress ?? "").trim();
|
|
110076
110476
|
const reports = [];
|
|
110077
110477
|
const deferred = [];
|
|
110078
|
-
const ownGroups = (
|
|
110478
|
+
const ownGroups = (groups2) => groups2.filter((group) => group.walletAddress === walletAddress.toLowerCase());
|
|
110079
110479
|
for (const symbol2 of listStoredClientProtectiveSymbols(profileId)) {
|
|
110080
|
-
const
|
|
110480
|
+
const groups2 = ownGroups(readFreshClientProtectiveGroups(profileId, symbol2));
|
|
110081
110481
|
if (hasClientProtectiveGroupReadFailure(profileId, symbol2)) {
|
|
110082
110482
|
deferred.push({ symbol: symbol2, reasonCode: "protective_lifecycle_storage_invalid" });
|
|
110083
110483
|
continue;
|
|
110084
110484
|
}
|
|
110085
|
-
if (!hasUnresolvedClientProtectiveIdentity(
|
|
110485
|
+
if (!hasUnresolvedClientProtectiveIdentity(groups2)) continue;
|
|
110086
110486
|
let symbolReports = [];
|
|
110087
110487
|
try {
|
|
110088
110488
|
const sizeDecimals = await resolveExchangeSizeDecimals(symbol2, input.config, "trading_reconcile");
|
|
@@ -110102,7 +110502,7 @@ var init_runtime_execution = __esm({
|
|
|
110102
110502
|
runtimeDeviceId: authority.runtimeDeviceId,
|
|
110103
110503
|
schedulerInstanceId: authority.schedulerInstanceId
|
|
110104
110504
|
} : { ...core, mutationAuthority: "manual_session" },
|
|
110105
|
-
|
|
110505
|
+
groups2
|
|
110106
110506
|
);
|
|
110107
110507
|
} catch (error48) {
|
|
110108
110508
|
if (isClientRuntimeLeaseOwnershipError(error48)) throw error48;
|
|
@@ -110134,12 +110534,12 @@ var init_runtime_execution = __esm({
|
|
|
110134
110534
|
exportClientProtectiveGroupsForAdoption = (profileId, walletAddress) => {
|
|
110135
110535
|
const normalizedProfileId = String(profileId ?? "").trim();
|
|
110136
110536
|
const normalizedWallet = String(walletAddress ?? "").trim().toLowerCase();
|
|
110137
|
-
const
|
|
110537
|
+
const groups2 = [];
|
|
110138
110538
|
for (const symbol2 of listStoredClientProtectiveSymbols(normalizedProfileId)) {
|
|
110139
110539
|
for (const group of readClientProtectiveGroups(normalizedProfileId, symbol2)) {
|
|
110140
110540
|
if (group.walletAddress !== normalizedWallet) continue;
|
|
110141
110541
|
const journal = group.attachmentJournal;
|
|
110142
|
-
|
|
110542
|
+
groups2.push({
|
|
110143
110543
|
entry_mutation_id: group.pendingEntry?.entryMutationId ?? null,
|
|
110144
110544
|
symbol: group.symbol,
|
|
110145
110545
|
is_long: group.isLong,
|
|
@@ -110176,10 +110576,10 @@ var init_runtime_execution = __esm({
|
|
|
110176
110576
|
});
|
|
110177
110577
|
}
|
|
110178
110578
|
}
|
|
110179
|
-
return
|
|
110579
|
+
return groups2;
|
|
110180
110580
|
};
|
|
110181
110581
|
adoptionGroupKey = (group) => `${group.symbol}|${group.entry_order_id ?? ""}|${group.entry_mutation_id ?? ""}`;
|
|
110182
|
-
applyClientProtectiveAdoptionOutcomes = (profileId, walletAddress,
|
|
110582
|
+
applyClientProtectiveAdoptionOutcomes = (profileId, walletAddress, groups2, legOutcomes) => {
|
|
110183
110583
|
const normalizedProfileId = String(profileId ?? "").trim();
|
|
110184
110584
|
const normalizedWallet = String(walletAddress ?? "").trim().toLowerCase();
|
|
110185
110585
|
const application = {
|
|
@@ -110197,7 +110597,7 @@ var init_runtime_execution = __esm({
|
|
|
110197
110597
|
}
|
|
110198
110598
|
const dispositions = /* @__PURE__ */ new Map();
|
|
110199
110599
|
const exportedDroppedOrderIds = /* @__PURE__ */ new Set();
|
|
110200
|
-
|
|
110600
|
+
groups2.forEach((group, groupIndex) => {
|
|
110201
110601
|
const dropped = droppedLegIndexes.get(groupIndex) ?? /* @__PURE__ */ new Set();
|
|
110202
110602
|
const disposition = { retainedKinds: /* @__PURE__ */ new Set(), droppedKinds: /* @__PURE__ */ new Set() };
|
|
110203
110603
|
group.legs.forEach((leg, legIndex) => {
|
|
@@ -110288,8 +110688,8 @@ var init_runtime_execution = __esm({
|
|
|
110288
110688
|
const normalizedWallet = String(walletAddress ?? "").trim().toLowerCase();
|
|
110289
110689
|
if (!normalizedWallet) return false;
|
|
110290
110690
|
return listStoredClientProtectiveSymbols(normalizedProfileId).some((symbol2) => {
|
|
110291
|
-
const
|
|
110292
|
-
return hasClientProtectiveGroupReadFailure(normalizedProfileId, symbol2) ||
|
|
110691
|
+
const groups2 = readClientProtectiveGroups(normalizedProfileId, symbol2);
|
|
110692
|
+
return hasClientProtectiveGroupReadFailure(normalizedProfileId, symbol2) || groups2.some((group) => group.walletAddress === normalizedWallet);
|
|
110293
110693
|
});
|
|
110294
110694
|
};
|
|
110295
110695
|
hasPendingClientProtectiveGroups = (profileId) => listPendingClientProtectiveSymbols(String(profileId ?? "").trim()).length > 0;
|
|
@@ -110302,7 +110702,7 @@ var init_runtime_execution = __esm({
|
|
|
110302
110702
|
throwIfAborted2(input.signal);
|
|
110303
110703
|
const retired = [];
|
|
110304
110704
|
const reports = await withClientProtectivePlanSetMutation({ profileId, signal: input.signal }, symbol2, async () => {
|
|
110305
|
-
const
|
|
110705
|
+
const groups2 = readFreshClientProtectiveGroups(profileId, symbol2);
|
|
110306
110706
|
if (hasClientProtectiveGroupReadFailure(profileId, symbol2)) {
|
|
110307
110707
|
return [{
|
|
110308
110708
|
order_id: null,
|
|
@@ -110312,7 +110712,7 @@ var init_runtime_execution = __esm({
|
|
|
110312
110712
|
execution_metadata: { reason_code: "protective_lifecycle_storage_invalid" }
|
|
110313
110713
|
}];
|
|
110314
110714
|
}
|
|
110315
|
-
const ownGroups =
|
|
110715
|
+
const ownGroups = groups2.filter((group) => group.pendingEntry != null && group.walletAddress === walletAddress.toLowerCase());
|
|
110316
110716
|
if (ownGroups.length === 0) return [];
|
|
110317
110717
|
input.beforeRead?.();
|
|
110318
110718
|
const sizeDecimals = await resolveExchangeSizeDecimals(symbol2, input.config, "trading_reconcile");
|
|
@@ -112553,12 +112953,12 @@ var init_protective_cutover = __esm({
|
|
|
112553
112953
|
}
|
|
112554
112954
|
}
|
|
112555
112955
|
};
|
|
112556
|
-
adoptionLegOutcomes = (
|
|
112956
|
+
adoptionLegOutcomes = (groups2, adoption) => {
|
|
112557
112957
|
if (Array.isArray(adoption.leg_outcomes)) return adoption.leg_outcomes;
|
|
112558
112958
|
const groupOutcomes = new Map(
|
|
112559
112959
|
(adoption.group_outcomes ?? []).map((item) => [item.group_index, item.outcome])
|
|
112560
112960
|
);
|
|
112561
|
-
return
|
|
112961
|
+
return groups2.flatMap((group, groupIndex) => group.legs.map((leg, legIndex) => ({
|
|
112562
112962
|
group_index: groupIndex,
|
|
112563
112963
|
leg_index: legIndex,
|
|
112564
112964
|
leg_kind: leg.kind === "sl" ? "stop_loss" : leg.kind === "tp" ? "take_profit" : null,
|
|
@@ -112622,9 +113022,9 @@ var init_protective_cutover = __esm({
|
|
|
112622
113022
|
});
|
|
112623
113023
|
return null;
|
|
112624
113024
|
}
|
|
112625
|
-
const
|
|
113025
|
+
const groups2 = exportClientProtectiveGroupsForAdoption(input.profileId, input.walletAddress);
|
|
112626
113026
|
const reportedProtectiveOrderIds = [
|
|
112627
|
-
...new Set(
|
|
113027
|
+
...new Set(groups2.flatMap((group) => group.legs.map((leg) => String(leg.order_id ?? "").trim()).filter(Boolean)))
|
|
112628
113028
|
];
|
|
112629
113029
|
let openOrders;
|
|
112630
113030
|
try {
|
|
@@ -112635,7 +113035,7 @@ var init_protective_cutover = __esm({
|
|
|
112635
113035
|
signal: input.signal,
|
|
112636
113036
|
hyperliquidApiUrl: listedEvidence.hyperliquidApiUrl
|
|
112637
113037
|
},
|
|
112638
|
-
|
|
113038
|
+
groups2.map((group) => getHyperliquidMarketDex(normalizeHyperliquidMarketSymbol(group.symbol)))
|
|
112639
113039
|
);
|
|
112640
113040
|
} catch {
|
|
112641
113041
|
appendRuntimeDebugEvent({
|
|
@@ -112651,7 +113051,7 @@ var init_protective_cutover = __esm({
|
|
|
112651
113051
|
answer = await adoptWithinTimeout(
|
|
112652
113052
|
input.profileId,
|
|
112653
113053
|
{
|
|
112654
|
-
groups,
|
|
113054
|
+
groups: groups2,
|
|
112655
113055
|
reportedProtectiveOrderIds,
|
|
112656
113056
|
walletAddress: input.walletAddress,
|
|
112657
113057
|
openOrders: openOrdersEvidenceForUpload(openOrders)
|
|
@@ -112673,8 +113073,8 @@ var init_protective_cutover = __esm({
|
|
|
112673
113073
|
const { retainedLegs } = applyClientProtectiveAdoptionOutcomes(
|
|
112674
113074
|
input.profileId,
|
|
112675
113075
|
input.walletAddress,
|
|
112676
|
-
|
|
112677
|
-
adoptionLegOutcomes(
|
|
113076
|
+
groups2,
|
|
113077
|
+
adoptionLegOutcomes(groups2, answer)
|
|
112678
113078
|
);
|
|
112679
113079
|
if (retainedLegs > 0) {
|
|
112680
113080
|
adoptionRetryAt.set(
|
|
@@ -112833,8 +113233,8 @@ var init_provider_observability = __esm({
|
|
|
112833
113233
|
const characters = Array.from(value);
|
|
112834
113234
|
if (characters.length <= PROVIDER_DIAGNOSTIC_LIMITS.MAX_ERROR_MESSAGE_CHARS) return value;
|
|
112835
113235
|
let cut = characters.slice(0, PROVIDER_DIAGNOSTIC_LIMITS.MAX_ERROR_MESSAGE_CHARS).join("");
|
|
112836
|
-
const
|
|
112837
|
-
if (
|
|
113236
|
+
const marker2 = cut.lastIndexOf(REDACTED_MARKER_START);
|
|
113237
|
+
if (marker2 !== -1 && value.indexOf("]", marker2) >= cut.length) cut = cut.slice(0, marker2);
|
|
112838
113238
|
return cut.replace(/ +$/, "");
|
|
112839
113239
|
};
|
|
112840
113240
|
normalizeProviderError = (value) => {
|
|
@@ -116210,6 +116610,27 @@ var init_portfolio_evidence = __esm({
|
|
|
116210
116610
|
}
|
|
116211
116611
|
});
|
|
116212
116612
|
|
|
116613
|
+
// lib/runtime/host-wake-schedule.ts
|
|
116614
|
+
var marker, markBatchableTimer, markDeferrableTimer;
|
|
116615
|
+
var init_host_wake_schedule = __esm({
|
|
116616
|
+
"lib/runtime/host-wake-schedule.ts"() {
|
|
116617
|
+
"use strict";
|
|
116618
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
116619
|
+
init_define_VTX_EXO_POLICY();
|
|
116620
|
+
init_define_VTX_GROK_POLICY();
|
|
116621
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
116622
|
+
marker = null;
|
|
116623
|
+
markBatchableTimer = (handle) => {
|
|
116624
|
+
marker?.(handle, "batchable");
|
|
116625
|
+
return handle;
|
|
116626
|
+
};
|
|
116627
|
+
markDeferrableTimer = (handle) => {
|
|
116628
|
+
marker?.(handle, "deferrable");
|
|
116629
|
+
return handle;
|
|
116630
|
+
};
|
|
116631
|
+
}
|
|
116632
|
+
});
|
|
116633
|
+
|
|
116213
116634
|
// lib/runtime/sl-tp-execution-settings.ts
|
|
116214
116635
|
var hasOwn, defaultConfigKey, resolveSetting, resolveBooleanSetting, resolveFiniteNumberSetting, resolveEnumSetting, RISK_MODES, STOP_LOSS_TYPES, buildRuntimeSlTpExecutionSettings;
|
|
116215
116636
|
var init_sl_tp_execution_settings = __esm({
|
|
@@ -116466,9 +116887,9 @@ var init_prompt_variable_validation_contract = __esm({
|
|
|
116466
116887
|
const addedLengths = [];
|
|
116467
116888
|
let added = 0;
|
|
116468
116889
|
for (const pair of template.matchAll(ESCAPED_BRACE_PAIR_PATTERN)) {
|
|
116469
|
-
const
|
|
116890
|
+
const marker2 = pair[0] === "{{" ? ESCAPED_OPEN_BRACE : ESCAPED_CLOSE_BRACE;
|
|
116470
116891
|
markerStarts.push(pair.index + added);
|
|
116471
|
-
added +=
|
|
116892
|
+
added += marker2.length - pair[0].length;
|
|
116472
116893
|
markerEnds.push(pair.index + pair[0].length + added);
|
|
116473
116894
|
addedLengths.push(added);
|
|
116474
116895
|
}
|
|
@@ -118280,7 +118701,7 @@ var init_native_request_parameters = __esm({
|
|
|
118280
118701
|
});
|
|
118281
118702
|
|
|
118282
118703
|
// lib/runtime/provider-client.ts
|
|
118283
|
-
var mapOpenAiCompatibleNativeRequestPath, isRetryableProviderFailureForFallback, extractRuntimeProviderFailureStatusCode, isModelSpecificProviderFailure, emptyProviderContentError, isEmptyProviderContentFailure, emptyReplyForInternalAttempt, isEmptyProviderMessageFailure, isRetryableProviderAttemptFailure, providerRejectedRequestError, OPTIONAL_CONTRACT_PARAMETER_TOKENS, OPTIONAL_CONTRACT_REJECTION_TOKENS, OPTIONAL_CONTRACT_GRAMMAR_TOKENS, isOptionalContractParameterRejection, OPTIONAL_CONTRACT_REQUEST_KEYS, OPTIONAL_CONTRACT_EXTRA_BODY_KEYS, resolveEmptyContentRetryPolicy, isKeySpecificOrTransientProviderFailure, providerDispatchClockMs, beginProviderDispatch, providerDispatchLatencyMs, attachProviderDispatchFailure, attachProviderFailureTrace, toRuntimeExecutionMode, buildNoneReasoningPayload, normalizeLevelValue, buildRuntimeReasoningPayload, resolveProviderReasoningParameters, requestedReasoningParameters, usesReasoningCompletionTokens, shouldRequestReasoningTrace, normalizeProviderToken, runtimeProviderForByokProvider, findByokProviderForRuntime, findNativeRequestParametersForModel, modelHasNativeRequestApiSurface, asRequestRecord, setDottedRequestValue, normalizeProviderMaxTokens, applyRuntimeRequestContract, normalizeProvider2, requireProviderEndpoint, SSE_DATA_FIELD_PREFIX2, estimateTokenCount, normalizeUsageCount, buildOpenAiUsagePayload, buildAnthropicUsagePayload, buildGoogleUsagePayload, normalizeProviderUsageMetrics, providerResponseSignals, fetchProvider, readProviderPayload, emitRuntimeDelta, readProviderTextStream, extractOpenAiCompatibleDeltaText, readOpenAiCompatibleTextStream, rawProviderTextForDebug, extractProviderErrorDetail, buildCanonicalProviderFailureMessage, toProviderNetworkDebugError, REASONING_ONLY_CONTENT_TYPES, extractOpenAiContentPartText, extractOpenAiReasoningPartText, extractOpenAiMessageContent, extractOpenAiMessageReasoningContent, extractOpenAiCompatibleText, normalizeRuntimeChatHistory, calculateProviderCost, callOpenAiCompatible, extractOpenAiResponsesText, extractOpenAiResponsesReasoning, callOpenAiResponses, extractAnthropicMessageText, extractAnthropicReasoningContent, callAnthropic, isAqGoogleKey, googleKeySurfaces, googleKeySurfaceProbes, probeGoogleKeySurface, resolveGoogleKeySurface, forgetGoogleKeySurfaceAfterAuthorizationFailure, googlePublicModelIdRegexes, shouldUseGooglePublicEndpointForModel, normalizeGoogleModelId, shouldRetryGoogleVertexRequestPublicly, GOOGLE_VERTEX_PUBLIC_RETRY_NOTE, buildGoogleRequest, isGoogleReasoningPart, extractGoogleMessageText, extractGoogleReasoningContent, extractGoogleSafetyMetadata, GOOGLE_BLOCKED_FINISH_REASONS, googleProviderBlockReason, callGoogle, resolveRuntimeProvider, defaultInvocationContext, defaultProviderTransport, invocationFailureCode, buildBrowserInvocation, resolveProviderSecretKey, resolveNativeProviderCredentialSlots, resolveProviderSecretKeySlots, requireOpenAiCompatibleRuntimeBaseUrl, runtimeSubscriptionPlan, runtimeKeySlotSupportsModel, invokeRuntimeProviderAttempt, invokeRuntimeProvider;
|
|
118704
|
+
var mapOpenAiCompatibleNativeRequestPath, isRetryableProviderFailureForFallback, extractRuntimeProviderFailureStatusCode, isModelSpecificProviderFailure, emptyProviderContentError, isEmptyProviderContentFailure, emptyReplyForInternalAttempt, isEmptyProviderMessageFailure, isRetryableProviderAttemptFailure, providerRejectedRequestError, OPTIONAL_CONTRACT_PARAMETER_TOKENS, OPTIONAL_CONTRACT_REJECTION_TOKENS, OPTIONAL_CONTRACT_GRAMMAR_TOKENS, isOptionalContractParameterRejection, OPTIONAL_CONTRACT_REQUEST_KEYS, OPTIONAL_CONTRACT_EXTRA_BODY_KEYS, resolveEmptyContentRetryPolicy, isKeySpecificOrTransientProviderFailure, providerDispatchClockMs, beginProviderDispatch, providerDispatchLatencyMs, attachProviderDispatchFailure, attachProviderFailureTrace, toRuntimeExecutionMode, buildNoneReasoningPayload, normalizeLevelValue, buildRuntimeReasoningPayload, resolveProviderReasoningParameters, requestedReasoningParameters, usesReasoningCompletionTokens, shouldRequestReasoningTrace, normalizeProviderToken, runtimeProviderForByokProvider, findByokProviderForRuntime, findNativeRequestParametersForModel, modelHasNativeRequestApiSurface, asRequestRecord, setDottedRequestValue, normalizeProviderMaxTokens, applyRuntimeRequestContract, normalizeProvider2, requireProviderEndpoint, SSE_DATA_FIELD_PREFIX2, estimateTokenCount, normalizeUsageCount, buildOpenAiUsagePayload, buildAnthropicUsagePayload, buildGoogleUsagePayload, normalizeProviderUsageMetrics, providerResponseSignals, fetchProvider, readProviderPayload, emitRuntimeDelta, readProviderTextStream, extractOpenAiCompatibleDeltaText, readOpenAiCompatibleTextStream, rawProviderTextForDebug, extractProviderErrorDetail, buildCanonicalProviderFailureMessage, toProviderNetworkDebugError, REASONING_ONLY_CONTENT_TYPES, extractOpenAiContentPartText, extractOpenAiReasoningPartText, extractOpenAiMessageContent, extractOpenAiMessageReasoningContent, extractOpenAiCompatibleText, normalizeRuntimeChatHistory, calculateProviderCost, callOpenAiCompatible, extractOpenAiResponsesText, extractOpenAiResponsesReasoning, callOpenAiResponses, extractAnthropicMessageText, extractAnthropicReasoningContent, callAnthropic, isAqGoogleKey, googleKeySurfaces, googleKeySurfaceProbes, probeGoogleKeySurface, resolveGoogleKeySurface, forgetGoogleKeySurfaceAfterAuthorizationFailure, googlePublicModelIdRegexes, shouldUseGooglePublicEndpointForModel, normalizeGoogleModelId, shouldRetryGoogleVertexRequestPublicly, GOOGLE_VERTEX_PUBLIC_RETRY_NOTE, buildGoogleRequest, GOOGLE_JSON_MODE_REFUSAL_PHRASES, googleTradeResponseMimeType, providerRequestFailure, isGoogleJsonModeRefusal, isGoogleReasoningPart, extractGoogleMessageText, extractGoogleReasoningContent, extractGoogleSafetyMetadata, GOOGLE_BLOCKED_FINISH_REASONS, googleProviderBlockReason, callGoogle, resolveRuntimeProvider, defaultInvocationContext, defaultProviderTransport, invocationFailureCode, buildBrowserInvocation, resolveProviderSecretKey, resolveNativeProviderCredentialSlots, resolveProviderSecretKeySlots, requireOpenAiCompatibleRuntimeBaseUrl, runtimeSubscriptionPlan, runtimeKeySlotSupportsModel, invokeRuntimeProviderAttempt, invokeRuntimeProvider;
|
|
118284
118705
|
var init_provider_client = __esm({
|
|
118285
118706
|
"lib/runtime/provider-client.ts"() {
|
|
118286
118707
|
"use strict";
|
|
@@ -118401,27 +118822,27 @@ var init_provider_client = __esm({
|
|
|
118401
118822
|
startedAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
118402
118823
|
startedAtMs: providerDispatchClockMs()
|
|
118403
118824
|
});
|
|
118404
|
-
providerDispatchLatencyMs = (
|
|
118405
|
-
attachProviderDispatchFailure = (error48,
|
|
118825
|
+
providerDispatchLatencyMs = (marker2) => Math.max(0, providerDispatchClockMs() - marker2.startedAtMs);
|
|
118826
|
+
attachProviderDispatchFailure = (error48, marker2, response = null) => {
|
|
118406
118827
|
const sanitizedError = toSanitizedRuntimeError(error48);
|
|
118407
118828
|
if (error48 instanceof NativeModelTimeoutError) {
|
|
118408
118829
|
sanitizedError.runtimeNativeFailureKind = "timeout";
|
|
118409
|
-
} else if (
|
|
118830
|
+
} else if (marker2 && error48 instanceof TypeError && /failed to fetch|fetch failed|networkerror|load failed/i.test(error48.message)) {
|
|
118410
118831
|
sanitizedError.runtimeNativeFailureKind = "transport";
|
|
118411
118832
|
}
|
|
118412
118833
|
sanitizedError.runtimeProviderStatusCode = response?.status ?? null;
|
|
118413
118834
|
sanitizedError.runtimeProviderRequestId = providerRequestId(response);
|
|
118414
118835
|
sanitizedError.runtimeProviderDiagnostics = {
|
|
118415
|
-
...
|
|
118836
|
+
...marker2?.providerDiagnostics ?? {},
|
|
118416
118837
|
...error48 instanceof NativeModelTimeoutError && error48.attemptCapExpired ? { timeout_bound: "attempt_cap" } : {}
|
|
118417
118838
|
};
|
|
118418
|
-
if (
|
|
118419
|
-
sanitizedError.runtimeRequestInputTokens =
|
|
118420
|
-
if (
|
|
118421
|
-
sanitizedError.runtimeSentReasoningParameters =
|
|
118422
|
-
sanitizedError.runtimeEffectiveReasoningParameters =
|
|
118423
|
-
sanitizedError.runtimeDispatchStartedAt =
|
|
118424
|
-
sanitizedError.runtimeDispatchLatencyMs = providerDispatchLatencyMs(
|
|
118839
|
+
if (marker2?.googleQuotaFailure) sanitizedError.runtimeGoogleQuotaFailure = true;
|
|
118840
|
+
sanitizedError.runtimeRequestInputTokens = marker2?.requestInputTokens ?? null;
|
|
118841
|
+
if (marker2) {
|
|
118842
|
+
sanitizedError.runtimeSentReasoningParameters = marker2.sentReasoningParameters;
|
|
118843
|
+
sanitizedError.runtimeEffectiveReasoningParameters = marker2.effectiveReasoningParameters;
|
|
118844
|
+
sanitizedError.runtimeDispatchStartedAt = marker2.startedAt;
|
|
118845
|
+
sanitizedError.runtimeDispatchLatencyMs = providerDispatchLatencyMs(marker2);
|
|
118425
118846
|
}
|
|
118426
118847
|
return sanitizedError;
|
|
118427
118848
|
};
|
|
@@ -119508,8 +119929,8 @@ var init_provider_client = __esm({
|
|
|
119508
119929
|
const dispatch = async (body) => {
|
|
119509
119930
|
if (body !== finalRequestBody) trace.attachRequest({ url: requestUrl2, method: "POST", headers: requestHeaders, body });
|
|
119510
119931
|
response = null;
|
|
119511
|
-
const
|
|
119512
|
-
dispatchMarker =
|
|
119932
|
+
const marker2 = beginProviderDispatch(body);
|
|
119933
|
+
dispatchMarker = marker2;
|
|
119513
119934
|
const dispatched = useRelay ? await relayNativeProviderRequest(provider, String(apiKey || "").trim(), body, {
|
|
119514
119935
|
profileId: profileId == null ? void 0 : Number(profileId),
|
|
119515
119936
|
signal,
|
|
@@ -119523,7 +119944,7 @@ var init_provider_client = __esm({
|
|
|
119523
119944
|
});
|
|
119524
119945
|
response = dispatched;
|
|
119525
119946
|
const payload = typeof onDelta === "function" ? await readOpenAiCompatibleTextStream(dispatched, runtimeMode, onDelta, (rawPayload) => {
|
|
119526
|
-
Object.assign(
|
|
119947
|
+
Object.assign(marker2.effectiveReasoningParameters, extractProviderReasoningParameters(rawPayload));
|
|
119527
119948
|
}).then(({ payload: streamPayload, rawText }) => {
|
|
119528
119949
|
trace.attachResponse({
|
|
119529
119950
|
status: dispatched.status,
|
|
@@ -119533,7 +119954,7 @@ var init_provider_client = __esm({
|
|
|
119533
119954
|
});
|
|
119534
119955
|
return streamPayload;
|
|
119535
119956
|
}) : await extractOpenAiCompatibleText(dispatched, runtimeMode, (payloadJson, rawText) => {
|
|
119536
|
-
|
|
119957
|
+
marker2.effectiveReasoningParameters = extractProviderReasoningParameters(payloadJson);
|
|
119537
119958
|
trace.attachResponse({
|
|
119538
119959
|
status: dispatched.status,
|
|
119539
119960
|
statusText: dispatched.statusText ?? "",
|
|
@@ -119543,13 +119964,13 @@ var init_provider_client = __esm({
|
|
|
119543
119964
|
});
|
|
119544
119965
|
return {
|
|
119545
119966
|
...payload,
|
|
119546
|
-
sentReasoningParameters:
|
|
119547
|
-
effectiveReasoningParameters:
|
|
119548
|
-
requestInputTokens:
|
|
119549
|
-
providerDiagnostics:
|
|
119967
|
+
sentReasoningParameters: marker2.sentReasoningParameters,
|
|
119968
|
+
effectiveReasoningParameters: marker2.effectiveReasoningParameters,
|
|
119969
|
+
requestInputTokens: marker2.requestInputTokens,
|
|
119970
|
+
providerDiagnostics: marker2.providerDiagnostics,
|
|
119550
119971
|
providerStatusCode: dispatched.status,
|
|
119551
|
-
dispatchStartedAt:
|
|
119552
|
-
dispatchLatencyMs: providerDispatchLatencyMs(
|
|
119972
|
+
dispatchStartedAt: marker2.startedAt,
|
|
119973
|
+
dispatchLatencyMs: providerDispatchLatencyMs(marker2)
|
|
119553
119974
|
};
|
|
119554
119975
|
};
|
|
119555
119976
|
const attemptDispatch = async (body) => {
|
|
@@ -119727,7 +120148,7 @@ var init_provider_client = __esm({
|
|
|
119727
120148
|
});
|
|
119728
120149
|
if (!response.ok) {
|
|
119729
120150
|
const detail = extractProviderErrorDetail(payload, rawText) || "OpenAI Responses request failed";
|
|
119730
|
-
throw
|
|
120151
|
+
throw providerRequestFailure({ response, detail, runtimeMode });
|
|
119731
120152
|
}
|
|
119732
120153
|
const text = extractOpenAiResponsesText(payload);
|
|
119733
120154
|
if (!text) {
|
|
@@ -119874,7 +120295,7 @@ var init_provider_client = __esm({
|
|
|
119874
120295
|
});
|
|
119875
120296
|
if (!response.ok) {
|
|
119876
120297
|
const detail = extractProviderErrorDetail(payload, rawText) || "Anthropic request failed";
|
|
119877
|
-
throw
|
|
120298
|
+
throw providerRequestFailure({ response, detail, runtimeMode });
|
|
119878
120299
|
}
|
|
119879
120300
|
const text = extractAnthropicMessageText(payload);
|
|
119880
120301
|
if (!text) {
|
|
@@ -119987,7 +120408,7 @@ var init_provider_client = __esm({
|
|
|
119987
120408
|
return detail.includes("publisher model") || detail.includes("was not found") || detail.includes("does not have access");
|
|
119988
120409
|
};
|
|
119989
120410
|
GOOGLE_VERTEX_PUBLIC_RETRY_NOTE = "Google Vertex Express could not access this publisher model, so VTX retried the request through the public Gemini endpoint.";
|
|
119990
|
-
buildGoogleRequest = (apiKey, config2, model, systemPrompt, userPrompt, extraMessages, temperature, maxTokens, vertexExpress) => {
|
|
120411
|
+
buildGoogleRequest = (apiKey, config2, model, systemPrompt, userPrompt, extraMessages, temperature, maxTokens, vertexExpress, responseMimeType) => {
|
|
119991
120412
|
const modelId = normalizeGoogleModelId(model, vertexExpress);
|
|
119992
120413
|
const template = vertexExpress ? requireProviderEndpoint(config2, "google_vertex_express_generate_content_url_template") : requireProviderEndpoint(config2, "google_public_generate_content_url_template");
|
|
119993
120414
|
const url2 = template.replace("{model_id}", modelId);
|
|
@@ -119998,6 +120419,9 @@ var init_provider_client = __esm({
|
|
|
119998
120419
|
if (resolvedMaxTokens !== null) {
|
|
119999
120420
|
generationConfig.maxOutputTokens = resolvedMaxTokens;
|
|
120000
120421
|
}
|
|
120422
|
+
if (responseMimeType) {
|
|
120423
|
+
generationConfig.responseMimeType = responseMimeType;
|
|
120424
|
+
}
|
|
120001
120425
|
const payload = vertexExpress ? {
|
|
120002
120426
|
systemInstruction: { parts: [{ text: systemPrompt }] },
|
|
120003
120427
|
contents: [
|
|
@@ -120021,6 +120445,18 @@ var init_provider_client = __esm({
|
|
|
120021
120445
|
};
|
|
120022
120446
|
return { requestUrl: requestUrl2, payload };
|
|
120023
120447
|
};
|
|
120448
|
+
GOOGLE_JSON_MODE_REFUSAL_PHRASES = ["json mode", "response_mime_type", "responsemimetype", "response mime type"];
|
|
120449
|
+
googleTradeResponseMimeType = (config2, model, context) => {
|
|
120450
|
+
const contract = config2.google_trade_request_contract;
|
|
120451
|
+
if (!contract || context.use_case !== "trader") return null;
|
|
120452
|
+
const modelId = model.trim().replace(/^models\//, "");
|
|
120453
|
+
return contract.json_mode_model_id_regexes.some((pattern) => new RegExp(pattern).test(modelId)) ? contract.response_mime_type : null;
|
|
120454
|
+
};
|
|
120455
|
+
providerRequestFailure = (input) => new Error(buildCanonicalProviderFailureMessage(input));
|
|
120456
|
+
isGoogleJsonModeRefusal = (status, detail) => {
|
|
120457
|
+
const lowered = detail.toLowerCase();
|
|
120458
|
+
return status === HTTP_STATUS.BAD_REQUEST && GOOGLE_JSON_MODE_REFUSAL_PHRASES.some((phrase) => lowered.includes(phrase));
|
|
120459
|
+
};
|
|
120024
120460
|
isGoogleReasoningPart = (part) => {
|
|
120025
120461
|
const partType = typeof part.type === "string" ? part.type.trim().toLowerCase() : "";
|
|
120026
120462
|
if (partType === "thinking" || partType === "thought" || partType === "reasoning" || partType === "reasoning_content") {
|
|
@@ -120111,38 +120547,44 @@ var init_provider_client = __esm({
|
|
|
120111
120547
|
const finishReason = typeof payload?.candidates?.[0]?.finishReason === "string" ? payload.candidates[0].finishReason.trim() : "";
|
|
120112
120548
|
return GOOGLE_BLOCKED_FINISH_REASONS.has(finishReason.toLowerCase()) ? finishReason : null;
|
|
120113
120549
|
};
|
|
120114
|
-
callGoogle = async (apiKey, config2, model, systemPrompt, userPrompt, extraMessages, temperature, maxTokens, reasoningPayload, runtimeRequestContract, runtimeMode, signal, nativeRequestParameters, nativeRequestParameterValues, egress) => {
|
|
120550
|
+
callGoogle = async (apiKey, config2, model, systemPrompt, userPrompt, extraMessages, temperature, maxTokens, reasoningPayload, runtimeRequestContract, runtimeMode, signal, nativeRequestParameters, nativeRequestParameterValues, egress, responseMimeType = null) => {
|
|
120115
120551
|
const vertexExpress = !shouldUseGooglePublicEndpointForModel(config2, model) && await resolveGoogleKeySurface(apiKey, config2, signal) === "vertex";
|
|
120116
120552
|
const reasoningParams = resolveProviderReasoningParameters("google", reasoningPayload);
|
|
120117
|
-
|
|
120118
|
-
|
|
120119
|
-
|
|
120120
|
-
|
|
120121
|
-
|
|
120122
|
-
|
|
120123
|
-
|
|
120124
|
-
|
|
120125
|
-
|
|
120126
|
-
|
|
120127
|
-
|
|
120128
|
-
|
|
120129
|
-
|
|
120130
|
-
|
|
120131
|
-
|
|
120132
|
-
|
|
120133
|
-
|
|
120134
|
-
|
|
120135
|
-
|
|
120136
|
-
|
|
120553
|
+
const buildPayload = (onVertex, mimeType) => {
|
|
120554
|
+
const built = buildGoogleRequest(
|
|
120555
|
+
apiKey,
|
|
120556
|
+
config2,
|
|
120557
|
+
model,
|
|
120558
|
+
systemPrompt,
|
|
120559
|
+
userPrompt,
|
|
120560
|
+
extraMessages,
|
|
120561
|
+
temperature,
|
|
120562
|
+
maxTokens,
|
|
120563
|
+
onVertex,
|
|
120564
|
+
mimeType
|
|
120565
|
+
);
|
|
120566
|
+
const generationConfig = built.payload.generationConfig;
|
|
120567
|
+
if (Number.isFinite(Number(reasoningParams.thinkingBudget))) {
|
|
120568
|
+
generationConfig.thinkingConfig = { thinkingBudget: Math.trunc(Number(reasoningParams.thinkingBudget)) };
|
|
120569
|
+
}
|
|
120570
|
+
if (typeof reasoningParams.thinkingLevel === "string" && reasoningParams.thinkingLevel.trim()) {
|
|
120571
|
+
generationConfig.thinkingConfig = {
|
|
120572
|
+
...generationConfig.thinkingConfig || {},
|
|
120573
|
+
thinkingLevel: reasoningParams.thinkingLevel.trim().toLowerCase()
|
|
120574
|
+
};
|
|
120575
|
+
}
|
|
120576
|
+
return {
|
|
120577
|
+
requestUrl: built.requestUrl,
|
|
120578
|
+
payload: applyNativeRequestParameters(
|
|
120579
|
+
built.payload,
|
|
120580
|
+
nativeRequestParameters,
|
|
120581
|
+
nativeRequestParameterValues,
|
|
120582
|
+
"gemini_generate_content",
|
|
120583
|
+
{ includeAppManaged: true }
|
|
120584
|
+
)
|
|
120137
120585
|
};
|
|
120138
|
-
}
|
|
120139
|
-
payload =
|
|
120140
|
-
payload,
|
|
120141
|
-
nativeRequestParameters,
|
|
120142
|
-
nativeRequestParameterValues,
|
|
120143
|
-
"gemini_generate_content",
|
|
120144
|
-
{ includeAppManaged: true }
|
|
120145
|
-
);
|
|
120586
|
+
};
|
|
120587
|
+
let { requestUrl: requestUrl2, payload } = buildPayload(vertexExpress, responseMimeType);
|
|
120146
120588
|
const trace = startRuntimeNetworkDebugTrace({
|
|
120147
120589
|
kind: "provider",
|
|
120148
120590
|
label: "google",
|
|
@@ -120187,52 +120629,27 @@ var init_provider_client = __esm({
|
|
|
120187
120629
|
dispatchMarker.providerDiagnostics = credentialDiagnostics;
|
|
120188
120630
|
response = await dispatch();
|
|
120189
120631
|
let { payload: payloadJson, rawText } = await readProviderPayload(response);
|
|
120190
|
-
|
|
120191
|
-
retriedPublicGeminiEndpoint = true;
|
|
120192
|
-
const firstErrorDetail = extractProviderErrorDetail(payloadJson, rawText) || `Google request failed with HTTP ${response.status}`;
|
|
120632
|
+
const recordRetriedDispatch = async (marker2, answered, errorDetail) => {
|
|
120193
120633
|
internalDispatchAttempts.push({
|
|
120194
|
-
sentReasoningParameters:
|
|
120634
|
+
sentReasoningParameters: marker2.sentReasoningParameters,
|
|
120195
120635
|
effectiveReasoningParameters: extractProviderReasoningParameters(payloadJson),
|
|
120196
|
-
startedAt:
|
|
120197
|
-
latencyMs: providerDispatchLatencyMs(
|
|
120636
|
+
startedAt: marker2.startedAt,
|
|
120637
|
+
latencyMs: providerDispatchLatencyMs(marker2),
|
|
120198
120638
|
transport: "google_generate_content_rest",
|
|
120199
|
-
requestInputTokens:
|
|
120200
|
-
providerDiagnostics: { ...credentialDiagnostics, ...await extractProviderDiagnostics(payloadJson,
|
|
120201
|
-
providerRequestId: providerRequestId(
|
|
120202
|
-
errorDetail
|
|
120203
|
-
statusCode:
|
|
120639
|
+
requestInputTokens: marker2.requestInputTokens,
|
|
120640
|
+
providerDiagnostics: { ...credentialDiagnostics, ...await extractProviderDiagnostics(payloadJson, answered) },
|
|
120641
|
+
providerRequestId: providerRequestId(answered),
|
|
120642
|
+
errorDetail,
|
|
120643
|
+
statusCode: answered.status,
|
|
120204
120644
|
retryable: false
|
|
120205
120645
|
});
|
|
120646
|
+
};
|
|
120647
|
+
if (vertexExpress && shouldRetryGoogleVertexRequestPublicly(response, payloadJson, rawText)) {
|
|
120648
|
+
retriedPublicGeminiEndpoint = true;
|
|
120649
|
+
const firstErrorDetail = extractProviderErrorDetail(payloadJson, rawText) || `Google request failed with HTTP ${response.status}`;
|
|
120650
|
+
await recordRetriedDispatch(dispatchMarker, response, firstErrorDetail);
|
|
120206
120651
|
dispatchMarker = null;
|
|
120207
|
-
({ requestUrl: requestUrl2, payload } =
|
|
120208
|
-
apiKey,
|
|
120209
|
-
config2,
|
|
120210
|
-
model,
|
|
120211
|
-
systemPrompt,
|
|
120212
|
-
userPrompt,
|
|
120213
|
-
extraMessages,
|
|
120214
|
-
temperature,
|
|
120215
|
-
maxTokens,
|
|
120216
|
-
false
|
|
120217
|
-
));
|
|
120218
|
-
if (Number.isFinite(Number(reasoningParams.thinkingBudget))) {
|
|
120219
|
-
payload.generationConfig.thinkingConfig = {
|
|
120220
|
-
thinkingBudget: Math.trunc(Number(reasoningParams.thinkingBudget))
|
|
120221
|
-
};
|
|
120222
|
-
}
|
|
120223
|
-
if (typeof reasoningParams.thinkingLevel === "string" && reasoningParams.thinkingLevel.trim()) {
|
|
120224
|
-
payload.generationConfig.thinkingConfig = {
|
|
120225
|
-
...payload.generationConfig.thinkingConfig || {},
|
|
120226
|
-
thinkingLevel: reasoningParams.thinkingLevel.trim().toLowerCase()
|
|
120227
|
-
};
|
|
120228
|
-
}
|
|
120229
|
-
payload = applyNativeRequestParameters(
|
|
120230
|
-
payload,
|
|
120231
|
-
nativeRequestParameters,
|
|
120232
|
-
nativeRequestParameterValues,
|
|
120233
|
-
"gemini_generate_content",
|
|
120234
|
-
{ includeAppManaged: true }
|
|
120235
|
-
);
|
|
120652
|
+
({ requestUrl: requestUrl2, payload } = buildPayload(false, responseMimeType));
|
|
120236
120653
|
appendRuntimeDebugEvent({
|
|
120237
120654
|
label: "google_vertex_public_retry",
|
|
120238
120655
|
note: GOOGLE_VERTEX_PUBLIC_RETRY_NOTE
|
|
@@ -120250,6 +120667,19 @@ var init_provider_client = __esm({
|
|
|
120250
120667
|
response = await dispatch();
|
|
120251
120668
|
({ payload: payloadJson, rawText } = await readProviderPayload(response));
|
|
120252
120669
|
}
|
|
120670
|
+
const refusalDetail = !response.ok && responseMimeType ? extractProviderErrorDetail(payloadJson, rawText) || "" : "";
|
|
120671
|
+
if (refusalDetail && dispatchMarker && isGoogleJsonModeRefusal(response.status, refusalDetail)) {
|
|
120672
|
+
await recordRetriedDispatch(dispatchMarker, response, refusalDetail);
|
|
120673
|
+
dispatchMarker = null;
|
|
120674
|
+
({ requestUrl: requestUrl2, payload } = buildPayload(vertexExpress && !retriedPublicGeminiEndpoint, null));
|
|
120675
|
+
appendRuntimeDebugEvent({ label: "google_json_mode_refused", note: `model=${model}` });
|
|
120676
|
+
trace.attachRequest({ url: requestUrl2.toString(), method: "POST", headers: requestHeaders, body: payload });
|
|
120677
|
+
response = null;
|
|
120678
|
+
dispatchMarker = beginProviderDispatch(payload);
|
|
120679
|
+
dispatchMarker.providerDiagnostics = credentialDiagnostics;
|
|
120680
|
+
response = await dispatch();
|
|
120681
|
+
({ payload: payloadJson, rawText } = await readProviderPayload(response));
|
|
120682
|
+
}
|
|
120253
120683
|
if (dispatchMarker) {
|
|
120254
120684
|
dispatchMarker.googleQuotaFailure = Array.isArray(payloadJson?.error?.details) && payloadJson.error.details.some((detail) => detail !== null && typeof detail === "object" && detail["@type"] === "type.googleapis.com/google.rpc.QuotaFailure");
|
|
120255
120685
|
dispatchMarker.effectiveReasoningParameters = extractProviderReasoningParameters(payloadJson);
|
|
@@ -120265,7 +120695,7 @@ var init_provider_client = __esm({
|
|
|
120265
120695
|
forgetGoogleKeySurfaceAfterAuthorizationFailure(apiKey, response.status);
|
|
120266
120696
|
const providerDetail = extractProviderErrorDetail(payloadJson, rawText) || "Google request failed";
|
|
120267
120697
|
const detail = retriedPublicGeminiEndpoint ? `${GOOGLE_VERTEX_PUBLIC_RETRY_NOTE} The Gemini retry also failed: ${providerDetail}` : providerDetail;
|
|
120268
|
-
throw
|
|
120698
|
+
throw providerRequestFailure({ response, detail, runtimeMode });
|
|
120269
120699
|
}
|
|
120270
120700
|
const reasoningContent = extractGoogleReasoningContent(payloadJson);
|
|
120271
120701
|
const finishReason = typeof payloadJson?.candidates?.[0]?.finishReason === "string" ? payloadJson.candidates[0].finishReason : null;
|
|
@@ -120754,7 +121184,8 @@ var init_provider_client = __esm({
|
|
|
120754
121184
|
attemptController?.signal ?? signal,
|
|
120755
121185
|
nativeRequestParameters,
|
|
120756
121186
|
nativeRequestParameterValues,
|
|
120757
|
-
egress ? { route: googleRoute, budget: egress, profileId: Number(profileId), timeoutSeconds: timeoutMs / MS_PER_SECOND } : void 0
|
|
121187
|
+
egress ? { route: googleRoute, budget: egress, profileId: Number(profileId), timeoutSeconds: timeoutMs / MS_PER_SECOND } : void 0,
|
|
121188
|
+
googleTradeResponseMimeType(config2, model, invocationContext)
|
|
120758
121189
|
);
|
|
120759
121190
|
} finally {
|
|
120760
121191
|
if (attemptTimer !== void 0) clearTimeout(attemptTimer);
|
|
@@ -122565,6 +122996,7 @@ __export(local_analysis_exports, {
|
|
|
122565
122996
|
buildPromptBehaviorStateValue: () => buildPromptBehaviorStateValue,
|
|
122566
122997
|
buildPromptCandleTimeframeComponent: () => buildPromptCandleTimeframeComponent,
|
|
122567
122998
|
capacityUnitSize: () => capacityUnitSize,
|
|
122999
|
+
currentModelOutputJsonText: () => currentModelOutputJsonText,
|
|
122568
123000
|
derivePromptVisibleSections: () => derivePromptVisibleSections,
|
|
122569
123001
|
isClientRuntimeAgentInstructionEmpty: () => isClientRuntimeAgentInstructionEmpty,
|
|
122570
123002
|
isClientRuntimeAiSchedulePaused: () => isClientRuntimeAiSchedulePaused,
|
|
@@ -122579,7 +123011,7 @@ __export(local_analysis_exports, {
|
|
|
122579
123011
|
runLocalRuntimeCycle: () => runLocalRuntimeCycle,
|
|
122580
123012
|
summarizeReviewFailureExplanation: () => summarizeReviewFailureExplanation
|
|
122581
123013
|
});
|
|
122582
|
-
var CYCLE_TIMEOUT_FLOOR_MS, DECISION_SETTLEMENT_RESERVE_MAX_BUDGET_DIVISOR, MIN_AGENT_INSTRUCTION_RETRY_AFTER_MS, PROMPT_PARITY_ERROR_DETAIL_MAX_CHARS, EXTERNAL_INFERENCE_RUNTIME_POLL_INTERVAL_MS, EXTERNAL_INFERENCE_RESULT_WAIT_MS, REVIEW_PROVIDER_SERVER_ERROR_STATUSES, TRUNCATION_ELLIPSIS2, normalizeNativeValues, assertPromptModelController, resolveRuntimeReasoningControlsForModel, modelScopedKey, resolveNativeValuesForModel, observeRuntimeCycle, observeAccountState, aiOrderSlippageFraction, serverBehaviorStateArtifacts, ClientRuntimeAgentInstructionEmpty, isClientRuntimeAgentInstructionEmpty, ClientRuntimeAiSchedulePaused, ClientRuntimeAiScheduleStillActive, isClientRuntimeAiScheduleStillActive, ServerDispatchAccountStateStale, isServerDispatchAccountStateStale, isClientRuntimeAiSchedulePaused, acceptancePositionCaps, accountSnapshotCapturedAt, buildClaimedAgentRuntimeCycleResult, resolveRuntimeMarginModePreference, resolveRuntimeLeveragePreference, resolveBooleanSetting2, CLIENT_RUNTIME_LIVE_CONTEXT_UNAVAILABLE_ERRORS, BEHAVIOR_STATE_UNAVAILABLE_ERROR, CriticalBehaviorStateError, BEHAVIOR_MEMORY_UNAVAILABLE_ERROR, BehaviorMemoryUnavailableError, clampNumber, resolveExternalInferenceRuntimeTimeoutSeconds, toPositiveFinite3, compactSnippet, hashRuntimeDebugText, EFFECTIVE_INPUT_MANIFEST_SCHEMA_VERSION, PROMPT_ASSEMBLY_DEFINITION_VERSION, RUNTIME_SOURCE_DEFINITION_VERSION, DECISION_INPUT_DEFINITION_VERSION, CONTEXT_ENVELOPE_DEFINITION_VERSION, CLIENT_RUNTIME_SOURCE_VERSION, CLIENT_MAIN_PROMPT_RENDERER, SERVER_MAIN_PROMPT_RENDERER, CLIENT_REVIEW_PROMPT_RENDERER, SERVER_REVIEW_PROMPT_RENDERER, resolveEffectivePromptRuntimeProvenance, canonicalManifestValue, canonicalManifestJson, sha256ManifestHex, effectiveInputComponent, buildEffectiveInputManifest, MANIFEST_COMPONENT_NAME, derivePromptVisibleSections, decodeDecisionTracePayload, extractDecisionSymbolTrace, formatDecisionSymbolTrace, formatActionableDecisionSymbols, decisionRecordsBySymbol, normalizePromptSymbols, JSON_MODEL_OUTPUT_FENCE_PATTERN, STRICT_MODEL_OUTPUT_KEYS, currentModelOutputValidationErrors, currentModelOutputMatchesContract, projectCurrentModelDecisionContent, modelOutputValidationError, SERVER_UNREADABLE_REPLY_HOLD_REASONING, buildMissingDecisionHold, buildDecisionPlansFromResponse, buildReviewCandidatePlansFromResponse, forceUnavailableSymbolsToHold, extractTemplatePlaceholders, requireReviewPrimaryUserPromptTemplate, containsCompetingBehaviorStateMarkup, containsCompetingMainBehaviorStateMarkup, requireStrategyReviewTemplates, preflightStrategyReviewPromptContract, extractRuntimeReasoningSelection, isAbortError, isRuntimeTimeoutAbortReason, REVIEW_FAILURE_SENSITIVE_DB_TOKENS, REVIEW_FAILURE_SCHEMA_DISCLOSURE_TOKENS, REVIEW_FAILURE_SQL_STATEMENT_PATTERN, REVIEW_FAILURE_TRACEBACK_PATTERN, isSensitiveReviewFailureDetail, summarizeReviewFailureExplanation, buildReviewFailureHoldReason, createAbortError2, settleRuntimeCyclePromise, unwrapRuntimeCycleSettledResult, normalizeDecisionLabel, normalizeRuntimeSymbol, PromptContractFetchError, isLivePromptContextUnavailableError, buildFailClosedHoldResult, buildPromptConstructionFailureResult, buildLivePromptContextUnavailableFailureResult, pickFirstString, normalizeRuntimeStringList, requirePositiveRuntimeLimit, resolveRuntimeTradingScope, normalizeRuntimeProviderAlias, resolveCatalogModelEntry, createClientRuntimeProviderSetupError, createProviderSetupRejectionError, evaluateModelEligibility, extractReviewRuntimeReasoningSelection, isUsableRuntimeSettingsFallback, resolveRuntimeSettings, formatRuntimeDurationMs, normalizeRuntimeTimingNote, appendRuntimeTimingEvent, reportPromptParityTelemetry, resolveLocalRuntimeSecretRequirements, resolveLocalRuntimeSecretProvider, toEpochSeconds, AI_INDICATOR_KEYS_NEWER_THAN_SOME_SERVERS, sortTradingTimeframes, normalizePromptIdentityTimestamp, resolveCompletedCandleBoundary, normalizeAiIndicatorFlags, getPromptLookback, computeSma, computeEma, computeRsi, computeAtr, computeMacd, computeBollingerBands, getIndicatorValue, buildPromptCandlesComponent, buildPromptCandleTimeframeComponent, resolvePromptRelativeVolumeContext, promptRelativeVolumeBaseline, CANDLE_CLOSE_TICKER_TIMEFRAME, candleCloseTicker, buildPromptCandlesPayload, formatUtcTimestampWithWeekday, formatUtcNowWithWeekday, formatPromptPrice, capacityUnitSize, computePromptUnitsUsedForPosition, buildPromptAccountStatusValue, buildPromptPositionsValue, sanitizePromptSymbol, fillTimeMs, fillSize, normalizeFillSide, normalizeFillOrderId, normalizeFillRiskOrderIdentity, fillStartPosition, fillSortValue, sortFillsAscending, sortFillsDescending, inferEntryFromStartPositionChain, inferEntryFromCurrentPositionSize, calculateCurrentPositionState, calculatePositionEntryTimes, countPositionAdds, latestPositionRiskIncreaseTimeMs, latestPositionRiskIncreaseEvidence, compactPromptRiskIncrease, roundPositiveDecimalHalfUp, compactPromptLastTrade, ENTRY_TRADE_FIELDS, PREVIOUS_DECISION_FIELDS, PREVIOUS_CAMPAIGN_FIELDS, hasExactKeys2, isNonnegativeInteger, isFiniteNumber, isExactEnumString, isNonemptyPromptText, isCampaignReasoningText, projectBackendDecisionMemoryItem, requireRenderedStrategyBehaviorState, canonicalFillSideForRiskEvidence, isValidRiskEvidenceFill, isValidCampaignBoundaryFill, normalizeFillHistoryCoverage, resolveFillHistoryCoverageForSymbol, buildPromptBehaviorStateArtifacts, buildPromptBehaviorStateValue, shouldCompareServerPromptParity, buildLocalRuntimePromptArtifacts, createRuntimeId2, asRecord, buildRuntimeConstraintRejectionMessage, hasDeviceProviderSecret, requireNonEmptyStringField, requirePositiveIntegerField, compareContractVersion, parsePromptContractTimestamp, assertPromptContractCompatibility, assertPromptContractTemporalBounds, sleepWithAbort, requireAgentPollRetryAfterMs, materializeClaimedClientRuntimeAgentInstruction, attachClientRuntimeErrorProvenance, isExternalRuntimeProviderResult, invokeClientExternalInference, assertPromptContractBindingTupleEqual, assertPromptContractScopeMatch, fetchBoundPromptContracts, carryReturnedModelCalls, runLocalRuntimeCycle;
|
|
123014
|
+
var CYCLE_TIMEOUT_FLOOR_MS, DECISION_SETTLEMENT_RESERVE_MAX_BUDGET_DIVISOR, MIN_AGENT_INSTRUCTION_RETRY_AFTER_MS, PROMPT_PARITY_ERROR_DETAIL_MAX_CHARS, EXTERNAL_INFERENCE_RUNTIME_POLL_INTERVAL_MS, EXTERNAL_INFERENCE_RESULT_WAIT_MS, REVIEW_PROVIDER_SERVER_ERROR_STATUSES, TRUNCATION_ELLIPSIS2, normalizeNativeValues, assertPromptModelController, resolveRuntimeReasoningControlsForModel, modelScopedKey, resolveNativeValuesForModel, observeRuntimeCycle, observeAccountState, aiOrderSlippageFraction, serverBehaviorStateArtifacts, ClientRuntimeAgentInstructionEmpty, isClientRuntimeAgentInstructionEmpty, ClientRuntimeAiSchedulePaused, ClientRuntimeAiScheduleStillActive, isClientRuntimeAiScheduleStillActive, ServerDispatchAccountStateStale, isServerDispatchAccountStateStale, isClientRuntimeAiSchedulePaused, acceptancePositionCaps, accountSnapshotCapturedAt, buildClaimedAgentRuntimeCycleResult, resolveRuntimeMarginModePreference, resolveRuntimeLeveragePreference, resolveBooleanSetting2, CLIENT_RUNTIME_LIVE_CONTEXT_UNAVAILABLE_ERRORS, BEHAVIOR_STATE_UNAVAILABLE_ERROR, CriticalBehaviorStateError, BEHAVIOR_MEMORY_UNAVAILABLE_ERROR, BehaviorMemoryUnavailableError, clampNumber, resolveExternalInferenceRuntimeTimeoutSeconds, toPositiveFinite3, compactSnippet, hashRuntimeDebugText, EFFECTIVE_INPUT_MANIFEST_SCHEMA_VERSION, PROMPT_ASSEMBLY_DEFINITION_VERSION, RUNTIME_SOURCE_DEFINITION_VERSION, DECISION_INPUT_DEFINITION_VERSION, CONTEXT_ENVELOPE_DEFINITION_VERSION, CLIENT_RUNTIME_SOURCE_VERSION, CLIENT_MAIN_PROMPT_RENDERER, SERVER_MAIN_PROMPT_RENDERER, CLIENT_REVIEW_PROMPT_RENDERER, SERVER_REVIEW_PROMPT_RENDERER, resolveEffectivePromptRuntimeProvenance, canonicalManifestValue, canonicalManifestJson, sha256ManifestHex, effectiveInputComponent, buildEffectiveInputManifest, MANIFEST_COMPONENT_NAME, derivePromptVisibleSections, decodeDecisionTracePayload, extractDecisionSymbolTrace, formatDecisionSymbolTrace, formatActionableDecisionSymbols, decisionRecordsBySymbol, normalizePromptSymbols, JSON_MODEL_OUTPUT_FENCE_PATTERN, currentModelOutputJsonText, STRICT_MODEL_OUTPUT_KEYS, currentModelOutputValidationErrors, currentModelOutputMatchesContract, projectCurrentModelDecisionContent, modelOutputValidationError, SERVER_UNREADABLE_REPLY_HOLD_REASONING, buildMissingDecisionHold, buildDecisionPlansFromResponse, buildReviewCandidatePlansFromResponse, forceUnavailableSymbolsToHold, extractTemplatePlaceholders, requireReviewPrimaryUserPromptTemplate, containsCompetingBehaviorStateMarkup, containsCompetingMainBehaviorStateMarkup, requireStrategyReviewTemplates, preflightStrategyReviewPromptContract, extractRuntimeReasoningSelection, isAbortError, isRuntimeTimeoutAbortReason, REVIEW_FAILURE_SENSITIVE_DB_TOKENS, REVIEW_FAILURE_SCHEMA_DISCLOSURE_TOKENS, REVIEW_FAILURE_SQL_STATEMENT_PATTERN, REVIEW_FAILURE_TRACEBACK_PATTERN, isSensitiveReviewFailureDetail, summarizeReviewFailureExplanation, buildReviewFailureHoldReason, createAbortError2, settleRuntimeCyclePromise, unwrapRuntimeCycleSettledResult, normalizeDecisionLabel, normalizeRuntimeSymbol, PromptContractFetchError, isLivePromptContextUnavailableError, buildFailClosedHoldResult, buildPromptConstructionFailureResult, buildLivePromptContextUnavailableFailureResult, pickFirstString, normalizeRuntimeStringList, requirePositiveRuntimeLimit, resolveRuntimeTradingScope, normalizeRuntimeProviderAlias, resolveCatalogModelEntry, createClientRuntimeProviderSetupError, createProviderSetupRejectionError, evaluateModelEligibility, extractReviewRuntimeReasoningSelection, isUsableRuntimeSettingsFallback, resolveRuntimeSettings, formatRuntimeDurationMs, normalizeRuntimeTimingNote, appendRuntimeTimingEvent, reportPromptParityTelemetry, resolveLocalRuntimeSecretRequirements, resolveLocalRuntimeSecretProvider, toEpochSeconds, AI_INDICATOR_KEYS_NEWER_THAN_SOME_SERVERS, sortTradingTimeframes, normalizePromptIdentityTimestamp, resolveCompletedCandleBoundary, normalizeAiIndicatorFlags, getPromptLookback, computeSma, computeEma, computeRsi, computeAtr, computeMacd, computeBollingerBands, getIndicatorValue, buildPromptCandlesComponent, buildPromptCandleTimeframeComponent, resolvePromptRelativeVolumeContext, promptRelativeVolumeBaseline, CANDLE_CLOSE_TICKER_TIMEFRAME, candleCloseTicker, buildPromptCandlesPayload, formatUtcTimestampWithWeekday, formatUtcNowWithWeekday, formatPromptPrice, capacityUnitSize, computePromptUnitsUsedForPosition, buildPromptAccountStatusValue, buildPromptPositionsValue, sanitizePromptSymbol, fillTimeMs, fillSize, normalizeFillSide, normalizeFillOrderId, normalizeFillRiskOrderIdentity, fillStartPosition, fillSortValue, sortFillsAscending, sortFillsDescending, inferEntryFromStartPositionChain, inferEntryFromCurrentPositionSize, calculateCurrentPositionState, calculatePositionEntryTimes, countPositionAdds, latestPositionRiskIncreaseTimeMs, latestPositionRiskIncreaseEvidence, compactPromptRiskIncrease, roundPositiveDecimalHalfUp, compactPromptLastTrade, ENTRY_TRADE_FIELDS, PREVIOUS_DECISION_FIELDS, PREVIOUS_CAMPAIGN_FIELDS, hasExactKeys2, isNonnegativeInteger, isFiniteNumber, isExactEnumString, isNonemptyPromptText, isCampaignReasoningText, projectBackendDecisionMemoryItem, requireRenderedStrategyBehaviorState, canonicalFillSideForRiskEvidence, isValidRiskEvidenceFill, isValidCampaignBoundaryFill, normalizeFillHistoryCoverage, resolveFillHistoryCoverageForSymbol, buildPromptBehaviorStateArtifacts, buildPromptBehaviorStateValue, shouldCompareServerPromptParity, buildLocalRuntimePromptArtifacts, createRuntimeId2, asRecord, buildRuntimeConstraintRejectionMessage, hasDeviceProviderSecret, requireNonEmptyStringField, requirePositiveIntegerField, compareContractVersion, parsePromptContractTimestamp, assertPromptContractCompatibility, assertPromptContractTemporalBounds, sleepWithAbort, requireAgentPollRetryAfterMs, materializeClaimedClientRuntimeAgentInstruction, attachClientRuntimeErrorProvenance, isExternalRuntimeProviderResult, invokeClientExternalInference, assertPromptContractBindingTupleEqual, assertPromptContractScopeMatch, fetchBoundPromptContracts, carryReturnedModelCalls, runLocalRuntimeCycle;
|
|
122583
123015
|
var init_local_analysis = __esm({
|
|
122584
123016
|
"lib/runtime/local-analysis.ts"() {
|
|
122585
123017
|
"use strict";
|
|
@@ -122588,6 +123020,7 @@ var init_local_analysis = __esm({
|
|
|
122588
123020
|
init_define_VTX_GROK_POLICY();
|
|
122589
123021
|
init_define_VTX_PI_MODEL_POLICY();
|
|
122590
123022
|
init_sl_tp_execution_settings();
|
|
123023
|
+
init_runtime_error_reason_rules2();
|
|
122591
123024
|
init_retired_model_source();
|
|
122592
123025
|
init_profile_model_cascade();
|
|
122593
123026
|
init_profile_model_fallbacks();
|
|
@@ -122774,9 +123207,9 @@ var init_local_analysis = __esm({
|
|
|
122774
123207
|
const symbols = normalizePromptSymbols(scope.symbols);
|
|
122775
123208
|
const symbol2 = requireNonEmptyStringField(symbols[0], "trading_symbols[0]");
|
|
122776
123209
|
const timeframe = requireNonEmptyStringField(scope.primaryTimeframe, "trading_timeframes[0]");
|
|
122777
|
-
const content = stringifyPromptJson(instruction.candidate);
|
|
123210
|
+
const content = currentModelOutputJsonText(stringifyPromptJson(instruction.candidate));
|
|
122778
123211
|
if (!currentModelOutputMatchesContract(content, symbols)) {
|
|
122779
|
-
throw new
|
|
123212
|
+
throw new RuntimeReasonError("The agent's instruction could not be read.", "model_output_schema_invalid");
|
|
122780
123213
|
}
|
|
122781
123214
|
const tradeSize = clampNumber(
|
|
122782
123215
|
settings.size,
|
|
@@ -123453,6 +123886,19 @@ var init_local_analysis = __esm({
|
|
|
123453
123886
|
return normalized;
|
|
123454
123887
|
};
|
|
123455
123888
|
JSON_MODEL_OUTPUT_FENCE_PATTERN = /^```(?:json)?\s*\n?([\s\S]*?)\n?```$/i;
|
|
123889
|
+
currentModelOutputJsonText = (rawText) => {
|
|
123890
|
+
const trimmed = String(rawText ?? "").trim();
|
|
123891
|
+
const content = String(trimmed.match(JSON_MODEL_OUTPUT_FENCE_PATTERN)?.[1] ?? trimmed).trim();
|
|
123892
|
+
if (!content.startsWith("[")) return content;
|
|
123893
|
+
try {
|
|
123894
|
+
const parsed = JSON.parse(content);
|
|
123895
|
+
if (Array.isArray(parsed) && parsed.length === 1 && parsed[0] && typeof parsed[0] === "object" && !Array.isArray(parsed[0])) {
|
|
123896
|
+
return JSON.stringify(parsed[0]);
|
|
123897
|
+
}
|
|
123898
|
+
} catch {
|
|
123899
|
+
}
|
|
123900
|
+
return content;
|
|
123901
|
+
};
|
|
123456
123902
|
STRICT_MODEL_OUTPUT_KEYS = /* @__PURE__ */ new Set([
|
|
123457
123903
|
"decision",
|
|
123458
123904
|
"units",
|
|
@@ -123466,9 +123912,7 @@ var init_local_analysis = __esm({
|
|
|
123466
123912
|
if (expectedSymbols.length === 0) {
|
|
123467
123913
|
return ["expected_symbols_empty"];
|
|
123468
123914
|
}
|
|
123469
|
-
const
|
|
123470
|
-
const fencedMatch = rawContent.match(JSON_MODEL_OUTPUT_FENCE_PATTERN);
|
|
123471
|
-
const content = String(fencedMatch?.[1] ?? rawContent).trim();
|
|
123915
|
+
const content = currentModelOutputJsonText(rawText);
|
|
123472
123916
|
if (!content.startsWith("{") || !content.endsWith("}")) {
|
|
123473
123917
|
return ["json_object_required"];
|
|
123474
123918
|
}
|
|
@@ -123522,10 +123966,10 @@ var init_local_analysis = __esm({
|
|
|
123522
123966
|
currentModelOutputMatchesContract = (rawText, allowedSymbols) => currentModelOutputValidationErrors(rawText, allowedSymbols).length === 0;
|
|
123523
123967
|
projectCurrentModelDecisionContent = (rawText) => {
|
|
123524
123968
|
const trimmed = rawText.trim();
|
|
123525
|
-
const content =
|
|
123969
|
+
const content = currentModelOutputJsonText(rawText);
|
|
123526
123970
|
const payload = JSON.parse(content);
|
|
123527
123971
|
if (Object.values(payload).every((entry) => Object.keys(entry).length === STRICT_MODEL_OUTPUT_KEYS.size)) {
|
|
123528
|
-
return rawText;
|
|
123972
|
+
return content === String(trimmed.match(JSON_MODEL_OUTPUT_FENCE_PATTERN)?.[1] ?? trimmed).trim() ? rawText : content;
|
|
123529
123973
|
}
|
|
123530
123974
|
return JSON.stringify(Object.fromEntries(Object.entries(payload).map(([symbol2, entry]) => [
|
|
123531
123975
|
symbol2,
|
|
@@ -123541,7 +123985,7 @@ var init_local_analysis = __esm({
|
|
|
123541
123985
|
});
|
|
123542
123986
|
const rejectedIndex = attempts.findLastIndex((item) => item.role === role && item.status === "succeeded");
|
|
123543
123987
|
return Object.assign(
|
|
123544
|
-
new
|
|
123988
|
+
new RuntimeReasonError(`The ${lane} Model's reply could not be read.`, "model_output_schema_invalid"),
|
|
123545
123989
|
{
|
|
123546
123990
|
// Preserve the completed call and its expected symbol scope. The normal
|
|
123547
123991
|
// error reporter / Review safety-HOLD path owns persistence.
|
|
@@ -125991,7 +126435,7 @@ ${behaviorJson}
|
|
|
125991
126435
|
}
|
|
125992
126436
|
}
|
|
125993
126437
|
if (delivered.lane !== input.lane || delivered.job_id !== jobId) {
|
|
125994
|
-
throw new
|
|
126438
|
+
throw new RuntimeReasonError("External inference delivery identity did not match the requested lane.", "internal_data_error");
|
|
125995
126439
|
}
|
|
125996
126440
|
const attemptId = requireNonEmptyStringField(
|
|
125997
126441
|
delivered.attempt_id,
|
|
@@ -126006,7 +126450,7 @@ ${behaviorJson}
|
|
|
126006
126450
|
"external_inference.response_mode"
|
|
126007
126451
|
);
|
|
126008
126452
|
if (responseMode !== "provider_response" && responseMode !== "decision_candidate") {
|
|
126009
|
-
throw new
|
|
126453
|
+
throw new RuntimeReasonError("External inference response mode is invalid.", "internal_data_error");
|
|
126010
126454
|
}
|
|
126011
126455
|
const outputSchemaVersion = requireNonEmptyStringField(
|
|
126012
126456
|
delivered.output_schema_version,
|
|
@@ -126019,7 +126463,7 @@ ${behaviorJson}
|
|
|
126019
126463
|
const authoritative = delivered.authoritative;
|
|
126020
126464
|
const invocation = normalizeAiInvocationTelemetry(authoritative.invocation);
|
|
126021
126465
|
if (invocation.provider !== "external_agent" || invocation.role !== (input.lane === "main" ? "primary" : "review")) {
|
|
126022
|
-
throw new
|
|
126466
|
+
throw new RuntimeReasonError("External inference invocation evidence is invalid.", "internal_data_error");
|
|
126023
126467
|
}
|
|
126024
126468
|
const candidateContent = JSON.stringify(delivered.candidate);
|
|
126025
126469
|
const promptTokens = invocation.usage.input_tokens;
|
|
@@ -127951,7 +128395,7 @@ ${stringifyPromptJson(candlesPayload)}
|
|
|
127951
128395
|
// The loop records this one code for a reply its strict parser rejects.
|
|
127952
128396
|
validationErrorCodes: ["model_output_schema_invalid"],
|
|
127953
128397
|
discardedFields: []
|
|
127954
|
-
} : classifyDecisionParseOutcome(providerResponse.content, symbol2, promptSymbols);
|
|
128398
|
+
} : classifyDecisionParseOutcome(currentModelOutputJsonText(providerResponse.content), symbol2, promptSymbols);
|
|
127955
128399
|
invocationAttempts = applyInvocationParseOutcome(
|
|
127956
128400
|
providerResponse.invocations,
|
|
127957
128401
|
{
|
|
@@ -128276,7 +128720,7 @@ ${reviewOutputContract}`;
|
|
|
128276
128720
|
reviewDecisionContent = projectCurrentModelDecisionContent(reviewResponse.content);
|
|
128277
128721
|
}
|
|
128278
128722
|
const reviewParseOutcome = classifyDecisionParseOutcome(
|
|
128279
|
-
reviewResponse.content,
|
|
128723
|
+
currentModelOutputJsonText(reviewResponse.content),
|
|
128280
128724
|
reviewSymbols[0] ?? symbol2,
|
|
128281
128725
|
reviewSymbols
|
|
128282
128726
|
);
|
|
@@ -128806,7 +129250,7 @@ ${reviewOutputContract}`;
|
|
|
128806
129250
|
});
|
|
128807
129251
|
|
|
128808
129252
|
// lib/runtime/engine.ts
|
|
128809
|
-
var DEVICE_DIAGNOSTICS3, FALLBACK_ERROR_MAX_CHARS, localAnalysis, getExchangeFailureDiagnostics, getRuntimeFallbackAttempts, sentInvocationAttemptCount, boundRuntimeFallbackAttempts, isProviderFailureDiagnosticsCandidate, getEventBoundProviderLabel, getEventBoundProviderTraceId, CLIENT_RUNTIME_POLICY, getRecentProviderFailureDiagnostics, getClientRuntimeErrorProvenance, getRuntimeProviderSetupDiagnostics, buildProviderSetupErrorDiagnosticFields, buildClientRuntimeErrorProvenanceDiagnosticFields, buildRuntimeRequestErrorDiagnosticFields, getCycleErrorModelCalls, isReturnedModelCall, hasEventBoundProviderFailureEvidence, endsWithNeverSentAttempt, classifyRuntimeErrorStage, buildHyperliquidPublicReadDiagnosticFields, buildRuntimeErrorDiagnostics, positiveNumber, resolveRuntimeEngineOptions, withServerPositionEvents, CLIENT_KILLSWITCH_BLOCK_STORAGE_PREFIX, getClientKillswitchBlockStorageKey, isClientRuntimeKillswitchBlocked, persistClientRuntimeKillswitchBlock, clearClientRuntimeKillswitchBlock, hashRuntimeDebugText2, createRuntimeUuid2, getRuntimeContractIdentityToken, getRuntimeStatusContractIdentityToken, getRuntimeContractBindingTokenFromCycleResult, getRuntimeContractBindingTupleToken, getRuntimeStatusContractBindingTupleToken, isTransientRuntimeConflictError, createRuntimeStartCancelledError, isRuntimeContractMismatchError, isClientExecutionModeMismatchError, isClientRuntimeSessionStoppedError, isClientRuntimeLeaseAuthError, isClientRuntimeReleasedError, deriveFailedStartCleanupOwnershipLossReason, isRuntimeAbortError, isExplicitClientExecutionMode, createStopAbortError, isRuntimeContractIdentityAdvancedAbort, CLIENT_RUNTIME_NO_DECISION_RECOVERY_REASON, sanitizeSettingsSnapshotForFallback, preflightClientRuntime, onCadenceGridPoint, ClientExecutionEngine, createStoppedRuntimeSnapshot, ClientRuntimeRegistry, botEngine;
|
|
129253
|
+
var DEVICE_DIAGNOSTICS3, FALLBACK_ERROR_MAX_CHARS, localAnalysis, getExchangeFailureDiagnostics, getRuntimeFallbackAttempts, sentInvocationAttemptCount, boundRuntimeFallbackAttempts, isProviderFailureDiagnosticsCandidate, getEventBoundProviderLabel, getEventBoundProviderTraceId, CLIENT_RUNTIME_POLICY, getRecentProviderFailureDiagnostics, getClientRuntimeErrorProvenance, getRuntimeProviderSetupDiagnostics, buildProviderSetupErrorDiagnosticFields, buildClientRuntimeErrorProvenanceDiagnosticFields, buildRuntimeRequestErrorDiagnosticFields, getCycleErrorModelCalls, isReturnedModelCall, hasEventBoundProviderFailureEvidence, endsWithNeverSentAttempt, classifyRuntimeErrorStage, buildHyperliquidPublicReadDiagnosticFields, buildRuntimeErrorDiagnostics, positiveNumber, resolveRuntimeEngineOptions, withServerPositionEvents, CLIENT_KILLSWITCH_BLOCK_STORAGE_PREFIX, getClientKillswitchBlockStorageKey, isClientRuntimeKillswitchBlocked, persistClientRuntimeKillswitchBlock, clearClientRuntimeKillswitchBlock, hashRuntimeDebugText2, createRuntimeUuid2, getRuntimeContractIdentityToken, getRuntimeStatusContractIdentityToken, getRuntimeContractBindingTokenFromCycleResult, getRuntimeContractBindingTupleToken, getRuntimeStatusContractBindingTupleToken, isTransientRuntimeConflictError, createRuntimeStartCancelledError, isRuntimeContractMismatchError, isClientExecutionModeMismatchError, isClientRuntimeSessionStoppedError, isClientRuntimeLeaseAuthError, isClientRuntimeReleasedError, deriveFailedStartCleanupOwnershipLossReason, isRuntimeAbortError, isExplicitClientExecutionMode, createStopAbortError, isRuntimeContractIdentityAdvancedAbort, CLIENT_RUNTIME_NO_DECISION_RECOVERY_REASON, CLIENT_RUNTIME_NO_DECISION_MESSAGE, sanitizeSettingsSnapshotForFallback, preflightClientRuntime, onCadenceGridPoint, ClientExecutionEngine, createStoppedRuntimeSnapshot, ClientRuntimeRegistry, botEngine;
|
|
128810
129254
|
var init_engine = __esm({
|
|
128811
129255
|
"lib/runtime/engine.ts"() {
|
|
128812
129256
|
"use strict";
|
|
@@ -128852,6 +129296,8 @@ var init_engine = __esm({
|
|
|
128852
129296
|
init_history_evidence();
|
|
128853
129297
|
init_portfolio_evidence();
|
|
128854
129298
|
init_signing_key_messages();
|
|
129299
|
+
init_runtime_error_reason_rules2();
|
|
129300
|
+
init_host_wake_schedule();
|
|
128855
129301
|
init_copy_trading_evidence();
|
|
128856
129302
|
DEVICE_DIAGNOSTICS3 = runtime_policy_generated_default2.trading.engine.client_runtime.device_diagnostics;
|
|
128857
129303
|
FALLBACK_ERROR_MAX_CHARS = runtime_policy_generated_default2.trading.engine.client_runtime.request_bounds.max_fallback_error_length;
|
|
@@ -129197,6 +129643,7 @@ var init_engine = __esm({
|
|
|
129197
129643
|
runtime_error_name: reason instanceof Error && reason.name ? sanitizeRuntimeDiagnosticValue(reason.name) : null,
|
|
129198
129644
|
runtime_error_message: sanitizeRuntimeDiagnosticValue(getSanitizedRuntimeErrorMessage(reason) || "Unknown runtime error."),
|
|
129199
129645
|
fallback_attempt_count: getRuntimeFallbackAttempts(reason)?.length ?? 0,
|
|
129646
|
+
runtime_reason_code: raisedRuntimeErrorReasonCode(reason),
|
|
129200
129647
|
...buildRuntimeRequestErrorDiagnosticFields(reason),
|
|
129201
129648
|
...buildProviderSetupErrorDiagnosticFields(reason),
|
|
129202
129649
|
...buildClientRuntimeErrorProvenanceDiagnosticFields(reason),
|
|
@@ -129211,6 +129658,8 @@ var init_engine = __esm({
|
|
|
129211
129658
|
runtime_error_name: reason instanceof Error && reason.name ? sanitizeRuntimeDiagnosticValue(reason.name) : null,
|
|
129212
129659
|
runtime_error_message: sanitizeRuntimeDiagnosticValue(getSanitizedRuntimeErrorMessage(reason) || "Unknown runtime error."),
|
|
129213
129660
|
fallback_attempt_count: getRuntimeFallbackAttempts(reason)?.length ?? 0,
|
|
129661
|
+
// The code the error was raised with; the server stores it when listed.
|
|
129662
|
+
runtime_reason_code: raisedRuntimeErrorReasonCode(reason),
|
|
129214
129663
|
browser: getRuntimeBrowserDiagnosticsSnapshot(),
|
|
129215
129664
|
...buildRuntimeRequestErrorDiagnosticFields(reason),
|
|
129216
129665
|
...buildProviderSetupErrorDiagnosticFields(reason),
|
|
@@ -129382,6 +129831,7 @@ var init_engine = __esm({
|
|
|
129382
129831
|
return `${recordedReason || ""} ${reasonMessage} ${errorMessage}`.toLowerCase().includes("runtime_contract_identity_advanced");
|
|
129383
129832
|
};
|
|
129384
129833
|
CLIENT_RUNTIME_NO_DECISION_RECOVERY_REASON = "client_runtime_no_decision_cycle";
|
|
129834
|
+
CLIENT_RUNTIME_NO_DECISION_MESSAGE = "This analysis ended before it reached a decision. VTX picks the bot up again automatically.";
|
|
129385
129835
|
sanitizeSettingsSnapshotForFallback = (settingsSnapshot) => {
|
|
129386
129836
|
const { context_snapshots: _contextSnapshots, ...safeSettingsSnapshot } = settingsSnapshot;
|
|
129387
129837
|
return safeSettingsSnapshot;
|
|
@@ -129726,8 +130176,7 @@ var init_engine = __esm({
|
|
|
129726
130176
|
}
|
|
129727
130177
|
/**
|
|
129728
130178
|
* Close on Stop: a Trader's schedule window ended with the option on, so
|
|
129729
|
-
* its open positions close
|
|
129730
|
-
* _handle_schedule_stop does. A failure is reported as a runtime error and
|
|
130179
|
+
* its open positions close. A failure is reported as a runtime error and
|
|
129731
130180
|
* the bot stays paused.
|
|
129732
130181
|
*/
|
|
129733
130182
|
async _closePositionsAtScheduleEnd(profileId, paused, cancelled) {
|
|
@@ -130075,7 +130524,7 @@ var init_engine = __esm({
|
|
|
130075
130524
|
}
|
|
130076
130525
|
}
|
|
130077
130526
|
);
|
|
130078
|
-
await this.reportError(
|
|
130527
|
+
await this.reportError(new RuntimeReasonError(CLIENT_RUNTIME_NO_DECISION_MESSAGE, "cycle_ended_without_decision"), { fatal: false });
|
|
130079
130528
|
this._scheduleRecoverableSuspendAfterExecutionLoop({
|
|
130080
130529
|
reason: CLIENT_RUNTIME_NO_DECISION_RECOVERY_REASON
|
|
130081
130530
|
});
|
|
@@ -130699,6 +131148,14 @@ var init_engine = __esm({
|
|
|
130699
131148
|
get schedulerInstanceId() {
|
|
130700
131149
|
return this._instanceId;
|
|
130701
131150
|
}
|
|
131151
|
+
/** Its own trader lease authority while it runs the profile as a trader, or null (as a CLI host's sweep signs). */
|
|
131152
|
+
get traderLeaseAuthority() {
|
|
131153
|
+
const { _profileId: profileId, _sessionId: sessionId, _deviceId: deviceId } = this;
|
|
131154
|
+
if (this._state !== "running" || this._mode !== "trader" || !profileId || !sessionId || !deviceId) return null;
|
|
131155
|
+
const lease = getPersistedClientRuntimeServerLease(profileId);
|
|
131156
|
+
if (lease?.runtimeSessionId !== sessionId || lease.deviceId !== deviceId || lease.mode !== "trader" || !lease.runtimeLeaseToken) return null;
|
|
131157
|
+
return { runtimeSessionId: sessionId, runtimeLeaseToken: lease.runtimeLeaseToken, runtimeDeviceId: deviceId, schedulerInstanceId: this._instanceId };
|
|
131158
|
+
}
|
|
130702
131159
|
/** Whether this engine runs, starts, or stops a runtime (never claim it again). */
|
|
130703
131160
|
/**
|
|
130704
131161
|
* Resolves once no cycle is in flight, or after the timeout: a Node runtime
|
|
@@ -130904,7 +131361,7 @@ var init_engine = __esm({
|
|
|
130904
131361
|
void this.sendHeartbeat({ confirmGrant: true });
|
|
130905
131362
|
await this._reportAuthoritativeRuntimePresence(profileId);
|
|
130906
131363
|
this._attachLifecycleListeners();
|
|
130907
|
-
this._heartbeatIntervalId = setInterval(() => void this.sendHeartbeat(), this._heartbeatIntervalMs);
|
|
131364
|
+
this._heartbeatIntervalId = markDeferrableTimer(setInterval(() => void this.sendHeartbeat(), this._heartbeatIntervalMs));
|
|
130908
131365
|
await this._startClientKillswitchMonitor(startController);
|
|
130909
131366
|
if (this._state !== "running" || this._killswitchLatched) {
|
|
130910
131367
|
return;
|
|
@@ -133600,6 +134057,7 @@ var init_engine = __esm({
|
|
|
133600
134057
|
}) : null;
|
|
133601
134058
|
const projected = projectRuntimeErrorSurfaceContract({
|
|
133602
134059
|
error: sanitizeRuntimeDiagnosticValue(sanitizedReason),
|
|
134060
|
+
reasonCode: raisedRuntimeErrorReasonCode(reason),
|
|
133603
134061
|
runtimeLiveStatus: this._runtimeStatus?.runtime_live_status ?? "active",
|
|
133604
134062
|
runtimeStopReason: this._runtimeStatus?.runtime_stop_reason ?? null,
|
|
133605
134063
|
isActive: this._mode !== "assistant",
|
|
@@ -133962,6 +134420,8 @@ var init_engine = __esm({
|
|
|
133962
134420
|
mode: this._mode,
|
|
133963
134421
|
lastRunAt: this._lastRunAt,
|
|
133964
134422
|
flushReason: reason,
|
|
134423
|
+
// Its telemetry goes out together, in one request.
|
|
134424
|
+
together: true,
|
|
133965
134425
|
reporter: (profileId, payload) => reportClientRuntimeLifecycleEvent(
|
|
133966
134426
|
profileId,
|
|
133967
134427
|
{ ...payload, schedulerInstanceId: this._instanceId }
|
|
@@ -134012,10 +134472,10 @@ var init_engine = __esm({
|
|
|
134012
134472
|
if (this._state !== "running" || this._mode !== "trader" || this._killswitchLatched) {
|
|
134013
134473
|
return;
|
|
134014
134474
|
}
|
|
134015
|
-
this._killswitchIntervalId = setInterval(
|
|
134475
|
+
this._killswitchIntervalId = markBatchableTimer(setInterval(
|
|
134016
134476
|
() => void this._runClientKillswitchCheck(),
|
|
134017
134477
|
Math.max(CLIENT_RUNTIME_POLICY.killswitch_timer_floor_milliseconds, Math.round(pollIntervalSeconds * MS_PER_SECOND))
|
|
134018
|
-
);
|
|
134478
|
+
));
|
|
134019
134479
|
}
|
|
134020
134480
|
async _runClientKillswitchCheck() {
|
|
134021
134481
|
if (!this._ownsKillswitch() || this._state !== "running" || this._mode !== "trader" || this._killswitchLatched || this._killswitchCheckInFlight || !this._profileId || !this._sessionId || !this._deviceId) {
|
|
@@ -134936,6 +135396,11 @@ var init_engine = __esm({
|
|
|
134936
135396
|
if (!normalized) throw new Error("Missing profile id for client runtime claim.");
|
|
134937
135397
|
return this._getEngine(normalized).schedulerInstanceId;
|
|
134938
135398
|
}
|
|
135399
|
+
/** The local engine's own trader lease authority for this profile, or null. */
|
|
135400
|
+
traderLeaseAuthority(profileId) {
|
|
135401
|
+
const normalized = this._normalizeProfileId(profileId);
|
|
135402
|
+
return normalized ? this._getEngine(normalized, false)?.traderLeaseAuthority ?? null : null;
|
|
135403
|
+
}
|
|
134939
135404
|
/** Whether a local engine runs, starts, or stops this profile. */
|
|
134940
135405
|
isProfileActive(profileId) {
|
|
134941
135406
|
const normalized = this._normalizeProfileId(profileId);
|