@vtxmacro/cli 2026.10.22 → 2026.10.23
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/vtx-mcp.js +1 -1
- package/bin/vtx-service-bootstrap.js +1 -1
- package/bin/vtx.js +1232 -160
- package/package.json +1 -1
package/bin/vtx.js
CHANGED
|
@@ -113,7 +113,7 @@ var init_routing = __esm({
|
|
|
113
113
|
var agent_cli_release_default;
|
|
114
114
|
var init_agent_cli_release = __esm({
|
|
115
115
|
"agent-cli-release.json"() {
|
|
116
|
-
agent_cli_release_default = { package_name: "@vtxmacro/cli", package_version: "2026.10.
|
|
116
|
+
agent_cli_release_default = { package_name: "@vtxmacro/cli", package_version: "2026.10.23", codex_package_name: "@openai/codex", codex_version: "0.155.0", copilot_sdk_package_name: "@github/copilot-sdk", copilot_sdk_version: "1.0.0-beta.8", copilot_cli_package_name: "@github/copilot", copilot_cli_version: "1.0.80", deepseek_harness_version: "0.1.1-rc.2", deepseek_harness_packages: ["@deepseek-ai/dsh-agent", "@deepseek-ai/dsh-agent-instructions", "@deepseek-ai/dsh-agent-loop", "@deepseek-ai/dsh-agent-spine-demo", "@deepseek-ai/dsh-anonymous-user-id", "@deepseek-ai/dsh-atomic-write", "@deepseek-ai/dsh-attachment", "@deepseek-ai/dsh-brand", "@deepseek-ai/dsh-code-runtime", "@deepseek-ai/dsh-credentials", "@deepseek-ai/dsh-fs", "@deepseek-ai/dsh-goal", "@deepseek-ai/dsh-goal-round-driver", "@deepseek-ai/dsh-home-paths", "@deepseek-ai/dsh-invariants", "@deepseek-ai/dsh-jobs", "@deepseek-ai/dsh-jobs-local", "@deepseek-ai/dsh-launch-environment", "@deepseek-ai/dsh-llm", "@deepseek-ai/dsh-llm-deepseek", "@deepseek-ai/dsh-llm-retry", "@deepseek-ai/dsh-output-retention", "@deepseek-ai/dsh-sandbox", "@deepseek-ai/dsh-sandbox-policy", "@deepseek-ai/dsh-scope", "@deepseek-ai/dsh-session", "@deepseek-ai/dsh-session-checkpoint-policy", "@deepseek-ai/dsh-session-persistence", "@deepseek-ai/dsh-session-persistence-jsonl", "@deepseek-ai/dsh-session-projection", "@deepseek-ai/dsh-session-title", "@deepseek-ai/dsh-settings", "@deepseek-ai/dsh-shell", "@deepseek-ai/dsh-shell-env", "@deepseek-ai/dsh-skill", "@deepseek-ai/dsh-skill-filesystem", "@deepseek-ai/dsh-subprocess", "@deepseek-ai/dsh-system-prompt", "@deepseek-ai/dsh-timeout", "@deepseek-ai/dsh-tool-bash", "@deepseek-ai/dsh-tool-goal", "@deepseek-ai/dsh-tool-jobs", "@deepseek-ai/dsh-tool-skill", "@deepseek-ai/dsh-tools", "@deepseek-ai/dsh-typert-protocol", "@deepseek-ai/dsh-user-approval"], deepseek_cordis_package_name: "@deepseek-ai/cordis", deepseek_cordis_version: "4.0.1", deepseek_support_packages: { "@deepseek-ai/cordis-plugin-timer": "1.1.3" }, platforms: { "linux-x64": { package_name: "@openai/codex-linux-x64", target: "x86_64-unknown-linux-musl", binary_name: "codex", sha256: "660e159a49e823ac8e5986cb238f73158ce4b957d40d9292f8de90862644b501" }, "win32-x64": { package_name: "@openai/codex-win32-x64", target: "x86_64-pc-windows-msvc", binary_name: "codex.exe", sha256: "e4c11374bd9de8ad5c3b7617fd4654bb7839901edb0863f9930666863c7a021b" } }, pi_coding_agent_package_name: "@earendil-works/pi-coding-agent", pi_ai_package_name: "@earendil-works/pi-ai", pi_version: "0.85.1", pi_support_packages: ["@earendil-works/pi-agent-core", "@earendil-works/pi-telemetry", "@earendil-works/pi-tui", "@earendil-works/chord"], grok_version: "1.0.30", grok_platforms: { "linux-x64": { package_name: "@xai-official/grok-linux-x64", binary_name: "grok", sha256: "504dd6546ab991b75d36698242875ce461489cd1f8cd84285873cb55bd5c7d54" }, "win32-x64": { package_name: "@xai-official/grok-win32-x64", binary_name: "grok.exe", sha256: "48736d1a4342a801ea26d0ecde4c516b653f791399065adaa55973f83abd8867" } } };
|
|
117
117
|
}
|
|
118
118
|
});
|
|
119
119
|
|
|
@@ -3163,13 +3163,13 @@ async function replaceAtomicInferencePrivateFile(temporaryPath, destinationPath,
|
|
|
3163
3163
|
const sleep4 = options.sleep ?? ((milliseconds) => new Promise((resolve14) => setTimeout(resolve14, milliseconds)));
|
|
3164
3164
|
const maxAttempts = Math.max(1, options.maxAttempts ?? HOST_CORE_POLICY.private_file_replace_attempts);
|
|
3165
3165
|
const retryDelayMs = Math.max(0, options.retryDelayMs ?? HOST_CORE_POLICY.private_file_replace_retry_delay_ms);
|
|
3166
|
-
for (let
|
|
3166
|
+
for (let attempt2 = 0; attempt2 < maxAttempts; attempt2 += 1) {
|
|
3167
3167
|
try {
|
|
3168
3168
|
await renameFile(temporaryPath, destinationPath);
|
|
3169
3169
|
return;
|
|
3170
3170
|
} catch (error48) {
|
|
3171
3171
|
const code = String(error48.code ?? "");
|
|
3172
|
-
if (platform !== "win32" || !WINDOWS_PRIVATE_FILE_REPLACE_ERROR_CODES.has(code) ||
|
|
3172
|
+
if (platform !== "win32" || !WINDOWS_PRIVATE_FILE_REPLACE_ERROR_CODES.has(code) || attempt2 === maxAttempts - 1) {
|
|
3173
3173
|
throw error48;
|
|
3174
3174
|
}
|
|
3175
3175
|
await sleep4(retryDelayMs);
|
|
@@ -4203,11 +4203,11 @@ while(($line=[Console]::In.ReadLine()) -ne $null) {
|
|
|
4203
4203
|
const directory2 = dirname2(lockPath);
|
|
4204
4204
|
const prefix = `${basename(lockPath)}.reclaim-ballot.`;
|
|
4205
4205
|
try {
|
|
4206
|
-
for (let
|
|
4207
|
-
if (
|
|
4206
|
+
for (let attempt2 = 0; attempt2 < PROCESS_LOCK_GUARD_ELECTION_ATTEMPTS; attempt2 += 1) {
|
|
4207
|
+
if (attempt2 > 0) {
|
|
4208
4208
|
await new Promise((resolvePromise) => setTimeout(
|
|
4209
4209
|
resolvePromise,
|
|
4210
|
-
Math.floor(Math.random() * PROCESS_LOCK_GUARD_ELECTION_BACKOFF_MS * BACKOFF_GROWTH_FACTOR ** Math.min(
|
|
4210
|
+
Math.floor(Math.random() * PROCESS_LOCK_GUARD_ELECTION_BACKOFF_MS * BACKOFF_GROWTH_FACTOR ** Math.min(attempt2, HOST_CORE_POLICY.process_lock_guard_election_backoff_exponent_max))
|
|
4211
4211
|
));
|
|
4212
4212
|
let current;
|
|
4213
4213
|
try {
|
|
@@ -4261,7 +4261,7 @@ while(($line=[Console]::In.ReadLine()) -ne $null) {
|
|
|
4261
4261
|
acquireProcessLockReclaimGuard = async (lockPath, ownerRecord, probes) => {
|
|
4262
4262
|
const guardPath = `${lockPath}.reclaim`;
|
|
4263
4263
|
const guardToken = randomBytes(INFERENCE_HOST_RANDOM_BYTES.LOCK_TOKEN).toString("base64url");
|
|
4264
|
-
for (let
|
|
4264
|
+
for (let attempt2 = 0; attempt2 < INFERENCE_HOST_RECLAIM_GUARD_CREATE_PASSES; attempt2 += 1) {
|
|
4265
4265
|
const handle = await openExclusiveProcessLockFile(guardPath);
|
|
4266
4266
|
if (handle) {
|
|
4267
4267
|
try {
|
|
@@ -4311,7 +4311,7 @@ while(($line=[Console]::In.ReadLine()) -ne $null) {
|
|
|
4311
4311
|
}
|
|
4312
4312
|
};
|
|
4313
4313
|
}
|
|
4314
|
-
if (
|
|
4314
|
+
if (attempt2 > 0) break;
|
|
4315
4315
|
const inspection = await inspectProcessLockFile(guardPath, PROCESS_LOCK_GUARD_LABEL, probes);
|
|
4316
4316
|
if (inspection.state === "busy") break;
|
|
4317
4317
|
if (inspection.state === "stale") {
|
|
@@ -5248,7 +5248,7 @@ var init_updater = __esm({
|
|
|
5248
5248
|
const paths = resolveCliUpdatePaths(env);
|
|
5249
5249
|
const now = dependencies.now ?? (() => /* @__PURE__ */ new Date());
|
|
5250
5250
|
const current = dependencies.currentVersion ?? agent_cli_release_default.package_version;
|
|
5251
|
-
for (let
|
|
5251
|
+
for (let attempt2 = 0; attempt2 < runtime_policy_generated_default.agent_cli.update_plan_max_attempts; attempt2 += 1) {
|
|
5252
5252
|
const plan = await planCliEntryUpdate(entry, argv2, env, script, dependencies);
|
|
5253
5253
|
if (plan.kind === "refuse") {
|
|
5254
5254
|
stderr.write(`${plan.message}
|
|
@@ -25968,25 +25968,25 @@ var init_mcp_client = __esm({
|
|
|
25968
25968
|
structuredContent: external_exports.unknown()
|
|
25969
25969
|
}).passthrough().parse(rawResult);
|
|
25970
25970
|
if (callResult.isError === true) {
|
|
25971
|
-
const
|
|
25971
|
+
const errorText2 = (callResult.content ?? []).filter((block) => block.type === "text").map((block) => block.text ?? "").join("\n");
|
|
25972
25972
|
const structuredPublicToolError = structuredPublicToolErrorSchema.safeParse(
|
|
25973
25973
|
callResult.structuredContent
|
|
25974
25974
|
);
|
|
25975
25975
|
const structuredDocument = callResult.structuredContent !== null && typeof callResult.structuredContent === "object" && !Array.isArray(callResult.structuredContent) ? callResult.structuredContent : null;
|
|
25976
25976
|
const hasStructuredPublicToolErrorMarker = structuredDocument?.schema_version === "vtx_insights_tool_error_v1";
|
|
25977
|
-
const publicToolError = structuredPublicToolError.success ? structuredPublicToolError.data : hasStructuredPublicToolErrorMarker ? null : parsePublicToolError(
|
|
25978
|
-
const hasPublicToolErrorMarker = hasStructuredPublicToolErrorMarker ||
|
|
25979
|
-
const completionEvidenceExpired = name === "inference.job.complete" && (publicToolError ? publicToolError.failure_code === "completion_evidence_expired" && publicToolError.phase === "validation" && publicToolError.retryable === false && publicToolError.terminal_before_execution === true : !hasPublicToolErrorMarker &&
|
|
25977
|
+
const publicToolError = structuredPublicToolError.success ? structuredPublicToolError.data : hasStructuredPublicToolErrorMarker ? null : parsePublicToolError(errorText2);
|
|
25978
|
+
const hasPublicToolErrorMarker = hasStructuredPublicToolErrorMarker || errorText2.includes(PUBLIC_TOOL_ERROR_PREFIX);
|
|
25979
|
+
const completionEvidenceExpired = name === "inference.job.complete" && (publicToolError ? publicToolError.failure_code === "completion_evidence_expired" && publicToolError.phase === "validation" && publicToolError.retryable === false && publicToolError.terminal_before_execution === true : !hasPublicToolErrorMarker && errorText2.includes("External inference completion evidence window expired"));
|
|
25980
25980
|
const hostNotClaimable = name === "inference.job.claim" && publicToolError?.failure_code === "host_not_claimable" && publicToolError.phase === "admission" && publicToolError.retryable === true && publicToolError.terminal_before_execution === true;
|
|
25981
|
-
const definitivelyNotApplied = (name === "inference.agent.decision.submit" || name === "inference.agent.data.call") && publicToolError?.phase === "validation" && publicToolError.retryable === false && publicToolError.terminal_before_execution === true && (name === "inference.agent.decision.submit" && publicToolError.failure_code === "agent_decision_schema_invalid" || publicToolError.failure_code === "invalid_arguments" && publicToolError.reason_code === "schema_validation") || (name === "inference.host.register" || name === "inference.host.advertise") && (
|
|
25981
|
+
const definitivelyNotApplied = (name === "inference.agent.decision.submit" || name === "inference.agent.data.call") && publicToolError?.phase === "validation" && publicToolError.retryable === false && publicToolError.terminal_before_execution === true && (name === "inference.agent.decision.submit" && publicToolError.failure_code === "agent_decision_schema_invalid" || publicToolError.failure_code === "invalid_arguments" && publicToolError.reason_code === "schema_validation") || (name === "inference.host.register" || name === "inference.host.advertise") && (errorText2.includes("Advertisement time is outside the allowed clock skew.") || errorText2.includes("Advertisement is already expired.")) || (name === "inference.agent.next" || name === "inference.agent.heartbeat") && (errorText2.includes("Advertisement time is outside the allowed clock skew.") || errorText2.includes("Advertisement is already expired.") || errorText2.includes("Heartbeat time is outside the allowed clock skew.")) || name === "inference.host.heartbeat" && errorText2.includes("Heartbeat time is outside the allowed clock skew.") || name === "inference.job.claim" && (errorText2.includes(
|
|
25982
25982
|
"External inference claim request was not applied before its generation became stale"
|
|
25983
|
-
) ||
|
|
25984
|
-
const retryableInfrastructureRejection = EXTERNAL_INFERENCE_AUTOMATED_HOST_TOOLS.includes(name) && (
|
|
25985
|
-
const retryableClaimRejection = name === "inference.job.claim" && !definitivelyNotApplied && (retryableInfrastructureRejection || hostNotClaimable ||
|
|
25983
|
+
) || errorText2.includes("External inference host advertisement is expired or superseded")) || name === "inference.job.complete" && completionEvidenceExpired;
|
|
25984
|
+
const retryableInfrastructureRejection = EXTERNAL_INFERENCE_AUTOMATED_HOST_TOOLS.includes(name) && (errorText2.includes("External inference polling is at its configured concurrency limit") || errorText2.includes("The Insights action reached the response timeout") || errorText2.includes("Insights capability failed without exposing private runtime details"));
|
|
25985
|
+
const retryableClaimRejection = name === "inference.job.claim" && !definitivelyNotApplied && (retryableInfrastructureRejection || hostNotClaimable || errorText2.includes("External inference host is not live enough to claim work") || errorText2.includes("External inference host request generation is stale") || errorText2.includes("External inference claim runtime fence is stale"));
|
|
25986
25986
|
const retryableHeartbeatClockSkew = name === "inference.host.heartbeat" && definitivelyNotApplied;
|
|
25987
25987
|
const retryableAdvertisementClockSkew = (name === "inference.host.register" || name === "inference.host.advertise") && definitivelyNotApplied;
|
|
25988
|
-
const staleHostHeartbeatGeneration = name === "inference.host.heartbeat" &&
|
|
25989
|
-
const obsoleteClaimReplay = name === "inference.job.claim" &&
|
|
25988
|
+
const staleHostHeartbeatGeneration = name === "inference.host.heartbeat" && errorText2.includes("Heartbeat generations do not match the current host authority.");
|
|
25989
|
+
const obsoleteClaimReplay = name === "inference.job.claim" && errorText2.includes(
|
|
25990
25990
|
"External inference claim replay is no longer dispatchable"
|
|
25991
25991
|
);
|
|
25992
25992
|
throw new ExternalInferenceMcpError(
|
|
@@ -33318,13 +33318,13 @@ child.once('close', async (code, signal) => {
|
|
|
33318
33318
|
const sleep4 = options.sleep ?? ((milliseconds) => new Promise((resolve14) => setTimeout(resolve14, milliseconds)));
|
|
33319
33319
|
const maxAttempts = Math.max(1, options.maxAttempts ?? HOST_RUNTIME_POLICY.codex_guardian_receipt_replace_attempts);
|
|
33320
33320
|
const retryDelayMs = Math.max(0, options.retryDelayMs ?? HOST_RUNTIME_POLICY.codex_guardian_receipt_replace_retry_ms);
|
|
33321
|
-
for (let
|
|
33321
|
+
for (let attempt2 = 0; attempt2 < maxAttempts; attempt2 += 1) {
|
|
33322
33322
|
try {
|
|
33323
33323
|
await renameFile(temporaryPath, receiptPath);
|
|
33324
33324
|
return;
|
|
33325
33325
|
} catch (error48) {
|
|
33326
33326
|
const code = String(error48.code ?? "");
|
|
33327
|
-
if (platform !== "win32" || !WINDOWS_RECEIPT_REPLACE_ERROR_CODES.has(code) ||
|
|
33327
|
+
if (platform !== "win32" || !WINDOWS_RECEIPT_REPLACE_ERROR_CODES.has(code) || attempt2 === maxAttempts - 1) {
|
|
33328
33328
|
throw error48;
|
|
33329
33329
|
}
|
|
33330
33330
|
try {
|
|
@@ -35649,14 +35649,14 @@ var init_runner = __esm({
|
|
|
35649
35649
|
terminal_pending: 0
|
|
35650
35650
|
};
|
|
35651
35651
|
const terminalOperations = [];
|
|
35652
|
-
for (const
|
|
35653
|
-
phaseCounts[
|
|
35654
|
-
const terminal =
|
|
35652
|
+
for (const attempt2 of Object.values(receipt.attempts)) {
|
|
35653
|
+
phaseCounts[attempt2.phase] += 1;
|
|
35654
|
+
const terminal = attempt2.terminal_request;
|
|
35655
35655
|
if (!terminal) continue;
|
|
35656
35656
|
const failed = terminal.schema_version === "external_inference_job_fail_v1";
|
|
35657
35657
|
terminalOperations.push({
|
|
35658
|
-
job_id:
|
|
35659
|
-
attempt_id:
|
|
35658
|
+
job_id: attempt2.job_id,
|
|
35659
|
+
attempt_id: attempt2.attempt_id,
|
|
35660
35660
|
operation_kind: failed ? "fail" : "complete",
|
|
35661
35661
|
dispatch_outcome: terminal.outcome.dispatch_outcome,
|
|
35662
35662
|
failure_category: failed ? terminal.failure_category : null,
|
|
@@ -35678,7 +35678,7 @@ var init_runner = __esm({
|
|
|
35678
35678
|
async read() {
|
|
35679
35679
|
let raw = null;
|
|
35680
35680
|
const attempts = runtime_policy_generated_default.external_inference.host_core.atomic_replacement_read_attempts;
|
|
35681
|
-
for (let
|
|
35681
|
+
for (let attempt2 = 0; attempt2 < attempts; attempt2 += 1) {
|
|
35682
35682
|
try {
|
|
35683
35683
|
raw = await this.readPrivateFile(
|
|
35684
35684
|
this.path,
|
|
@@ -35687,7 +35687,7 @@ var init_runner = __esm({
|
|
|
35687
35687
|
break;
|
|
35688
35688
|
} catch (error48) {
|
|
35689
35689
|
const changedDuringRead = error48 instanceof Error && error48.message === "Inference host runtime receipt file changed while it was opened.";
|
|
35690
|
-
if (!changedDuringRead ||
|
|
35690
|
+
if (!changedDuringRead || attempt2 === attempts - 1) throw error48;
|
|
35691
35691
|
}
|
|
35692
35692
|
}
|
|
35693
35693
|
if (raw === null) return null;
|
|
@@ -35858,8 +35858,8 @@ var init_runner = __esm({
|
|
|
35858
35858
|
throw new Error("Inference host pending claim receipt is invalid.");
|
|
35859
35859
|
}
|
|
35860
35860
|
const attempts = Object.fromEntries(
|
|
35861
|
-
Object.entries(record5.attempts).map(([key,
|
|
35862
|
-
const validated = validateAttemptReceipt(
|
|
35861
|
+
Object.entries(record5.attempts).map(([key, attempt2]) => {
|
|
35862
|
+
const validated = validateAttemptReceipt(attempt2);
|
|
35863
35863
|
if (key !== validated.attempt_id) {
|
|
35864
35864
|
throw new Error("Inference host attempt receipt key is invalid.");
|
|
35865
35865
|
}
|
|
@@ -36746,7 +36746,7 @@ var init_runner = __esm({
|
|
|
36746
36746
|
const envelopePublicKey = await this.dependencies.envelopePublicKey(credential);
|
|
36747
36747
|
const retryExact = async (operation, boundary = {}) => {
|
|
36748
36748
|
let lastError;
|
|
36749
|
-
for (let
|
|
36749
|
+
for (let attempt2 = 1; attempt2 <= settings.remoteRetryLimit; attempt2 += 1) {
|
|
36750
36750
|
if (boundary.signal?.aborted) {
|
|
36751
36751
|
throw new ExternalInferenceMcpError(
|
|
36752
36752
|
"request_aborted",
|
|
@@ -36764,10 +36764,10 @@ var init_runner = __esm({
|
|
|
36764
36764
|
return await operation();
|
|
36765
36765
|
} catch (error48) {
|
|
36766
36766
|
lastError = error48;
|
|
36767
|
-
if (!retryableRemoteError(error48) || error48 instanceof ExternalInferenceMcpError && error48.definitivelyNotApplied ||
|
|
36767
|
+
if (!retryableRemoteError(error48) || error48 instanceof ExternalInferenceMcpError && error48.definitivelyNotApplied || attempt2 === settings.remoteRetryLimit) throw error48;
|
|
36768
36768
|
const requestedRetryDelay = remoteRetryAfterMs(
|
|
36769
36769
|
error48,
|
|
36770
|
-
Math.min(HOST_RUNTIME_POLICY2.remote_retry_backoff_step_ms *
|
|
36770
|
+
Math.min(HOST_RUNTIME_POLICY2.remote_retry_backoff_step_ms * attempt2, HOST_RUNTIME_POLICY2.remote_retry_backoff_max_ms)
|
|
36771
36771
|
);
|
|
36772
36772
|
const remaining = boundary.deadlineAtMs === void 0 ? Number.POSITIVE_INFINITY : Math.max(0, boundary.deadlineAtMs - now());
|
|
36773
36773
|
if (requestedRetryDelay < 1 || requestedRetryDelay >= remaining) {
|
|
@@ -36795,7 +36795,7 @@ var init_runner = __esm({
|
|
|
36795
36795
|
const retained = /* @__PURE__ */ new Set([
|
|
36796
36796
|
receipt.advertisement_generation,
|
|
36797
36797
|
receipt.pending_claim_request?.advertisement_generation,
|
|
36798
|
-
...Object.values(receipt.attempts).map((
|
|
36798
|
+
...Object.values(receipt.attempts).map((attempt2) => attempt2.claim.advertisement_generation)
|
|
36799
36799
|
]);
|
|
36800
36800
|
for (const generation of modelSnapshots.keys()) {
|
|
36801
36801
|
if (!retained.has(generation)) modelSnapshots.delete(generation);
|
|
@@ -37868,11 +37868,11 @@ var init_runner = __esm({
|
|
|
37868
37868
|
const batchReceiptDurability = mutateReceipt((current) => {
|
|
37869
37869
|
if (current.pending_claim_request?.claim_request_id !== request.claim_request_id) runnerIdentityMismatch("Batched claim receipt");
|
|
37870
37870
|
const attempts = { ...current.attempts };
|
|
37871
|
-
for (const
|
|
37872
|
-
if (attempts[
|
|
37871
|
+
for (const attempt2 of prepared) {
|
|
37872
|
+
if (attempts[attempt2.attempt_id]) {
|
|
37873
37873
|
runnerIdentityMismatch("Batched attempt receipt");
|
|
37874
37874
|
}
|
|
37875
|
-
attempts[
|
|
37875
|
+
attempts[attempt2.attempt_id] = attempt2;
|
|
37876
37876
|
}
|
|
37877
37877
|
const promoted = {
|
|
37878
37878
|
...current,
|
|
@@ -40153,14 +40153,14 @@ var init_owned_directory_removal = __esm({
|
|
|
40153
40153
|
}));
|
|
40154
40154
|
const maxAttempts = Math.max(1, options.maxAttempts ?? runtime_policy_generated_default.external_inference.host_core.owned_directory_removal_attempts);
|
|
40155
40155
|
const retryDelayMs = Math.max(0, options.retryDelayMs ?? runtime_policy_generated_default.external_inference.host_core.owned_directory_removal_retry_step_ms);
|
|
40156
|
-
for (let
|
|
40156
|
+
for (let attempt2 = 1; ; attempt2 += 1) {
|
|
40157
40157
|
try {
|
|
40158
40158
|
await removeDirectory(path, { recursive: true, force: options.force ?? true });
|
|
40159
40159
|
return;
|
|
40160
40160
|
} catch (error48) {
|
|
40161
40161
|
const code = String(error48?.code ?? "");
|
|
40162
|
-
if (
|
|
40163
|
-
await sleep4(retryDelayMs *
|
|
40162
|
+
if (attempt2 >= maxAttempts || !TRANSIENT_REMOVAL_ERROR_CODES.has(code)) throw error48;
|
|
40163
|
+
await sleep4(retryDelayMs * attempt2);
|
|
40164
40164
|
}
|
|
40165
40165
|
}
|
|
40166
40166
|
};
|
|
@@ -41389,7 +41389,7 @@ var init_codex_adapter = __esm({
|
|
|
41389
41389
|
[...sessions].map((session) => this.invalidateDurableSession(session))
|
|
41390
41390
|
);
|
|
41391
41391
|
await Promise.allSettled(
|
|
41392
|
-
[...this.inFlightAttempts.values()].map((
|
|
41392
|
+
[...this.inFlightAttempts.values()].map((attempt2) => attempt2.promise)
|
|
41393
41393
|
);
|
|
41394
41394
|
await Promise.allSettled(
|
|
41395
41395
|
[...this.attemptCleanups.values()]
|
|
@@ -45809,9 +45809,9 @@ var init_grok_adapter = __esm({
|
|
|
45809
45809
|
if (existing.inputSha256 !== input.inputSha256) return Promise.reject(new Error("grok_attempt_input_mismatch"));
|
|
45810
45810
|
return existing.promise;
|
|
45811
45811
|
}
|
|
45812
|
-
const
|
|
45813
|
-
this.attempts.set(input.attemptId, { inputSha256: input.inputSha256, promise:
|
|
45814
|
-
return
|
|
45812
|
+
const attempt2 = this.track(this.run(input, null).then((result) => result.turn).finally(() => this.attempts.delete(input.attemptId)));
|
|
45813
|
+
this.attempts.set(input.attemptId, { inputSha256: input.inputSha256, promise: attempt2 });
|
|
45814
|
+
return attempt2;
|
|
45815
45815
|
}
|
|
45816
45816
|
runTurn(input) {
|
|
45817
45817
|
return this.track(this.run(null, input));
|
|
@@ -46417,9 +46417,9 @@ var init_exo_adapter = __esm({
|
|
|
46417
46417
|
if (request.url === "/dispatch") {
|
|
46418
46418
|
if (body.model !== providerModel || body.reasoningEffort !== input.requestedReasoningEffort) throw failure("exo_dispatch_identity_mismatch");
|
|
46419
46419
|
if (!agent) {
|
|
46420
|
-
const
|
|
46421
|
-
if (!dispatched && Date.now() >= (
|
|
46422
|
-
if (!dispatched)
|
|
46420
|
+
const attempt2 = input;
|
|
46421
|
+
if (!dispatched && Date.now() >= (attempt2.providerDispatchNotAfterMs ?? input.deadlineAtMs)) throw failure("exo_dispatch_freshness_expired");
|
|
46422
|
+
if (!dispatched) attempt2.onProviderDispatch?.();
|
|
46423
46423
|
}
|
|
46424
46424
|
dispatched = true;
|
|
46425
46425
|
reply(HTTP_STATUS.OK, { ok: true });
|
|
@@ -47503,7 +47503,7 @@ var init_service = __esm({
|
|
|
47503
47503
|
}
|
|
47504
47504
|
};
|
|
47505
47505
|
readManifestAcrossAtomicReplacement = async (path) => {
|
|
47506
|
-
for (let
|
|
47506
|
+
for (let attempt2 = 0; attempt2 < ATOMIC_REPLACEMENT_READ_ATTEMPTS; attempt2 += 1) {
|
|
47507
47507
|
try {
|
|
47508
47508
|
return await readInferenceHostServiceManifest(path);
|
|
47509
47509
|
} catch (error48) {
|
|
@@ -47527,7 +47527,7 @@ var init_service = __esm({
|
|
|
47527
47527
|
}
|
|
47528
47528
|
};
|
|
47529
47529
|
readRuntimeAcrossAtomicReplacement = async (path) => {
|
|
47530
|
-
for (let
|
|
47530
|
+
for (let attempt2 = 0; attempt2 < ATOMIC_REPLACEMENT_READ_ATTEMPTS; attempt2 += 1) {
|
|
47531
47531
|
try {
|
|
47532
47532
|
return await readInferenceHostServiceRuntime(path);
|
|
47533
47533
|
} catch (error48) {
|
|
@@ -47549,7 +47549,7 @@ var init_service = __esm({
|
|
|
47549
47549
|
}
|
|
47550
47550
|
};
|
|
47551
47551
|
readDesiredAcrossAtomicReplacement = async (path) => {
|
|
47552
|
-
for (let
|
|
47552
|
+
for (let attempt2 = 0; attempt2 < ATOMIC_REPLACEMENT_READ_ATTEMPTS; attempt2 += 1) {
|
|
47553
47553
|
try {
|
|
47554
47554
|
return await readInferenceHostServiceDesired(path);
|
|
47555
47555
|
} catch (error48) {
|
|
@@ -47727,7 +47727,7 @@ WantedBy=default.target
|
|
|
47727
47727
|
}
|
|
47728
47728
|
async withControlLock(operation) {
|
|
47729
47729
|
let lock2 = null;
|
|
47730
|
-
for (let
|
|
47730
|
+
for (let attempt2 = 0; attempt2 < SERVICE_POLICY.control_lock_wait_attempts; attempt2 += 1) {
|
|
47731
47731
|
try {
|
|
47732
47732
|
lock2 = await this.acquireProcessLock(this.controlLockPath());
|
|
47733
47733
|
break;
|
|
@@ -47812,7 +47812,7 @@ WantedBy=default.target
|
|
|
47812
47812
|
return await this.runCommand("systemctl", ["--user", "disable", "--now", SYSTEMD_UNIT]);
|
|
47813
47813
|
}
|
|
47814
47814
|
async waitForManagerActive() {
|
|
47815
|
-
for (let
|
|
47815
|
+
for (let attempt2 = 0; attempt2 < this.startWaitAttempts; attempt2 += 1) {
|
|
47816
47816
|
const status = await this.status();
|
|
47817
47817
|
if (status.manager_active) return status;
|
|
47818
47818
|
await this.sleep(SERVICE_POLICY.startup_poll_interval_ms);
|
|
@@ -47860,7 +47860,7 @@ ${result.stderr}`)) {
|
|
|
47860
47860
|
}
|
|
47861
47861
|
async waitForManifestApplied(manifest, targetInstanceName, maxAttempts = this.reconcileWaitAttempts, minimumRuntimeUpdatedAtExclusive) {
|
|
47862
47862
|
let consecutiveReadyObservations = 0;
|
|
47863
|
-
for (let
|
|
47863
|
+
for (let attempt2 = 0; attempt2 < maxAttempts; attempt2 += 1) {
|
|
47864
47864
|
let runtime = null;
|
|
47865
47865
|
try {
|
|
47866
47866
|
runtime = await readRuntimeAcrossAtomicReplacement(this.runtimePath());
|
|
@@ -48256,7 +48256,7 @@ ${result.stderr}`)) {
|
|
|
48256
48256
|
this.serviceBootstrapLockPath()
|
|
48257
48257
|
];
|
|
48258
48258
|
let serviceReleased = false;
|
|
48259
|
-
for (let
|
|
48259
|
+
for (let attempt2 = 0; attempt2 < this.stopWaitAttempts; attempt2 += 1) {
|
|
48260
48260
|
let allReleased = true;
|
|
48261
48261
|
for (const serviceLockPath of serviceLockPaths) {
|
|
48262
48262
|
try {
|
|
@@ -55621,19 +55621,19 @@ var init_shared = __esm({
|
|
|
55621
55621
|
if (Number.isFinite(retryAtMs)) return Math.max(0, retryAtMs - Date.now());
|
|
55622
55622
|
return null;
|
|
55623
55623
|
};
|
|
55624
|
-
resolveAuthBootstrapRetryDelayMs = (response,
|
|
55624
|
+
resolveAuthBootstrapRetryDelayMs = (response, attempt2) => {
|
|
55625
55625
|
const retryAfterMs = parseRetryAfterMs2(response.headers.get("Retry-After"));
|
|
55626
|
-
const baseDelayMs = retryAfterMs ?? runtime_policy_generated_default2.ui.auth_bootstrap_retry.base_delay_milliseconds * BACKOFF_GROWTH_FACTOR ** (
|
|
55626
|
+
const baseDelayMs = retryAfterMs ?? runtime_policy_generated_default2.ui.auth_bootstrap_retry.base_delay_milliseconds * BACKOFF_GROWTH_FACTOR ** (attempt2 - 1);
|
|
55627
55627
|
const jitterMs = Math.floor(Math.random() * AUTH_BOOTSTRAP_RETRY_JITTER_MS);
|
|
55628
55628
|
return Math.min(runtime_policy_generated_default2.ui.auth_bootstrap_retry.max_delay_milliseconds, Math.max(runtime_policy_generated_default2.ui.auth_bootstrap_retry.min_delay_milliseconds, baseDelayMs + jitterMs));
|
|
55629
55629
|
};
|
|
55630
55630
|
fetchAuthBootstrapGetWithRetry = async (input, init2) => {
|
|
55631
|
-
for (let
|
|
55631
|
+
for (let attempt2 = 1; attempt2 <= AUTH_BOOTSTRAP_GET_MAX_ATTEMPTS; attempt2 += 1) {
|
|
55632
55632
|
const response = await apiFetch(input, init2);
|
|
55633
|
-
if (response.ok ||
|
|
55633
|
+
if (response.ok || attempt2 >= AUTH_BOOTSTRAP_GET_MAX_ATTEMPTS || response.status !== HTTP_STATUS.TOO_MANY_REQUESTS && response.status !== HTTP_STATUS.SERVICE_UNAVAILABLE) {
|
|
55634
55634
|
return response;
|
|
55635
55635
|
}
|
|
55636
|
-
await sleep(resolveAuthBootstrapRetryDelayMs(response,
|
|
55636
|
+
await sleep(resolveAuthBootstrapRetryDelayMs(response, attempt2));
|
|
55637
55637
|
}
|
|
55638
55638
|
return apiFetch(input, init2);
|
|
55639
55639
|
};
|
|
@@ -56491,7 +56491,7 @@ var init_network_debug = __esm({
|
|
|
56491
56491
|
const attempts = [];
|
|
56492
56492
|
for (const candidate of buildLocalProviderProbeUrls(entry)) {
|
|
56493
56493
|
const startedAt = Date.now();
|
|
56494
|
-
const
|
|
56494
|
+
const attempt2 = {
|
|
56495
56495
|
path: candidate.path,
|
|
56496
56496
|
startedAt,
|
|
56497
56497
|
completedAt: null,
|
|
@@ -56500,7 +56500,7 @@ var init_network_debug = __esm({
|
|
|
56500
56500
|
error: null,
|
|
56501
56501
|
elapsedMs: null
|
|
56502
56502
|
};
|
|
56503
|
-
attempts.push(
|
|
56503
|
+
attempts.push(attempt2);
|
|
56504
56504
|
patchRuntimeProviderFailureDebugEntry(entry.id, (current) => ({
|
|
56505
56505
|
...current,
|
|
56506
56506
|
healthProbe: {
|
|
@@ -56516,17 +56516,17 @@ var init_network_debug = __esm({
|
|
|
56516
56516
|
signal: controller?.signal
|
|
56517
56517
|
});
|
|
56518
56518
|
const completedAt2 = Date.now();
|
|
56519
|
-
|
|
56520
|
-
|
|
56521
|
-
|
|
56522
|
-
|
|
56523
|
-
|
|
56519
|
+
attempt2.completedAt = completedAt2;
|
|
56520
|
+
attempt2.outcome = response.ok ? "ok" : "error";
|
|
56521
|
+
attempt2.status = response.status;
|
|
56522
|
+
attempt2.error = response.ok ? null : `HTTP ${response.status}`;
|
|
56523
|
+
attempt2.elapsedMs = Math.max(0, completedAt2 - startedAt);
|
|
56524
56524
|
} catch (error48) {
|
|
56525
56525
|
const completedAt2 = Date.now();
|
|
56526
|
-
|
|
56527
|
-
|
|
56528
|
-
|
|
56529
|
-
|
|
56526
|
+
attempt2.completedAt = completedAt2;
|
|
56527
|
+
attempt2.outcome = "error";
|
|
56528
|
+
attempt2.error = getSanitizedRuntimeErrorMessage(error48) || "health probe failed";
|
|
56529
|
+
attempt2.elapsedMs = Math.max(0, completedAt2 - startedAt);
|
|
56530
56530
|
} finally {
|
|
56531
56531
|
if (timeoutId) {
|
|
56532
56532
|
clearTimeout(timeoutId);
|
|
@@ -56539,7 +56539,7 @@ var init_network_debug = __esm({
|
|
|
56539
56539
|
attempts: attempts.slice()
|
|
56540
56540
|
}
|
|
56541
56541
|
}));
|
|
56542
|
-
if (
|
|
56542
|
+
if (attempt2.outcome === "ok") {
|
|
56543
56543
|
break;
|
|
56544
56544
|
}
|
|
56545
56545
|
}
|
|
@@ -61221,8 +61221,8 @@ var init_fetch = __esm({
|
|
|
61221
61221
|
this.#throttle.maxAttempts = params.maxAttempts;
|
|
61222
61222
|
}
|
|
61223
61223
|
}
|
|
61224
|
-
async #send(
|
|
61225
|
-
if (
|
|
61224
|
+
async #send(attempt2, expires, delay3, _request, _response) {
|
|
61225
|
+
if (attempt2 >= this.#throttle.maxAttempts) {
|
|
61226
61226
|
return _response.makeServerError("exceeded maximum retry limit");
|
|
61227
61227
|
}
|
|
61228
61228
|
assert2(getTime() <= expires, "timeout", "TIMEOUT", {
|
|
@@ -61261,18 +61261,18 @@ var init_fetch = __esm({
|
|
|
61261
61261
|
if (response.statusCode === 301 || response.statusCode === 302) {
|
|
61262
61262
|
try {
|
|
61263
61263
|
const location2 = response.headers.location || "";
|
|
61264
|
-
return req.redirect(location2).#send(
|
|
61264
|
+
return req.redirect(location2).#send(attempt2 + 1, expires, 0, _request, response);
|
|
61265
61265
|
} catch (error48) {
|
|
61266
61266
|
}
|
|
61267
61267
|
return response;
|
|
61268
61268
|
} else if (response.statusCode === 429) {
|
|
61269
|
-
if (this.retryFunc == null || await this.retryFunc(req, response,
|
|
61269
|
+
if (this.retryFunc == null || await this.retryFunc(req, response, attempt2)) {
|
|
61270
61270
|
const retryAfter = response.headers["retry-after"];
|
|
61271
|
-
let delay4 = this.#throttle.slotInterval * Math.trunc(Math.random() * Math.pow(2,
|
|
61271
|
+
let delay4 = this.#throttle.slotInterval * Math.trunc(Math.random() * Math.pow(2, attempt2));
|
|
61272
61272
|
if (typeof retryAfter === "string" && retryAfter.match(/^[1-9][0-9]*$/)) {
|
|
61273
61273
|
delay4 = parseInt(retryAfter);
|
|
61274
61274
|
}
|
|
61275
|
-
return req.clone().#send(
|
|
61275
|
+
return req.clone().#send(attempt2 + 1, expires, delay4, _request, response);
|
|
61276
61276
|
}
|
|
61277
61277
|
}
|
|
61278
61278
|
if (this.processFunc) {
|
|
@@ -61283,12 +61283,12 @@ var init_fetch = __esm({
|
|
|
61283
61283
|
if (error48.throttle == null || typeof error48.stall !== "number") {
|
|
61284
61284
|
response.makeServerError("error in post-processing function", error48).assertOk();
|
|
61285
61285
|
}
|
|
61286
|
-
let delay4 = this.#throttle.slotInterval * Math.trunc(Math.random() * Math.pow(2,
|
|
61286
|
+
let delay4 = this.#throttle.slotInterval * Math.trunc(Math.random() * Math.pow(2, attempt2));
|
|
61287
61287
|
;
|
|
61288
61288
|
if (error48.stall >= 0) {
|
|
61289
61289
|
delay4 = error48.stall;
|
|
61290
61290
|
}
|
|
61291
|
-
return req.clone().#send(
|
|
61291
|
+
return req.clone().#send(attempt2 + 1, expires, delay4, _request, response);
|
|
61292
61292
|
}
|
|
61293
61293
|
}
|
|
61294
61294
|
return response;
|
|
@@ -78149,8 +78149,8 @@ var init_abstract_provider = __esm({
|
|
|
78149
78149
|
transaction: tx
|
|
78150
78150
|
}), "%response");
|
|
78151
78151
|
}
|
|
78152
|
-
async #call(tx, blockTag,
|
|
78153
|
-
assert2(
|
|
78152
|
+
async #call(tx, blockTag, attempt2) {
|
|
78153
|
+
assert2(attempt2 < MAX_CCIP_REDIRECTS, "CCIP read exceeded maximum redirections", "OFFCHAIN_FAULT", {
|
|
78154
78154
|
reason: "TOO_MANY_REDIRECTS",
|
|
78155
78155
|
transaction: Object.assign({}, tx, { blockTag, enableCcipRead: true })
|
|
78156
78156
|
});
|
|
@@ -78158,7 +78158,7 @@ var init_abstract_provider = __esm({
|
|
|
78158
78158
|
try {
|
|
78159
78159
|
return hexlify(await this._perform({ method: "call", transaction, blockTag }));
|
|
78160
78160
|
} catch (error48) {
|
|
78161
|
-
if (!this.disableCcipRead && isCallException(error48) && error48.data &&
|
|
78161
|
+
if (!this.disableCcipRead && isCallException(error48) && error48.data && attempt2 >= 0 && blockTag === "latest" && transaction.to != null && dataSlice(error48.data, 0, 4) === "0x556f1830") {
|
|
78162
78162
|
const data4 = error48.data;
|
|
78163
78163
|
const txSender = await resolveAddress(transaction.to, this);
|
|
78164
78164
|
let ccipArgs;
|
|
@@ -78195,7 +78195,7 @@ var init_abstract_provider = __esm({
|
|
|
78195
78195
|
};
|
|
78196
78196
|
this.emit("debug", { action: "sendCcipReadCall", transaction: tx2 });
|
|
78197
78197
|
try {
|
|
78198
|
-
const result = await this.#call(tx2, blockTag,
|
|
78198
|
+
const result = await this.#call(tx2, blockTag, attempt2 + 1);
|
|
78199
78199
|
this.emit("debug", { action: "receiveCcipReadCallResult", transaction: Object.assign({}, tx2), result });
|
|
78200
78200
|
return result;
|
|
78201
78201
|
} catch (error49) {
|
|
@@ -80120,7 +80120,7 @@ var init_provider_ankr = __esm({
|
|
|
80120
80120
|
const request = new FetchRequest(`https://${getHost(network.name)}/${apiKey}`);
|
|
80121
80121
|
request.allowGzip = true;
|
|
80122
80122
|
if (apiKey === defaultApiKey) {
|
|
80123
|
-
request.retryFunc = async (request2, response,
|
|
80123
|
+
request.retryFunc = async (request2, response, attempt2) => {
|
|
80124
80124
|
showThrottleMessage("AnkrProvider");
|
|
80125
80125
|
return true;
|
|
80126
80126
|
};
|
|
@@ -80252,7 +80252,7 @@ var init_provider_alchemy = __esm({
|
|
|
80252
80252
|
const request = new FetchRequest(`https://${getHost2(network.name)}/v2/${apiKey}`);
|
|
80253
80253
|
request.allowGzip = true;
|
|
80254
80254
|
if (apiKey === defaultApiKey2) {
|
|
80255
|
-
request.retryFunc = async (request2, response,
|
|
80255
|
+
request.retryFunc = async (request2, response, attempt2) => {
|
|
80256
80256
|
showThrottleMessage("alchemy");
|
|
80257
80257
|
return true;
|
|
80258
80258
|
};
|
|
@@ -80341,7 +80341,7 @@ var init_provider_chainstack = __esm({
|
|
|
80341
80341
|
const request = new FetchRequest(`https://${getHost3(network.name)}/${apiKey}`);
|
|
80342
80342
|
request.allowGzip = true;
|
|
80343
80343
|
if (apiKey === getApiKey(network.name)) {
|
|
80344
|
-
request.retryFunc = async (request2, response,
|
|
80344
|
+
request.retryFunc = async (request2, response, attempt2) => {
|
|
80345
80345
|
showThrottleMessage("ChainstackProvider");
|
|
80346
80346
|
return true;
|
|
80347
80347
|
};
|
|
@@ -80533,7 +80533,7 @@ var init_provider_etherscan = __esm({
|
|
|
80533
80533
|
this.emit("debug", { action: "sendRequest", id: id2, url: url2, payload });
|
|
80534
80534
|
const request = new FetchRequest(url2);
|
|
80535
80535
|
request.setThrottleParams({ slotInterval: 1e3 });
|
|
80536
|
-
request.retryFunc = (req, resp,
|
|
80536
|
+
request.retryFunc = (req, resp, attempt2) => {
|
|
80537
80537
|
if (this.isCommunityResource()) {
|
|
80538
80538
|
showThrottleMessage("Etherscan");
|
|
80539
80539
|
}
|
|
@@ -85137,7 +85137,7 @@ var init_provider_infura = __esm({
|
|
|
85137
85137
|
request.setCredentials("", projectSecret);
|
|
85138
85138
|
}
|
|
85139
85139
|
if (projectId === defaultProjectId) {
|
|
85140
|
-
request.retryFunc = async (request2, response,
|
|
85140
|
+
request.retryFunc = async (request2, response, attempt2) => {
|
|
85141
85141
|
showThrottleMessage("InfuraProvider");
|
|
85142
85142
|
return true;
|
|
85143
85143
|
};
|
|
@@ -85242,7 +85242,7 @@ var init_provider_quicknode = __esm({
|
|
|
85242
85242
|
const request = new FetchRequest(`https://${getHost5(network.name)}/${token}`);
|
|
85243
85243
|
request.allowGzip = true;
|
|
85244
85244
|
if (token === defaultToken) {
|
|
85245
|
-
request.retryFunc = async (request2, response,
|
|
85245
|
+
request.retryFunc = async (request2, response, attempt2) => {
|
|
85246
85246
|
showThrottleMessage("QuickNodeProvider");
|
|
85247
85247
|
return true;
|
|
85248
85248
|
};
|
|
@@ -86395,7 +86395,7 @@ var init_provider_pocket = __esm({
|
|
|
86395
86395
|
request.setCredentials("", applicationSecret);
|
|
86396
86396
|
}
|
|
86397
86397
|
if (applicationId === defaultApplicationId) {
|
|
86398
|
-
request.retryFunc = async (request2, response,
|
|
86398
|
+
request.retryFunc = async (request2, response, attempt2) => {
|
|
86399
86399
|
showThrottleMessage("PocketProvider");
|
|
86400
86400
|
return true;
|
|
86401
86401
|
};
|
|
@@ -90355,7 +90355,7 @@ var init_hyperliquid_signer = __esm({
|
|
|
90355
90355
|
});
|
|
90356
90356
|
|
|
90357
90357
|
// lib/runtime/hyperliquid-client.ts
|
|
90358
|
-
var HyperliquidExchangeRejectionError, durableMutationAuthorityArgs, assertFreshPreparedExecutionContext, normalizeSymbol, HYPERLIQUID_NONCE_STORAGE_KEY, HYPERLIQUID_NONCE_LOCK_NAME, lastGeneratedNonce, readBrowserStoredHyperliquidNonce, writeBrowserStoredHyperliquidNonce, browserNonceCoordinator, allocateHyperliquidNonce, hostNonceAllocator, allocateActionNonce, generateHyperliquidNonce, normalizeDecimalString, HYPERLIQUID_PRICE_SIGNIFICANT_FIGURES, HYPERLIQUID_INTEGER_PRICE_MINIMUM, shortestDecimalParts, formatHyperliquidPerpPriceGrid, formatHyperliquidTriggerPriceWire, hyperliquidOrderPriceRounding, formatHyperliquidOrderPriceWire, countSignificantDigits, countDecimalPlaces, validateHyperliquidPerpPriceWire, validateHyperliquidSizeWire, formatSizeWire, inferApiUrl, inferIsTestnet, postHyperliquidInfoRead, postHyperliquidInfo, fetchBrowserHyperliquidInfoPayload, fetchBrowserHyperliquidInfoRead, fetchBrowserHyperliquidInfoText, coerceMarketMaxLeverage, toFiniteNumber, OPEN_ORDER_NUMERIC_STRING, OPEN_ORDER_ID_STRING, parseCanonicalOpenOrderId, parseOpenOrderFiniteNumber, parseOpenOrderNonNegativeNumber, NATIVE_FIRED_TRIGGER_CONDITION, parseOpenOrderPositiveNumber, parseOpenOrderPresentationNumber, readOpenOrderField, firstFiniteNumber, parseFundingUsdcFromInfoPosition, isExchangeIsolatedOnly, resolveLeverageTarget, computeHip3AssetId, getPerpDexIndexMap, buildAssetInfosFromMetaResponse, requireWalletAddress, assertPositiveInteger, assertPositiveNumber, normalizeOrderSide, normalizeHyperliquidClientOrderId, resolveAssets, findResolvedAsset, normalizeExecutionAssetMetadata, resolveHyperliquidAsset, resolveHyperliquidAssetIndex, decimalUnits, quantizeHyperliquidOrderSizeValue, hyperliquidSignedSizeMatchesRequestedSize, finitePositive, readDevicePrivateExecutionContext, quantizeHyperliquidOrderSize, fetchBrowserAvailableAssets, fetchBrowserAllMids, fetchBrowserSymbolMidPrice, fetchBrowserOpenOrders, parseCanonicalHyperliquidOrderStatusEvidence, fetchBrowserOrderStatusEvidence, fetchBrowserUserRole, fetchBrowserAccountState, fetchBrowserPosition, buildHyperliquidOrderWire, buildHyperliquidTriggerOrderWire, signHyperliquidPayload, signHyperliquidPreparedAction, buildHyperliquidCancelPayload, buildHyperliquidUpdateLeveragePayload, buildHyperliquidMarketOrderPayload, buildHyperliquidLimitOrderPayload, buildHyperliquidTriggerOrderPayload, buildHyperliquidOrderBatchPayload, buildHyperliquidModifyOrderPayload, extractHyperliquidExchangeError, resolveHyperliquidTriggerAcknowledgements, isDefinitiveHyperliquidExchangeResponse, extractDefinitiveHyperliquidOrderId, CANONICAL_POSITIVE_DECIMAL_PATTERN, extractCanonicalHyperliquidOrderStateAcknowledgement, extractCanonicalHyperliquidOrderStateAcknowledgements, extractCanonicalHyperliquidFilledOrderAcknowledgement, extractDefinitiveHyperliquidOrderMemberResults, buildHyperliquidOrderDiagnostics, loadClientExecutionReferenceEvidence, sha256Hex, extractSignedPayloadClientOrderId, extractSignedPayloadMutationCorrelation, assertDurableMutationMatchesSignedAction, exchangeRejectionReason, exchangeActionPriority, submitHyperliquidExchangePayload;
|
|
90358
|
+
var HyperliquidExchangeRejectionError, durableMutationAuthorityArgs, assertFreshPreparedExecutionContext, normalizeSymbol, HYPERLIQUID_NONCE_STORAGE_KEY, HYPERLIQUID_NONCE_LOCK_NAME, lastGeneratedNonce, readBrowserStoredHyperliquidNonce, writeBrowserStoredHyperliquidNonce, browserNonceCoordinator, allocateHyperliquidNonce, hostNonceAllocator, allocateActionNonce, generateHyperliquidNonce, normalizeDecimalString, HYPERLIQUID_PRICE_SIGNIFICANT_FIGURES, HYPERLIQUID_INTEGER_PRICE_MINIMUM, shortestDecimalParts, formatHyperliquidPerpPriceGrid, formatHyperliquidTriggerPriceWire, hyperliquidOrderPriceRounding, formatHyperliquidOrderPriceWire, countSignificantDigits, countDecimalPlaces, validateHyperliquidPerpPriceWire, validateHyperliquidSizeWire, formatSizeWire, inferApiUrl, inferIsTestnet, postHyperliquidInfoRead, postHyperliquidInfo, fetchBrowserHyperliquidInfoPayload, fetchBrowserHyperliquidInfoRead, fetchBrowserHyperliquidInfoText, coerceMarketMaxLeverage, toFiniteNumber, OPEN_ORDER_NUMERIC_STRING, OPEN_ORDER_ID_STRING, parseCanonicalOpenOrderId, parseOpenOrderFiniteNumber, parseOpenOrderNonNegativeNumber, NATIVE_FIRED_TRIGGER_CONDITION, parseOpenOrderPositiveNumber, parseOpenOrderPresentationNumber, readOpenOrderField, firstFiniteNumber, parseFundingUsdcFromInfoPosition, isExchangeIsolatedOnly, resolveLeverageTarget, computeHip3AssetId, getPerpDexIndexMap, buildAssetInfosFromMetaResponse, requireWalletAddress, assertPositiveInteger, assertPositiveNumber, normalizeOrderSide, normalizeHyperliquidClientOrderId, resolveAssets, findResolvedAsset, normalizeExecutionAssetMetadata, resolveHyperliquidAsset, resolveHyperliquidAssetIndex, decimalUnits, quantizeHyperliquidOrderSizeValue, hyperliquidSignedSizeMatchesRequestedSize, finitePositive, readDevicePrivateExecutionContext, quantizeHyperliquidOrderSize, fetchBrowserAvailableAssets, fetchBrowserAllMids, fetchBrowserSymbolMidPrice, fetchBrowserOpenOrders, parseCanonicalHyperliquidOrderStatusEvidence, fetchBrowserOrderStatusEvidence, fetchBrowserUserRole, fetchBrowserAccountState, fetchBrowserPosition, buildHyperliquidOrderWire, buildHyperliquidTriggerOrderWire, signHyperliquidPayload, signHyperliquidPreparedAction, buildHyperliquidCancelPayload, buildHyperliquidUpdateLeveragePayload, buildHyperliquidMarketOrderPayload, buildHyperliquidLimitOrderPayload, buildHyperliquidTriggerOrderPayload, buildHyperliquidOrderBatchPayload, buildHyperliquidModifyOrderPayload, extractHyperliquidExchangeError, resolveHyperliquidTriggerAcknowledgements, resolveHyperliquidModifyAcknowledgement, isDefinitiveHyperliquidExchangeResponse, extractDefinitiveHyperliquidOrderId, CANONICAL_POSITIVE_DECIMAL_PATTERN, extractCanonicalHyperliquidOrderStateAcknowledgement, extractCanonicalHyperliquidOrderStateAcknowledgements, extractCanonicalHyperliquidFilledOrderAcknowledgement, extractDefinitiveHyperliquidOrderMemberResults, buildHyperliquidOrderDiagnostics, loadClientExecutionReferenceEvidence, sha256Hex, extractSignedPayloadClientOrderId, extractSignedPayloadMutationCorrelation, assertDurableMutationMatchesSignedAction, exchangeRejectionReason, exchangeActionPriority, submitHyperliquidExchangePayload;
|
|
90359
90359
|
var init_hyperliquid_client = __esm({
|
|
90360
90360
|
"lib/runtime/hyperliquid-client.ts"() {
|
|
90361
90361
|
"use strict";
|
|
@@ -91895,6 +91895,36 @@ var init_hyperliquid_client = __esm({
|
|
|
91895
91895
|
}
|
|
91896
91896
|
return { ...root, response: { ...response, data: { ...data4, statuses: resolved } } };
|
|
91897
91897
|
};
|
|
91898
|
+
resolveHyperliquidModifyAcknowledgement = async (payload, action, lookup) => {
|
|
91899
|
+
if (action.type !== "modify" || payload == null || typeof payload !== "object" || Array.isArray(payload)) {
|
|
91900
|
+
return payload;
|
|
91901
|
+
}
|
|
91902
|
+
const root = payload;
|
|
91903
|
+
const response = root.response;
|
|
91904
|
+
const order = action.order;
|
|
91905
|
+
const clientOrderId = String(order?.c ?? "").trim().toLowerCase();
|
|
91906
|
+
if (root.status !== "ok" || response?.type !== "default" || !/^0x[0-9a-f]{32}$/.test(clientOrderId)) {
|
|
91907
|
+
return payload;
|
|
91908
|
+
}
|
|
91909
|
+
let evidence;
|
|
91910
|
+
try {
|
|
91911
|
+
evidence = await lookup(clientOrderId);
|
|
91912
|
+
} catch {
|
|
91913
|
+
return payload;
|
|
91914
|
+
}
|
|
91915
|
+
const orderId = Number(evidence.orderId);
|
|
91916
|
+
const state2 = classifyHyperliquidOrderStatus(evidence.orderStatus);
|
|
91917
|
+
if (!evidence.responseValid || !evidence.orderMatches || !Number.isSafeInteger(orderId) || orderId <= 0 || state2 !== "open" && state2 !== "filled") {
|
|
91918
|
+
return payload;
|
|
91919
|
+
}
|
|
91920
|
+
return {
|
|
91921
|
+
...root,
|
|
91922
|
+
response: {
|
|
91923
|
+
type: "order",
|
|
91924
|
+
data: { statuses: [state2 === "open" ? { resting: { oid: orderId, cloid: clientOrderId } } : { filled: { oid: orderId } }] }
|
|
91925
|
+
}
|
|
91926
|
+
};
|
|
91927
|
+
};
|
|
91898
91928
|
isDefinitiveHyperliquidExchangeResponse = (payload, action) => {
|
|
91899
91929
|
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
91900
91930
|
return false;
|
|
@@ -92641,7 +92671,17 @@ var init_hyperliquid_client = __esm({
|
|
|
92641
92671
|
);
|
|
92642
92672
|
}
|
|
92643
92673
|
const triggerWallet = String(input.triggerAcknowledgementWalletAddress ?? "").trim();
|
|
92644
|
-
if (triggerWallet) {
|
|
92674
|
+
if (triggerWallet && input.payload.action.type === "modify") {
|
|
92675
|
+
payload = await resolveHyperliquidModifyAcknowledgement(
|
|
92676
|
+
payload,
|
|
92677
|
+
input.payload.action,
|
|
92678
|
+
(clientOrderId) => fetchBrowserOrderStatusEvidence({
|
|
92679
|
+
...input,
|
|
92680
|
+
walletAddress: triggerWallet,
|
|
92681
|
+
orderId: clientOrderId
|
|
92682
|
+
})
|
|
92683
|
+
);
|
|
92684
|
+
} else if (triggerWallet) {
|
|
92645
92685
|
payload = await resolveHyperliquidTriggerAcknowledgements(
|
|
92646
92686
|
payload,
|
|
92647
92687
|
input.payload.action,
|
|
@@ -93164,7 +93204,7 @@ async function postClientRuntime(path, profileId, body, options) {
|
|
|
93164
93204
|
let lastNetworkError = null;
|
|
93165
93205
|
let replacementLeaseRetryUsed = false;
|
|
93166
93206
|
let lastRequestId = null;
|
|
93167
|
-
const deadlineError = (
|
|
93207
|
+
const deadlineError = (attempt2, cause) => annotateRuntimeRequestError(
|
|
93168
93208
|
Object.assign(
|
|
93169
93209
|
new Error("Client runtime decision persistence deadline exceeded after the AI run completed."),
|
|
93170
93210
|
cause && (typeof cause === "object" || typeof cause === "function") ? { cause } : {}
|
|
@@ -93172,7 +93212,7 @@ async function postClientRuntime(path, profileId, body, options) {
|
|
|
93172
93212
|
{
|
|
93173
93213
|
path,
|
|
93174
93214
|
method: "POST",
|
|
93175
|
-
attempt,
|
|
93215
|
+
attempt: attempt2,
|
|
93176
93216
|
maxAttempts: null,
|
|
93177
93217
|
status: Number.isFinite(Number(cause?.status)) ? Number(cause.status) : null,
|
|
93178
93218
|
keepalive,
|
|
@@ -93182,21 +93222,21 @@ async function postClientRuntime(path, profileId, body, options) {
|
|
|
93182
93222
|
requestId: lastRequestId
|
|
93183
93223
|
}
|
|
93184
93224
|
);
|
|
93185
|
-
const waitBeforeRetry = async (delayMs,
|
|
93225
|
+
const waitBeforeRetry = async (delayMs, attempt2, cause) => {
|
|
93186
93226
|
if (deadlineAtMs === null) {
|
|
93187
93227
|
await sleep(delayMs);
|
|
93188
93228
|
return;
|
|
93189
93229
|
}
|
|
93190
93230
|
const remainingMs = deadlineAtMs - Date.now();
|
|
93191
93231
|
if (remainingMs <= delayMs) {
|
|
93192
|
-
throw deadlineError(
|
|
93232
|
+
throw deadlineError(attempt2, cause);
|
|
93193
93233
|
}
|
|
93194
93234
|
await sleep(delayMs);
|
|
93195
93235
|
};
|
|
93196
|
-
for (let
|
|
93236
|
+
for (let attempt2 = 1; attempt2 <= maxAttempts; attempt2 += 1) {
|
|
93197
93237
|
const deadlineRemainingMs = deadlineAtMs === null ? null : deadlineAtMs - Date.now();
|
|
93198
93238
|
if (deadlineRemainingMs !== null && deadlineRemainingMs <= 0) {
|
|
93199
|
-
throw deadlineError(Math.max(0,
|
|
93239
|
+
throw deadlineError(Math.max(0, attempt2 - 1), lastNetworkError);
|
|
93200
93240
|
}
|
|
93201
93241
|
let response = null;
|
|
93202
93242
|
let requestTimedOut = false;
|
|
@@ -93224,7 +93264,7 @@ async function postClientRuntime(path, profileId, body, options) {
|
|
|
93224
93264
|
label: "client_runtime_api",
|
|
93225
93265
|
method: "POST",
|
|
93226
93266
|
url: requestUrl2,
|
|
93227
|
-
note: `path=${path} attempt=${
|
|
93267
|
+
note: `path=${path} attempt=${attempt2}/${maxAttempts}${lastRequestId ? ` reconcile_only=${options?.reconcileOnly === true} request_id=${lastRequestId}` : ""}`
|
|
93228
93268
|
});
|
|
93229
93269
|
try {
|
|
93230
93270
|
response = await apiFetch(requestUrl2, {
|
|
@@ -93250,11 +93290,11 @@ async function postClientRuntime(path, profileId, body, options) {
|
|
|
93250
93290
|
if (replacementLeaseToken) {
|
|
93251
93291
|
resolvedRuntimeLeaseToken = replacementLeaseToken;
|
|
93252
93292
|
attachRuntimeLeaseHeader(requestHeaders, resolvedRuntimeLeaseToken);
|
|
93253
|
-
if (
|
|
93293
|
+
if (attempt2 >= maxAttempts && !replacementLeaseRetryUsed) {
|
|
93254
93294
|
replacementLeaseRetryUsed = true;
|
|
93255
93295
|
maxAttempts += 1;
|
|
93256
93296
|
}
|
|
93257
|
-
if (
|
|
93297
|
+
if (attempt2 >= maxAttempts) {
|
|
93258
93298
|
throw error48;
|
|
93259
93299
|
}
|
|
93260
93300
|
continue;
|
|
@@ -93269,10 +93309,10 @@ async function postClientRuntime(path, profileId, body, options) {
|
|
|
93269
93309
|
hadRuntimeLeaseToken: Boolean(resolvedRuntimeLeaseToken),
|
|
93270
93310
|
leaseCleared
|
|
93271
93311
|
});
|
|
93272
|
-
if (!keepalive &&
|
|
93312
|
+
if (!keepalive && attempt2 < maxAttempts && !leaseInvalidatingError && (shouldRetryClientRuntimeHttpStatus(path, response.status) || isRuntimeIdempotencyInProgressError(response.status, error48.message) || Boolean(idempotencyKey) && isRetryableRuntimeConflictError(response.status, error48))) {
|
|
93273
93313
|
await waitBeforeRetry(
|
|
93274
|
-
resolveClientRuntimeRetryDelayMs(
|
|
93275
|
-
|
|
93314
|
+
resolveClientRuntimeRetryDelayMs(attempt2, response.headers.get("Retry-After")),
|
|
93315
|
+
attempt2,
|
|
93276
93316
|
error48
|
|
93277
93317
|
);
|
|
93278
93318
|
continue;
|
|
@@ -93293,13 +93333,13 @@ async function postClientRuntime(path, profileId, body, options) {
|
|
|
93293
93333
|
lastNetworkError = requestError;
|
|
93294
93334
|
trace.completeError(requestError, response?.status ?? null);
|
|
93295
93335
|
if (deadlineAtMs !== null && Date.now() >= deadlineAtMs) {
|
|
93296
|
-
throw deadlineError(
|
|
93336
|
+
throw deadlineError(attempt2, requestError);
|
|
93297
93337
|
}
|
|
93298
|
-
if (signal?.aborted || !requestTimedOut && !isTransientNetworkFetchError(requestError) ||
|
|
93338
|
+
if (signal?.aborted || !requestTimedOut && !isTransientNetworkFetchError(requestError) || attempt2 >= maxAttempts) {
|
|
93299
93339
|
throw annotateRuntimeRequestError(requestError, {
|
|
93300
93340
|
path,
|
|
93301
93341
|
method: "POST",
|
|
93302
|
-
attempt,
|
|
93342
|
+
attempt: attempt2,
|
|
93303
93343
|
maxAttempts: deadlineAtMs === null ? maxAttempts : null,
|
|
93304
93344
|
status: response?.status ?? null,
|
|
93305
93345
|
keepalive,
|
|
@@ -93309,8 +93349,8 @@ async function postClientRuntime(path, profileId, body, options) {
|
|
|
93309
93349
|
});
|
|
93310
93350
|
}
|
|
93311
93351
|
await waitBeforeRetry(
|
|
93312
|
-
resolveClientRuntimeRetryDelayMs(
|
|
93313
|
-
|
|
93352
|
+
resolveClientRuntimeRetryDelayMs(attempt2, null),
|
|
93353
|
+
attempt2,
|
|
93314
93354
|
requestError
|
|
93315
93355
|
);
|
|
93316
93356
|
continue;
|
|
@@ -94722,13 +94762,13 @@ var init_api2 = __esm({
|
|
|
94722
94762
|
};
|
|
94723
94763
|
isRuntimeIdempotencyInProgressError = (status, message) => status === HTTP_STATUS.CONFLICT && (message.toLowerCase().includes("duplicate request already in progress") || message.toLowerCase().includes("duplicate request in-flight"));
|
|
94724
94764
|
isRetryableRuntimeConflictError = (status, error48) => status === HTTP_STATUS.CONFLICT && error48.retryable === true && (error48.code === "profile_runtime_contract_busy" || error48.code === "runtime_decision_finalizing" || error48.code === "runtime_trade_sync_finalizing" || error48.code === "runtime_decision_unconfirmed");
|
|
94725
|
-
resolveClientRuntimeRetryDelayMs = (
|
|
94765
|
+
resolveClientRuntimeRetryDelayMs = (attempt2, retryAfterHeader) => {
|
|
94726
94766
|
const policy2 = runtime_policy_generated_default2.trading.engine.client_runtime.request_retry;
|
|
94727
94767
|
const retryAfterMs = parseRetryAfterMs2(retryAfterHeader);
|
|
94728
94768
|
if (retryAfterMs != null) {
|
|
94729
94769
|
return Math.min(policy2.max_delay_milliseconds, Math.max(policy2.min_retry_after_milliseconds, retryAfterMs));
|
|
94730
94770
|
}
|
|
94731
|
-
return Math.min(policy2.max_delay_milliseconds, policy2.base_delay_milliseconds * BACKOFF_GROWTH_FACTOR ** (
|
|
94771
|
+
return Math.min(policy2.max_delay_milliseconds, policy2.base_delay_milliseconds * BACKOFF_GROWTH_FACTOR ** (attempt2 - 1));
|
|
94732
94772
|
};
|
|
94733
94773
|
reconcilePendingClientExchangeMutation = async (profileId, requestOptions) => {
|
|
94734
94774
|
let reconciliation;
|
|
@@ -96483,6 +96523,7 @@ var init_browser_trading = __esm({
|
|
|
96483
96523
|
triggerPrice: input.triggerPrice,
|
|
96484
96524
|
triggerKind: input.triggerKind,
|
|
96485
96525
|
triggerIsMarket: input.triggerIsMarket,
|
|
96526
|
+
...input.positionOrder === true ? { positionOrder: true } : {},
|
|
96486
96527
|
clientOrderId: mutation.clientOrderId,
|
|
96487
96528
|
expiresAfterSeconds: requireClientExchangeExpiresAfterSeconds(input.config)
|
|
96488
96529
|
});
|
|
@@ -96502,7 +96543,10 @@ var init_browser_trading = __esm({
|
|
|
96502
96543
|
operationKind: "order",
|
|
96503
96544
|
symbol: input.symbol,
|
|
96504
96545
|
onExchangeOrderDispatched: input.onExchangeOrderDispatched
|
|
96505
|
-
}
|
|
96546
|
+
},
|
|
96547
|
+
// A modify's answer names no order; its status read by the new client
|
|
96548
|
+
// order id does (resolveHyperliquidModifyAcknowledgement).
|
|
96549
|
+
triggerAcknowledgementWalletAddress: input.walletAddress ?? null
|
|
96506
96550
|
});
|
|
96507
96551
|
};
|
|
96508
96552
|
executeClientCancelOrder = async (input) => {
|
|
@@ -99557,6 +99601,750 @@ var init_protective_entry_cover = __esm({
|
|
|
99557
99601
|
}
|
|
99558
99602
|
});
|
|
99559
99603
|
|
|
99604
|
+
// lib/runtime/native-position-protection.ts
|
|
99605
|
+
var nativeProtectionSettings, memberSetting, KINDS, formatTriggerOrNull, nativePositionTriggerPrice, nativeEntryRequest, HALF_UP_DIGIT, roundDecimalHalfUp, nativeTrailingRetracement, nativeAfterFillActions, classifyNativeOrderEnd, isOpenInDirection, nativePlacementGate, nativeStrayOrderDecision, explainAbsentProtectiveOrder;
|
|
99606
|
+
var init_native_position_protection = __esm({
|
|
99607
|
+
"lib/runtime/native-position-protection.ts"() {
|
|
99608
|
+
"use strict";
|
|
99609
|
+
init_define_VTX_EXO_POLICY();
|
|
99610
|
+
init_define_VTX_GROK_POLICY();
|
|
99611
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
99612
|
+
init_constants();
|
|
99613
|
+
init_hyperliquid_client();
|
|
99614
|
+
init_hyperliquid_order_status();
|
|
99615
|
+
init_protective_stop_replacement();
|
|
99616
|
+
nativeProtectionSettings = (resolved) => ({
|
|
99617
|
+
stopLoss: resolved.tpSlEnabled && resolved.stopLossEnabled ? {
|
|
99618
|
+
mode: resolved.stopLossMode,
|
|
99619
|
+
value: resolved.stopLossMode === "usdc" ? resolved.stopLossUsdc : resolved.stopLossPct,
|
|
99620
|
+
trailing: resolved.stopLossType === "trailing"
|
|
99621
|
+
} : null,
|
|
99622
|
+
takeProfit: resolved.tpSlEnabled && resolved.takeProfitEnabled ? {
|
|
99623
|
+
mode: resolved.takeProfitMode,
|
|
99624
|
+
value: resolved.takeProfitMode === "usdc" ? resolved.takeProfitUsdc : resolved.takeProfitPct
|
|
99625
|
+
} : null
|
|
99626
|
+
});
|
|
99627
|
+
memberSetting = (settings, kind) => kind === "sl" ? settings.stopLoss : settings.takeProfit;
|
|
99628
|
+
KINDS = ["sl", "tp"];
|
|
99629
|
+
formatTriggerOrNull = (raw, sizeDecimals) => {
|
|
99630
|
+
try {
|
|
99631
|
+
const wire = formatHyperliquidTriggerPriceWire(raw, sizeDecimals);
|
|
99632
|
+
return Number(wire) > 0 ? wire : null;
|
|
99633
|
+
} catch {
|
|
99634
|
+
return null;
|
|
99635
|
+
}
|
|
99636
|
+
};
|
|
99637
|
+
nativePositionTriggerPrice = (input) => {
|
|
99638
|
+
const size = Math.abs(input.positionSize);
|
|
99639
|
+
if (!(input.averageEntry > 0) || !(input.value > 0) || input.mode === "usdc" && !(size > 0)) return null;
|
|
99640
|
+
const away = input.kind === "tp" === input.isLong;
|
|
99641
|
+
const raw = input.mode === "percent" ? away ? input.averageEntry * (1 + input.value / PERCENT_SCALE) : input.averageEntry * (1 - input.value / PERCENT_SCALE) : away ? input.averageEntry + input.value / size : input.averageEntry - input.value / size;
|
|
99642
|
+
if (!Number.isFinite(raw) || raw <= 0) return null;
|
|
99643
|
+
return formatTriggerOrNull(raw, input.sizeDecimals);
|
|
99644
|
+
};
|
|
99645
|
+
nativeEntryRequest = (input) => {
|
|
99646
|
+
if (input.positionHasLegacyLegs) return { shape: "legacy_per_entry" };
|
|
99647
|
+
const alone = { shape: "entry_alone", grouping: "na", children: [] };
|
|
99648
|
+
if (input.positionBefore !== 0) return alone;
|
|
99649
|
+
const children = [];
|
|
99650
|
+
for (const kind of KINDS) {
|
|
99651
|
+
const setting = memberSetting(input.settings, kind);
|
|
99652
|
+
if (!setting) continue;
|
|
99653
|
+
const trigger = nativePositionTriggerPrice({
|
|
99654
|
+
averageEntry: input.referencePrice,
|
|
99655
|
+
positionSize: input.entrySize,
|
|
99656
|
+
isLong: input.isLong,
|
|
99657
|
+
kind,
|
|
99658
|
+
mode: setting.mode,
|
|
99659
|
+
value: setting.value,
|
|
99660
|
+
sizeDecimals: input.sizeDecimals
|
|
99661
|
+
});
|
|
99662
|
+
if (trigger !== null) children.push({ kind, trigger });
|
|
99663
|
+
}
|
|
99664
|
+
return children.length > 0 ? { shape: "entry_with_position_children", grouping: "normalTpsl", children } : alone;
|
|
99665
|
+
};
|
|
99666
|
+
HALF_UP_DIGIT = "5";
|
|
99667
|
+
roundDecimalHalfUp = (value, decimals) => {
|
|
99668
|
+
const text = String(value);
|
|
99669
|
+
if (text.includes("e")) return "0";
|
|
99670
|
+
const [integer3, fraction = ""] = text.split(".");
|
|
99671
|
+
if (fraction.length <= decimals) return fraction ? `${integer3}.${fraction}`.replace(/\.?0+$/, "") : integer3;
|
|
99672
|
+
let units = BigInt(`${integer3}${fraction.slice(0, decimals)}`);
|
|
99673
|
+
if (fraction[decimals] >= HALF_UP_DIGIT) units += BigInt(1);
|
|
99674
|
+
const digits = units.toString().padStart(decimals + 1, "0");
|
|
99675
|
+
const rounded = `${digits.slice(0, -decimals)}.${digits.slice(-decimals)}`;
|
|
99676
|
+
return rounded.replace(/\.?0+$/, "");
|
|
99677
|
+
};
|
|
99678
|
+
nativeTrailingRetracement = (input) => {
|
|
99679
|
+
if (!(input.value > 0) || !Number.isFinite(input.value)) return null;
|
|
99680
|
+
if (input.mode === "percent") {
|
|
99681
|
+
if (input.value >= PERCENT_SCALE) return null;
|
|
99682
|
+
const pct = roundDecimalHalfUp(
|
|
99683
|
+
input.value,
|
|
99684
|
+
HYPERLIQUID_EXCHANGE_SPECIFICATION.trailing_retracement_pct_max_decimals
|
|
99685
|
+
);
|
|
99686
|
+
return Number(pct) > 0 ? { pct: `${pct}%` } : null;
|
|
99687
|
+
}
|
|
99688
|
+
const size = Math.abs(input.lotSize);
|
|
99689
|
+
if (!(size > 0)) return null;
|
|
99690
|
+
const px = formatTriggerOrNull(input.value / size, input.sizeDecimals);
|
|
99691
|
+
return px === null ? null : { px };
|
|
99692
|
+
};
|
|
99693
|
+
nativeAfterFillActions = (input) => {
|
|
99694
|
+
const actions = [];
|
|
99695
|
+
for (const kind of KINDS) {
|
|
99696
|
+
const setting = memberSetting(input.settings, kind);
|
|
99697
|
+
if (!setting) continue;
|
|
99698
|
+
const trigger = nativePositionTriggerPrice({
|
|
99699
|
+
averageEntry: input.position.entryPrice,
|
|
99700
|
+
positionSize: input.position.size,
|
|
99701
|
+
isLong: input.isLong,
|
|
99702
|
+
kind,
|
|
99703
|
+
mode: setting.mode,
|
|
99704
|
+
value: setting.value,
|
|
99705
|
+
sizeDecimals: input.sizeDecimals
|
|
99706
|
+
});
|
|
99707
|
+
if (trigger === null) continue;
|
|
99708
|
+
const resting = input.resting[kind];
|
|
99709
|
+
if (resting === null) {
|
|
99710
|
+
actions.push({ action: "place_position", kind, trigger });
|
|
99711
|
+
} else if (Number(resting) !== Number(trigger)) {
|
|
99712
|
+
actions.push({ action: "modify", kind, trigger });
|
|
99713
|
+
}
|
|
99714
|
+
}
|
|
99715
|
+
const stopLoss = input.settings.stopLoss;
|
|
99716
|
+
if (stopLoss?.trailing) {
|
|
99717
|
+
const retracement = nativeTrailingRetracement({
|
|
99718
|
+
mode: stopLoss.mode,
|
|
99719
|
+
value: stopLoss.value,
|
|
99720
|
+
lotSize: Number(input.fillSize),
|
|
99721
|
+
sizeDecimals: input.sizeDecimals
|
|
99722
|
+
});
|
|
99723
|
+
if (retracement) actions.push({ action: "place_trailing", size: input.fillSize, retracement });
|
|
99724
|
+
}
|
|
99725
|
+
return actions;
|
|
99726
|
+
};
|
|
99727
|
+
classifyNativeOrderEnd = (input) => {
|
|
99728
|
+
const status = input.orderStatus;
|
|
99729
|
+
const state2 = classifyHyperliquidOrderStatus(status);
|
|
99730
|
+
if (state2 === "open") return "resting";
|
|
99731
|
+
if (state2 === "pending_trigger") return "pending";
|
|
99732
|
+
if (state2 === "filled") return "fired";
|
|
99733
|
+
if (state2 === null) return "unknown";
|
|
99734
|
+
if (status === "siblingFilledCanceled" || POSITION_ENDED_ORDER_STATUSES.has(status)) return "ended_with_position";
|
|
99735
|
+
if (status === "canceled") {
|
|
99736
|
+
if (input.replacedByOwnModify) return "superseded";
|
|
99737
|
+
return input.userCancelledThroughVtx ? "user_cancelled" : "lost";
|
|
99738
|
+
}
|
|
99739
|
+
return protectiveStopRejectionIsPermanent(status) ? "lost_permanent" : "lost";
|
|
99740
|
+
};
|
|
99741
|
+
isOpenInDirection = (position, isLong) => isLong ? position > 0 : position < 0;
|
|
99742
|
+
nativePlacementGate = (input) => {
|
|
99743
|
+
if (!(input.positionStateMs > input.eventMs)) return "need_reads";
|
|
99744
|
+
return isOpenInDirection(input.position, input.isLong) ? "place" : "not_required";
|
|
99745
|
+
};
|
|
99746
|
+
nativeStrayOrderDecision = (input) => {
|
|
99747
|
+
if (isOpenInDirection(input.position, input.isLong)) return "keep";
|
|
99748
|
+
return input.positionStateMs > input.placedMs ? "cancel" : "need_reads";
|
|
99749
|
+
};
|
|
99750
|
+
explainAbsentProtectiveOrder = (input) => {
|
|
99751
|
+
if (isOpenInDirection(input.position, input.isLong)) return "status_read";
|
|
99752
|
+
return input.positionStateMs > input.lastSeenRestingMs ? "ended_with_position" : "need_reads";
|
|
99753
|
+
};
|
|
99754
|
+
}
|
|
99755
|
+
});
|
|
99756
|
+
|
|
99757
|
+
// lib/runtime/native-protection-device.ts
|
|
99758
|
+
var NATIVE_PROTECTION_RECORD_VERSION, nativeProtectionStorage, resolveStorage, setNativeProtectionStorage, recordKey, isMember, readNativeProtectionRecord, writeNativeProtectionRecord, NativeOrderNotSentError, withDispatchBoundary, attempt, errorText, actionOf, isOpenInDirection2, restingOrderIdAt, definitivelyRefused, planNativeOpen, recordEntryChildren, observeMembers, UNKNOWN_ORDER_RESPONSE, resolveUnknownOrderIds, settleNativeProtectionAfterFill, reconcileNativeProtection;
|
|
99759
|
+
var init_native_protection_device = __esm({
|
|
99760
|
+
"lib/runtime/native-protection-device.ts"() {
|
|
99761
|
+
"use strict";
|
|
99762
|
+
init_define_VTX_EXO_POLICY();
|
|
99763
|
+
init_define_VTX_GROK_POLICY();
|
|
99764
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
99765
|
+
init_order_identity();
|
|
99766
|
+
init_native_position_protection();
|
|
99767
|
+
NATIVE_PROTECTION_RECORD_VERSION = 1;
|
|
99768
|
+
nativeProtectionStorage = null;
|
|
99769
|
+
resolveStorage = () => {
|
|
99770
|
+
if (nativeProtectionStorage) return nativeProtectionStorage;
|
|
99771
|
+
if (typeof window === "undefined") return null;
|
|
99772
|
+
try {
|
|
99773
|
+
return window.localStorage ?? null;
|
|
99774
|
+
} catch {
|
|
99775
|
+
return null;
|
|
99776
|
+
}
|
|
99777
|
+
};
|
|
99778
|
+
setNativeProtectionStorage = (storage3) => {
|
|
99779
|
+
nativeProtectionStorage = storage3;
|
|
99780
|
+
};
|
|
99781
|
+
recordKey = (profileId, symbol2) => `vtx:native-protection:${profileId}:${symbol2}`;
|
|
99782
|
+
isMember = (value) => {
|
|
99783
|
+
if (!value || typeof value !== "object") return false;
|
|
99784
|
+
const member = value;
|
|
99785
|
+
return (member.kind === "sl" || member.kind === "tp") && typeof member.clientOrderId === "string" && (member.orderId === null || typeof member.orderId === "number" && Number.isSafeInteger(member.orderId)) && typeof member.trigger === "string" && (member.placedAtMs === null || typeof member.placedAtMs === "number") && typeof member.sentAtMs === "number" && typeof member.replacedOnce === "boolean" && (member.pendingModify === void 0 || typeof member.pendingModify === "object" && member.pendingModify !== null && typeof member.pendingModify.clientOrderId === "string" && typeof member.pendingModify.trigger === "string" && typeof member.pendingModify.sentAtMs === "number");
|
|
99786
|
+
};
|
|
99787
|
+
readNativeProtectionRecord = (profileId, symbol2) => {
|
|
99788
|
+
const storage3 = resolveStorage();
|
|
99789
|
+
if (!storage3) return null;
|
|
99790
|
+
const raw = storage3.getItem(recordKey(profileId, symbol2));
|
|
99791
|
+
if (raw == null) return null;
|
|
99792
|
+
const parsed = JSON.parse(raw);
|
|
99793
|
+
if (parsed?.version !== NATIVE_PROTECTION_RECORD_VERSION || parsed.profileId !== profileId || parsed.symbol !== symbol2 || typeof parsed.walletAddress !== "string" || typeof parsed.isLong !== "boolean" || parsed.phase !== "entry_pending" && parsed.phase !== "active" || typeof parsed.entryMutationId !== "string" || typeof parsed.entryClientOrderId !== "string" || typeof parsed.createdAtMs !== "number" || !Array.isArray(parsed.members) || !parsed.members.every(isMember)) {
|
|
99794
|
+
throw new Error("Stored native protection record is invalid.");
|
|
99795
|
+
}
|
|
99796
|
+
return parsed;
|
|
99797
|
+
};
|
|
99798
|
+
writeNativeProtectionRecord = (profileId, symbol2, record5) => {
|
|
99799
|
+
const storage3 = resolveStorage();
|
|
99800
|
+
if (!storage3) return false;
|
|
99801
|
+
try {
|
|
99802
|
+
if (record5 == null) storage3.removeItem(recordKey(profileId, symbol2));
|
|
99803
|
+
else storage3.setItem(recordKey(profileId, symbol2), JSON.stringify(record5));
|
|
99804
|
+
return true;
|
|
99805
|
+
} catch {
|
|
99806
|
+
return false;
|
|
99807
|
+
}
|
|
99808
|
+
};
|
|
99809
|
+
NativeOrderNotSentError = class extends Error {
|
|
99810
|
+
constructor(cause) {
|
|
99811
|
+
super(cause instanceof Error ? cause.message : "The exchange call failed before dispatch.");
|
|
99812
|
+
this.name = "NativeOrderNotSentError";
|
|
99813
|
+
this.cause = cause;
|
|
99814
|
+
}
|
|
99815
|
+
};
|
|
99816
|
+
withDispatchBoundary = async (call) => {
|
|
99817
|
+
let dispatched = false;
|
|
99818
|
+
try {
|
|
99819
|
+
return await call(() => {
|
|
99820
|
+
dispatched = true;
|
|
99821
|
+
});
|
|
99822
|
+
} catch (error48) {
|
|
99823
|
+
throw dispatched ? error48 : new NativeOrderNotSentError(error48);
|
|
99824
|
+
}
|
|
99825
|
+
};
|
|
99826
|
+
attempt = async (io, call) => {
|
|
99827
|
+
try {
|
|
99828
|
+
const response = await call();
|
|
99829
|
+
return definitivelyRefused(response) ? { ok: false, refused: true, error: response } : { ok: true, response };
|
|
99830
|
+
} catch (error48) {
|
|
99831
|
+
return { ok: false, refused: io.isDefinitiveRefusal(error48), error: error48 };
|
|
99832
|
+
}
|
|
99833
|
+
};
|
|
99834
|
+
errorText = (error48) => error48 instanceof Error ? error48.message : typeof error48 === "string" ? error48 : "Exchange call failed.";
|
|
99835
|
+
actionOf = (kind) => kind === "sl" ? "AUTO_SL" : "AUTO_TP";
|
|
99836
|
+
isOpenInDirection2 = (position, isLong) => isLong ? position > 0 : position < 0;
|
|
99837
|
+
restingOrderIdAt = (response, index) => {
|
|
99838
|
+
const statuses = response?.response?.data?.statuses;
|
|
99839
|
+
const status = Array.isArray(statuses) ? statuses[index] : void 0;
|
|
99840
|
+
const resting = status && typeof status === "object" ? status.resting : void 0;
|
|
99841
|
+
const orderId = Number(resting?.oid);
|
|
99842
|
+
return Number.isSafeInteger(orderId) && orderId > 0 ? orderId : null;
|
|
99843
|
+
};
|
|
99844
|
+
definitivelyRefused = (response) => {
|
|
99845
|
+
const root = response;
|
|
99846
|
+
if (root?.status === "err") return true;
|
|
99847
|
+
const statuses = root?.response?.data?.statuses;
|
|
99848
|
+
return Array.isArray(statuses) && statuses.length > 0 && statuses.every((status) => Boolean(status && typeof status === "object" && "error" in status));
|
|
99849
|
+
};
|
|
99850
|
+
planNativeOpen = (input) => {
|
|
99851
|
+
if (input.settings.stopLoss?.trailing) return null;
|
|
99852
|
+
const request = nativeEntryRequest({
|
|
99853
|
+
settings: input.settings,
|
|
99854
|
+
isLong: input.isLong,
|
|
99855
|
+
sizeDecimals: input.sizeDecimals,
|
|
99856
|
+
referencePrice: input.referencePrice,
|
|
99857
|
+
entrySize: input.entrySize,
|
|
99858
|
+
positionBefore: input.positionBefore,
|
|
99859
|
+
positionHasLegacyLegs: input.positionHasLegacyLegs
|
|
99860
|
+
});
|
|
99861
|
+
if (request.shape !== "entry_with_position_children") return null;
|
|
99862
|
+
const members = request.children.map((child) => ({
|
|
99863
|
+
kind: child.kind,
|
|
99864
|
+
clientOrderId: clientOrderIdForMutation(input.newMutationId()),
|
|
99865
|
+
orderId: null,
|
|
99866
|
+
trigger: child.trigger,
|
|
99867
|
+
placedAtMs: null,
|
|
99868
|
+
sentAtMs: input.nowMs,
|
|
99869
|
+
replacedOnce: false
|
|
99870
|
+
}));
|
|
99871
|
+
return {
|
|
99872
|
+
children: members.map((member) => ({
|
|
99873
|
+
kind: member.kind,
|
|
99874
|
+
triggerPrice: Number(member.trigger),
|
|
99875
|
+
clientOrderId: member.clientOrderId
|
|
99876
|
+
})),
|
|
99877
|
+
record: {
|
|
99878
|
+
version: NATIVE_PROTECTION_RECORD_VERSION,
|
|
99879
|
+
profileId: input.profileId,
|
|
99880
|
+
symbol: input.symbol,
|
|
99881
|
+
walletAddress: input.walletAddress.toLowerCase(),
|
|
99882
|
+
isLong: input.isLong,
|
|
99883
|
+
phase: "entry_pending",
|
|
99884
|
+
entryMutationId: input.entryMutationId,
|
|
99885
|
+
entryClientOrderId: input.entryClientOrderId,
|
|
99886
|
+
createdAtMs: input.nowMs,
|
|
99887
|
+
members
|
|
99888
|
+
}
|
|
99889
|
+
};
|
|
99890
|
+
};
|
|
99891
|
+
recordEntryChildren = (record5, entryResponse) => ({
|
|
99892
|
+
...record5,
|
|
99893
|
+
phase: "active",
|
|
99894
|
+
members: record5.members.map((member, index) => ({
|
|
99895
|
+
...member,
|
|
99896
|
+
// The entry is member 0 of the action; its children follow in order.
|
|
99897
|
+
orderId: member.orderId ?? restingOrderIdAt(entryResponse, index + 1)
|
|
99898
|
+
}))
|
|
99899
|
+
});
|
|
99900
|
+
observeMembers = (record5, page) => record5.members.map((member) => ({
|
|
99901
|
+
member,
|
|
99902
|
+
row: member.orderId == null ? null : page.find((order) => order.oid === member.orderId) ?? null
|
|
99903
|
+
}));
|
|
99904
|
+
UNKNOWN_ORDER_RESPONSE = "unknownOid";
|
|
99905
|
+
resolveUnknownOrderIds = async (record5, io, unknownClientOrderIds = /* @__PURE__ */ new Set()) => {
|
|
99906
|
+
const members = [];
|
|
99907
|
+
for (const member of record5.members) {
|
|
99908
|
+
if (member.pendingModify) {
|
|
99909
|
+
const pending3 = member.pendingModify;
|
|
99910
|
+
const evidence2 = await io.readOrderStatus(pending3.clientOrderId);
|
|
99911
|
+
const orderId2 = Number(evidence2.orderId);
|
|
99912
|
+
if (evidence2.responseValid && evidence2.orderMatches && Number.isSafeInteger(orderId2) && orderId2 > 0) {
|
|
99913
|
+
const { pendingModify: _settled, ...rest } = member;
|
|
99914
|
+
members.push({
|
|
99915
|
+
...rest,
|
|
99916
|
+
clientOrderId: pending3.clientOrderId,
|
|
99917
|
+
orderId: orderId2,
|
|
99918
|
+
trigger: pending3.trigger,
|
|
99919
|
+
placedAtMs: evidence2.orderTimestampMs ?? null,
|
|
99920
|
+
sentAtMs: pending3.sentAtMs
|
|
99921
|
+
});
|
|
99922
|
+
} else if (evidence2.responseStatus === UNKNOWN_ORDER_RESPONSE && io.nowMs() > io.neverLandsAfterMs(pending3.sentAtMs)) {
|
|
99923
|
+
const { pendingModify: _neverLanded, ...rest } = member;
|
|
99924
|
+
members.push(rest);
|
|
99925
|
+
} else {
|
|
99926
|
+
members.push(member);
|
|
99927
|
+
}
|
|
99928
|
+
continue;
|
|
99929
|
+
}
|
|
99930
|
+
if (member.orderId != null || member.retiredReason) {
|
|
99931
|
+
members.push(member);
|
|
99932
|
+
continue;
|
|
99933
|
+
}
|
|
99934
|
+
const evidence = await io.readOrderStatus(member.clientOrderId);
|
|
99935
|
+
if (evidence.responseStatus === UNKNOWN_ORDER_RESPONSE) unknownClientOrderIds.add(member.clientOrderId);
|
|
99936
|
+
const orderId = Number(evidence.orderId);
|
|
99937
|
+
members.push(
|
|
99938
|
+
evidence.responseValid && evidence.orderMatches && Number.isSafeInteger(orderId) && orderId > 0 ? { ...member, orderId, placedAtMs: evidence.orderTimestampMs ?? member.placedAtMs } : member
|
|
99939
|
+
);
|
|
99940
|
+
}
|
|
99941
|
+
return { ...record5, members };
|
|
99942
|
+
};
|
|
99943
|
+
settleNativeProtectionAfterFill = async (input) => {
|
|
99944
|
+
const { io } = input;
|
|
99945
|
+
const reports = [];
|
|
99946
|
+
const unknownClientOrderIds = /* @__PURE__ */ new Set();
|
|
99947
|
+
let record5 = await resolveUnknownOrderIds(input.record, io, unknownClientOrderIds);
|
|
99948
|
+
const page = await io.readOpenOrders();
|
|
99949
|
+
const position = await io.readPosition();
|
|
99950
|
+
const symbol2 = record5.symbol;
|
|
99951
|
+
if (!isOpenInDirection2(position.size, record5.isLong)) {
|
|
99952
|
+
reports.push({
|
|
99953
|
+
order_id: input.entryOrderId,
|
|
99954
|
+
symbol: symbol2,
|
|
99955
|
+
action: "PROTECTIVE_RECONCILIATION",
|
|
99956
|
+
status: "blocked",
|
|
99957
|
+
execution_metadata: {
|
|
99958
|
+
reason_code: position.size === 0 ? "protective_position_flat" : "protective_position_drift",
|
|
99959
|
+
live_position_size: position.size
|
|
99960
|
+
}
|
|
99961
|
+
});
|
|
99962
|
+
return { record: { ...record5, phase: "active" }, reports };
|
|
99963
|
+
}
|
|
99964
|
+
const observations = observeMembers(record5, page);
|
|
99965
|
+
const restingTrigger = (kind) => {
|
|
99966
|
+
const observed = observations.find((entry) => entry.member.kind === kind);
|
|
99967
|
+
return observed?.row?.trigger_px != null ? String(observed.row.trigger_px) : null;
|
|
99968
|
+
};
|
|
99969
|
+
if (position.entryPrice == null) {
|
|
99970
|
+
reports.push({
|
|
99971
|
+
order_id: input.entryOrderId,
|
|
99972
|
+
symbol: symbol2,
|
|
99973
|
+
action: "PROTECTIVE_RECONCILIATION",
|
|
99974
|
+
status: "failed",
|
|
99975
|
+
execution_metadata: { reason_code: "protective_position_entry_unresolved" }
|
|
99976
|
+
});
|
|
99977
|
+
return { record: record5, reports };
|
|
99978
|
+
}
|
|
99979
|
+
const actions = nativeAfterFillActions({
|
|
99980
|
+
settings: { ...input.settings, stopLoss: input.settings.stopLoss && { ...input.settings.stopLoss, trailing: false } },
|
|
99981
|
+
isLong: record5.isLong,
|
|
99982
|
+
sizeDecimals: input.sizeDecimals,
|
|
99983
|
+
position: { size: position.size, entryPrice: position.entryPrice },
|
|
99984
|
+
fillSize: input.fillSize,
|
|
99985
|
+
resting: { sl: restingTrigger("sl"), tp: restingTrigger("tp") }
|
|
99986
|
+
});
|
|
99987
|
+
let eventMs = Math.max(
|
|
99988
|
+
0,
|
|
99989
|
+
...observations.map((entry) => entry.row?.timestamp ?? entry.member.placedAtMs ?? 0)
|
|
99990
|
+
);
|
|
99991
|
+
if (eventMs <= 0 && input.entryOrderId) {
|
|
99992
|
+
const entryStatus = await io.readOrderStatus(input.entryOrderId);
|
|
99993
|
+
eventMs = entryStatus.statusTimestampMs ?? 0;
|
|
99994
|
+
}
|
|
99995
|
+
const gate = nativePlacementGate({
|
|
99996
|
+
eventMs,
|
|
99997
|
+
position: position.size,
|
|
99998
|
+
positionStateMs: position.stateTimeMs ?? Number.NEGATIVE_INFINITY,
|
|
99999
|
+
isLong: record5.isLong
|
|
100000
|
+
});
|
|
100001
|
+
const members = [...record5.members];
|
|
100002
|
+
for (const step of actions) {
|
|
100003
|
+
if (step.action === "place_trailing") continue;
|
|
100004
|
+
const index = members.findIndex((member) => member.kind === step.kind);
|
|
100005
|
+
const existing = index >= 0 ? members[index] : null;
|
|
100006
|
+
if (existing?.userCancelledOrderId != null || existing?.retiredReason) continue;
|
|
100007
|
+
const clientOrderId = clientOrderIdForMutation(io.newMutationId());
|
|
100008
|
+
if (step.action === "modify") {
|
|
100009
|
+
const row = observations.find((entry) => entry.member.kind === step.kind)?.row;
|
|
100010
|
+
if (!row) continue;
|
|
100011
|
+
const sentAtMs2 = io.nowMs();
|
|
100012
|
+
members[index] = {
|
|
100013
|
+
...members[index],
|
|
100014
|
+
orderId: row.oid,
|
|
100015
|
+
pendingModify: { clientOrderId, trigger: step.trigger, sentAtMs: sentAtMs2 }
|
|
100016
|
+
};
|
|
100017
|
+
if (!io.persist({ ...record5, phase: "active", members })) {
|
|
100018
|
+
members[index] = existing;
|
|
100019
|
+
reports.push({
|
|
100020
|
+
order_id: String(row.oid),
|
|
100021
|
+
symbol: symbol2,
|
|
100022
|
+
action: actionOf(step.kind),
|
|
100023
|
+
status: "failed",
|
|
100024
|
+
execution_metadata: { reason_code: "protective_lifecycle_persistence_failed", trigger_price: step.trigger }
|
|
100025
|
+
});
|
|
100026
|
+
continue;
|
|
100027
|
+
}
|
|
100028
|
+
const outcome2 = await attempt(io, () => io.modifyPositionOrder({
|
|
100029
|
+
orderId: row.oid,
|
|
100030
|
+
kind: step.kind,
|
|
100031
|
+
triggerPrice: Number(step.trigger),
|
|
100032
|
+
clientOrderId
|
|
100033
|
+
}));
|
|
100034
|
+
if (!outcome2.ok && outcome2.refused) {
|
|
100035
|
+
members[index] = { ...existing, orderId: row.oid };
|
|
100036
|
+
reports.push({
|
|
100037
|
+
order_id: String(row.oid),
|
|
100038
|
+
symbol: symbol2,
|
|
100039
|
+
action: actionOf(step.kind),
|
|
100040
|
+
status: "failed",
|
|
100041
|
+
execution_metadata: {
|
|
100042
|
+
reason_code: "protective_modify_rejected",
|
|
100043
|
+
trigger_price: step.trigger,
|
|
100044
|
+
error: errorText(outcome2.error)
|
|
100045
|
+
}
|
|
100046
|
+
});
|
|
100047
|
+
continue;
|
|
100048
|
+
}
|
|
100049
|
+
const newOrderId = outcome2.ok ? restingOrderIdAt(outcome2.response, 0) : null;
|
|
100050
|
+
if (newOrderId != null) {
|
|
100051
|
+
const { pendingModify: _applied, ...rest } = members[index];
|
|
100052
|
+
members[index] = { ...rest, clientOrderId, orderId: newOrderId, trigger: step.trigger, placedAtMs: null, sentAtMs: sentAtMs2 };
|
|
100053
|
+
}
|
|
100054
|
+
reports.push({
|
|
100055
|
+
order_id: String(newOrderId ?? row.oid),
|
|
100056
|
+
symbol: symbol2,
|
|
100057
|
+
action: actionOf(step.kind),
|
|
100058
|
+
status: newOrderId != null ? "executed" : "failed",
|
|
100059
|
+
execution_metadata: {
|
|
100060
|
+
reason_code: newOrderId != null ? "protective_native_moved_to_position_entry" : "protective_modify_outcome_unknown",
|
|
100061
|
+
trigger_price: step.trigger,
|
|
100062
|
+
position_tpsl: true,
|
|
100063
|
+
protected_size: Math.abs(position.size),
|
|
100064
|
+
...newOrderId != null ? { replaced_order_id: String(row.oid) } : {}
|
|
100065
|
+
}
|
|
100066
|
+
});
|
|
100067
|
+
continue;
|
|
100068
|
+
}
|
|
100069
|
+
if (existing != null && existing.orderId == null && !unknownClientOrderIds.has(existing.clientOrderId)) {
|
|
100070
|
+
continue;
|
|
100071
|
+
}
|
|
100072
|
+
if (gate !== "place") {
|
|
100073
|
+
reports.push({
|
|
100074
|
+
order_id: input.entryOrderId,
|
|
100075
|
+
symbol: symbol2,
|
|
100076
|
+
action: actionOf(step.kind),
|
|
100077
|
+
status: "failed",
|
|
100078
|
+
execution_metadata: {
|
|
100079
|
+
reason_code: gate === "need_reads" ? "protective_position_evidence_stale" : "protective_position_flat"
|
|
100080
|
+
}
|
|
100081
|
+
});
|
|
100082
|
+
continue;
|
|
100083
|
+
}
|
|
100084
|
+
const sentAtMs = io.nowMs();
|
|
100085
|
+
const outcome = await attempt(io, () => io.placePositionOrder({
|
|
100086
|
+
kind: step.kind,
|
|
100087
|
+
triggerPrice: Number(step.trigger),
|
|
100088
|
+
clientOrderId
|
|
100089
|
+
}));
|
|
100090
|
+
if (!outcome.ok && outcome.refused) {
|
|
100091
|
+
reports.push({
|
|
100092
|
+
order_id: null,
|
|
100093
|
+
symbol: symbol2,
|
|
100094
|
+
action: actionOf(step.kind),
|
|
100095
|
+
status: "failed",
|
|
100096
|
+
execution_metadata: {
|
|
100097
|
+
reason_code: "protective_place_rejected",
|
|
100098
|
+
trigger_price: step.trigger,
|
|
100099
|
+
error: errorText(outcome.error)
|
|
100100
|
+
}
|
|
100101
|
+
});
|
|
100102
|
+
continue;
|
|
100103
|
+
}
|
|
100104
|
+
const placed = {
|
|
100105
|
+
kind: step.kind,
|
|
100106
|
+
clientOrderId,
|
|
100107
|
+
orderId: outcome.ok ? restingOrderIdAt(outcome.response, 0) : null,
|
|
100108
|
+
trigger: step.trigger,
|
|
100109
|
+
placedAtMs: null,
|
|
100110
|
+
sentAtMs,
|
|
100111
|
+
replacedOnce: existing?.replacedOnce ?? false
|
|
100112
|
+
};
|
|
100113
|
+
if (index >= 0) members[index] = placed;
|
|
100114
|
+
else members.push(placed);
|
|
100115
|
+
reports.push({
|
|
100116
|
+
order_id: placed.orderId == null ? null : String(placed.orderId),
|
|
100117
|
+
symbol: symbol2,
|
|
100118
|
+
action: actionOf(step.kind),
|
|
100119
|
+
status: "executed",
|
|
100120
|
+
execution_metadata: {
|
|
100121
|
+
trigger_price: step.trigger,
|
|
100122
|
+
position_tpsl: true,
|
|
100123
|
+
protected_size: Math.abs(position.size)
|
|
100124
|
+
}
|
|
100125
|
+
});
|
|
100126
|
+
}
|
|
100127
|
+
for (const entry of observations) {
|
|
100128
|
+
if (!entry.row || reports.some((report) => report.order_id === String(entry.row?.oid))) continue;
|
|
100129
|
+
reports.push({
|
|
100130
|
+
order_id: String(entry.row.oid),
|
|
100131
|
+
symbol: symbol2,
|
|
100132
|
+
action: actionOf(entry.member.kind),
|
|
100133
|
+
status: "executed",
|
|
100134
|
+
execution_metadata: {
|
|
100135
|
+
trigger_price: entry.member.trigger,
|
|
100136
|
+
position_tpsl: true,
|
|
100137
|
+
protected_size: Math.abs(position.size)
|
|
100138
|
+
}
|
|
100139
|
+
});
|
|
100140
|
+
}
|
|
100141
|
+
record5 = { ...record5, phase: "active", members };
|
|
100142
|
+
return { record: record5, reports };
|
|
100143
|
+
};
|
|
100144
|
+
reconcileNativeProtection = async (input) => {
|
|
100145
|
+
const { io } = input;
|
|
100146
|
+
const reports = [];
|
|
100147
|
+
const unknownClientOrderIds = /* @__PURE__ */ new Set();
|
|
100148
|
+
let record5 = await resolveUnknownOrderIds(input.record, io, unknownClientOrderIds);
|
|
100149
|
+
const page = await io.readOpenOrders();
|
|
100150
|
+
const position = await io.readPosition();
|
|
100151
|
+
const symbol2 = record5.symbol;
|
|
100152
|
+
const stateMs = position.stateTimeMs ?? Number.NEGATIVE_INFINITY;
|
|
100153
|
+
const observations = observeMembers(record5, page).map((entry) => ({
|
|
100154
|
+
...entry,
|
|
100155
|
+
member: entry.row ? { ...entry.member, placedAtMs: entry.row.timestamp || entry.member.placedAtMs } : entry.member
|
|
100156
|
+
}));
|
|
100157
|
+
const members = [];
|
|
100158
|
+
let anyResting = false;
|
|
100159
|
+
const positionOpen = isOpenInDirection2(position.size, record5.isLong);
|
|
100160
|
+
const currentTrigger = (member) => {
|
|
100161
|
+
const setting = member.kind === "sl" ? input.settings.stopLoss : input.settings.takeProfit;
|
|
100162
|
+
return setting && position.entryPrice != null ? nativePositionTriggerPrice({
|
|
100163
|
+
averageEntry: position.entryPrice,
|
|
100164
|
+
positionSize: position.size,
|
|
100165
|
+
isLong: record5.isLong,
|
|
100166
|
+
kind: member.kind,
|
|
100167
|
+
mode: setting.mode,
|
|
100168
|
+
value: setting.value,
|
|
100169
|
+
sizeDecimals: input.sizeDecimals
|
|
100170
|
+
}) : null;
|
|
100171
|
+
};
|
|
100172
|
+
const placeMember = async (args) => {
|
|
100173
|
+
const gate = nativePlacementGate({
|
|
100174
|
+
eventMs: args.eventMs,
|
|
100175
|
+
position: position.size,
|
|
100176
|
+
positionStateMs: stateMs,
|
|
100177
|
+
isLong: record5.isLong
|
|
100178
|
+
});
|
|
100179
|
+
if (gate !== "place") return args.member;
|
|
100180
|
+
const clientOrderId = clientOrderIdForMutation(io.newMutationId());
|
|
100181
|
+
const sentAtMs = io.nowMs();
|
|
100182
|
+
const outcome = await attempt(io, () => io.placePositionOrder({
|
|
100183
|
+
kind: args.member.kind,
|
|
100184
|
+
triggerPrice: Number(args.trigger),
|
|
100185
|
+
clientOrderId
|
|
100186
|
+
}));
|
|
100187
|
+
const refused = !outcome.ok && outcome.refused;
|
|
100188
|
+
const placed = {
|
|
100189
|
+
kind: args.member.kind,
|
|
100190
|
+
clientOrderId: refused ? args.member.clientOrderId : clientOrderId,
|
|
100191
|
+
orderId: refused ? args.member.orderId : outcome.ok ? restingOrderIdAt(outcome.response, 0) : null,
|
|
100192
|
+
trigger: refused ? args.member.trigger : args.trigger,
|
|
100193
|
+
placedAtMs: null,
|
|
100194
|
+
sentAtMs: refused ? args.member.sentAtMs : sentAtMs,
|
|
100195
|
+
replacedOnce: args.replacedOnce,
|
|
100196
|
+
...refused ? { retiredReason: "protective_replacement_rejected" } : {}
|
|
100197
|
+
};
|
|
100198
|
+
reports.push({
|
|
100199
|
+
order_id: placed.orderId == null ? null : String(placed.orderId),
|
|
100200
|
+
symbol: symbol2,
|
|
100201
|
+
action: actionOf(args.member.kind),
|
|
100202
|
+
status: refused ? "failed" : "executed",
|
|
100203
|
+
execution_metadata: {
|
|
100204
|
+
reason_code: refused ? "protective_replacement_rejected" : args.reasonCode,
|
|
100205
|
+
...args.member.orderId != null ? { replaced_order_id: String(args.member.orderId) } : {},
|
|
100206
|
+
trigger_price: args.trigger,
|
|
100207
|
+
position_tpsl: true,
|
|
100208
|
+
protected_size: Math.abs(position.size),
|
|
100209
|
+
...refused ? { error: errorText(outcome.error) } : {}
|
|
100210
|
+
}
|
|
100211
|
+
});
|
|
100212
|
+
return placed;
|
|
100213
|
+
};
|
|
100214
|
+
for (const { member, row } of observations) {
|
|
100215
|
+
if (row) {
|
|
100216
|
+
const stray = nativeStrayOrderDecision({
|
|
100217
|
+
placedMs: member.placedAtMs ?? Number.POSITIVE_INFINITY,
|
|
100218
|
+
position: position.size,
|
|
100219
|
+
positionStateMs: stateMs,
|
|
100220
|
+
isLong: record5.isLong
|
|
100221
|
+
});
|
|
100222
|
+
if (stray === "cancel") {
|
|
100223
|
+
const outcome = await attempt(io, () => io.cancelOrder(row.oid));
|
|
100224
|
+
reports.push({
|
|
100225
|
+
order_id: String(row.oid),
|
|
100226
|
+
symbol: symbol2,
|
|
100227
|
+
action: actionOf(member.kind),
|
|
100228
|
+
status: outcome.ok ? "executed" : "failed",
|
|
100229
|
+
execution_metadata: {
|
|
100230
|
+
reason_code: outcome.ok ? "protective_native_stray_cancelled" : "protective_native_stray_cancel_failed",
|
|
100231
|
+
live_position_size: position.size,
|
|
100232
|
+
...outcome.ok ? {} : { error: errorText(outcome.error) }
|
|
100233
|
+
}
|
|
100234
|
+
});
|
|
100235
|
+
if (!outcome.ok) {
|
|
100236
|
+
anyResting = true;
|
|
100237
|
+
members.push(member);
|
|
100238
|
+
}
|
|
100239
|
+
continue;
|
|
100240
|
+
}
|
|
100241
|
+
anyResting = true;
|
|
100242
|
+
members.push(member);
|
|
100243
|
+
continue;
|
|
100244
|
+
}
|
|
100245
|
+
if (member.retiredReason || member.userCancelledOrderId != null) {
|
|
100246
|
+
members.push(member);
|
|
100247
|
+
continue;
|
|
100248
|
+
}
|
|
100249
|
+
if (member.pendingModify) {
|
|
100250
|
+
anyResting = true;
|
|
100251
|
+
members.push(member);
|
|
100252
|
+
continue;
|
|
100253
|
+
}
|
|
100254
|
+
if (member.orderId == null) {
|
|
100255
|
+
if (io.nowMs() <= io.neverLandsAfterMs(member.sentAtMs) || !unknownClientOrderIds.has(member.clientOrderId)) {
|
|
100256
|
+
anyResting = true;
|
|
100257
|
+
members.push(member);
|
|
100258
|
+
continue;
|
|
100259
|
+
}
|
|
100260
|
+
if (!positionOpen) continue;
|
|
100261
|
+
const placed = await placeMember({
|
|
100262
|
+
member,
|
|
100263
|
+
trigger: currentTrigger(member) ?? member.trigger,
|
|
100264
|
+
replacedOnce: member.replacedOnce,
|
|
100265
|
+
eventMs: Number.NEGATIVE_INFINITY,
|
|
100266
|
+
reasonCode: "protective_order_never_landed_placed"
|
|
100267
|
+
});
|
|
100268
|
+
members.push(placed);
|
|
100269
|
+
if (!placed.retiredReason) anyResting = true;
|
|
100270
|
+
continue;
|
|
100271
|
+
}
|
|
100272
|
+
if (!positionOpen) {
|
|
100273
|
+
let explained;
|
|
100274
|
+
if (member.placedAtMs != null) {
|
|
100275
|
+
explained = explainAbsentProtectiveOrder({
|
|
100276
|
+
lastSeenRestingMs: member.placedAtMs,
|
|
100277
|
+
position: position.size,
|
|
100278
|
+
positionStateMs: stateMs,
|
|
100279
|
+
isLong: record5.isLong
|
|
100280
|
+
});
|
|
100281
|
+
} else {
|
|
100282
|
+
const evidence2 = await io.readOrderStatus(member.orderId);
|
|
100283
|
+
const end2 = classifyNativeOrderEnd({
|
|
100284
|
+
orderStatus: evidence2.responseValid ? String(evidence2.orderStatus ?? "") : "",
|
|
100285
|
+
replacedByOwnModify: false,
|
|
100286
|
+
userCancelledThroughVtx: false
|
|
100287
|
+
});
|
|
100288
|
+
explained = end2 === "resting" || end2 === "pending" || end2 === "unknown" ? "status_read" : "ended_with_position";
|
|
100289
|
+
}
|
|
100290
|
+
if (explained !== "ended_with_position") {
|
|
100291
|
+
anyResting = true;
|
|
100292
|
+
members.push(member);
|
|
100293
|
+
}
|
|
100294
|
+
continue;
|
|
100295
|
+
}
|
|
100296
|
+
const evidence = await io.readOrderStatus(member.orderId);
|
|
100297
|
+
const end = classifyNativeOrderEnd({
|
|
100298
|
+
orderStatus: evidence.responseValid ? String(evidence.orderStatus ?? "") : "",
|
|
100299
|
+
replacedByOwnModify: false,
|
|
100300
|
+
userCancelledThroughVtx: false
|
|
100301
|
+
});
|
|
100302
|
+
if (end === "resting" || end === "pending" || end === "unknown" || end === "superseded" || end === "user_cancelled") {
|
|
100303
|
+
members.push(member);
|
|
100304
|
+
continue;
|
|
100305
|
+
}
|
|
100306
|
+
if (end === "fired" || end === "ended_with_position") {
|
|
100307
|
+
continue;
|
|
100308
|
+
}
|
|
100309
|
+
if (end === "lost_permanent" || member.replacedOnce) {
|
|
100310
|
+
members.push({ ...member, retiredReason: end === "lost_permanent" ? "protective_stop_execution_rejected" : "protective_replacement_lost" });
|
|
100311
|
+
reports.push({
|
|
100312
|
+
order_id: String(member.orderId),
|
|
100313
|
+
symbol: symbol2,
|
|
100314
|
+
action: actionOf(member.kind),
|
|
100315
|
+
status: "failed",
|
|
100316
|
+
execution_metadata: {
|
|
100317
|
+
reason_code: end === "lost_permanent" ? "protective_stop_execution_rejected" : "protective_replacement_lost",
|
|
100318
|
+
order_status: evidence.orderStatus,
|
|
100319
|
+
manual_intervention: true
|
|
100320
|
+
}
|
|
100321
|
+
});
|
|
100322
|
+
continue;
|
|
100323
|
+
}
|
|
100324
|
+
if (member.kind === "tp") {
|
|
100325
|
+
members.push({ ...member, retiredReason: "protective_take_profit_lost" });
|
|
100326
|
+
continue;
|
|
100327
|
+
}
|
|
100328
|
+
const trigger = currentTrigger(member) ?? member.trigger;
|
|
100329
|
+
const replacement = await placeMember({
|
|
100330
|
+
member,
|
|
100331
|
+
trigger,
|
|
100332
|
+
replacedOnce: true,
|
|
100333
|
+
eventMs: evidence.statusTimestampMs ?? Number.POSITIVE_INFINITY,
|
|
100334
|
+
reasonCode: "protective_stop_replaced"
|
|
100335
|
+
});
|
|
100336
|
+
members.push(replacement);
|
|
100337
|
+
if (replacement !== member && !replacement.retiredReason) anyResting = true;
|
|
100338
|
+
}
|
|
100339
|
+
if (!positionOpen && !anyResting) {
|
|
100340
|
+
return { record: null, reports };
|
|
100341
|
+
}
|
|
100342
|
+
record5 = { ...record5, members };
|
|
100343
|
+
return { record: record5, reports };
|
|
100344
|
+
};
|
|
100345
|
+
}
|
|
100346
|
+
});
|
|
100347
|
+
|
|
99560
100348
|
// lib/runtime/runtime-execution.ts
|
|
99561
100349
|
function capCopiedToActual(copied, actual) {
|
|
99562
100350
|
if (Math.abs(copied) <= COPY_TRADING_SIZE_EPSILON) return 0;
|
|
@@ -99592,7 +100380,7 @@ function copiedTargetNow(reconciliation, recordedTarget, actualPosition) {
|
|
|
99592
100380
|
);
|
|
99593
100381
|
return { copiedNow, targetNow, kept: copiedTargetBesideOwnPosition(targetNow, copiedNow, actualPosition) };
|
|
99594
100382
|
}
|
|
99595
|
-
var clientProtectiveMutationAuthority, executionReadPriority, serverEntryLeverageAlreadyHeld, fetchClientRuntimeOpenOrders, _extractOrderResponseStates, createRuntimeId, _extractFilledSize, _extractOrderId, _toExecutionMetadata, _extractClientMutationId, _stableMutationIdentity, trailingStopMemory, protectiveGroupMemory, protectiveGroupReadFailures, windowHandoffCleanupAttempts, clientRuntimeProtectionStorage, resolveClientRuntimeProtectionStorage, setClientRuntimeProtectionStorage, trailingStopStorageKey, readTrackedTrailingStops, writeTrackedTrailingStops, rememberTrailingStop, protectiveGroupStorageKey, LOST_LEG_EVIDENCE_MAX_AGE_MS, EPISODE_END_FILL_LOOKBACK_MS, withClientProtectivePlanSetLock, readClientProtectiveGroups, writeClientProtectiveGroups, hasClientProtectiveGroupReadFailure, readFreshClientProtectiveGroups, stableProtectionSnapshot, exactClientProtectiveGroupSnapshot, exactClientProtectiveGroupSetSnapshot, storableClientProtectiveGroup, replaceExactClientProtectiveGroup, replaceExactClientProtectiveGroupSet, isClientRuntimeLeaseOwnershipError, hasClientRuntimeProtectionState, clearClientRuntimeVetoedProtectiveIntent, rethrowWindowHandoffAfterProtectiveReplacementVeto, canPersistClientProtectiveGroups, removeTrackedTrailingStop, replaceTrackedTrailingStop, replaceProtectiveLeg, replacementJournalEntryOrderId, buildProtectiveReplacementJournalGroup, isProtectiveReplacementJournalGroup, reserveProtectiveLegReplacement, ensureProtectiveReplacementJournalCompanion, buildVetoedProtectiveReplacementCleanup, assertExactProtectiveReplacementDispatchAuthority, transitionProtectiveReplacementAcknowledgement, transitionTerminalProtectiveReplacement, pendingProtectiveReplacementReport, isConfiguredProtectionRequested, protectiveAction, executedProtectiveReport, isExactClientPositionTpslPair, deviceOwnsClientProtectiveLegKind, isAdoptionNarrowedPositionTpslLeg, hasAmbiguousClientPositionTpslAuthority, protectiveStableShapeMatches, observedProtectiveGroupingMatches, protectiveLiveShapeMatches, protectiveTerminalShapeMatches, cancelClientProtectiveLeg, buildPendingProtectivePlan, persistPendingClientProtectiveGroup, attachmentMemberNeverLanded, storedClientProtectiveCover, attachClientProtectivePlan, resolveJournaledAttachmentContinuity, protectiveMemberRested, ledgerOrderIdsByClientOrderId, journaledAttachmentNeverLanded, recoverJournaledClientProtectiveAttachments, readClientOrderMutation, readPendingEntryMutation, clientOrderNeverLandsAfterMs, requireClientRuntimeConfigSeconds, replacePendingEntryRecovery, recoverPendingClientProtectiveGroups, recoverPendingProtectiveReplacements, liveProtectiveOrderShape, observedStandaloneProtectiveGroup, migrateTrackedTrailingStopsToStandalone, reconcileClientProtectiveGroups, cancelAllClientProtectiveGroups, tightenClientTrailingStops, throwIfAborted2, sleep2, isDefinitiveEntryRejection, resolveExchangeSizeDecimals, roundAssetSize, resolvePositionSize, readServerOrderMarkPrice, serverOrderMetadataRetry, resolveCurrentPositionSize, buildPositionSnapshot, signedRemainingExposureAfterConfirmedReduction, runtimeProtectionAuthority, runtimeProtectionOwners, resolveRuntimeProtectionOwner, drainServerProtectionForRuntime, drainServerProtectionIfOwned, verifyNoLiveClientProtectiveTriggers, clientExecutionMutations, CLIENT_EXECUTION_QUEUE_TIMEOUT_MESSAGE, withClientExecutionMutation, withClientProtectivePlanSetMutation, allocateServerExecutionCapacity, withClientProtectiveAdoptionMutation, executeClientRuntimeDecisionLocked, unsentDecisionOrderReport, withCapacityTrim, SERVER_AUDIT_RECORDED_ELSEWHERE, serverExecutionAuditOutcome, decisionLegOf, withExecutionAuditId, executeClientRuntimeDecision, waitForFlipCloseFreshness, maintainClientRuntimeTrailingStops, listPendingClientProtectiveSymbols, listStoredClientProtectiveSymbols, hasUnresolvedClientProtectiveIdentity, resolveClientProtectiveIdentitiesForAdoption, exportClientProtectiveGroupsForAdoption, adoptionGroupKey, applyClientProtectiveAdoptionOutcomes, hasStoredClientProtectiveGroupsForWallet, hasPendingClientProtectiveGroups, recoverManualClientProtectiveGroups, clientRuntimeDecisionSizesOrders, COMMITTED_EXECUTION_REPORTS, COMMITTED_DECISION_ORDER, getCommittedExecutionReports, getCommittedDecisionOrder, withCommittedExecutionReports, executeClientRuntimeDecisionUnlocked, executeClientCopyTradingIntent, _copyCancelOrderId, executeClientCopyTradingOrderAction;
|
|
100383
|
+
var clientProtectiveMutationAuthority, executionReadPriority, serverEntryLeverageAlreadyHeld, fetchClientRuntimeOpenOrders, _extractOrderResponseStates, createRuntimeId, _extractFilledSize, firstMemberAcknowledgement, _extractOrderId, _toExecutionMetadata, _extractClientMutationId, _stableMutationIdentity, trailingStopMemory, protectiveGroupMemory, protectiveGroupReadFailures, windowHandoffCleanupAttempts, clientRuntimeProtectionStorage, resolveClientRuntimeProtectionStorage, setClientRuntimeProtectionStorage, trailingStopStorageKey, readTrackedTrailingStops, writeTrackedTrailingStops, rememberTrailingStop, protectiveGroupStorageKey, LOST_LEG_EVIDENCE_MAX_AGE_MS, EPISODE_END_FILL_LOOKBACK_MS, withClientProtectivePlanSetLock, readClientProtectiveGroups, writeClientProtectiveGroups, hasClientProtectiveGroupReadFailure, readFreshClientProtectiveGroups, stableProtectionSnapshot, exactClientProtectiveGroupSnapshot, exactClientProtectiveGroupSetSnapshot, storableClientProtectiveGroup, replaceExactClientProtectiveGroup, replaceExactClientProtectiveGroupSet, isClientRuntimeLeaseOwnershipError, hasClientRuntimeProtectionState, clearClientRuntimeVetoedProtectiveIntent, rethrowWindowHandoffAfterProtectiveReplacementVeto, canPersistClientProtectiveGroups, removeTrackedTrailingStop, replaceTrackedTrailingStop, replaceProtectiveLeg, replacementJournalEntryOrderId, buildProtectiveReplacementJournalGroup, isProtectiveReplacementJournalGroup, reserveProtectiveLegReplacement, ensureProtectiveReplacementJournalCompanion, buildVetoedProtectiveReplacementCleanup, assertExactProtectiveReplacementDispatchAuthority, transitionProtectiveReplacementAcknowledgement, transitionTerminalProtectiveReplacement, pendingProtectiveReplacementReport, isConfiguredProtectionRequested, protectiveAction, executedProtectiveReport, isExactClientPositionTpslPair, deviceOwnsClientProtectiveLegKind, isAdoptionNarrowedPositionTpslLeg, hasAmbiguousClientPositionTpslAuthority, protectiveStableShapeMatches, observedProtectiveGroupingMatches, protectiveLiveShapeMatches, protectiveTerminalShapeMatches, cancelClientProtectiveLeg, buildPendingProtectivePlan, persistPendingClientProtectiveGroup, attachmentMemberNeverLanded, storedClientProtectiveCover, attachClientProtectivePlan, resolveJournaledAttachmentContinuity, protectiveMemberRested, ledgerOrderIdsByClientOrderId, journaledAttachmentNeverLanded, recoverJournaledClientProtectiveAttachments, readClientOrderMutation, readPendingEntryMutation, clientOrderNeverLandsAfterMs, requireClientRuntimeConfigSeconds, replacePendingEntryRecovery, recoverPendingClientProtectiveGroups, recoverPendingProtectiveReplacements, liveProtectiveOrderShape, observedStandaloneProtectiveGroup, migrateTrackedTrailingStopsToStandalone, nativeSettingsOf, nativeProtectionIo, nativeStorageReport, readNativeRecord, reconcileNativeProtectionForDecision, reconcileClientProtectiveGroups, cancelAllClientProtectiveGroups, tightenClientTrailingStops, throwIfAborted2, sleep2, isDefinitiveEntryRejection, resolveExchangeSizeDecimals, roundAssetSize, resolvePositionSize, readServerOrderMarkPrice, serverOrderMetadataRetry, resolveCurrentPositionSize, buildPositionSnapshot, signedRemainingExposureAfterConfirmedReduction, runtimeProtectionAuthority, runtimeProtectionOwners, resolveRuntimeProtectionOwner, drainServerProtectionForRuntime, drainServerProtectionIfOwned, verifyNoLiveClientProtectiveTriggers, clientExecutionMutations, CLIENT_EXECUTION_QUEUE_TIMEOUT_MESSAGE, withClientExecutionMutation, withClientProtectivePlanSetMutation, allocateServerExecutionCapacity, withClientProtectiveAdoptionMutation, executeClientRuntimeDecisionLocked, unsentDecisionOrderReport, withCapacityTrim, SERVER_AUDIT_RECORDED_ELSEWHERE, serverExecutionAuditOutcome, decisionLegOf, withExecutionAuditId, executeClientRuntimeDecision, waitForFlipCloseFreshness, maintainClientRuntimeTrailingStops, listPendingClientProtectiveSymbols, listStoredClientProtectiveSymbols, hasUnresolvedClientProtectiveIdentity, resolveClientProtectiveIdentitiesForAdoption, exportClientProtectiveGroupsForAdoption, adoptionGroupKey, applyClientProtectiveAdoptionOutcomes, hasStoredClientProtectiveGroupsForWallet, hasPendingClientProtectiveGroups, recoverManualClientProtectiveGroups, clientRuntimeDecisionSizesOrders, COMMITTED_EXECUTION_REPORTS, COMMITTED_DECISION_ORDER, getCommittedExecutionReports, getCommittedDecisionOrder, withCommittedExecutionReports, executeClientRuntimeDecisionUnlocked, executeClientCopyTradingIntent, _copyCancelOrderId, executeClientCopyTradingOrderAction;
|
|
99596
100384
|
var init_runtime_execution = __esm({
|
|
99597
100385
|
"lib/runtime/runtime-execution.ts"() {
|
|
99598
100386
|
"use strict";
|
|
@@ -99621,6 +100409,8 @@ var init_runtime_execution = __esm({
|
|
|
99621
100409
|
init_protective_stop_replacement();
|
|
99622
100410
|
init_protective_entry_cover();
|
|
99623
100411
|
init_error_surface_contract();
|
|
100412
|
+
init_native_position_protection();
|
|
100413
|
+
init_native_protection_device();
|
|
99624
100414
|
init_runtime_handoff();
|
|
99625
100415
|
clientProtectiveMutationAuthority = (request) => request.mutationAuthority === "manual_session" ? {} : {
|
|
99626
100416
|
runtimeSessionId: request.sessionId || "__missing_runtime_session__",
|
|
@@ -99740,6 +100530,12 @@ var init_runtime_execution = __esm({
|
|
|
99740
100530
|
walk(value);
|
|
99741
100531
|
return found ? total : null;
|
|
99742
100532
|
};
|
|
100533
|
+
firstMemberAcknowledgement = (payload) => {
|
|
100534
|
+
const root = payload;
|
|
100535
|
+
const statuses = root?.response?.data?.statuses;
|
|
100536
|
+
if (!root || !Array.isArray(statuses) || statuses.length === 0) return payload;
|
|
100537
|
+
return { ...root, response: { ...root.response, data: { ...root.response?.data, statuses: [statuses[0]] } } };
|
|
100538
|
+
};
|
|
99743
100539
|
_extractOrderId = (value) => {
|
|
99744
100540
|
const seen = /* @__PURE__ */ new Set();
|
|
99745
100541
|
const walk = (node) => {
|
|
@@ -99830,6 +100626,7 @@ var init_runtime_execution = __esm({
|
|
|
99830
100626
|
setClientRuntimeProtectionStorage = (storage3) => {
|
|
99831
100627
|
if (clientRuntimeProtectionStorage === storage3) return;
|
|
99832
100628
|
clientRuntimeProtectionStorage = storage3;
|
|
100629
|
+
setNativeProtectionStorage(storage3);
|
|
99833
100630
|
trailingStopMemory.clear();
|
|
99834
100631
|
protectiveGroupMemory.clear();
|
|
99835
100632
|
protectiveGroupReadFailures.clear();
|
|
@@ -103145,6 +103942,165 @@ var init_runtime_execution = __esm({
|
|
|
103145
103942
|
}
|
|
103146
103943
|
writeTrackedTrailingStops(profileId, symbol2, records.map((record5) => orderIds.has(String(record5.orderId)) ? { ...record5, positionTpsl: false } : record5));
|
|
103147
103944
|
};
|
|
103945
|
+
nativeSettingsOf = (context) => nativeProtectionSettings({
|
|
103946
|
+
tpSlEnabled: context.tpSlEnabled === true,
|
|
103947
|
+
stopLossEnabled: context.stopLossEnabled !== false,
|
|
103948
|
+
stopLossType: context.stopLossType === "trailing" ? "trailing" : "fixed",
|
|
103949
|
+
stopLossMode: context.stopLossMode === "usdc" ? "usdc" : "percent",
|
|
103950
|
+
stopLossPct: toPositiveNumber(context.stopLossPct),
|
|
103951
|
+
stopLossUsdc: toPositiveNumber(context.stopLossUsdc),
|
|
103952
|
+
takeProfitEnabled: context.takeProfitEnabled !== false,
|
|
103953
|
+
takeProfitMode: context.takeProfitMode === "usdc" ? "usdc" : "percent",
|
|
103954
|
+
takeProfitPct: toPositiveNumber(context.takeProfitPct),
|
|
103955
|
+
takeProfitUsdc: toPositiveNumber(context.takeProfitUsdc)
|
|
103956
|
+
});
|
|
103957
|
+
nativeProtectionIo = (request, isLong) => {
|
|
103958
|
+
const symbol2 = request.executionContext.symbol;
|
|
103959
|
+
const walletAddress = String(request.executionContext.walletAddress || "").trim();
|
|
103960
|
+
const exitSide = isLong ? "sell" : "buy";
|
|
103961
|
+
const common = {
|
|
103962
|
+
profileId: request.profileId,
|
|
103963
|
+
...clientProtectiveMutationAuthority(request),
|
|
103964
|
+
walletAddress,
|
|
103965
|
+
config: request.config ?? null,
|
|
103966
|
+
signal: request.signal,
|
|
103967
|
+
signingKey: request.signingKey,
|
|
103968
|
+
symbol: symbol2
|
|
103969
|
+
};
|
|
103970
|
+
const mutationOf = (clientOrderId) => {
|
|
103971
|
+
const mutationId = mutationIdForClientOrderId(clientOrderId);
|
|
103972
|
+
if (!mutationId) throw new Error("Native protective order id is malformed.");
|
|
103973
|
+
return mutationId;
|
|
103974
|
+
};
|
|
103975
|
+
return {
|
|
103976
|
+
readPosition: async () => {
|
|
103977
|
+
const snapshot = await fetchBrowserPositionSnapshot(
|
|
103978
|
+
request.config ?? {},
|
|
103979
|
+
walletAddress,
|
|
103980
|
+
symbol2,
|
|
103981
|
+
request.signal,
|
|
103982
|
+
"trading_reduce"
|
|
103983
|
+
);
|
|
103984
|
+
return { size: snapshot.size, entryPrice: snapshot.entryPrice, stateTimeMs: snapshot.stateTimeMs };
|
|
103985
|
+
},
|
|
103986
|
+
readOpenOrders: () => fetchClientRuntimeOpenOrders(request, "trading_reduce"),
|
|
103987
|
+
readOrderStatus: (orderId) => fetchBrowserOrderStatusEvidence({
|
|
103988
|
+
publicRequestPriority: "trading_reduce",
|
|
103989
|
+
config: request.config ?? null,
|
|
103990
|
+
walletAddress,
|
|
103991
|
+
signal: request.signal,
|
|
103992
|
+
orderId
|
|
103993
|
+
}),
|
|
103994
|
+
placePositionOrder: ({ kind, triggerPrice, clientOrderId }) => withDispatchBoundary((onExchangeOrderDispatched) => executeClientOrderBatch({
|
|
103995
|
+
...common,
|
|
103996
|
+
onExchangeOrderDispatched,
|
|
103997
|
+
mutationId: mutationOf(clientOrderId),
|
|
103998
|
+
clientOrderId,
|
|
103999
|
+
grouping: "positionTpsl",
|
|
104000
|
+
members: [{
|
|
104001
|
+
side: exitSide,
|
|
104002
|
+
size: 0,
|
|
104003
|
+
limitPrice: triggerPrice,
|
|
104004
|
+
orderKind: "trigger",
|
|
104005
|
+
reduceOnly: true,
|
|
104006
|
+
triggerPrice,
|
|
104007
|
+
triggerKind: kind,
|
|
104008
|
+
triggerIsMarket: true,
|
|
104009
|
+
positionOrder: true,
|
|
104010
|
+
clientOrderId
|
|
104011
|
+
}]
|
|
104012
|
+
})),
|
|
104013
|
+
modifyPositionOrder: ({ orderId, kind, triggerPrice, clientOrderId }) => withDispatchBoundary((onExchangeOrderDispatched) => executeClientModifyOrder({
|
|
104014
|
+
...common,
|
|
104015
|
+
onExchangeOrderDispatched,
|
|
104016
|
+
mutationId: mutationOf(clientOrderId),
|
|
104017
|
+
clientOrderId,
|
|
104018
|
+
orderId,
|
|
104019
|
+
side: exitSide,
|
|
104020
|
+
size: 0,
|
|
104021
|
+
limitPrice: triggerPrice,
|
|
104022
|
+
orderKind: "trigger",
|
|
104023
|
+
reduceOnly: true,
|
|
104024
|
+
triggerPrice,
|
|
104025
|
+
triggerKind: kind,
|
|
104026
|
+
triggerIsMarket: true,
|
|
104027
|
+
positionOrder: true
|
|
104028
|
+
})),
|
|
104029
|
+
cancelOrder: (orderId) => withDispatchBoundary((onExchangeOrderDispatched) => executeClientCancelOrder({
|
|
104030
|
+
...common,
|
|
104031
|
+
onExchangeOrderDispatched,
|
|
104032
|
+
publicRequestPriority: "trading_reduce",
|
|
104033
|
+
orderId
|
|
104034
|
+
})),
|
|
104035
|
+
isDefinitiveRefusal: (error48) => error48 instanceof HyperliquidExchangeRejectionError || error48 instanceof NativeOrderNotSentError,
|
|
104036
|
+
neverLandsAfterMs: (sentAtMs) => clientOrderNeverLandsAfterMs(request.config, { kind: "absent", ageStartMs: sentAtMs }),
|
|
104037
|
+
newMutationId: () => createRuntimeId().toLowerCase(),
|
|
104038
|
+
nowMs: () => Date.now(),
|
|
104039
|
+
persist: (record5) => writeNativeProtectionRecord(String(request.profileId).trim(), symbol2, record5)
|
|
104040
|
+
};
|
|
104041
|
+
};
|
|
104042
|
+
nativeStorageReport = (symbol2, reasonCode) => ({
|
|
104043
|
+
order_id: null,
|
|
104044
|
+
symbol: symbol2,
|
|
104045
|
+
action: "PROTECTIVE_RECONCILIATION",
|
|
104046
|
+
status: "failed",
|
|
104047
|
+
execution_metadata: { reason_code: reasonCode }
|
|
104048
|
+
});
|
|
104049
|
+
readNativeRecord = (profileId, symbol2) => {
|
|
104050
|
+
try {
|
|
104051
|
+
const record5 = readNativeProtectionRecord(profileId, symbol2);
|
|
104052
|
+
return record5 == null ? { kind: "none" } : { kind: "record", record: record5 };
|
|
104053
|
+
} catch {
|
|
104054
|
+
return { kind: "invalid" };
|
|
104055
|
+
}
|
|
104056
|
+
};
|
|
104057
|
+
reconcileNativeProtectionForDecision = async (request) => {
|
|
104058
|
+
const profileId = String(request.profileId).trim();
|
|
104059
|
+
const symbol2 = request.executionContext.symbol;
|
|
104060
|
+
const read = readNativeRecord(profileId, symbol2);
|
|
104061
|
+
if (read.kind === "none") return [];
|
|
104062
|
+
if (read.kind === "invalid") return [nativeStorageReport(symbol2, "protective_lifecycle_storage_invalid")];
|
|
104063
|
+
const wallet = String(request.executionContext.walletAddress || "").trim().toLowerCase();
|
|
104064
|
+
if (read.record.walletAddress !== wallet) return [nativeStorageReport(symbol2, "protective_wallet_mismatch")];
|
|
104065
|
+
try {
|
|
104066
|
+
const io = nativeProtectionIo(request, read.record.isLong);
|
|
104067
|
+
if (read.record.phase === "entry_pending") {
|
|
104068
|
+
const settled = await settleNativeProtectionAfterFill({
|
|
104069
|
+
record: read.record,
|
|
104070
|
+
settings: nativeSettingsOf(request.executionContext),
|
|
104071
|
+
sizeDecimals: request.executionContext.sizeDecimals,
|
|
104072
|
+
fillSize: "0",
|
|
104073
|
+
entryOrderId: read.record.entryClientOrderId,
|
|
104074
|
+
io
|
|
104075
|
+
});
|
|
104076
|
+
const reports2 = [...settled.reports];
|
|
104077
|
+
if (!writeNativeProtectionRecord(profileId, symbol2, settled.record)) {
|
|
104078
|
+
reports2.push(nativeStorageReport(symbol2, "protective_lifecycle_persistence_failed"));
|
|
104079
|
+
}
|
|
104080
|
+
return reports2;
|
|
104081
|
+
}
|
|
104082
|
+
const result = await reconcileNativeProtection({
|
|
104083
|
+
record: read.record,
|
|
104084
|
+
settings: nativeSettingsOf(request.executionContext),
|
|
104085
|
+
sizeDecimals: request.executionContext.sizeDecimals,
|
|
104086
|
+
io
|
|
104087
|
+
});
|
|
104088
|
+
const reports = [...result.reports];
|
|
104089
|
+
if (!writeNativeProtectionRecord(profileId, symbol2, result.record)) {
|
|
104090
|
+
reports.push(nativeStorageReport(symbol2, "protective_lifecycle_persistence_failed"));
|
|
104091
|
+
}
|
|
104092
|
+
return reports;
|
|
104093
|
+
} catch (error48) {
|
|
104094
|
+
if (request.signal?.aborted) throw error48;
|
|
104095
|
+
return [{
|
|
104096
|
+
...nativeStorageReport(symbol2, "protective_open_orders_unresolved"),
|
|
104097
|
+
execution_metadata: {
|
|
104098
|
+
reason_code: "protective_open_orders_unresolved",
|
|
104099
|
+
error: getSanitizedRuntimeErrorMessage(error48) || "Unable to read native protection."
|
|
104100
|
+
}
|
|
104101
|
+
}];
|
|
104102
|
+
}
|
|
104103
|
+
};
|
|
103148
104104
|
reconcileClientProtectiveGroups = async (request, knownPositionSize) => {
|
|
103149
104105
|
const profileId = String(request.profileId).trim();
|
|
103150
104106
|
const symbol2 = request.executionContext.symbol;
|
|
@@ -105779,6 +106735,7 @@ var init_runtime_execution = __esm({
|
|
|
105779
106735
|
status: "failed",
|
|
105780
106736
|
execution_metadata: { reason_code: "protective_lifecycle_storage_invalid" }
|
|
105781
106737
|
}] : hasTrackedProtection ? await reconcileClientProtectiveGroups(input) : [];
|
|
106738
|
+
reconciliationReports.push(...await reconcileNativeProtectionForDecision(input));
|
|
105782
106739
|
if (input.decision === "HOLD" || requestedUnits <= 0) {
|
|
105783
106740
|
const shouldTrail = !input.skipTrailingMaintenance && input.executionContext.tpSlEnabled === true && input.executionContext.stopLossEnabled !== false && input.executionContext.stopLossType === "trailing" && decisionSnapshotPositionSize !== 0;
|
|
105784
106741
|
if (shouldTrail && !reconciliationReports.some((report) => report.status === "failed")) {
|
|
@@ -106406,7 +107363,85 @@ var init_runtime_execution = __esm({
|
|
|
106406
107363
|
const localProtection = shouldAttachSlTp && !serverOwnedProtection;
|
|
106407
107364
|
entryMutationId = await decisionLegMutationId("entry");
|
|
106408
107365
|
if (entryMutationId) entryClientOrderId = clientOrderIdForMutation(entryMutationId);
|
|
107366
|
+
let nativeOpen = null;
|
|
107367
|
+
let nativeAddRecord = null;
|
|
107368
|
+
const nativeProfileId = String(input.profileId).trim();
|
|
107369
|
+
const nativeBlocked = (reasonCode, message) => ({
|
|
107370
|
+
// A flip whose close already filled reports that close as executed.
|
|
107371
|
+
status: progress.committedReports != null ? "executed" : "skipped",
|
|
107372
|
+
intent: classified.intent,
|
|
107373
|
+
side: classified.side,
|
|
107374
|
+
reduceOnly: classified.reduceOnly,
|
|
107375
|
+
requestedUnits: classified.requestedUnits,
|
|
107376
|
+
targetSignedUnits: classified.targetSignedUnits,
|
|
107377
|
+
executedSizeAsset: progress.committedOrder?.executedSizeAsset ?? 0,
|
|
107378
|
+
executionReports: [
|
|
107379
|
+
...executionReports,
|
|
107380
|
+
{
|
|
107381
|
+
order_id: null,
|
|
107382
|
+
symbol: input.executionContext.symbol,
|
|
107383
|
+
action: "PROTECTIVE_RECONCILIATION",
|
|
107384
|
+
status: "blocked",
|
|
107385
|
+
execution_metadata: { reason_code: reasonCode, execution_stage: "entry_precondition" }
|
|
107386
|
+
}
|
|
107387
|
+
],
|
|
107388
|
+
message,
|
|
107389
|
+
executionSnapshotId,
|
|
107390
|
+
executionSnapshotCapturedAt
|
|
107391
|
+
});
|
|
106409
107392
|
if (localProtection) {
|
|
107393
|
+
let existingNative = readNativeRecord(nativeProfileId, input.executionContext.symbol);
|
|
107394
|
+
if (existingNative.kind === "record" && targetResolution.closeOpposingPosition) {
|
|
107395
|
+
executionReports.push(...await reconcileNativeProtectionForDecision(input));
|
|
107396
|
+
existingNative = readNativeRecord(nativeProfileId, input.executionContext.symbol);
|
|
107397
|
+
}
|
|
107398
|
+
if (existingNative.kind === "invalid") {
|
|
107399
|
+
return nativeBlocked(
|
|
107400
|
+
"protective_lifecycle_storage_invalid",
|
|
107401
|
+
"Blocked new exposure because the stored position protection could not be read."
|
|
107402
|
+
);
|
|
107403
|
+
}
|
|
107404
|
+
if (classified.intent === "add") {
|
|
107405
|
+
if (existingNative.kind === "record" && existingNative.record.isLong === (classified.side === "buy")) {
|
|
107406
|
+
nativeAddRecord = existingNative.record;
|
|
107407
|
+
}
|
|
107408
|
+
} else if (existingNative.kind === "record") {
|
|
107409
|
+
return nativeBlocked(
|
|
107410
|
+
"protective_reconciliation_unresolved",
|
|
107411
|
+
"Blocked new exposure because the earlier position's protection is still being resolved."
|
|
107412
|
+
);
|
|
107413
|
+
} else if (input.config?.client_native_position_protection_enabled === true) {
|
|
107414
|
+
entryMutationId ??= createRuntimeId().toLowerCase();
|
|
107415
|
+
entryClientOrderId = clientOrderIdForMutation(entryMutationId);
|
|
107416
|
+
nativeOpen = planNativeOpen({
|
|
107417
|
+
profileId: nativeProfileId,
|
|
107418
|
+
symbol: input.executionContext.symbol,
|
|
107419
|
+
walletAddress: String(input.executionContext.walletAddress || ""),
|
|
107420
|
+
settings: nativeSettingsOf(input.executionContext),
|
|
107421
|
+
isLong: classified.side === "buy",
|
|
107422
|
+
sizeDecimals: input.executionContext.sizeDecimals,
|
|
107423
|
+
referencePrice: executionPrice,
|
|
107424
|
+
entrySize: sizeAsset,
|
|
107425
|
+
// An entry that closed the opposing position first starts from flat;
|
|
107426
|
+
// otherwise from the live position, which may differ from the
|
|
107427
|
+
// decision's snapshot.
|
|
107428
|
+
positionBefore: targetResolution.closeOpposingPosition ? 0 : currentPositionSize,
|
|
107429
|
+
positionHasLegacyLegs: readClientProtectiveGroups(nativeProfileId, input.executionContext.symbol).length > 0,
|
|
107430
|
+
entryMutationId,
|
|
107431
|
+
entryClientOrderId,
|
|
107432
|
+
newMutationId: () => createRuntimeId().toLowerCase(),
|
|
107433
|
+
nowMs: Date.now()
|
|
107434
|
+
});
|
|
107435
|
+
if (nativeOpen != null && !writeNativeProtectionRecord(nativeProfileId, input.executionContext.symbol, nativeOpen.record)) {
|
|
107436
|
+
return nativeBlocked(
|
|
107437
|
+
"protective_lifecycle_persistence_failed",
|
|
107438
|
+
"Blocked new exposure because its position protection could not be stored."
|
|
107439
|
+
);
|
|
107440
|
+
}
|
|
107441
|
+
}
|
|
107442
|
+
}
|
|
107443
|
+
const nativeProtection = nativeOpen != null || nativeAddRecord != null;
|
|
107444
|
+
if (localProtection && !nativeProtection) {
|
|
106410
107445
|
entryMutationId ??= createRuntimeId().toLowerCase();
|
|
106411
107446
|
entryClientOrderId = clientOrderIdForMutation(entryMutationId);
|
|
106412
107447
|
const pendingProtection = persistPendingClientProtectiveGroup({
|
|
@@ -106494,6 +107529,7 @@ var init_runtime_execution = __esm({
|
|
|
106494
107529
|
reduceOnly: classified.reduceOnly,
|
|
106495
107530
|
mutationId: entryMutationId,
|
|
106496
107531
|
clientOrderId: entryClientOrderId,
|
|
107532
|
+
...nativeOpen != null ? { positionChildren: nativeOpen.children } : {},
|
|
106497
107533
|
...serverOwnedProtection ? {
|
|
106498
107534
|
// The server attaches the configured Auto SL/TP to this entry.
|
|
106499
107535
|
protection: {
|
|
@@ -106522,6 +107558,9 @@ var init_runtime_execution = __esm({
|
|
|
106522
107558
|
marketOrderResponse = await sendEntry();
|
|
106523
107559
|
}
|
|
106524
107560
|
} catch (entryDispatchError) {
|
|
107561
|
+
if (nativeOpen != null && (!entryDispatchBoundaryPassed || isDefinitiveEntryRejection(entryDispatchError, entryMutationId))) {
|
|
107562
|
+
writeNativeProtectionRecord(nativeProfileId, input.executionContext.symbol, null);
|
|
107563
|
+
}
|
|
106525
107564
|
const handoffVeto = isClientRuntimeWindowHandoffBeforePlanDispatch(entryDispatchError);
|
|
106526
107565
|
const handoffBeforeDispatch = handoffVeto || !entryDispatchBoundaryPassed && input.shouldCancelBeforeExchangeOrderDispatch?.() === true;
|
|
106527
107566
|
const hasCommittedReports = executionReports.some((report) => report.status === "executed" && String(report.order_id || "").trim().length > 0);
|
|
@@ -106569,7 +107608,8 @@ var init_runtime_execution = __esm({
|
|
|
106569
107608
|
throw entryDispatchError;
|
|
106570
107609
|
}
|
|
106571
107610
|
const confirmedMarketFill = extractCanonicalHyperliquidFilledOrderAcknowledgement(
|
|
106572
|
-
|
|
107611
|
+
// An entry carrying position children is member 0 of its action.
|
|
107612
|
+
nativeOpen != null ? firstMemberAcknowledgement(marketOrderResponse) : marketOrderResponse
|
|
106573
107613
|
);
|
|
106574
107614
|
executionReports.push({
|
|
106575
107615
|
order_id: _extractOrderId(marketOrderResponse),
|
|
@@ -106639,7 +107679,39 @@ var init_runtime_execution = __esm({
|
|
|
106639
107679
|
const settledEntry = settledServerProtectedEntry;
|
|
106640
107680
|
await drainServerProtectionForRuntime(input, settledEntry?.protective_actions ?? null);
|
|
106641
107681
|
}
|
|
106642
|
-
if (
|
|
107682
|
+
if (nativeProtection) {
|
|
107683
|
+
const symbol2 = input.executionContext.symbol;
|
|
107684
|
+
let record5 = nativeOpen != null ? recordEntryChildren(nativeOpen.record, marketOrderResponse) : nativeAddRecord;
|
|
107685
|
+
if (confirmedMarketFill == null) {
|
|
107686
|
+
executionReports.push({
|
|
107687
|
+
order_id: _extractOrderId(marketOrderResponse),
|
|
107688
|
+
symbol: symbol2,
|
|
107689
|
+
action: "PROTECTIVE_RECONCILIATION",
|
|
107690
|
+
status: "blocked",
|
|
107691
|
+
execution_metadata: { reason_code: "entry_fill_unresolved", execution_stage: "protective_trigger_precondition" }
|
|
107692
|
+
});
|
|
107693
|
+
} else {
|
|
107694
|
+
try {
|
|
107695
|
+
const settled = await settleNativeProtectionAfterFill({
|
|
107696
|
+
record: record5,
|
|
107697
|
+
settings: nativeSettingsOf(input.executionContext),
|
|
107698
|
+
sizeDecimals: input.executionContext.sizeDecimals,
|
|
107699
|
+
fillSize: String(confirmedMarketFill.filledSize),
|
|
107700
|
+
entryOrderId: confirmedMarketFill.orderId,
|
|
107701
|
+
io: nativeProtectionIo(input, record5.isLong)
|
|
107702
|
+
});
|
|
107703
|
+
executionReports.push(...settled.reports);
|
|
107704
|
+
if (settled.record != null) record5 = settled.record;
|
|
107705
|
+
} catch (postEntryProtectionError) {
|
|
107706
|
+
if (isClientRuntimeLeaseOwnershipError(postEntryProtectionError)) throw postEntryProtectionError;
|
|
107707
|
+
appendPostEntryProtectionFailure(postEntryProtectionError);
|
|
107708
|
+
}
|
|
107709
|
+
}
|
|
107710
|
+
if (!writeNativeProtectionRecord(nativeProfileId, symbol2, record5)) {
|
|
107711
|
+
executionReports.push(nativeStorageReport(symbol2, "protective_lifecycle_persistence_failed"));
|
|
107712
|
+
}
|
|
107713
|
+
}
|
|
107714
|
+
if (localProtection && !nativeProtection) {
|
|
106643
107715
|
let protectionBlockReason = confirmedMarketFill == null ? "entry_fill_unresolved" : classified.intent === "flip" && !flipCloseFillConfirmed ? "flip_close_fill_unresolved" : null;
|
|
106644
107716
|
const protectionFill = protectionBlockReason == null ? confirmedMarketFill : null;
|
|
106645
107717
|
const protectionSize = protectionFill == null ? 0 : protectionFill.filledSize;
|
|
@@ -108390,7 +109462,7 @@ var init_inference_observability = __esm({
|
|
|
108390
109462
|
AI_INVOCATION_PARSER_CONTRACT_VERSION = 1;
|
|
108391
109463
|
NEVER_SENT_FAILURE_CATEGORY = "configuration";
|
|
108392
109464
|
MISSING_API_KEY_FAILURE_CODE = "missing_api_key";
|
|
108393
|
-
isNeverSentInvocation = (
|
|
109465
|
+
isNeverSentInvocation = (attempt2) => attempt2.failure_category === NEVER_SENT_FAILURE_CATEGORY;
|
|
108394
109466
|
USE_CASES = /* @__PURE__ */ new Set(["trader", "decision_chat", "screener"]);
|
|
108395
109467
|
ROLES_BY_USE_CASE = {
|
|
108396
109468
|
trader: /* @__PURE__ */ new Set(["primary", "review"]),
|
|
@@ -111346,7 +112418,7 @@ function canAdvanceProfileModel(error48, external, signal, ownAttempts) {
|
|
|
111346
112418
|
if (failure2.runtimePartialOutput || failure2.result?.content || failure2.result?.reasoningContent) return false;
|
|
111347
112419
|
if (external) return failure2.modelFallbackSafe === true;
|
|
111348
112420
|
const attempts = ownAttempts ?? failure2.runtimeInvocationAttempts ?? [];
|
|
111349
|
-
if (attempts.some((
|
|
112421
|
+
if (attempts.some((attempt2) => attempt2.status === "succeeded" || attempt2.provider_status_code == null && !isNeverSentInvocation(attempt2) && !(failure2.runtimeNativeRecoverySafe === true && ["timeout", "transport_error"].includes(attempt2.failure_code ?? "")) || Boolean(attempt2.response_content) || Boolean(attempt2.reasoning_content))) return false;
|
|
111350
112422
|
const message = error48.message.toLowerCase();
|
|
111351
112423
|
if (/outcome.?unknown|dispatch.?unknown/.test(message)) return false;
|
|
111352
112424
|
if (failure2.runtimeNativeRecoverySafe === true && failure2.runtimeNativeFailureKind && attempts.length > 0) return true;
|
|
@@ -111376,17 +112448,17 @@ async function invokeProfileModelCascade(input) {
|
|
|
111376
112448
|
if (attempted.has(identity2)) continue;
|
|
111377
112449
|
attempted.add(identity2);
|
|
111378
112450
|
if (input.signal?.aborted) throw input.signal.reason ?? new DOMException("Cancelled", "AbortError");
|
|
111379
|
-
const priorIds = new Set(attempts.map((
|
|
112451
|
+
const priorIds = new Set(attempts.map((attempt2) => attempt2.client_invocation_id));
|
|
111380
112452
|
try {
|
|
111381
112453
|
const result = await input.invoke(entry, index, attempts);
|
|
111382
112454
|
const resultInvocations = result.invocations ?? [];
|
|
111383
|
-
const ids = new Set(resultInvocations.map((
|
|
111384
|
-
return { ...result, invocations: [...attempts.filter((
|
|
112455
|
+
const ids = new Set(resultInvocations.map((attempt2) => attempt2.client_invocation_id));
|
|
112456
|
+
return { ...result, invocations: [...attempts.filter((attempt2) => !ids.has(attempt2.client_invocation_id)), ...resultInvocations] };
|
|
111385
112457
|
} catch (error48) {
|
|
111386
112458
|
const observed = error48?.runtimeInvocationAttempts;
|
|
111387
112459
|
if (Array.isArray(observed)) attempts = observed;
|
|
111388
112460
|
if (error48 instanceof Error) error48.runtimeInvocationAttempts = attempts;
|
|
111389
|
-
const ownAttempts = attempts.filter((
|
|
112461
|
+
const ownAttempts = attempts.filter((attempt2) => !priorIds.has(attempt2.client_invocation_id));
|
|
111390
112462
|
if (error48 instanceof Error) failedModels.push(fallbackAttemptFor(entry, error48, ownAttempts));
|
|
111391
112463
|
if (index === entries.length - 1 || !canAdvanceProfileModel(error48, entry.kind === "external_agent" || entry.source === "external_agent", input.signal, ownAttempts)) surface(error48);
|
|
111392
112464
|
lastFailure = error48;
|
|
@@ -115593,19 +116665,19 @@ var init_provider_client = __esm({
|
|
|
115593
116665
|
if (!rawAttempt || typeof rawAttempt !== "object") {
|
|
115594
116666
|
continue;
|
|
115595
116667
|
}
|
|
115596
|
-
const
|
|
115597
|
-
const errorDetail = String(
|
|
116668
|
+
const attempt2 = rawAttempt;
|
|
116669
|
+
const errorDetail = String(attempt2.errorDetail || "Provider compatibility dispatch failed.");
|
|
115598
116670
|
chain.push(await buildBrowserInvocation({
|
|
115599
116671
|
context: invocationContext,
|
|
115600
116672
|
attemptIndex: chain.length,
|
|
115601
116673
|
status: "failed",
|
|
115602
116674
|
provider,
|
|
115603
|
-
transport:
|
|
116675
|
+
transport: attempt2.transport ?? defaultProviderTransport(provider),
|
|
115604
116676
|
requestedModel: model,
|
|
115605
116677
|
actualModel: model,
|
|
115606
116678
|
credentialSlotIndex: provider === "local" ? null : providerKeySlotIndex + 1,
|
|
115607
|
-
startedAt:
|
|
115608
|
-
latencyMs: Number(
|
|
116679
|
+
startedAt: attempt2.startedAt ?? invocationStartedAt,
|
|
116680
|
+
latencyMs: Number(attempt2.latencyMs ?? 0),
|
|
115609
116681
|
systemPrompt,
|
|
115610
116682
|
userPrompt,
|
|
115611
116683
|
extraMessages: normalizedExtraMessages,
|
|
@@ -115614,15 +116686,15 @@ var init_provider_client = __esm({
|
|
|
115614
116686
|
reasoningPayload,
|
|
115615
116687
|
nativeRequestParameters,
|
|
115616
116688
|
nativeRequestParameterValues,
|
|
115617
|
-
sentReasoningParameters:
|
|
115618
|
-
effectiveReasoningParameters:
|
|
116689
|
+
sentReasoningParameters: attempt2.sentReasoningParameters,
|
|
116690
|
+
effectiveReasoningParameters: attempt2.effectiveReasoningParameters,
|
|
115619
116691
|
errorDetail,
|
|
115620
|
-
statusCode:
|
|
115621
|
-
requestInputTokens:
|
|
115622
|
-
providerDiagnostics:
|
|
115623
|
-
providerRequestId:
|
|
115624
|
-
response:
|
|
115625
|
-
retryable:
|
|
116692
|
+
statusCode: attempt2.statusCode ?? null,
|
|
116693
|
+
requestInputTokens: attempt2.requestInputTokens,
|
|
116694
|
+
providerDiagnostics: attempt2.providerDiagnostics,
|
|
116695
|
+
providerRequestId: attempt2.providerRequestId,
|
|
116696
|
+
response: attempt2.response ?? null,
|
|
116697
|
+
retryable: attempt2.retryable ?? false,
|
|
115626
116698
|
fallbackFrom: chain.at(-1) ?? null
|
|
115627
116699
|
}));
|
|
115628
116700
|
}
|
|
@@ -115909,7 +116981,7 @@ var init_provider_client = __esm({
|
|
|
115909
116981
|
error48?.runtimeDispatchStartedAt
|
|
115910
116982
|
);
|
|
115911
116983
|
const invocationAttempts2 = [...observedInvocationAttempts2];
|
|
115912
|
-
const nativeRecoverySafe = input.nativeRecoverySafe !== false && !input.tools?.length && !inputOnDelta && !emittedDelta && (statusCode !== null || Boolean(nativeFailureKind)) && (!Array.isArray(rawInternalDispatchAttempts) || rawInternalDispatchAttempts.every((
|
|
116984
|
+
const nativeRecoverySafe = input.nativeRecoverySafe !== false && !input.tools?.length && !inputOnDelta && !emittedDelta && (statusCode !== null || Boolean(nativeFailureKind)) && (!Array.isArray(rawInternalDispatchAttempts) || rawInternalDispatchAttempts.every((attempt2) => attempt2.statusCode != null));
|
|
115913
116985
|
if (currentDispatchObserved) {
|
|
115914
116986
|
const failedProviderResponse = error48?.runtimeProviderResult && typeof error48.runtimeProviderResult === "object" ? error48.runtimeProviderResult : null;
|
|
115915
116987
|
const failedCostInfo = failedProviderResponse ? calculateProviderCost(
|
|
@@ -121075,7 +122147,7 @@ ${behaviorJson}
|
|
|
121075
122147
|
}
|
|
121076
122148
|
};
|
|
121077
122149
|
fetchBoundPromptContracts = async (profileId, payload, signal, walletAddress, getEquity, getTotalUnrealizedPnl, getAccountStateResolvedAtMs, getUserFills, waitForLiveAccountState, initialMetadata, getPositions, getPerpDexAccounts, runsWithoutEquity = false) => {
|
|
121078
|
-
let
|
|
122150
|
+
let attempt2 = 0;
|
|
121079
122151
|
while (true) {
|
|
121080
122152
|
if (waitForLiveAccountState) {
|
|
121081
122153
|
const accountStateWaitStartedAtMs = Date.now();
|
|
@@ -121106,7 +122178,7 @@ ${behaviorJson}
|
|
|
121106
122178
|
appendRuntimeTimingEvent(
|
|
121107
122179
|
"prompt_parity_account_state_ready",
|
|
121108
122180
|
accountStateWaitStartedAtMs,
|
|
121109
|
-
`attempt=${
|
|
122181
|
+
`attempt=${attempt2 + 1}`
|
|
121110
122182
|
);
|
|
121111
122183
|
reportPromptParityTelemetry(
|
|
121112
122184
|
profileId,
|
|
@@ -121115,7 +122187,7 @@ ${behaviorJson}
|
|
|
121115
122187
|
"phase=account_state_wait",
|
|
121116
122188
|
{
|
|
121117
122189
|
phase: "account_state_wait",
|
|
121118
|
-
attempt:
|
|
122190
|
+
attempt: attempt2 + 1,
|
|
121119
122191
|
duration_ms: Date.now() - accountStateWaitStartedAtMs
|
|
121120
122192
|
}
|
|
121121
122193
|
);
|
|
@@ -121130,7 +122202,7 @@ ${behaviorJson}
|
|
|
121130
122202
|
const accountStateAgeMs = typeof accountStateResolvedAtMs === "number" ? Math.max(0, parityPreparedAtMs - accountStateResolvedAtMs) : null;
|
|
121131
122203
|
appendRuntimeDebugEvent({
|
|
121132
122204
|
label: "prompt_parity_context_prepared",
|
|
121133
|
-
note: `attempt=${
|
|
122205
|
+
note: `attempt=${attempt2 + 1} parity_included=${parityIncluded ? "yes" : "no"} account_equity=${liveEquity.toFixed(RUNTIME_DEBUG_USD_DECIMALS)} account_state_age_ms=${accountStateAgeMs ?? "unresolved"}`
|
|
121134
122206
|
});
|
|
121135
122207
|
reportPromptParityTelemetry(
|
|
121136
122208
|
profileId,
|
|
@@ -121139,7 +122211,7 @@ ${behaviorJson}
|
|
|
121139
122211
|
`phase=derived_context_preflight parity_included=${parityIncluded ? "yes" : "no"}`,
|
|
121140
122212
|
{
|
|
121141
122213
|
phase: "derived_context_preflight",
|
|
121142
|
-
attempt:
|
|
122214
|
+
attempt: attempt2 + 1,
|
|
121143
122215
|
parity_included: parityIncluded,
|
|
121144
122216
|
account_equity_positive: liveEquity > 0,
|
|
121145
122217
|
account_state_age_ms: accountStateAgeMs,
|
|
@@ -121157,7 +122229,7 @@ ${behaviorJson}
|
|
|
121157
122229
|
"phase=derived_context_preflight parity_included=no",
|
|
121158
122230
|
{
|
|
121159
122231
|
phase: "derived_context_preflight",
|
|
121160
|
-
attempt:
|
|
122232
|
+
attempt: attempt2 + 1,
|
|
121161
122233
|
account_state_age_ms: accountStateAgeMs,
|
|
121162
122234
|
account_equity_positive: false
|
|
121163
122235
|
}
|
|
@@ -121186,7 +122258,7 @@ ${behaviorJson}
|
|
|
121186
122258
|
};
|
|
121187
122259
|
appendRuntimeDebugEvent({
|
|
121188
122260
|
label: "prompt_parity_fills_prepared",
|
|
121189
|
-
note: `attempt=${
|
|
122261
|
+
note: `attempt=${attempt2 + 1} fills=${fills.length}`
|
|
121190
122262
|
});
|
|
121191
122263
|
}
|
|
121192
122264
|
const derivedPayload = {
|
|
@@ -121204,7 +122276,7 @@ ${behaviorJson}
|
|
|
121204
122276
|
});
|
|
121205
122277
|
} catch (error48) {
|
|
121206
122278
|
const detail = error48 instanceof Error ? error48.message : String(error48);
|
|
121207
|
-
const errorMetadata =
|
|
122279
|
+
const errorMetadata = attempt2 === 0 && initialMetadata ? initialMetadata : await fetchClientRuntimePromptMetadata(profileId, payload, {
|
|
121208
122280
|
schedulerInstanceId: payload.schedulerInstanceId,
|
|
121209
122281
|
signal
|
|
121210
122282
|
});
|
|
@@ -121224,7 +122296,7 @@ ${behaviorJson}
|
|
|
121224
122296
|
);
|
|
121225
122297
|
const metadataStartedAtMs = Date.now();
|
|
121226
122298
|
let embeddedMetadata = derived.prompt_metadata;
|
|
121227
|
-
const initialMetadataPrecedesDerived =
|
|
122299
|
+
const initialMetadataPrecedesDerived = attempt2 === 0 && initialMetadata !== null;
|
|
121228
122300
|
const legacyMetadataFollowsDerived = !embeddedMetadata && !initialMetadataPrecedesDerived;
|
|
121229
122301
|
let metadata;
|
|
121230
122302
|
if (embeddedMetadata && typeof embeddedMetadata === "object") {
|
|
@@ -121291,23 +122363,23 @@ ${behaviorJson}
|
|
|
121291
122363
|
assertPromptContractTemporalBounds(metadata, derived);
|
|
121292
122364
|
appendRuntimeDebugEvent({
|
|
121293
122365
|
label: "prompt_contract_binding_validated",
|
|
121294
|
-
note: `attempt=${
|
|
122366
|
+
note: `attempt=${attempt2 + 1} contract_hash=${metadata.envelope.contract_hash} cycle_snapshot_id=${derived.cycle_snapshot_id}`
|
|
121295
122367
|
});
|
|
121296
122368
|
return { metadata, derived };
|
|
121297
122369
|
} catch (error48) {
|
|
121298
122370
|
const detail = error48 instanceof Error ? error48.message : String(error48);
|
|
121299
|
-
if (
|
|
121300
|
-
throw new Error(`Prompt contract binding mismatch after ${
|
|
122371
|
+
if (attempt2 >= maxBindingRetries) {
|
|
122372
|
+
throw new Error(`Prompt contract binding mismatch after ${attempt2 + 1} attempt(s): ${detail}`);
|
|
121301
122373
|
}
|
|
121302
|
-
const exponentialBackoff = Math.min(backoffMaxMs, backoffBaseMs * BACKOFF_GROWTH_FACTOR **
|
|
122374
|
+
const exponentialBackoff = Math.min(backoffMaxMs, backoffBaseMs * BACKOFF_GROWTH_FACTOR ** attempt2);
|
|
121303
122375
|
const jitter = backoffJitterMs > 0 ? Math.floor(Math.random() * (backoffJitterMs + 1)) : 0;
|
|
121304
122376
|
const waitMs = exponentialBackoff + jitter;
|
|
121305
122377
|
appendRuntimeDebugEvent({
|
|
121306
122378
|
label: "prompt_contract_binding_retry",
|
|
121307
|
-
note: `attempt=${
|
|
122379
|
+
note: `attempt=${attempt2 + 1} wait_ms=${waitMs} reason=${detail}`
|
|
121308
122380
|
});
|
|
121309
122381
|
await sleepWithAbort(waitMs, signal);
|
|
121310
|
-
|
|
122382
|
+
attempt2 += 1;
|
|
121311
122383
|
}
|
|
121312
122384
|
}
|
|
121313
122385
|
};
|
|
@@ -123833,11 +124905,11 @@ var init_engine = __esm({
|
|
|
123833
124905
|
if (!Array.isArray(attempts)) {
|
|
123834
124906
|
return null;
|
|
123835
124907
|
}
|
|
123836
|
-
const normalized = attempts.map((
|
|
123837
|
-
if (!
|
|
124908
|
+
const normalized = attempts.map((attempt2) => {
|
|
124909
|
+
if (!attempt2 || typeof attempt2 !== "object") {
|
|
123838
124910
|
return null;
|
|
123839
124911
|
}
|
|
123840
|
-
const record5 =
|
|
124912
|
+
const record5 = attempt2;
|
|
123841
124913
|
const model = String(record5.model || "").trim();
|
|
123842
124914
|
if (!model) {
|
|
123843
124915
|
return null;
|
|
@@ -123850,10 +124922,10 @@ var init_engine = __esm({
|
|
|
123850
124922
|
error: sanitizeRuntimeDiagnosticValue(String(record5.error || "")).slice(0, FALLBACK_ERROR_MAX_CHARS) || null,
|
|
123851
124923
|
statusCode: Number.isInteger(statusCode) ? statusCode : null
|
|
123852
124924
|
};
|
|
123853
|
-
}).filter((
|
|
124925
|
+
}).filter((attempt2) => attempt2 !== null);
|
|
123854
124926
|
return normalized.length > 0 ? normalized : null;
|
|
123855
124927
|
};
|
|
123856
|
-
sentInvocationAttemptCount = (record5) => Array.isArray(record5.runtimeInvocationAttempts) ? record5.runtimeInvocationAttempts.filter((
|
|
124928
|
+
sentInvocationAttemptCount = (record5) => Array.isArray(record5.runtimeInvocationAttempts) ? record5.runtimeInvocationAttempts.filter((attempt2) => !attempt2 || typeof attempt2 !== "object" || !isNeverSentInvocation(attempt2)).length : 0;
|
|
123857
124929
|
boundRuntimeFallbackAttempts = (reason, maxModels) => {
|
|
123858
124930
|
const attempts = getRuntimeFallbackAttempts(reason);
|
|
123859
124931
|
return attempts ? boundRuntimeReportAttempts(attempts, maxModels) : null;
|
|
@@ -127399,8 +128471,8 @@ var init_engine = __esm({
|
|
|
127399
128471
|
}
|
|
127400
128472
|
if (decisionError instanceof Error && decisionError.status === HTTP_STATUS.CONFLICT && (decisionError.code === "snapshot_stale" || decisionError.message.startsWith("Runtime decision rejected by constraints:"))) {
|
|
127401
128473
|
Object.assign(decisionError, {
|
|
127402
|
-
runtimeInvocationAttempts: result.invocations?.map((
|
|
127403
|
-
...
|
|
128474
|
+
runtimeInvocationAttempts: result.invocations?.map((attempt2) => ({
|
|
128475
|
+
...attempt2,
|
|
127404
128476
|
used_for_final_decision: false
|
|
127405
128477
|
}))
|
|
127406
128478
|
});
|
|
@@ -130290,13 +131362,13 @@ async function runHeadlessRuntime(options) {
|
|
|
130290
131362
|
const waitForServerBackup = async () => {
|
|
130291
131363
|
if (options.once || stopController.signal.aborted) return "not_backup";
|
|
130292
131364
|
let status = null;
|
|
130293
|
-
for (let
|
|
131365
|
+
for (let attempt2 = 0; ; attempt2 += 1) {
|
|
130294
131366
|
const read = await readWaitStatus();
|
|
130295
131367
|
if (read === "ended" || typeof read === "object" && "refused" in read) return "not_backup";
|
|
130296
131368
|
status = read === "retry" ? null : read.status;
|
|
130297
|
-
if (status ||
|
|
131369
|
+
if (status || attempt2 >= BACKUP_FIRST_READ_RETRY_MS.length || stopController.signal.aborted) break;
|
|
130298
131370
|
try {
|
|
130299
|
-
await sleep3(BACKUP_FIRST_READ_RETRY_MS[
|
|
131371
|
+
await sleep3(BACKUP_FIRST_READ_RETRY_MS[attempt2], void 0, { signal: stopController.signal });
|
|
130300
131372
|
} catch {
|
|
130301
131373
|
break;
|
|
130302
131374
|
}
|