@vtxmacro/cli 2026.10.52 → 2026.10.54
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 +902 -385
- package/package.json +1 -1
package/bin/vtx.js
CHANGED
|
@@ -122,7 +122,7 @@ var init_routing = __esm({
|
|
|
122
122
|
var agent_cli_release_default;
|
|
123
123
|
var init_agent_cli_release = __esm({
|
|
124
124
|
"agent-cli-release.json"() {
|
|
125
|
-
agent_cli_release_default = { package_name: "@vtxmacro/cli", package_version: "2026.10.
|
|
125
|
+
agent_cli_release_default = { package_name: "@vtxmacro/cli", package_version: "2026.10.54", codex_package_name: "@openai/codex", codex_version: "0.155.0", copilot_sdk_package_name: "@github/copilot-sdk", copilot_sdk_version: "1.0.0-beta.8", copilot_cli_package_name: "@github/copilot", copilot_cli_version: "1.0.80", deepseek_harness_version: "0.1.1-rc.2", deepseek_harness_packages: ["@deepseek-ai/dsh-agent", "@deepseek-ai/dsh-agent-instructions", "@deepseek-ai/dsh-agent-loop", "@deepseek-ai/dsh-agent-spine-demo", "@deepseek-ai/dsh-anonymous-user-id", "@deepseek-ai/dsh-atomic-write", "@deepseek-ai/dsh-attachment", "@deepseek-ai/dsh-brand", "@deepseek-ai/dsh-code-runtime", "@deepseek-ai/dsh-credentials", "@deepseek-ai/dsh-fs", "@deepseek-ai/dsh-goal", "@deepseek-ai/dsh-goal-round-driver", "@deepseek-ai/dsh-home-paths", "@deepseek-ai/dsh-invariants", "@deepseek-ai/dsh-jobs", "@deepseek-ai/dsh-jobs-local", "@deepseek-ai/dsh-launch-environment", "@deepseek-ai/dsh-llm", "@deepseek-ai/dsh-llm-deepseek", "@deepseek-ai/dsh-llm-retry", "@deepseek-ai/dsh-output-retention", "@deepseek-ai/dsh-sandbox", "@deepseek-ai/dsh-sandbox-policy", "@deepseek-ai/dsh-scope", "@deepseek-ai/dsh-session", "@deepseek-ai/dsh-session-checkpoint-policy", "@deepseek-ai/dsh-session-persistence", "@deepseek-ai/dsh-session-persistence-jsonl", "@deepseek-ai/dsh-session-projection", "@deepseek-ai/dsh-session-title", "@deepseek-ai/dsh-settings", "@deepseek-ai/dsh-shell", "@deepseek-ai/dsh-shell-env", "@deepseek-ai/dsh-skill", "@deepseek-ai/dsh-skill-filesystem", "@deepseek-ai/dsh-subprocess", "@deepseek-ai/dsh-system-prompt", "@deepseek-ai/dsh-timeout", "@deepseek-ai/dsh-tool-bash", "@deepseek-ai/dsh-tool-goal", "@deepseek-ai/dsh-tool-jobs", "@deepseek-ai/dsh-tool-skill", "@deepseek-ai/dsh-tools", "@deepseek-ai/dsh-typert-protocol", "@deepseek-ai/dsh-user-approval"], deepseek_cordis_package_name: "@deepseek-ai/cordis", deepseek_cordis_version: "4.0.1", deepseek_support_packages: { "@deepseek-ai/cordis-plugin-timer": "1.1.3" }, platforms: { "linux-x64": { package_name: "@openai/codex-linux-x64", target: "x86_64-unknown-linux-musl", binary_name: "codex", sha256: "660e159a49e823ac8e5986cb238f73158ce4b957d40d9292f8de90862644b501" }, "win32-x64": { package_name: "@openai/codex-win32-x64", target: "x86_64-pc-windows-msvc", binary_name: "codex.exe", sha256: "e4c11374bd9de8ad5c3b7617fd4654bb7839901edb0863f9930666863c7a021b" } }, pi_coding_agent_package_name: "@earendil-works/pi-coding-agent", pi_ai_package_name: "@earendil-works/pi-ai", pi_version: "0.85.1", pi_support_packages: ["@earendil-works/pi-agent-core", "@earendil-works/pi-telemetry", "@earendil-works/pi-tui", "@earendil-works/chord"], grok_version: "1.0.30", grok_platforms: { "linux-x64": { package_name: "@xai-official/grok-linux-x64", binary_name: "grok", sha256: "504dd6546ab991b75d36698242875ce461489cd1f8cd84285873cb55bd5c7d54" }, "win32-x64": { package_name: "@xai-official/grok-win32-x64", binary_name: "grok.exe", sha256: "48736d1a4342a801ea26d0ecde4c516b653f791399065adaa55973f83abd8867" } } };
|
|
126
126
|
}
|
|
127
127
|
});
|
|
128
128
|
|
|
@@ -4728,7 +4728,7 @@ async function syncInferenceDirectory(path, platform = process.platform) {
|
|
|
4728
4728
|
async function replaceAtomicInferencePrivateFile(temporaryPath, destinationPath, options = {}) {
|
|
4729
4729
|
const platform = options.platform ?? process.platform;
|
|
4730
4730
|
const renameFile = options.renameFile ?? rename;
|
|
4731
|
-
const
|
|
4731
|
+
const sleep3 = options.sleep ?? ((milliseconds) => new Promise((resolve16) => setTimeout(resolve16, milliseconds)));
|
|
4732
4732
|
const maxAttempts = Math.max(1, options.maxAttempts ?? HOST_CORE_POLICY.private_file_replace_attempts);
|
|
4733
4733
|
const retryDelayMs = Math.max(0, options.retryDelayMs ?? HOST_CORE_POLICY.private_file_replace_retry_delay_ms);
|
|
4734
4734
|
for (let attempt2 = 0; attempt2 < maxAttempts; attempt2 += 1) {
|
|
@@ -4740,7 +4740,7 @@ async function replaceAtomicInferencePrivateFile(temporaryPath, destinationPath,
|
|
|
4740
4740
|
if (platform !== "win32" || !WINDOWS_PRIVATE_FILE_REPLACE_ERROR_CODES.has(code) || attempt2 === maxAttempts - 1) {
|
|
4741
4741
|
throw error48;
|
|
4742
4742
|
}
|
|
4743
|
-
await
|
|
4743
|
+
await sleep3(retryDelayMs);
|
|
4744
4744
|
}
|
|
4745
4745
|
}
|
|
4746
4746
|
}
|
|
@@ -5893,7 +5893,7 @@ while(($line=[Console]::In.ReadLine()) -ne $null) {
|
|
|
5893
5893
|
});
|
|
5894
5894
|
|
|
5895
5895
|
// lib/runtime/abort.ts
|
|
5896
|
-
var ABORT_MESSAGE_TOKENS, readAbortLikeMessage, isAbortLikeError, toAbortError;
|
|
5896
|
+
var ABORT_MESSAGE_TOKENS, readAbortLikeMessage, isAbortLikeError, toAbortError, throwIfAborted, abortableSleep;
|
|
5897
5897
|
var init_abort = __esm({
|
|
5898
5898
|
"lib/runtime/abort.ts"() {
|
|
5899
5899
|
"use strict";
|
|
@@ -5947,6 +5947,32 @@ var init_abort = __esm({
|
|
|
5947
5947
|
return fallback;
|
|
5948
5948
|
}
|
|
5949
5949
|
};
|
|
5950
|
+
throwIfAborted = (signal) => {
|
|
5951
|
+
if (signal?.aborted) {
|
|
5952
|
+
throw new DOMException("The operation was aborted.", "AbortError");
|
|
5953
|
+
}
|
|
5954
|
+
};
|
|
5955
|
+
abortableSleep = async (ms, signal) => {
|
|
5956
|
+
await new Promise((resolve16, reject) => {
|
|
5957
|
+
const timer = setTimeout(() => {
|
|
5958
|
+
cleanup();
|
|
5959
|
+
resolve16(void 0);
|
|
5960
|
+
}, ms);
|
|
5961
|
+
const cleanup = () => {
|
|
5962
|
+
clearTimeout(timer);
|
|
5963
|
+
signal?.removeEventListener("abort", onAbort);
|
|
5964
|
+
};
|
|
5965
|
+
const onAbort = () => {
|
|
5966
|
+
cleanup();
|
|
5967
|
+
reject(new DOMException("The operation was aborted.", "AbortError"));
|
|
5968
|
+
};
|
|
5969
|
+
if (signal?.aborted) {
|
|
5970
|
+
onAbort();
|
|
5971
|
+
return;
|
|
5972
|
+
}
|
|
5973
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
5974
|
+
});
|
|
5975
|
+
};
|
|
5950
5976
|
}
|
|
5951
5977
|
});
|
|
5952
5978
|
|
|
@@ -35221,7 +35247,7 @@ child.once('close', async (code, signal) => {
|
|
|
35221
35247
|
const platform = options.platform ?? process.platform;
|
|
35222
35248
|
const renameFile = options.renameFile ?? rename3;
|
|
35223
35249
|
const removeFile = options.removeFile ?? ((path) => rm4(path, { force: true }));
|
|
35224
|
-
const
|
|
35250
|
+
const sleep3 = options.sleep ?? ((milliseconds) => new Promise((resolve16) => setTimeout(resolve16, milliseconds)));
|
|
35225
35251
|
const maxAttempts = Math.max(1, options.maxAttempts ?? HOST_RUNTIME_POLICY.codex_guardian_receipt_replace_attempts);
|
|
35226
35252
|
const retryDelayMs = Math.max(0, options.retryDelayMs ?? HOST_RUNTIME_POLICY.codex_guardian_receipt_replace_retry_ms);
|
|
35227
35253
|
for (let attempt2 = 0; attempt2 < maxAttempts; attempt2 += 1) {
|
|
@@ -35241,7 +35267,7 @@ child.once('close', async (code, signal) => {
|
|
|
35241
35267
|
throw removeError;
|
|
35242
35268
|
}
|
|
35243
35269
|
}
|
|
35244
|
-
await
|
|
35270
|
+
await sleep3(retryDelayMs);
|
|
35245
35271
|
}
|
|
35246
35272
|
}
|
|
35247
35273
|
};
|
|
@@ -38343,7 +38369,7 @@ var init_runner = __esm({
|
|
|
38343
38369
|
receiptDurabilityTimeoutMs: this.options.receiptDurabilityTimeoutMs ?? await loadInferenceReceiptDurabilityTimeoutMs()
|
|
38344
38370
|
});
|
|
38345
38371
|
const now = this.dependencies.now ?? Date.now;
|
|
38346
|
-
const
|
|
38372
|
+
const sleep3 = this.dependencies.sleep ?? defaultSleep;
|
|
38347
38373
|
const lock2 = await this.dependencies.acquireProcessLock();
|
|
38348
38374
|
let unregisterSignals = () => {
|
|
38349
38375
|
};
|
|
@@ -38559,7 +38585,7 @@ var init_runner = __esm({
|
|
|
38559
38585
|
});
|
|
38560
38586
|
if (this.options.once) return;
|
|
38561
38587
|
try {
|
|
38562
|
-
await
|
|
38588
|
+
await sleep3(Math.max(MIN_SLEEP_MS, retryAtMs - now()), agentIdleSignal);
|
|
38563
38589
|
} catch {
|
|
38564
38590
|
return;
|
|
38565
38591
|
}
|
|
@@ -38647,11 +38673,11 @@ var init_runner = __esm({
|
|
|
38647
38673
|
const retained = await readInferenceAgentRuntimeState(agentRuntimeSettings.statePath);
|
|
38648
38674
|
const fence = await readInferenceAgentFailureFence(agentRuntimeSettings.statePath);
|
|
38649
38675
|
if (!fence || !canReplayFencedAgentTerminal(retained, fence)) return;
|
|
38650
|
-
await
|
|
38676
|
+
await sleep3(HOST_RUNTIME_POLICY2.agent_idle_retry_ms, agentIdleSignal).catch(() => void 0);
|
|
38651
38677
|
continue;
|
|
38652
38678
|
}
|
|
38653
38679
|
try {
|
|
38654
|
-
await
|
|
38680
|
+
await sleep3(Math.max(MIN_SLEEP_MS, retryAtMs - now()), agentIdleSignal);
|
|
38655
38681
|
} catch {
|
|
38656
38682
|
return;
|
|
38657
38683
|
}
|
|
@@ -38667,7 +38693,7 @@ var init_runner = __esm({
|
|
|
38667
38693
|
const retained = await readInferenceAgentRuntimeState(agentRuntimeSettings.statePath);
|
|
38668
38694
|
if (!retained || retained.schema_version !== "vtx_inference_agent_runtime_v3" || !retained.pending_turn?.terminal_receipt) return;
|
|
38669
38695
|
if (this.options.once) return;
|
|
38670
|
-
await
|
|
38696
|
+
await sleep3(HOST_RUNTIME_POLICY2.agent_idle_retry_ms, agentIdleSignal).catch((error49) => {
|
|
38671
38697
|
if (!quiesceRequested) throw error49;
|
|
38672
38698
|
});
|
|
38673
38699
|
continue;
|
|
@@ -38681,7 +38707,7 @@ var init_runner = __esm({
|
|
|
38681
38707
|
});
|
|
38682
38708
|
if (this.options.once) return;
|
|
38683
38709
|
try {
|
|
38684
|
-
await
|
|
38710
|
+
await sleep3(HOST_RUNTIME_POLICY2.agent_idle_retry_ms, agentIdleSignal).catch((error49) => {
|
|
38685
38711
|
if (!quiesceRequested) throw error49;
|
|
38686
38712
|
});
|
|
38687
38713
|
} catch {
|
|
@@ -38812,7 +38838,7 @@ var init_runner = __esm({
|
|
|
38812
38838
|
{ cause: error48 }
|
|
38813
38839
|
);
|
|
38814
38840
|
}
|
|
38815
|
-
await
|
|
38841
|
+
await sleep3(requestedRetryDelay, boundary.signal);
|
|
38816
38842
|
}
|
|
38817
38843
|
}
|
|
38818
38844
|
throw lastError;
|
|
@@ -39039,7 +39065,7 @@ var init_runner = __esm({
|
|
|
39039
39065
|
result = status === "draining" || !retryRemote ? await heartbeatOperation() : await retryExact(heartbeatOperation, requestOptions);
|
|
39040
39066
|
} catch (error48) {
|
|
39041
39067
|
if (status !== "draining" && retryRemote && error48 instanceof ExternalInferenceMcpError && error48.definitivelyNotApplied && error48.retryable && definitiveReseedAttempt < settings.remoteRetryLimit - 1) {
|
|
39042
|
-
await
|
|
39068
|
+
await sleep3(remoteRetryAfterMs(error48, MIN_SLEEP_MS), requestOptions.signal);
|
|
39043
39069
|
return await hostHeartbeat(
|
|
39044
39070
|
status,
|
|
39045
39071
|
requestOptions,
|
|
@@ -39237,7 +39263,7 @@ var init_runner = __esm({
|
|
|
39237
39263
|
hostHeartbeatLoop = (async () => {
|
|
39238
39264
|
while (!drainRequested && !hostHeartbeatAbort.signal.aborted) {
|
|
39239
39265
|
try {
|
|
39240
|
-
await
|
|
39266
|
+
await sleep3(
|
|
39241
39267
|
Math.max(MIN_SLEEP_MS, nextHostHeartbeatAt - now()),
|
|
39242
39268
|
hostHeartbeatAbort.signal
|
|
39243
39269
|
);
|
|
@@ -39253,7 +39279,7 @@ var init_runner = __esm({
|
|
|
39253
39279
|
try {
|
|
39254
39280
|
await Promise.race([
|
|
39255
39281
|
pendingAdvertisementHandoff,
|
|
39256
|
-
|
|
39282
|
+
sleep3(settings.hostHeartbeatMs, hostHeartbeatAbort.signal)
|
|
39257
39283
|
]);
|
|
39258
39284
|
} catch (error48) {
|
|
39259
39285
|
if (hostHeartbeatAbort.signal.aborted || drainRequested) return;
|
|
@@ -39395,7 +39421,7 @@ var init_runner = __esm({
|
|
|
39395
39421
|
signal: controller.signal,
|
|
39396
39422
|
attemptHeartbeatMs: settings.attemptHeartbeatMs,
|
|
39397
39423
|
receiptDurabilityTimeoutMs: settings.receiptDurabilityTimeoutMs,
|
|
39398
|
-
sleep:
|
|
39424
|
+
sleep: sleep3,
|
|
39399
39425
|
now,
|
|
39400
39426
|
onProviderCooldown: ({ retryAtMs, reason, rateLimits }) => {
|
|
39401
39427
|
if (!Number.isSafeInteger(retryAtMs) || retryAtMs <= now()) return;
|
|
@@ -40077,7 +40103,7 @@ var init_runner = __esm({
|
|
|
40077
40103
|
);
|
|
40078
40104
|
if (yieldRenewalToClaim) continue;
|
|
40079
40105
|
await Promise.race([
|
|
40080
|
-
|
|
40106
|
+
sleep3(Math.max(MIN_SLEEP_MS, wakeAt - now())),
|
|
40081
40107
|
drainSignal,
|
|
40082
40108
|
quiesceWake,
|
|
40083
40109
|
...active.values()
|
|
@@ -40104,7 +40130,7 @@ var init_runner = __esm({
|
|
|
40104
40130
|
let timedOut = false;
|
|
40105
40131
|
await Promise.race([
|
|
40106
40132
|
Promise.allSettled([...active.values()]),
|
|
40107
|
-
|
|
40133
|
+
sleep3(settings.drainTimeoutMs).then(() => {
|
|
40108
40134
|
timedOut = true;
|
|
40109
40135
|
})
|
|
40110
40136
|
]);
|
|
@@ -40113,7 +40139,7 @@ var init_runner = __esm({
|
|
|
40113
40139
|
for (const controller of attemptControllers.values()) controller.abort();
|
|
40114
40140
|
await Promise.race([
|
|
40115
40141
|
Promise.allSettled([...active.values()]),
|
|
40116
|
-
|
|
40142
|
+
sleep3(settings.drainTimeoutMs)
|
|
40117
40143
|
]);
|
|
40118
40144
|
requestDrain("drain_timeout");
|
|
40119
40145
|
}
|
|
@@ -42379,7 +42405,7 @@ var init_owned_directory_removal = __esm({
|
|
|
42379
42405
|
TRANSIENT_REMOVAL_ERROR_CODES = /* @__PURE__ */ new Set(["EBUSY", "EMFILE", "ENFILE", "ENOTEMPTY", "EPERM"]);
|
|
42380
42406
|
removeOwnedDirectory = async (path, options = {}) => {
|
|
42381
42407
|
const removeDirectory = options.removeDirectory ?? rm5;
|
|
42382
|
-
const
|
|
42408
|
+
const sleep3 = options.sleep ?? ((milliseconds) => new Promise((resolve16) => {
|
|
42383
42409
|
setTimeout(resolve16, milliseconds);
|
|
42384
42410
|
}));
|
|
42385
42411
|
const maxAttempts = Math.max(1, options.maxAttempts ?? runtime_policy_generated_default.external_inference.host_core.owned_directory_removal_attempts);
|
|
@@ -42391,7 +42417,7 @@ var init_owned_directory_removal = __esm({
|
|
|
42391
42417
|
} catch (error48) {
|
|
42392
42418
|
const code = String(error48?.code ?? "");
|
|
42393
42419
|
if (attempt2 >= maxAttempts || !TRANSIENT_REMOVAL_ERROR_CODES.has(code)) throw error48;
|
|
42394
|
-
await
|
|
42420
|
+
await sleep3(retryDelayMs * attempt2);
|
|
42395
42421
|
}
|
|
42396
42422
|
}
|
|
42397
42423
|
};
|
|
@@ -44269,7 +44295,7 @@ $items = @(Get-CimInstance Win32_Process | Where-Object { $_.Name -in @('node.ex
|
|
|
44269
44295
|
throw new Error("Same-boot service recovery is currently supported only on Windows.");
|
|
44270
44296
|
}
|
|
44271
44297
|
const queryProcesses = options.queryProcesses ?? queryWindowsProcesses;
|
|
44272
|
-
const
|
|
44298
|
+
const sleep3 = options.sleep ?? (async (milliseconds) => {
|
|
44273
44299
|
await new Promise((resolvePromise) => setTimeout(resolvePromise, milliseconds));
|
|
44274
44300
|
});
|
|
44275
44301
|
for (let observation = 0; observation < HOST_RUNTIME_POLICY5.codex_recovery_process_observations; observation += 1) {
|
|
@@ -44288,7 +44314,7 @@ $items = @(Get-CimInstance Win32_Process | Where-Object { $_.Name -in @('node.ex
|
|
|
44288
44314
|
);
|
|
44289
44315
|
}
|
|
44290
44316
|
if (observation + 1 < HOST_RUNTIME_POLICY5.codex_recovery_process_observations) {
|
|
44291
|
-
await
|
|
44317
|
+
await sleep3(HOST_RUNTIME_POLICY5.codex_recovery_process_observation_interval_ms);
|
|
44292
44318
|
}
|
|
44293
44319
|
}
|
|
44294
44320
|
};
|
|
@@ -44314,7 +44340,7 @@ $items = @(Get-CimInstance Win32_Process | Where-Object { $_.Name -in @('node.ex
|
|
|
44314
44340
|
return;
|
|
44315
44341
|
}
|
|
44316
44342
|
const queryProcesses = options.queryProcesses ?? queryWindowsProcesses;
|
|
44317
|
-
const
|
|
44343
|
+
const sleep3 = options.sleep ?? (async (milliseconds) => {
|
|
44318
44344
|
await new Promise((resolvePromise) => setTimeout(resolvePromise, milliseconds));
|
|
44319
44345
|
});
|
|
44320
44346
|
for (let observation = 0; observation < HOST_RUNTIME_POLICY5.codex_recovery_process_observations; observation += 1) {
|
|
@@ -44323,7 +44349,7 @@ $items = @(Get-CimInstance Win32_Process | Where-Object { $_.Name -in @('node.ex
|
|
|
44323
44349
|
throw new Error("Codex guardian process tree is still running; recovery evidence was preserved.");
|
|
44324
44350
|
}
|
|
44325
44351
|
if (observation + 1 < HOST_RUNTIME_POLICY5.codex_recovery_process_observations) {
|
|
44326
|
-
await
|
|
44352
|
+
await sleep3(HOST_RUNTIME_POLICY5.codex_recovery_process_observation_interval_ms);
|
|
44327
44353
|
}
|
|
44328
44354
|
}
|
|
44329
44355
|
};
|
|
@@ -52141,7 +52167,7 @@ ${result.stderr}`)) {
|
|
|
52141
52167
|
await controlLock.release();
|
|
52142
52168
|
}
|
|
52143
52169
|
};
|
|
52144
|
-
const
|
|
52170
|
+
const sleep3 = options.sleep ?? (async (milliseconds) => {
|
|
52145
52171
|
await new Promise((resolvePromise) => setTimeout(resolvePromise, milliseconds));
|
|
52146
52172
|
});
|
|
52147
52173
|
const launch = options.runWorker ?? options.spawnChild ?? spawnInferenceHostServiceChild;
|
|
@@ -52186,7 +52212,7 @@ ${result.stderr}`)) {
|
|
|
52186
52212
|
controller.signal.addEventListener("abort", finishAbort, { once: true });
|
|
52187
52213
|
signal.addEventListener("abort", finishAbort, { once: true });
|
|
52188
52214
|
try {
|
|
52189
|
-
await Promise.race([
|
|
52215
|
+
await Promise.race([sleep3(milliseconds), aborted2]);
|
|
52190
52216
|
} finally {
|
|
52191
52217
|
controller.signal.removeEventListener("abort", finishAbort);
|
|
52192
52218
|
signal.removeEventListener("abort", finishAbort);
|
|
@@ -52214,7 +52240,7 @@ ${result.stderr}`)) {
|
|
|
52214
52240
|
if (readinessSignalled) return;
|
|
52215
52241
|
readinessSignalled = true;
|
|
52216
52242
|
readinessTask = (async () => {
|
|
52217
|
-
await
|
|
52243
|
+
await sleep3(SERVICE_POLICY.worker_readiness_settle_ms);
|
|
52218
52244
|
if (!launchSettled && !attemptController.signal.aborted && !record6.controller.signal.aborted && !signal.aborted) {
|
|
52219
52245
|
await updateRecord(record6, "running");
|
|
52220
52246
|
}
|
|
@@ -52348,7 +52374,7 @@ ${result.stderr}`)) {
|
|
|
52348
52374
|
if (!storedNext) throw new Error("Inference-host service manifest is missing.");
|
|
52349
52375
|
const next = withServiceScript(storedNext);
|
|
52350
52376
|
if (next.generation !== appliedManifest.generation && next.generation !== rejectedManifestGeneration) await reconcile(next);
|
|
52351
|
-
await
|
|
52377
|
+
await sleep3(SERVICE_POLICY.supervisor_manifest_poll_interval_ms);
|
|
52352
52378
|
}
|
|
52353
52379
|
if (quiesceSignal.aborted && !signal.aborted) {
|
|
52354
52380
|
let finished = false;
|
|
@@ -52357,7 +52383,7 @@ ${result.stderr}`)) {
|
|
|
52357
52383
|
return results;
|
|
52358
52384
|
});
|
|
52359
52385
|
while (!finished && !signal.aborted && await readDesiredAcrossAtomicReplacement(desiredPath)) {
|
|
52360
|
-
await Promise.race([completion,
|
|
52386
|
+
await Promise.race([completion, sleep3(SERVICE_POLICY.supervisor_manifest_poll_interval_ms)]);
|
|
52361
52387
|
}
|
|
52362
52388
|
if (!finished) {
|
|
52363
52389
|
await drainWorkers();
|
|
@@ -54422,7 +54448,7 @@ Waiting for approval...
|
|
|
54422
54448
|
}
|
|
54423
54449
|
const session = await agentSession(config2, dependencies, warnings);
|
|
54424
54450
|
const now = dependencies.now ?? (() => /* @__PURE__ */ new Date());
|
|
54425
|
-
const
|
|
54451
|
+
const sleep3 = dependencies.sleep ?? (async (milliseconds) => {
|
|
54426
54452
|
await new Promise((resolve16) => setTimeout(resolve16, milliseconds));
|
|
54427
54453
|
});
|
|
54428
54454
|
const stopAt = now().getTime() + parsed.waitSeconds * MS_PER_SECOND;
|
|
@@ -54520,7 +54546,7 @@ Waiting for approval...
|
|
|
54520
54546
|
` : ""
|
|
54521
54547
|
};
|
|
54522
54548
|
}
|
|
54523
|
-
await
|
|
54549
|
+
await sleep3(Math.min(remaining, Math.max(HOST_RUNTIME_POLICY16.agent_next_poll_min_ms, result.retry_after_ms)));
|
|
54524
54550
|
}
|
|
54525
54551
|
};
|
|
54526
54552
|
foregroundAssignmentHeartbeat = async (config2, parsed, dependencies, warnings) => {
|
|
@@ -55054,7 +55080,7 @@ Waiting for approval...
|
|
|
55054
55080
|
}
|
|
55055
55081
|
const session = await agentSession(config2, dependencies, warnings);
|
|
55056
55082
|
const now = dependencies.now ?? (() => /* @__PURE__ */ new Date());
|
|
55057
|
-
const
|
|
55083
|
+
const sleep3 = dependencies.sleep ?? (async (milliseconds) => {
|
|
55058
55084
|
await new Promise((resolve16) => setTimeout(resolve16, milliseconds));
|
|
55059
55085
|
});
|
|
55060
55086
|
const stopAt = now().getTime() + parsed.waitSeconds * MS_PER_SECOND;
|
|
@@ -55172,7 +55198,7 @@ Waiting for approval...
|
|
|
55172
55198
|
` : ""
|
|
55173
55199
|
};
|
|
55174
55200
|
}
|
|
55175
|
-
await
|
|
55201
|
+
await sleep3(Math.max(
|
|
55176
55202
|
HOST_RUNTIME_POLICY16.agent_assignment_poll_min_ms,
|
|
55177
55203
|
Math.min(
|
|
55178
55204
|
result.retry_after_ms || HOST_RUNTIME_POLICY16.agent_assignment_poll_fallback_ms,
|
|
@@ -59016,7 +59042,7 @@ function getProfileHeaders(baseHeaders = {}, explicitProfileId) {
|
|
|
59016
59042
|
if (profileId) headers["x-profile-id"] = profileId.toString();
|
|
59017
59043
|
return headers;
|
|
59018
59044
|
}
|
|
59019
|
-
var configuredApiTransport, getApiUrl,
|
|
59045
|
+
var configuredApiTransport, getApiUrl, withoutContentType, browserRequestInit, sendApiRequest, apiFetch, sleep, DEVICE_CLOCK_HEADER, deviceClockHeader, API_NO_ROUTE_DETAIL, isMissingApiRoute, sendExchangeMutationReport, inFlightClientGetRequests, recentClientGetResponses, clientGetRequestGenerations, initializedClientGetRequestKeys, CLIENT_GET_DEDUPE_TTL_MS, CLIENT_RUNTIME_STATUSES_DEDUPE_TTL_MS, CLIENT_LLM_CONFIG_PRIME_TTL_MS, AUTH_BOOTSTRAP_GET_MAX_ATTEMPTS, AUTH_BOOTSTRAP_RETRY_JITTER_MS, singleUserHostCache, canUseClientGetRequestCache, clientGetRequestCacheActive, invalidateClientGetRequestCache, raceWithAbortSignal, shareClientGetRequest, clientGetRequestKey, clientPreferencesRequestKey, invalidateClientPreferencesCache, parseRetryAfterMs2, resolveAuthBootstrapRetryDelayMs, fetchAuthBootstrapGetWithRetry, annotateMarketDataRequestError, buildMarketDataFetchError, buildMarketDataNetworkError, buildMarketDataResponseBodyError, isTransientNetworkFetchError, createIdempotencyKey, getErrorMessage, getErrorPayloadOrEmpty, getErrorPayloadOrFallbackDetail, getErrorMessageFromResponse, throwUnauthorizedIfNeeded, activeProfileId, PROFILE_STORAGE_KEY;
|
|
59020
59046
|
var init_shared = __esm({
|
|
59021
59047
|
"lib/api/shared.ts"() {
|
|
59022
59048
|
"use strict";
|
|
@@ -59045,9 +59071,26 @@ var init_shared = __esm({
|
|
|
59045
59071
|
RFC1918_172_BLOCK_SECOND_OCTET
|
|
59046
59072
|
);
|
|
59047
59073
|
};
|
|
59048
|
-
|
|
59074
|
+
withoutContentType = (headers) => {
|
|
59075
|
+
if (headers instanceof Headers) {
|
|
59076
|
+
const kept2 = new Headers(headers);
|
|
59077
|
+
kept2.delete("Content-Type");
|
|
59078
|
+
return kept2;
|
|
59079
|
+
}
|
|
59080
|
+
const entries = Array.isArray(headers) ? headers : Object.entries(headers);
|
|
59081
|
+
const kept = entries.filter(([name]) => name.toLowerCase() !== "content-type");
|
|
59082
|
+
return Array.isArray(headers) ? kept : Object.fromEntries(kept);
|
|
59083
|
+
};
|
|
59084
|
+
browserRequestInit = (init2) => {
|
|
59085
|
+
if (typeof window === "undefined" || !init2) return init2;
|
|
59086
|
+
const shaped = init2.cache === "no-store" ? { ...init2, cache: "default" } : init2;
|
|
59087
|
+
const method = (init2.method ?? "GET").toUpperCase();
|
|
59088
|
+
const bodyless = init2.body == null && (method === "GET" || method === "HEAD");
|
|
59089
|
+
if (!bodyless || !init2.headers || !new Headers(init2.headers).has("Content-Type")) return shaped;
|
|
59090
|
+
return { ...shaped, headers: withoutContentType(init2.headers) };
|
|
59091
|
+
};
|
|
59049
59092
|
sendApiRequest = (input, requested) => {
|
|
59050
|
-
const init2 =
|
|
59093
|
+
const init2 = browserRequestInit(requested);
|
|
59051
59094
|
const transport = configuredApiTransport;
|
|
59052
59095
|
if (!transport) return fetch(input, init2);
|
|
59053
59096
|
const headers = new Headers(init2?.headers ?? (input instanceof Request ? input.headers : void 0));
|
|
@@ -60477,45 +60520,10 @@ var init_billing = __esm({
|
|
|
60477
60520
|
|
|
60478
60521
|
// lib/api/market-data.ts
|
|
60479
60522
|
async function getRecentCandles(limit, exchange = "kraken", symbol2 = "PI_XBTUSD", timeframe = "1m", signal) {
|
|
60480
|
-
|
|
60481
|
-
|
|
60482
|
-
|
|
60483
|
-
|
|
60484
|
-
kind: "runtime",
|
|
60485
|
-
label: "market_data_api:candles_recent",
|
|
60486
|
-
method: "GET",
|
|
60487
|
-
url: requestUrl2,
|
|
60488
|
-
note: `symbol=${symbol2} exchange=${exchange} timeframe=${timeframe} limit=${limit}`
|
|
60489
|
-
});
|
|
60490
|
-
let response = null;
|
|
60491
|
-
try {
|
|
60492
|
-
response = await apiFetch(requestUrl2, {
|
|
60493
|
-
cache: "no-store",
|
|
60494
|
-
signal: requestSignal
|
|
60495
|
-
});
|
|
60496
|
-
if (!response.ok) {
|
|
60497
|
-
const error48 = await buildMarketDataFetchError(response, "recent candles", "/candles/recent");
|
|
60498
|
-
trace.attachResponse({ status: response.status, statusText: response.statusText, url: response.url });
|
|
60499
|
-
trace.completeError(error48, response.status);
|
|
60500
|
-
console.error(`[API] ${error48.message} URL: ${response.url}`);
|
|
60501
|
-
throw error48;
|
|
60502
|
-
}
|
|
60503
|
-
trace.attachResponse({ status: response.status, statusText: response.statusText, url: response.url });
|
|
60504
|
-
const payload = await response.json();
|
|
60505
|
-
trace.completeSuccess(response.status);
|
|
60506
|
-
return payload;
|
|
60507
|
-
} catch (error48) {
|
|
60508
|
-
if (response && !response.ok) throw error48;
|
|
60509
|
-
if (response && !isAbortLikeError(error48)) {
|
|
60510
|
-
const failure2 = buildMarketDataResponseBodyError(error48, "recent candles", response, "/candles/recent");
|
|
60511
|
-
trace.completeError(failure2, response.status);
|
|
60512
|
-
throw failure2;
|
|
60513
|
-
}
|
|
60514
|
-
trace.completeError(error48, response?.status ?? null);
|
|
60515
|
-
if (isAbortLikeError(error48)) throw error48;
|
|
60516
|
-
throw buildMarketDataNetworkError(error48, "recent candles", "/candles/recent");
|
|
60517
|
-
}
|
|
60518
|
-
}, { signal, shareAbortScoped: true });
|
|
60523
|
+
return (await readRecentCandles(limit, exchange, symbol2, timeframe, signal, null)).candles;
|
|
60524
|
+
}
|
|
60525
|
+
async function getRecentCandlesForProfile(profileId, limit, exchange, symbol2, timeframe, signal) {
|
|
60526
|
+
return readRecentCandles(limit, exchange, symbol2, timeframe, signal, profileId);
|
|
60519
60527
|
}
|
|
60520
60528
|
async function getLiveTicker(symbol2 = "PI_XBTUSD", exchange = "kraken", signal) {
|
|
60521
60529
|
const requestKey = `live-ticker:${symbol2}:${exchange}`;
|
|
@@ -60579,7 +60587,7 @@ async function getExecutionAssetMetadata(exchange, symbol2, options) {
|
|
|
60579
60587
|
}
|
|
60580
60588
|
return response.json();
|
|
60581
60589
|
}
|
|
60582
|
-
var ExecutionAssetMetadataRequestError, CLIENT_EXECUTION_METADATA_DEVICE_READ, executionMetadataNeedsDeviceRead;
|
|
60590
|
+
var CANDLES_MISSING_HEADER, CandlesMissingRangeError, parseCandlesMissing, readRecentCandles, ExecutionAssetMetadataRequestError, CLIENT_EXECUTION_METADATA_DEVICE_READ, executionMetadataNeedsDeviceRead;
|
|
60583
60591
|
var init_market_data = __esm({
|
|
60584
60592
|
"lib/api/market-data.ts"() {
|
|
60585
60593
|
"use strict";
|
|
@@ -60592,6 +60600,67 @@ var init_market_data = __esm({
|
|
|
60592
60600
|
init_network_debug();
|
|
60593
60601
|
init_shared();
|
|
60594
60602
|
init_constants();
|
|
60603
|
+
CANDLES_MISSING_HEADER = "X-VTX-Candles-Missing";
|
|
60604
|
+
CandlesMissingRangeError = class extends Error {
|
|
60605
|
+
};
|
|
60606
|
+
parseCandlesMissing = (value) => {
|
|
60607
|
+
if (value === null || value.trim() === "") return null;
|
|
60608
|
+
const [startText, endText, ...extra] = value.split(",");
|
|
60609
|
+
const startMs = Number(startText?.trim());
|
|
60610
|
+
const endMs = Number(endText?.trim());
|
|
60611
|
+
if (extra.length > 0 || !Number.isSafeInteger(startMs) || !Number.isSafeInteger(endMs) || startMs > endMs) {
|
|
60612
|
+
throw new CandlesMissingRangeError(`The candle answer named an unreadable missing range: ${sanitizeRuntimeDiagnosticValue(value)}`);
|
|
60613
|
+
}
|
|
60614
|
+
return { startMs, endMs };
|
|
60615
|
+
};
|
|
60616
|
+
readRecentCandles = async (limit, exchange, symbol2, timeframe, signal, profileId) => {
|
|
60617
|
+
const params = new URLSearchParams({ limit: limit.toString(), exchange, symbol: symbol2, timeframe });
|
|
60618
|
+
const requestUrl2 = `${getApiUrl()}/candles/recent?${params.toString()}`;
|
|
60619
|
+
const forProfile = profileId === null ? {} : { credentials: "include", headers: getProfileHeaders({}, profileId) };
|
|
60620
|
+
return shareClientGetRequest(`recent-candles:${profileId ?? "none"}:${params.toString()}`, async (requestSignal) => {
|
|
60621
|
+
const trace = startRuntimeNetworkDebugTrace({
|
|
60622
|
+
kind: "runtime",
|
|
60623
|
+
label: "market_data_api:candles_recent",
|
|
60624
|
+
method: "GET",
|
|
60625
|
+
url: requestUrl2,
|
|
60626
|
+
note: `symbol=${symbol2} exchange=${exchange} timeframe=${timeframe} limit=${limit}`
|
|
60627
|
+
});
|
|
60628
|
+
let response = null;
|
|
60629
|
+
try {
|
|
60630
|
+
response = await apiFetch(requestUrl2, {
|
|
60631
|
+
...forProfile,
|
|
60632
|
+
cache: "no-store",
|
|
60633
|
+
signal: requestSignal
|
|
60634
|
+
});
|
|
60635
|
+
if (!response.ok) {
|
|
60636
|
+
const error48 = await buildMarketDataFetchError(response, "recent candles", "/candles/recent");
|
|
60637
|
+
trace.attachResponse({ status: response.status, statusText: response.statusText, url: response.url });
|
|
60638
|
+
trace.completeError(error48, response.status);
|
|
60639
|
+
console.error(`[API] ${error48.message} URL: ${response.url}`);
|
|
60640
|
+
throw error48;
|
|
60641
|
+
}
|
|
60642
|
+
trace.attachResponse({ status: response.status, statusText: response.statusText, url: response.url });
|
|
60643
|
+
const missing2 = parseCandlesMissing(response.headers.get(CANDLES_MISSING_HEADER));
|
|
60644
|
+
const payload = await response.json();
|
|
60645
|
+
trace.completeSuccess(response.status);
|
|
60646
|
+
return { candles: payload, missing: missing2 };
|
|
60647
|
+
} catch (error48) {
|
|
60648
|
+
if (response && !response.ok) throw error48;
|
|
60649
|
+
if (response && error48 instanceof CandlesMissingRangeError) {
|
|
60650
|
+
trace.completeError(error48, response.status);
|
|
60651
|
+
throw error48;
|
|
60652
|
+
}
|
|
60653
|
+
if (response && !isAbortLikeError(error48)) {
|
|
60654
|
+
const failure2 = buildMarketDataResponseBodyError(error48, "recent candles", response, "/candles/recent");
|
|
60655
|
+
trace.completeError(failure2, response.status);
|
|
60656
|
+
throw failure2;
|
|
60657
|
+
}
|
|
60658
|
+
trace.completeError(error48, response?.status ?? null);
|
|
60659
|
+
if (isAbortLikeError(error48)) throw error48;
|
|
60660
|
+
throw buildMarketDataNetworkError(error48, "recent candles", "/candles/recent");
|
|
60661
|
+
}
|
|
60662
|
+
}, { signal, shareAbortScoped: true });
|
|
60663
|
+
};
|
|
60595
60664
|
ExecutionAssetMetadataRequestError = class extends Error {
|
|
60596
60665
|
constructor(message, status, retryAfterMs, code = null) {
|
|
60597
60666
|
super(message);
|
|
@@ -61609,7 +61678,7 @@ var init_server_loop_account_value = __esm({
|
|
|
61609
61678
|
});
|
|
61610
61679
|
|
|
61611
61680
|
// lib/runtime/hyperliquid-account-contract.ts
|
|
61612
|
-
var toNumber2, firstNumber, roundTo, canonicalAvailableMargin, spotBalanceValueUsd, normalizeSpotBalancesFromInfoResponse, sumBalanceHoldUsd2, sumPositionUnrealizedPnl, resolveTotalUnrealizedPnl, approximatelyEqualAccountValues, accountValueThresholds, serverLoopValuation, serverLoopValuationCountsSpot, buildAccountSummaryFromInfoResponses;
|
|
61681
|
+
var toNumber2, firstNumber, roundTo, canonicalAvailableMargin, crossMarginRatio, spotBalanceValueUsd, normalizeSpotBalancesFromInfoResponse, sumBalanceHoldUsd2, sumPositionUnrealizedPnl, resolveTotalUnrealizedPnl, approximatelyEqualAccountValues, accountValueThresholds, serverLoopValuation, serverLoopValuationCountsSpot, buildAccountSummaryFromInfoResponses;
|
|
61613
61682
|
var init_hyperliquid_account_contract = __esm({
|
|
61614
61683
|
"lib/runtime/hyperliquid-account-contract.ts"() {
|
|
61615
61684
|
"use strict";
|
|
@@ -61638,6 +61707,7 @@ var init_hyperliquid_account_contract = __esm({
|
|
|
61638
61707
|
};
|
|
61639
61708
|
roundTo = (value, digits = HYPERLIQUID_ACCOUNT_ROUNDING_DECIMALS) => Number(value.toFixed(digits));
|
|
61640
61709
|
canonicalAvailableMargin = (accountValue, totalMarginUsed) => Math.max(0, accountValue - totalMarginUsed);
|
|
61710
|
+
crossMarginRatio = (maintenanceMargin, accountValue) => accountValue > 0 ? maintenanceMargin / accountValue : 0;
|
|
61641
61711
|
spotBalanceValueUsd = (balance, coin, total) => {
|
|
61642
61712
|
const explicit = firstNumber([balance?.value_usd, balance?.usdValue, balance?.usdcValue], Number.NaN);
|
|
61643
61713
|
if (Number.isFinite(explicit)) {
|
|
@@ -61764,7 +61834,7 @@ var init_hyperliquid_account_contract = __esm({
|
|
|
61764
61834
|
total_margin_used,
|
|
61765
61835
|
available_margin: roundTo(canonicalAvailableMargin(account_value, total_margin_used)),
|
|
61766
61836
|
withdrawable,
|
|
61767
|
-
cross_margin_ratio:
|
|
61837
|
+
cross_margin_ratio: crossMarginRatio(maintenance_margin, account_value),
|
|
61768
61838
|
maintenance_margin,
|
|
61769
61839
|
cross_account_leverage: account_value > 0 ? totalNtlPos / account_value : 0,
|
|
61770
61840
|
total_unrealized_pnl: resolveTotalUnrealizedPnl(perpsResponse),
|
|
@@ -94965,7 +95035,7 @@ var init_hyperliquid_signer = __esm({
|
|
|
94965
95035
|
});
|
|
94966
95036
|
|
|
94967
95037
|
// lib/runtime/hyperliquid-client.ts
|
|
94968
|
-
var HyperliquidExchangeRejectionError, durableMutationAuthorityArgs, assertFreshPreparedExecutionContext, normalizeSymbol, normalizeBotMarket, 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,
|
|
95038
|
+
var HyperliquidExchangeRejectionError, durableMutationAuthorityArgs, assertFreshPreparedExecutionContext, normalizeSymbol, normalizeBotMarket, 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, buildAssetInfosFromMetaResponse, requireWalletAddress, assertPositiveInteger, assertPositiveNumber, normalizeOrderSide, normalizeHyperliquidClientOrderId, resolveAssets, findResolvedAsset, normalizeExecutionAssetMetadata, readDeviceExecutionAssetMetadata, requireBotProfileId, executionAssetMetadataFor, resolveHyperliquidAsset, resolveHyperliquidAssetIndex, decimalUnits, quantizeHyperliquidOrderSizeValue, hyperliquidSignedSizeMatchesRequestedSize, finitePositive, readDevicePrivateExecutionContext, quantizeHyperliquidOrderSize, listBrowserMarketListDexes, browserMarketListMaxMarkets, cutBrowserMarketList, readBrowserPerpDexIndexes, readBrowserMarketListDex, fetchBrowserAvailableAssets, fetchBrowserAllMids, fetchBrowserSymbolMidPrice, fetchBrowserOpenOrders, parseCanonicalHyperliquidOrderStatusEvidence, fetchBrowserOrderStatusEvidence, fetchBrowserUserRole, fetchBrowserAccountState, fetchBrowserPosition, buildHyperliquidOrderWire, buildHyperliquidTriggerOrderWire, signHyperliquidPayload, signHyperliquidPreparedAction, buildHyperliquidCancelAction, buildHyperliquidCancelPayload, buildHyperliquidUpdateLeverageAction, buildHyperliquidUpdateLeveragePayload, buildHyperliquidMarketOrderAction, buildHyperliquidMarketOrderPayload, buildHyperliquidLimitOrderAction, buildHyperliquidLimitOrderPayload, buildHyperliquidTriggerOrderAction, buildHyperliquidTriggerOrderPayload, buildHyperliquidOrderBatchAction, buildHyperliquidOrderBatchPayload, buildHyperliquidModifyOrderAction, buildHyperliquidModifyOrderPayload, TRAILING_PCT_PATTERN, buildHyperliquidTrailingStopAction, buildHyperliquidTrailingStopPayload, extractHyperliquidExchangeError, acknowledgementLookupPacing, lookupUntilListed, resolveHyperliquidTriggerAcknowledgements, readHyperliquidTrailingStopAcknowledgement, resolveHyperliquidModifyAcknowledgement, isDefinitiveHyperliquidExchangeResponse, extractDefinitiveHyperliquidOrderId, CANONICAL_POSITIVE_DECIMAL_PATTERN, extractCanonicalHyperliquidOrderStateAcknowledgement, extractCanonicalHyperliquidOrderStateAcknowledgements, extractCanonicalHyperliquidFilledOrderAcknowledgement, extractDefinitiveHyperliquidOrderMemberResults, buildHyperliquidOrderDiagnostics, loadClientExecutionReferenceEvidence, sha256Hex, extractSignedPayloadClientOrderId, extractSignedPayloadMutationCorrelation, assertDurableMutationMatchesSignedAction, exchangeRejectionReason, exchangeActionPriority, submitHyperliquidExchangePayload;
|
|
94969
95039
|
var init_hyperliquid_client = __esm({
|
|
94970
95040
|
"lib/runtime/hyperliquid-client.ts"() {
|
|
94971
95041
|
"use strict";
|
|
@@ -95364,18 +95434,6 @@ var init_hyperliquid_client = __esm({
|
|
|
95364
95434
|
isCross: isExchangeIsolatedOnly(asset) ? false : isCross !== false
|
|
95365
95435
|
});
|
|
95366
95436
|
computeHip3AssetId = (perpDexIndex, indexInMeta) => HYPERLIQUID_EXCHANGE_SPECIFICATION.hip3_asset_id_base + Math.trunc(perpDexIndex) * HYPERLIQUID_EXCHANGE_SPECIFICATION.hip3_asset_id_dex_stride + Math.trunc(indexInMeta);
|
|
95367
|
-
getPerpDexIndexMap = (payload) => {
|
|
95368
|
-
if (!Array.isArray(payload)) {
|
|
95369
|
-
throw new Error("Malformed Hyperliquid perp DEX response.");
|
|
95370
|
-
}
|
|
95371
|
-
const indexes = /* @__PURE__ */ new Map();
|
|
95372
|
-
payload.forEach((raw, index) => {
|
|
95373
|
-
if (!raw || typeof raw !== "object" || Array.isArray(raw)) return;
|
|
95374
|
-
const name = String(raw.name || "").trim().toLowerCase();
|
|
95375
|
-
if (name) indexes.set(name, index);
|
|
95376
|
-
});
|
|
95377
|
-
return indexes;
|
|
95378
|
-
};
|
|
95379
95437
|
buildAssetInfosFromMetaResponse = (payload, options) => {
|
|
95380
95438
|
if (!Array.isArray(payload) || payload.length < HYPERLIQUID_META_AND_ASSET_CTXS_PARTS) {
|
|
95381
95439
|
throw new Error("Malformed Hyperliquid asset metadata response.");
|
|
@@ -95425,7 +95483,9 @@ var init_hyperliquid_client = __esm({
|
|
|
95425
95483
|
change_24h: prevDayPx > 0 ? (markPx - prevDayPx) / prevDayPx : 0,
|
|
95426
95484
|
funding_8h: toFiniteNumber(ctx.funding, 0),
|
|
95427
95485
|
volume_24h: volume,
|
|
95428
|
-
open_interest: toFiniteNumber(ctx.openInterest, 0)
|
|
95486
|
+
open_interest: toFiniteNumber(ctx.openInterest, 0),
|
|
95487
|
+
// As the server's catalog marks it: a delisted market is never a candidate.
|
|
95488
|
+
is_delisted: asset.isDelisted === true
|
|
95429
95489
|
});
|
|
95430
95490
|
if (options.maxMarkets !== null && assets.length >= options.maxMarkets) {
|
|
95431
95491
|
break;
|
|
@@ -95750,7 +95810,7 @@ var init_hyperliquid_client = __esm({
|
|
|
95750
95810
|
return Number.isInteger(maxMarketsTotal) && Number(maxMarketsTotal) > 0 ? Number(maxMarketsTotal) : null;
|
|
95751
95811
|
};
|
|
95752
95812
|
cutBrowserMarketList = (assets, config2) => [...assets].sort((a, b3) => toFiniteNumber(b3.volume_24h, 0) - toFiniteNumber(a.volume_24h, 0)).slice(0, browserMarketListMaxMarkets(config2) ?? assets.length);
|
|
95753
|
-
readBrowserPerpDexIndexes = async (input) =>
|
|
95813
|
+
readBrowserPerpDexIndexes = async (input) => perpDexIndexes(await postHyperliquidInfo(input, { type: "perpDexs" }, "hyperliquid.perpDexs"));
|
|
95754
95814
|
readBrowserMarketListDex = async (input, dex, perpDexIndex) => {
|
|
95755
95815
|
let payload;
|
|
95756
95816
|
try {
|
|
@@ -96156,7 +96216,7 @@ var init_hyperliquid_client = __esm({
|
|
|
96156
96216
|
total_margin_used: totalMarginUsed,
|
|
96157
96217
|
available_margin: canonicalAvailableMargin(accountValue, totalMarginUsed),
|
|
96158
96218
|
withdrawable,
|
|
96159
|
-
cross_margin_ratio:
|
|
96219
|
+
cross_margin_ratio: crossMarginRatio(maintenanceMargin, accountValue),
|
|
96160
96220
|
maintenance_margin: maintenanceMargin,
|
|
96161
96221
|
cross_account_leverage: accountValue > 0 ? totalNtlPos / accountValue : 0,
|
|
96162
96222
|
total_unrealized_pnl: positions.reduce((total, position) => total + toFiniteNumber(position.unrealized_pnl, 0), 0),
|
|
@@ -99077,7 +99137,7 @@ async function getClientRuntimeStatuses(profileIds, signal, options) {
|
|
|
99077
99137
|
ttlMs: viewer.requestKey ? 0 : CLIENT_RUNTIME_STATUSES_DEDUPE_TTL_MS
|
|
99078
99138
|
});
|
|
99079
99139
|
}
|
|
99080
|
-
var clientRuntimeSecretHeaders, preferencesWriteQueue, getCopyTradingRuntimeLeaseToken, getCopyTradingSchedulerInstanceId, AI_TRADE_HISTORY_BY_ORDER_IDS_MAX_BATCH, AI_TRADE_HISTORY_BY_ORDER_IDS_MAX_CONCURRENCY, resolveClientRuntimeStatusViewerHeaders, CLIENT_SUPPORTED_PROMPT_CONTRACT_VERSION, completedDeferredClientRuntimeStops, rememberCompletedDeferredClientRuntimeStop, consumeCompletedDeferredClientRuntimeStop, toNumericProfileId, buildClientRuntimeBody, shouldAttachRuntimeIdempotencyKey, attachRuntimeLeaseHeader, attachRuntimeSchedulerInstanceHeader, resolveRuntimeLeaseToken, resolveSchedulerBoundRuntimeLeaseToken, persistRuntimeLeaseFromPayload, persistRuntimeLeaseStatusMetadata, shouldClearPersistedRuntimeLeaseOnError, createRuntimeRequestError, parseClientRuntimeRequestContext, recordRuntimeAuthFailureBreadcrumb, classifyRuntimeRequestError, annotateRuntimeRequestError, CLIENT_RUNTIME_RETRYABLE_STATUSES, isRetryableClientRuntimeStatus, shouldRetryClientRuntimeHttpStatus, isRuntimeIdempotencyInProgressError, isRetryableRuntimeConflictError, resolveClientRuntimeRetryDelayMs, reconcilePendingClientExchangeMutation, CLIENT_RUNTIME_CLAIM_EXCHANGE_MUTATION_WAIT_CODES, resolveClientExchangeMutationAuthority, pinClientExchangeMutationAuthority, CLIENT_EXCHANGE_MUTATION_AUTHORITY_MISMATCH, isClientExchangeMutationAuthorityConflict, handOffClientExchangeMutationToReconciliation, clientExchangeMutationAuthorityBody, isPendingClientExchangeMutationError, isMissingActiveClientExchangeMutationError, clientExchangeMutationReconciliationTimers, ClientExchangeMutationRebuildRequiredError, isTerminalClientExchangeMutation, clientExchangeMutationReconciliationKey, clearScheduledClientExchangeMutationReconciliation, snapshotClientExchangeMutationReconciliationAuthority, completeClientExchangeMutationReconciliation, protectiveBoundClientExchangeMutations, rememberProtectiveBoundClientExchangeMutation, isProtectiveBoundClientExchangeMutation, postClientExchangeMutationReconciliation, scheduleClientExchangeMutationReconciliation, postClientDeviceReport, reportClientTradeMarketRead;
|
|
99140
|
+
var clientRuntimeSecretHeaders, preferencesWriteQueue, getCopyTradingRuntimeLeaseToken, getCopyTradingSchedulerInstanceId, AI_TRADE_HISTORY_BY_ORDER_IDS_MAX_BATCH, AI_TRADE_HISTORY_BY_ORDER_IDS_MAX_CONCURRENCY, resolveClientRuntimeStatusViewerHeaders, CLIENT_SUPPORTED_PROMPT_CONTRACT_VERSION, completedDeferredClientRuntimeStops, rememberCompletedDeferredClientRuntimeStop, consumeCompletedDeferredClientRuntimeStop, toNumericProfileId, buildClientRuntimeBody, shouldAttachRuntimeIdempotencyKey, attachRuntimeLeaseHeader, attachRuntimeSchedulerInstanceHeader, resolveRuntimeLeaseToken, resolveSchedulerBoundRuntimeLeaseToken, persistRuntimeLeaseFromPayload, persistRuntimeLeaseStatusMetadata, shouldClearPersistedRuntimeLeaseOnError, readRetryableRuntimeRefusalDelayMs, createRuntimeRequestError, parseClientRuntimeRequestContext, recordRuntimeAuthFailureBreadcrumb, classifyRuntimeRequestError, annotateRuntimeRequestError, CLIENT_RUNTIME_RETRYABLE_STATUSES, isRetryableClientRuntimeStatus, shouldRetryClientRuntimeHttpStatus, isRuntimeIdempotencyInProgressError, isRetryableRuntimeConflictError, resolveClientRuntimeRetryDelayMs, reconcilePendingClientExchangeMutation, CLIENT_RUNTIME_CLAIM_EXCHANGE_MUTATION_WAIT_CODES, resolveClientExchangeMutationAuthority, pinClientExchangeMutationAuthority, CLIENT_EXCHANGE_MUTATION_AUTHORITY_MISMATCH, isClientExchangeMutationAuthorityConflict, handOffClientExchangeMutationToReconciliation, clientExchangeMutationAuthorityBody, isPendingClientExchangeMutationError, isMissingActiveClientExchangeMutationError, clientExchangeMutationReconciliationTimers, ClientExchangeMutationRebuildRequiredError, isTerminalClientExchangeMutation, clientExchangeMutationReconciliationKey, clearScheduledClientExchangeMutationReconciliation, snapshotClientExchangeMutationReconciliationAuthority, completeClientExchangeMutationReconciliation, protectiveBoundClientExchangeMutations, rememberProtectiveBoundClientExchangeMutation, isProtectiveBoundClientExchangeMutation, postClientExchangeMutationReconciliation, scheduleClientExchangeMutationReconciliation, postClientDeviceReport, reportClientTradeMarketRead;
|
|
99081
99141
|
var init_api2 = __esm({
|
|
99082
99142
|
"lib/api.ts"() {
|
|
99083
99143
|
"use strict";
|
|
@@ -99310,6 +99370,17 @@ var init_api2 = __esm({
|
|
|
99310
99370
|
}
|
|
99311
99371
|
return clientRuntimeLeaseEndedFromCode(error48, statusCode) === true;
|
|
99312
99372
|
};
|
|
99373
|
+
readRetryableRuntimeRefusalDelayMs = (error48) => {
|
|
99374
|
+
const typed = error48;
|
|
99375
|
+
if (!typed || typed.retryable !== true || typed.status !== HTTP_STATUS.CONFLICT) return null;
|
|
99376
|
+
if (typeof typed.retryAfterMs === "number" && Number.isFinite(typed.retryAfterMs)) {
|
|
99377
|
+
return Math.max(0, typed.retryAfterMs);
|
|
99378
|
+
}
|
|
99379
|
+
if (typeof typed.retryAfterSeconds === "number" && Number.isFinite(typed.retryAfterSeconds)) {
|
|
99380
|
+
return Math.max(0, typed.retryAfterSeconds * MS_PER_SECOND);
|
|
99381
|
+
}
|
|
99382
|
+
return null;
|
|
99383
|
+
};
|
|
99313
99384
|
createRuntimeRequestError = async (response, defaultMessage) => {
|
|
99314
99385
|
const payload = await getErrorPayloadOrEmpty(response);
|
|
99315
99386
|
const nestedDetail = payload.detail && typeof payload.detail === "object" && !Array.isArray(payload.detail) ? payload.detail : null;
|
|
@@ -100734,7 +100805,7 @@ var init_vault = __esm({
|
|
|
100734
100805
|
});
|
|
100735
100806
|
|
|
100736
100807
|
// lib/runtime/browser-trading.ts
|
|
100737
|
-
var protectiveWriteRecorder, ProtectiveWriteRecordedError, recordInsteadOfSending, resolveProfileId, requirePositiveNumber, assertFreshPreparedContext,
|
|
100808
|
+
var protectiveWriteRecorder, ProtectiveWriteRecordedError, recordInsteadOfSending, resolveProfileId, requirePositiveNumber, assertFreshPreparedContext, throwIfAborted2, UUID_PATTERN2, createExchangeMutationIdentity, requireClientExchangeExpiresAfterSeconds, loadSigningKey, priorityOf, resolveSigningKey, requireWalletAddress2, resolveEstimatedPrice, executeClientLeverageUpdate, executeClientMarketOrder, resolveClientProtectiveSigningKey, executeClientPreparedProtectiveAction, executeClientLimitOrder, executeClientTriggerOrder, executeClientOrderBatch, executeClientModifyOrder, executeClientCancelOrder, executeClientTrailingStop, executeClientClosePosition;
|
|
100738
100809
|
var init_browser_trading = __esm({
|
|
100739
100810
|
"lib/runtime/browser-trading.ts"() {
|
|
100740
100811
|
"use strict";
|
|
@@ -100782,7 +100853,7 @@ var init_browser_trading = __esm({
|
|
|
100782
100853
|
throw new Error("Copy Trading private execution context expired before signing.");
|
|
100783
100854
|
}
|
|
100784
100855
|
};
|
|
100785
|
-
|
|
100856
|
+
throwIfAborted2 = (signal) => {
|
|
100786
100857
|
if (signal?.aborted) {
|
|
100787
100858
|
throw new DOMException("The operation was aborted.", "AbortError");
|
|
100788
100859
|
}
|
|
@@ -100896,9 +100967,9 @@ var init_browser_trading = __esm({
|
|
|
100896
100967
|
};
|
|
100897
100968
|
executeClientLeverageUpdate = async (input) => {
|
|
100898
100969
|
input = { ...input, publicRequestPriority: "trading_execute" };
|
|
100899
|
-
|
|
100970
|
+
throwIfAborted2(input.signal);
|
|
100900
100971
|
const signingKey = await resolveSigningKey(input);
|
|
100901
|
-
|
|
100972
|
+
throwIfAborted2(input.signal);
|
|
100902
100973
|
const mutation = createExchangeMutationIdentity(false, input);
|
|
100903
100974
|
const payload = await buildHyperliquidUpdateLeveragePayload({
|
|
100904
100975
|
config: input.config ?? null,
|
|
@@ -100933,11 +101004,11 @@ var init_browser_trading = __esm({
|
|
|
100933
101004
|
if ((input.positionChildren?.length ?? 0) > 0 && input.protection && !input.protection.native) {
|
|
100934
101005
|
throw new Error("An entry carries either native position children or server-owned protection, not both.");
|
|
100935
101006
|
}
|
|
100936
|
-
|
|
101007
|
+
throwIfAborted2(input.signal);
|
|
100937
101008
|
const signingKey = await resolveSigningKey(input);
|
|
100938
|
-
|
|
101009
|
+
throwIfAborted2(input.signal);
|
|
100939
101010
|
const estimatedPrice = await resolveEstimatedPrice(input.config, input.symbol, input.estimatedPrice, input.signal, input.publicRequestPriority);
|
|
100940
|
-
|
|
101011
|
+
throwIfAborted2(input.signal);
|
|
100941
101012
|
assertFreshPreparedContext(input.preparedContext);
|
|
100942
101013
|
const mutation = createExchangeMutationIdentity(true, input);
|
|
100943
101014
|
const payload = await buildHyperliquidMarketOrderPayload({
|
|
@@ -100985,9 +101056,9 @@ var init_browser_trading = __esm({
|
|
|
100985
101056
|
resolveClientProtectiveSigningKey = (input) => resolveSigningKey({ ...input, publicRequestPriority: "trading_reduce" });
|
|
100986
101057
|
executeClientPreparedProtectiveAction = async (input) => {
|
|
100987
101058
|
input = { ...input, publicRequestPriority: "trading_reduce" };
|
|
100988
|
-
|
|
101059
|
+
throwIfAborted2(input.signal);
|
|
100989
101060
|
const signingKey = await resolveSigningKey(input);
|
|
100990
|
-
|
|
101061
|
+
throwIfAborted2(input.signal);
|
|
100991
101062
|
const payload = await signHyperliquidPreparedAction({
|
|
100992
101063
|
config: input.config ?? null,
|
|
100993
101064
|
publicRequestPriority: priorityOf(input),
|
|
@@ -101019,9 +101090,9 @@ var init_browser_trading = __esm({
|
|
|
101019
101090
|
};
|
|
101020
101091
|
executeClientLimitOrder = async (input) => {
|
|
101021
101092
|
input = { ...input, publicRequestPriority: input.reduceOnly === true ? "trading_reduce" : "trading_execute" };
|
|
101022
|
-
|
|
101093
|
+
throwIfAborted2(input.signal);
|
|
101023
101094
|
const signingKey = await resolveSigningKey(input);
|
|
101024
|
-
|
|
101095
|
+
throwIfAborted2(input.signal);
|
|
101025
101096
|
const mutation = createExchangeMutationIdentity(true, input);
|
|
101026
101097
|
const payload = await buildHyperliquidLimitOrderPayload({
|
|
101027
101098
|
config: input.config ?? null,
|
|
@@ -101066,9 +101137,9 @@ var init_browser_trading = __esm({
|
|
|
101066
101137
|
triggerPrice: input.triggerPrice,
|
|
101067
101138
|
isTakeProfit: input.isTakeProfit
|
|
101068
101139
|
});
|
|
101069
|
-
|
|
101140
|
+
throwIfAborted2(input.signal);
|
|
101070
101141
|
const signingKey = await resolveSigningKey(input);
|
|
101071
|
-
|
|
101142
|
+
throwIfAborted2(input.signal);
|
|
101072
101143
|
const mutation = createExchangeMutationIdentity(true, input);
|
|
101073
101144
|
const payload = await buildHyperliquidTriggerOrderPayload({
|
|
101074
101145
|
config: input.config ?? null,
|
|
@@ -101119,9 +101190,9 @@ var init_browser_trading = __esm({
|
|
|
101119
101190
|
positionOrder: member.positionOrder === true
|
|
101120
101191
|
}))
|
|
101121
101192
|
});
|
|
101122
|
-
|
|
101193
|
+
throwIfAborted2(input.signal);
|
|
101123
101194
|
const signingKey = await resolveSigningKey(input);
|
|
101124
|
-
|
|
101195
|
+
throwIfAborted2(input.signal);
|
|
101125
101196
|
const mutation = createExchangeMutationIdentity(true, input);
|
|
101126
101197
|
const payload = await buildHyperliquidOrderBatchPayload({
|
|
101127
101198
|
config: input.config ?? null,
|
|
@@ -101164,9 +101235,9 @@ var init_browser_trading = __esm({
|
|
|
101164
101235
|
size: input.size,
|
|
101165
101236
|
triggerPrice: input.triggerPrice
|
|
101166
101237
|
});
|
|
101167
|
-
|
|
101238
|
+
throwIfAborted2(input.signal);
|
|
101168
101239
|
const signingKey = await resolveSigningKey(input);
|
|
101169
|
-
|
|
101240
|
+
throwIfAborted2(input.signal);
|
|
101170
101241
|
const mutation = createExchangeMutationIdentity(true, input);
|
|
101171
101242
|
const payload = await buildHyperliquidModifyOrderPayload({
|
|
101172
101243
|
config: input.config ?? null,
|
|
@@ -101213,9 +101284,9 @@ var init_browser_trading = __esm({
|
|
|
101213
101284
|
executeClientCancelOrder = async (input) => {
|
|
101214
101285
|
input = { ...input, publicRequestPriority: input.publicRequestPriority ?? "trading_execute" };
|
|
101215
101286
|
recordInsteadOfSending({ kind: "cancel", symbol: input.symbol, orderId: input.orderId });
|
|
101216
|
-
|
|
101287
|
+
throwIfAborted2(input.signal);
|
|
101217
101288
|
const signingKey = await resolveSigningKey(input);
|
|
101218
|
-
|
|
101289
|
+
throwIfAborted2(input.signal);
|
|
101219
101290
|
const mutation = createExchangeMutationIdentity(false, input);
|
|
101220
101291
|
const payload = await buildHyperliquidCancelPayload({
|
|
101221
101292
|
config: input.config ?? null,
|
|
@@ -101254,9 +101325,9 @@ var init_browser_trading = __esm({
|
|
|
101254
101325
|
size: input.size,
|
|
101255
101326
|
retracement: input.retracement
|
|
101256
101327
|
});
|
|
101257
|
-
|
|
101328
|
+
throwIfAborted2(input.signal);
|
|
101258
101329
|
const signingKey = await resolveSigningKey(input);
|
|
101259
|
-
|
|
101330
|
+
throwIfAborted2(input.signal);
|
|
101260
101331
|
const mutation = createExchangeMutationIdentity(false, input);
|
|
101261
101332
|
const payload = await buildHyperliquidTrailingStopPayload({
|
|
101262
101333
|
config: input.config ?? null,
|
|
@@ -101290,7 +101361,7 @@ var init_browser_trading = __esm({
|
|
|
101290
101361
|
};
|
|
101291
101362
|
executeClientClosePosition = async (input) => {
|
|
101292
101363
|
input = { ...input, publicRequestPriority: "trading_reduce" };
|
|
101293
|
-
|
|
101364
|
+
throwIfAborted2(input.signal);
|
|
101294
101365
|
const profileId = resolveProfileId(input.profileId);
|
|
101295
101366
|
const currentPosition = input.position ?? await fetchBrowserPosition({
|
|
101296
101367
|
config: input.config ?? null,
|
|
@@ -101490,7 +101561,7 @@ var init_server_prompt_rescue_account_contract = __esm({
|
|
|
101490
101561
|
total_margin_used: totalMarginUsed,
|
|
101491
101562
|
available_margin: availableMargin,
|
|
101492
101563
|
withdrawable,
|
|
101493
|
-
cross_margin_ratio:
|
|
101564
|
+
cross_margin_ratio: crossMarginRatio(maintenanceMargin, accountValue),
|
|
101494
101565
|
maintenance_margin: maintenanceMargin,
|
|
101495
101566
|
cross_account_leverage: accountValue > 0 ? totalNotional / accountValue : 0,
|
|
101496
101567
|
total_unrealized_pnl: totalUnrealizedPnl,
|
|
@@ -102127,7 +102198,7 @@ var init_hyperliquid_account_state_adapter = __esm({
|
|
|
102127
102198
|
}
|
|
102128
102199
|
const position = entry.position && typeof entry.position === "object" ? { ...entry.position } : entry.position;
|
|
102129
102200
|
const rawCoin = String(entry.coin || position?.coin || "").trim();
|
|
102130
|
-
const normalizedCoin = rawCoin.includes(":") ?
|
|
102201
|
+
const normalizedCoin = normalizeHyperliquidMarketSymbol(rawCoin.includes(":") ? rawCoin : `${dex}:${rawCoin}`);
|
|
102131
102202
|
return {
|
|
102132
102203
|
...entry,
|
|
102133
102204
|
coin: normalizedCoin,
|
|
@@ -105499,7 +105570,7 @@ var init_native_position_protection = __esm({
|
|
|
105499
105570
|
});
|
|
105500
105571
|
|
|
105501
105572
|
// lib/runtime/native-protection-device.ts
|
|
105502
|
-
var NATIVE_PROTECTION_RECORD_VERSION, nativeProtectionStorage, resolveStorage, setNativeProtectionStorage, recordKey, isMember, isRetracement, isLot, isStandbyAdd, readNativeProtectionRecord, versioned, writeNativeProtectionRecord, NO_FILLS, nativeFillsPageFromUserFills, fillsReader, flatReadOf, orderFillTimes, namedOrderId, NativeOrderNotSentError, withDispatchBoundary, attempt, notSentRestores, errorText, actionOf, isOpenInDirection2, coverRows, restingOrderIdAt, definitivelyRefused, TRAILING_LOT_FIRED, TRAILING_LOT_POSITION_ENDED, TRAILING_LOT_OTHER_SIDE, lotFillLeftPosition, lotOfAdd, ORDER_ID_PATTERN, lotFillOrderId, lotPositionSince, ownLotOrderIds, lotRetracement, lotReport, sendTrailingLot, planNativeFillLot, planNativeStandbyAdd, nameNativeStandbyAdd, dropNativeStandbyAdd, dropNativePendingLot, planNativePendingLot, planNativeOpen, recordEntryChildren, observeMembers, UNKNOWN_ORDER_RESPONSE, resolveUnknownOrderIds, plannedPair, resolveStandbyAdds, settleNativeProtectionAfterFill, reconcileNativeProtection;
|
|
105573
|
+
var NATIVE_PROTECTION_RECORD_VERSION, owesMove, owingMove, moveMade, nativeProtectionStorage, resolveStorage, setNativeProtectionStorage, recordKey, isMember, isRetracement, isLot, isStandbyAdd, readNativeProtectionRecord, versioned, writeNativeProtectionRecord, NO_FILLS, nativeFillsPageFromUserFills, fillsReader, flatReadOf, orderFillTimes, namedOrderId, NativeOrderNotSentError, withDispatchBoundary, attempt, notSentRestores, errorText, actionOf, isOpenInDirection2, coverRows, restingOrderIdAt, definitivelyRefused, TRAILING_LOT_FIRED, TRAILING_LOT_POSITION_ENDED, TRAILING_LOT_OTHER_SIDE, lotFillLeftPosition, lotOfAdd, ORDER_ID_PATTERN, lotFillOrderId, lotPositionSince, ownLotOrderIds, lotRetracement, lotReport, sendTrailingLot, planNativeFillLot, planNativeStandbyAdd, nameNativeStandbyAdd, dropNativeStandbyAdd, dropNativePendingLot, planNativePendingLot, planNativeOpen, recordEntryChildren, observeMembers, UNKNOWN_ORDER_RESPONSE, resolveUnknownOrderIds, cancellingThroughVtx, moveMember, plannedPair, resolveStandbyAdds, settleNativeProtectionAfterFill, reconcileNativeProtection;
|
|
105503
105574
|
var init_native_protection_device = __esm({
|
|
105504
105575
|
"lib/runtime/native-protection-device.ts"() {
|
|
105505
105576
|
"use strict";
|
|
@@ -105513,6 +105584,20 @@ var init_native_protection_device = __esm({
|
|
|
105513
105584
|
init_order_identity();
|
|
105514
105585
|
init_native_position_protection();
|
|
105515
105586
|
NATIVE_PROTECTION_RECORD_VERSION = 1;
|
|
105587
|
+
owesMove = (member) => member.pendingMove != null && (member.pendingMove.clientOrderId === member.clientOrderId || member.pendingMove.pendingClientOrderId != null && member.pendingMove.pendingClientOrderId === member.clientOrderId);
|
|
105588
|
+
owingMove = (member, afterMs) => ({
|
|
105589
|
+
...member,
|
|
105590
|
+
pendingMove: {
|
|
105591
|
+
afterMs: Math.max(owesMove(member) ? member.pendingMove?.afterMs ?? 0 : 0, afterMs),
|
|
105592
|
+
clientOrderId: member.clientOrderId,
|
|
105593
|
+
// A modify journaled before this fill still owes this move once it is named.
|
|
105594
|
+
...member.pendingModify ? { pendingClientOrderId: member.pendingModify.clientOrderId } : {}
|
|
105595
|
+
}
|
|
105596
|
+
});
|
|
105597
|
+
moveMade = (member) => {
|
|
105598
|
+
const { pendingMove: _made, ...rest } = member;
|
|
105599
|
+
return rest;
|
|
105600
|
+
};
|
|
105516
105601
|
nativeProtectionStorage = null;
|
|
105517
105602
|
resolveStorage = () => {
|
|
105518
105603
|
if (nativeProtectionStorage) return nativeProtectionStorage;
|
|
@@ -105530,7 +105615,7 @@ var init_native_protection_device = __esm({
|
|
|
105530
105615
|
isMember = (value) => {
|
|
105531
105616
|
if (!value || typeof value !== "object") return false;
|
|
105532
105617
|
const member = value;
|
|
105533
|
-
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.plannedAfterMs === void 0 || typeof member.plannedAfterMs === "number") && (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");
|
|
105618
|
+
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.plannedAfterMs === void 0 || typeof member.plannedAfterMs === "number") && (member.pendingMove === void 0 || typeof member.pendingMove === "object" && member.pendingMove !== null && Number.isFinite(member.pendingMove.afterMs) && typeof member.pendingMove.clientOrderId === "string" && (member.pendingMove.pendingClientOrderId === void 0 || typeof member.pendingMove.pendingClientOrderId === "string")) && (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");
|
|
105534
105619
|
};
|
|
105535
105620
|
isRetracement = (value) => {
|
|
105536
105621
|
if (!value || typeof value !== "object") return false;
|
|
@@ -105887,11 +105972,11 @@ var init_native_protection_device = __esm({
|
|
|
105887
105972
|
recordEntryChildren = (record6, entryResponse) => ({
|
|
105888
105973
|
...record6,
|
|
105889
105974
|
phase: "active",
|
|
105890
|
-
members: record6.members.map((member, index) => ({
|
|
105975
|
+
members: record6.members.map((member, index) => owingMove({
|
|
105891
105976
|
...member,
|
|
105892
105977
|
// The entry is member 0 of the action; its children follow in order.
|
|
105893
105978
|
orderId: member.orderId ?? restingOrderIdAt(entryResponse, index + 1)
|
|
105894
|
-
}))
|
|
105979
|
+
}, 0))
|
|
105895
105980
|
});
|
|
105896
105981
|
observeMembers = (record6, page) => record6.members.map((member) => ({
|
|
105897
105982
|
member,
|
|
@@ -105936,6 +106021,82 @@ var init_native_protection_device = __esm({
|
|
|
105936
106021
|
}
|
|
105937
106022
|
return { ...record6, members };
|
|
105938
106023
|
};
|
|
106024
|
+
cancellingThroughVtx = async (io, orderId) => {
|
|
106025
|
+
if (!io.userCancelledOrder) return false;
|
|
106026
|
+
try {
|
|
106027
|
+
return await io.userCancelledOrder(orderId);
|
|
106028
|
+
} catch (error48) {
|
|
106029
|
+
if (io.endsPass?.(error48)) throw error48;
|
|
106030
|
+
return true;
|
|
106031
|
+
}
|
|
106032
|
+
};
|
|
106033
|
+
moveMember = async (args) => {
|
|
106034
|
+
const { io, symbol: symbol2, member, orderId, trigger, clientOrderId } = args;
|
|
106035
|
+
const action = actionOf(member.kind);
|
|
106036
|
+
const sentAtMs = io.nowMs();
|
|
106037
|
+
const journaled = { ...member, orderId, pendingModify: { clientOrderId, trigger, sentAtMs } };
|
|
106038
|
+
if (!args.journal(journaled)) {
|
|
106039
|
+
return {
|
|
106040
|
+
member,
|
|
106041
|
+
landed: false,
|
|
106042
|
+
report: {
|
|
106043
|
+
order_id: String(orderId),
|
|
106044
|
+
symbol: symbol2,
|
|
106045
|
+
action,
|
|
106046
|
+
status: "failed",
|
|
106047
|
+
execution_metadata: { reason_code: "protective_lifecycle_persistence_failed", trigger_price: trigger }
|
|
106048
|
+
}
|
|
106049
|
+
};
|
|
106050
|
+
}
|
|
106051
|
+
const outcome = await notSentRestores(
|
|
106052
|
+
() => attempt(io, () => io.modifyPositionOrder({
|
|
106053
|
+
orderId,
|
|
106054
|
+
kind: member.kind,
|
|
106055
|
+
triggerPrice: Number(trigger),
|
|
106056
|
+
clientOrderId
|
|
106057
|
+
})),
|
|
106058
|
+
() => args.journal(member)
|
|
106059
|
+
);
|
|
106060
|
+
if (!outcome.ok && outcome.refused) {
|
|
106061
|
+
if (outcome.error instanceof NativeOrderNotSentError) args.journal(member);
|
|
106062
|
+
return {
|
|
106063
|
+
member: { ...member, orderId },
|
|
106064
|
+
landed: false,
|
|
106065
|
+
report: {
|
|
106066
|
+
order_id: String(orderId),
|
|
106067
|
+
symbol: symbol2,
|
|
106068
|
+
action,
|
|
106069
|
+
status: "failed",
|
|
106070
|
+
execution_metadata: {
|
|
106071
|
+
reason_code: outcome.error instanceof NativeOrderNotSentError ? "protective_modify_not_sent" : "protective_modify_rejected",
|
|
106072
|
+
trigger_price: trigger,
|
|
106073
|
+
error: errorText(outcome.error)
|
|
106074
|
+
}
|
|
106075
|
+
}
|
|
106076
|
+
};
|
|
106077
|
+
}
|
|
106078
|
+
const newOrderId = outcome.ok ? restingOrderIdAt(outcome.response, 0) : null;
|
|
106079
|
+
const { pendingModify: _applied, pendingMove: _moved, ...rest } = journaled;
|
|
106080
|
+
return {
|
|
106081
|
+
// Otherwise the journal stays: reconciliation names the new order or
|
|
106082
|
+
// proves it never landed.
|
|
106083
|
+
member: newOrderId != null ? { ...rest, clientOrderId, orderId: newOrderId, trigger, placedAtMs: null, sentAtMs } : journaled,
|
|
106084
|
+
landed: newOrderId != null,
|
|
106085
|
+
report: {
|
|
106086
|
+
order_id: String(newOrderId ?? orderId),
|
|
106087
|
+
symbol: symbol2,
|
|
106088
|
+
action,
|
|
106089
|
+
status: newOrderId != null ? "executed" : "failed",
|
|
106090
|
+
execution_metadata: {
|
|
106091
|
+
reason_code: newOrderId != null ? "protective_native_moved_to_position_entry" : "protective_modify_outcome_unknown",
|
|
106092
|
+
trigger_price: trigger,
|
|
106093
|
+
position_tpsl: true,
|
|
106094
|
+
protected_size: args.protectedSize,
|
|
106095
|
+
...newOrderId != null ? { replaced_order_id: String(orderId) } : {}
|
|
106096
|
+
}
|
|
106097
|
+
}
|
|
106098
|
+
};
|
|
106099
|
+
};
|
|
105939
106100
|
plannedPair = (settings, afterMs, io) => ["sl", "tp"].filter((kind) => (kind === "sl" ? settings.stopLoss : settings.takeProfit) != null).map((kind) => ({
|
|
105940
106101
|
kind,
|
|
105941
106102
|
clientOrderId: clientOrderIdForMutation(io.newMutationId()),
|
|
@@ -106051,6 +106212,13 @@ var init_native_protection_device = __esm({
|
|
|
106051
106212
|
const settlingAdds = (record6.standby ?? []).length > 0;
|
|
106052
106213
|
const boundary = await resolveStandbyAdds({ record: record6, settings: input.settings, io, fills, position, page });
|
|
106053
106214
|
record6 = boundary.record;
|
|
106215
|
+
if (record6.phase === "entry_pending" || boundary.addFillMs != null) {
|
|
106216
|
+
const afterMs = boundary.addFillMs ?? 0;
|
|
106217
|
+
record6 = {
|
|
106218
|
+
...record6,
|
|
106219
|
+
members: record6.members.map((member) => member.retiredReason || member.userCancelledOrderId != null || member.plannedAfterMs != null ? member : owingMove(member, afterMs))
|
|
106220
|
+
};
|
|
106221
|
+
}
|
|
106054
106222
|
if (boundary.undecided) {
|
|
106055
106223
|
return { record: record6, reports };
|
|
106056
106224
|
}
|
|
@@ -106058,6 +106226,29 @@ var init_native_protection_device = __esm({
|
|
|
106058
106226
|
if (record6.positionOrderId == null && boundary.addFillMs == null && !settlingAdds && ORDER_ID_PATTERN.test(entryOrderId)) {
|
|
106059
106227
|
record6 = { ...record6, positionOrderId: entryOrderId };
|
|
106060
106228
|
}
|
|
106229
|
+
const observations = observeMembers(record6, page);
|
|
106230
|
+
const restingTrigger = (kind) => {
|
|
106231
|
+
const observed = observations.find((entry) => entry.member.kind === kind);
|
|
106232
|
+
return observed?.row?.trigger_px != null ? String(observed.row.trigger_px) : null;
|
|
106233
|
+
};
|
|
106234
|
+
let eventMs = Math.max(
|
|
106235
|
+
0,
|
|
106236
|
+
...observations.map((entry) => entry.row?.timestamp ?? entry.member.placedAtMs ?? 0),
|
|
106237
|
+
// An add's own fill, the fill each member's move answers, and the fill a
|
|
106238
|
+
// planned pair answers: Hyperliquid's times.
|
|
106239
|
+
boundary.addFillMs ?? 0,
|
|
106240
|
+
...record6.members.map((member) => Math.max(owesMove(member) ? member.pendingMove?.afterMs ?? 0 : 0, member.plannedAfterMs ?? 0))
|
|
106241
|
+
);
|
|
106242
|
+
if (eventMs <= 0 && input.entryOrderId) {
|
|
106243
|
+
const entryStatus = await io.readOrderStatus(input.entryOrderId);
|
|
106244
|
+
eventMs = entryStatus.statusTimestampMs ?? 0;
|
|
106245
|
+
}
|
|
106246
|
+
const gate = nativePlacementGate({
|
|
106247
|
+
eventMs,
|
|
106248
|
+
position: position.size,
|
|
106249
|
+
positionStateMs: position.stateTimeMs ?? Number.NEGATIVE_INFINITY,
|
|
106250
|
+
isLong: record6.isLong
|
|
106251
|
+
});
|
|
106061
106252
|
if (!isOpenInDirection2(position.size, record6.isLong)) {
|
|
106062
106253
|
reports.push({
|
|
106063
106254
|
order_id: input.entryOrderId,
|
|
@@ -106069,13 +106260,15 @@ var init_native_protection_device = __esm({
|
|
|
106069
106260
|
live_position_size: position.size
|
|
106070
106261
|
}
|
|
106071
106262
|
});
|
|
106072
|
-
return {
|
|
106263
|
+
return {
|
|
106264
|
+
record: {
|
|
106265
|
+
...record6,
|
|
106266
|
+
phase: "active",
|
|
106267
|
+
...gate === "not_required" ? { members: record6.members.map(moveMade) } : {}
|
|
106268
|
+
},
|
|
106269
|
+
reports
|
|
106270
|
+
};
|
|
106073
106271
|
}
|
|
106074
|
-
const observations = observeMembers(record6, page);
|
|
106075
|
-
const restingTrigger = (kind) => {
|
|
106076
|
-
const observed = observations.find((entry) => entry.member.kind === kind);
|
|
106077
|
-
return observed?.row?.trigger_px != null ? String(observed.row.trigger_px) : null;
|
|
106078
|
-
};
|
|
106079
106272
|
if (position.entryPrice == null) {
|
|
106080
106273
|
reports.push({
|
|
106081
106274
|
order_id: input.entryOrderId,
|
|
@@ -106094,89 +106287,33 @@ var init_native_protection_device = __esm({
|
|
|
106094
106287
|
fillSize: input.fillSize,
|
|
106095
106288
|
resting: { sl: restingTrigger("sl"), tp: restingTrigger("tp") }
|
|
106096
106289
|
});
|
|
106097
|
-
let eventMs = Math.max(
|
|
106098
|
-
0,
|
|
106099
|
-
...observations.map((entry) => entry.row?.timestamp ?? entry.member.placedAtMs ?? 0),
|
|
106100
|
-
// An add's own fill, and the fill a planned pair answers: Hyperliquid's times.
|
|
106101
|
-
boundary.addFillMs ?? 0,
|
|
106102
|
-
...record6.members.map((member) => member.plannedAfterMs ?? 0)
|
|
106103
|
-
);
|
|
106104
|
-
if (eventMs <= 0 && input.entryOrderId) {
|
|
106105
|
-
const entryStatus = await io.readOrderStatus(input.entryOrderId);
|
|
106106
|
-
eventMs = entryStatus.statusTimestampMs ?? 0;
|
|
106107
|
-
}
|
|
106108
|
-
const gate = nativePlacementGate({
|
|
106109
|
-
eventMs,
|
|
106110
|
-
position: position.size,
|
|
106111
|
-
positionStateMs: position.stateTimeMs ?? Number.NEGATIVE_INFINITY,
|
|
106112
|
-
isLong: record6.isLong
|
|
106113
|
-
});
|
|
106114
106290
|
const members = [...record6.members];
|
|
106115
106291
|
for (const step of actions) {
|
|
106116
106292
|
if (step.action === "place_trailing") continue;
|
|
106117
106293
|
const index = members.findIndex((member) => member.kind === step.kind);
|
|
106118
106294
|
const existing = index >= 0 ? members[index] : null;
|
|
106119
106295
|
if (existing?.userCancelledOrderId != null || existing?.retiredReason) continue;
|
|
106296
|
+
if (existing?.pendingModify) continue;
|
|
106120
106297
|
const clientOrderId = clientOrderIdForMutation(io.newMutationId());
|
|
106121
106298
|
if (step.action === "modify") {
|
|
106122
106299
|
const row = observations.find((entry) => entry.member.kind === step.kind)?.row;
|
|
106123
106300
|
if (!row) continue;
|
|
106124
|
-
|
|
106125
|
-
|
|
106126
|
-
|
|
106127
|
-
orderId: row.oid,
|
|
106128
|
-
pendingModify: { clientOrderId, trigger: step.trigger, sentAtMs: sentAtMs2 }
|
|
106129
|
-
};
|
|
106130
|
-
if (!io.persist({ ...record6, phase: "active", members })) {
|
|
106131
|
-
members[index] = existing;
|
|
106132
|
-
reports.push({
|
|
106133
|
-
order_id: String(row.oid),
|
|
106134
|
-
symbol: symbol2,
|
|
106135
|
-
action: actionOf(step.kind),
|
|
106136
|
-
status: "failed",
|
|
106137
|
-
execution_metadata: { reason_code: "protective_lifecycle_persistence_failed", trigger_price: step.trigger }
|
|
106138
|
-
});
|
|
106139
|
-
continue;
|
|
106140
|
-
}
|
|
106141
|
-
const outcome2 = await attempt(io, () => io.modifyPositionOrder({
|
|
106142
|
-
orderId: row.oid,
|
|
106143
|
-
kind: step.kind,
|
|
106144
|
-
triggerPrice: Number(step.trigger),
|
|
106145
|
-
clientOrderId
|
|
106146
|
-
}));
|
|
106147
|
-
if (!outcome2.ok && outcome2.refused) {
|
|
106148
|
-
members[index] = { ...existing, orderId: row.oid };
|
|
106149
|
-
reports.push({
|
|
106150
|
-
order_id: String(row.oid),
|
|
106151
|
-
symbol: symbol2,
|
|
106152
|
-
action: actionOf(step.kind),
|
|
106153
|
-
status: "failed",
|
|
106154
|
-
execution_metadata: {
|
|
106155
|
-
reason_code: outcome2.error instanceof NativeOrderNotSentError ? "protective_modify_not_sent" : "protective_modify_rejected",
|
|
106156
|
-
trigger_price: step.trigger,
|
|
106157
|
-
error: errorText(outcome2.error)
|
|
106158
|
-
}
|
|
106159
|
-
});
|
|
106160
|
-
continue;
|
|
106161
|
-
}
|
|
106162
|
-
const newOrderId = outcome2.ok ? restingOrderIdAt(outcome2.response, 0) : null;
|
|
106163
|
-
if (newOrderId != null) {
|
|
106164
|
-
const { pendingModify: _applied, ...rest } = members[index];
|
|
106165
|
-
members[index] = { ...rest, clientOrderId, orderId: newOrderId, trigger: step.trigger, placedAtMs: null, sentAtMs: sentAtMs2 };
|
|
106166
|
-
}
|
|
106167
|
-
reports.push({
|
|
106168
|
-
order_id: String(newOrderId ?? row.oid),
|
|
106301
|
+
if (await cancellingThroughVtx(io, row.oid)) continue;
|
|
106302
|
+
const moved = await moveMember({
|
|
106303
|
+
io,
|
|
106169
106304
|
symbol: symbol2,
|
|
106170
|
-
|
|
106171
|
-
|
|
106172
|
-
|
|
106173
|
-
|
|
106174
|
-
|
|
106175
|
-
|
|
106176
|
-
|
|
106177
|
-
|
|
106305
|
+
member: members[index],
|
|
106306
|
+
orderId: row.oid,
|
|
106307
|
+
trigger: step.trigger,
|
|
106308
|
+
clientOrderId,
|
|
106309
|
+
protectedSize: Math.abs(position.size),
|
|
106310
|
+
journal: (member) => {
|
|
106311
|
+
members[index] = member;
|
|
106312
|
+
return io.persist({ ...record6, phase: "active", members });
|
|
106178
106313
|
}
|
|
106179
106314
|
});
|
|
106315
|
+
members[index] = moved.member;
|
|
106316
|
+
reports.push(moved.report);
|
|
106180
106317
|
continue;
|
|
106181
106318
|
}
|
|
106182
106319
|
if (existing != null && existing.orderId == null && existing.plannedAfterMs == null && !unknownClientOrderIds.has(existing.clientOrderId)) {
|
|
@@ -106239,7 +106376,10 @@ var init_native_protection_device = __esm({
|
|
|
106239
106376
|
() => io.persist({ ...record6, phase: "active", members: before })
|
|
106240
106377
|
);
|
|
106241
106378
|
if (!outcome.ok && outcome.refused) {
|
|
106242
|
-
if (outcome.error instanceof NativeOrderNotSentError)
|
|
106379
|
+
if (outcome.error instanceof NativeOrderNotSentError) {
|
|
106380
|
+
members.splice(0, members.length, ...before);
|
|
106381
|
+
io.persist({ ...record6, phase: "active", members: before });
|
|
106382
|
+
}
|
|
106243
106383
|
reports.push({
|
|
106244
106384
|
order_id: null,
|
|
106245
106385
|
symbol: symbol2,
|
|
@@ -106340,7 +106480,12 @@ var init_native_protection_device = __esm({
|
|
|
106340
106480
|
}
|
|
106341
106481
|
});
|
|
106342
106482
|
}
|
|
106343
|
-
|
|
106483
|
+
const movingKinds = new Set(actions.flatMap((step) => step.action === "modify" ? [step.kind] : []));
|
|
106484
|
+
const settledMembers = members.map((member) => {
|
|
106485
|
+
if (member.pendingMove && !owesMove(member)) return moveMade(member);
|
|
106486
|
+
return gate === "place" && member.pendingMove && !member.pendingModify && !movingKinds.has(member.kind) && observations.some((entry) => entry.row != null && entry.member.orderId === member.orderId) ? moveMade(member) : member;
|
|
106487
|
+
});
|
|
106488
|
+
record6 = { ...record6, phase: "active", members: settledMembers, ...lots.length > 0 ? { lots } : {} };
|
|
106344
106489
|
return { record: record6, reports };
|
|
106345
106490
|
};
|
|
106346
106491
|
reconcileNativeProtection = async (input) => {
|
|
@@ -106394,6 +106539,24 @@ var init_native_protection_device = __esm({
|
|
|
106394
106539
|
}) : null;
|
|
106395
106540
|
};
|
|
106396
106541
|
const kindEnabled = (member) => (member.kind === "sl" ? input.settings.stopLoss : input.settings.takeProfit) != null;
|
|
106542
|
+
const movable = positionOpen && !undecidedAdds && position.entryPrice != null;
|
|
106543
|
+
const moveTargets = /* @__PURE__ */ new Map();
|
|
106544
|
+
if (movable && position.entryPrice != null && record6.members.some(owesMove)) {
|
|
106545
|
+
const restingTrigger = (kind) => {
|
|
106546
|
+
const observed = observations.find((entry) => entry.member.kind === kind && entry.row != null && !entry.member.retiredReason && entry.member.userCancelledOrderId == null);
|
|
106547
|
+
return observed?.row?.trigger_px != null ? String(observed.row.trigger_px) : null;
|
|
106548
|
+
};
|
|
106549
|
+
for (const step of nativeAfterFillActions({
|
|
106550
|
+
settings: { ...input.settings, stopLoss: input.settings.stopLoss && { ...input.settings.stopLoss, trailing: false } },
|
|
106551
|
+
isLong: record6.isLong,
|
|
106552
|
+
sizeDecimals: input.sizeDecimals,
|
|
106553
|
+
position: { size: position.size, entryPrice: position.entryPrice },
|
|
106554
|
+
fillSize: "0",
|
|
106555
|
+
resting: { sl: restingTrigger("sl"), tp: restingTrigger("tp") }
|
|
106556
|
+
})) {
|
|
106557
|
+
if (step.action === "modify") moveTargets.set(step.kind, step.trigger);
|
|
106558
|
+
}
|
|
106559
|
+
}
|
|
106397
106560
|
const placeMember = async (args) => {
|
|
106398
106561
|
const gate = nativePlacementGate({
|
|
106399
106562
|
eventMs: args.eventMs,
|
|
@@ -106532,6 +106695,47 @@ var init_native_protection_device = __esm({
|
|
|
106532
106695
|
}
|
|
106533
106696
|
continue;
|
|
106534
106697
|
}
|
|
106698
|
+
if (member.pendingMove && !owesMove(member)) {
|
|
106699
|
+
anyResting = true;
|
|
106700
|
+
members.push(moveMade(member));
|
|
106701
|
+
continue;
|
|
106702
|
+
}
|
|
106703
|
+
if (member.pendingMove && movable && !member.retiredReason && member.userCancelledOrderId == null && !member.pendingModify && nativePlacementGate({
|
|
106704
|
+
eventMs: Math.max(member.pendingMove.afterMs, member.placedAtMs ?? 0),
|
|
106705
|
+
position: position.size,
|
|
106706
|
+
positionStateMs: stateMs,
|
|
106707
|
+
isLong: record6.isLong
|
|
106708
|
+
}) === "place") {
|
|
106709
|
+
const target = moveTargets.get(member.kind);
|
|
106710
|
+
if (target === void 0) {
|
|
106711
|
+
anyResting = true;
|
|
106712
|
+
members.push(moveMade(member));
|
|
106713
|
+
continue;
|
|
106714
|
+
}
|
|
106715
|
+
if (!await cancellingThroughVtx(io, row.oid)) {
|
|
106716
|
+
const moved = await moveMember({
|
|
106717
|
+
io,
|
|
106718
|
+
symbol: symbol2,
|
|
106719
|
+
member,
|
|
106720
|
+
orderId: row.oid,
|
|
106721
|
+
trigger: target,
|
|
106722
|
+
clientOrderId: clientOrderIdForMutation(io.newMutationId()),
|
|
106723
|
+
protectedSize: Math.abs(position.size),
|
|
106724
|
+
journal: (next) => io.persist({
|
|
106725
|
+
...record6,
|
|
106726
|
+
members: [
|
|
106727
|
+
...members,
|
|
106728
|
+
next,
|
|
106729
|
+
...observations.slice(observationIndex + 1).map((entry) => entry.member)
|
|
106730
|
+
]
|
|
106731
|
+
})
|
|
106732
|
+
});
|
|
106733
|
+
reports.push(moved.report);
|
|
106734
|
+
anyResting = true;
|
|
106735
|
+
members.push(moved.member);
|
|
106736
|
+
continue;
|
|
106737
|
+
}
|
|
106738
|
+
}
|
|
106535
106739
|
anyResting = true;
|
|
106536
106740
|
members.push(member);
|
|
106537
106741
|
continue;
|
|
@@ -106545,9 +106749,20 @@ var init_native_protection_device = __esm({
|
|
|
106545
106749
|
members.push(member);
|
|
106546
106750
|
continue;
|
|
106547
106751
|
}
|
|
106548
|
-
if (member.orderId != null && io.userCancelledOrder
|
|
106549
|
-
|
|
106550
|
-
|
|
106752
|
+
if (member.orderId != null && io.userCancelledOrder) {
|
|
106753
|
+
let cancelledByUser;
|
|
106754
|
+
try {
|
|
106755
|
+
cancelledByUser = await io.userCancelledOrder(member.orderId);
|
|
106756
|
+
} catch (error48) {
|
|
106757
|
+
if (io.endsPass?.(error48)) throw error48;
|
|
106758
|
+
anyResting = true;
|
|
106759
|
+
members.push(member);
|
|
106760
|
+
continue;
|
|
106761
|
+
}
|
|
106762
|
+
if (cancelledByUser) {
|
|
106763
|
+
members.push({ ...member, userCancelledOrderId: member.orderId });
|
|
106764
|
+
continue;
|
|
106765
|
+
}
|
|
106551
106766
|
}
|
|
106552
106767
|
if (member.plannedAfterMs != null) {
|
|
106553
106768
|
if (!kindEnabled(member)) continue;
|
|
@@ -106951,7 +107166,7 @@ var init_native_protection_device = __esm({
|
|
|
106951
107166
|
});
|
|
106952
107167
|
|
|
106953
107168
|
// lib/runtime/runtime-execution.ts
|
|
106954
|
-
var clientProtectiveMutationAuthority, executionReadPriority, serverEntryLeverageAlreadyHeld, fetchClientRuntimeOpenOrders, 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, nativePassEnded, nativeProtectionIo, nativeStorageReport, readNativeRecord, reconcileNativeProtectionForDecision, reconcileClientProtectiveGroups, cancelAllClientProtectiveGroups, tightenClientTrailingStops,
|
|
107169
|
+
var clientProtectiveMutationAuthority, executionReadPriority, serverEntryLeverageAlreadyHeld, fetchClientRuntimeOpenOrders, 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, nativePassEnded, nativeProtectionIo, nativeStorageReport, readNativeRecord, reconcileNativeProtectionForDecision, reconcileClientProtectiveGroups, cancelAllClientProtectiveGroups, tightenClientTrailingStops, isDefinitiveEntryRejection, resolveExchangeSizeDecimals, roundAssetSize, resolvePositionSize, readServerOrderMarkPrice, serverOrderMetadataRetry, resolveCurrentPositionSize, buildPositionSnapshot, signedRemainingExposureAfterConfirmedReduction, runtimeProtectionAuthority, runtimeProtectionListings, runtimeProtectionListing, resolveServerNativeEntry, SERVER_NATIVE_LEGACY_REFUSAL, isServerNativeLegacyRefusal, serverUserCancelLookup, serverModeProtectionOwner, runtimeProtectionOwners, resolveRuntimeProtectionOwner, drainServerProtectionForRuntime, drainServerProtectionIfOwned, verifyNoLiveClientProtectiveTriggers, clientExecutionMutations, CLIENT_EXECUTION_QUEUE_TIMEOUT_MESSAGE, withClientExecutionMutation, withClientProtectivePlanSetMutation, allocateServerExecutionCapacity, withClientProtectiveAdoptionMutation, executeClientRuntimeDecisionLocked, unsentDecisionOrderReport, 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;
|
|
106955
107170
|
var init_runtime_execution = __esm({
|
|
106956
107171
|
"lib/runtime/runtime-execution.ts"() {
|
|
106957
107172
|
"use strict";
|
|
@@ -106962,6 +107177,7 @@ var init_runtime_execution = __esm({
|
|
|
106962
107177
|
init_order_identity();
|
|
106963
107178
|
init_runtime_policy_generated2();
|
|
106964
107179
|
init_constants();
|
|
107180
|
+
init_abort();
|
|
106965
107181
|
init_bounded_lock();
|
|
106966
107182
|
init_client_runtime_ownership_errors();
|
|
106967
107183
|
init_api2();
|
|
@@ -107024,7 +107240,7 @@ var init_runtime_execution = __esm({
|
|
|
107024
107240
|
"hyperliquid.activeAssetData"
|
|
107025
107241
|
);
|
|
107026
107242
|
} catch {
|
|
107027
|
-
|
|
107243
|
+
throwIfAborted(input.signal);
|
|
107028
107244
|
return false;
|
|
107029
107245
|
}
|
|
107030
107246
|
const leverage = active?.leverage;
|
|
@@ -112117,7 +112333,7 @@ var init_runtime_execution = __esm({
|
|
|
112117
112333
|
let canonicalCleanupRetained = false;
|
|
112118
112334
|
let replacementDispatchBoundaryCompleted = false;
|
|
112119
112335
|
try {
|
|
112120
|
-
|
|
112336
|
+
throwIfAborted(request.signal);
|
|
112121
112337
|
const modifyResponse = await executeClientModifyOrder({
|
|
112122
112338
|
profileId: request.profileId,
|
|
112123
112339
|
...clientProtectiveMutationAuthority(request),
|
|
@@ -112274,32 +112490,6 @@ var init_runtime_execution = __esm({
|
|
|
112274
112490
|
writeTrackedTrailingStops(profileId, symbol2, updated);
|
|
112275
112491
|
return reports;
|
|
112276
112492
|
};
|
|
112277
|
-
throwIfAborted2 = (signal) => {
|
|
112278
|
-
if (signal?.aborted) {
|
|
112279
|
-
throw new DOMException("The operation was aborted.", "AbortError");
|
|
112280
|
-
}
|
|
112281
|
-
};
|
|
112282
|
-
sleep2 = async (ms, signal) => {
|
|
112283
|
-
await new Promise((resolve16, reject) => {
|
|
112284
|
-
const timer = setTimeout(() => {
|
|
112285
|
-
cleanup();
|
|
112286
|
-
resolve16(void 0);
|
|
112287
|
-
}, ms);
|
|
112288
|
-
const cleanup = () => {
|
|
112289
|
-
clearTimeout(timer);
|
|
112290
|
-
signal?.removeEventListener("abort", onAbort);
|
|
112291
|
-
};
|
|
112292
|
-
const onAbort = () => {
|
|
112293
|
-
cleanup();
|
|
112294
|
-
reject(new DOMException("The operation was aborted.", "AbortError"));
|
|
112295
|
-
};
|
|
112296
|
-
if (signal?.aborted) {
|
|
112297
|
-
onAbort();
|
|
112298
|
-
return;
|
|
112299
|
-
}
|
|
112300
|
-
signal?.addEventListener("abort", onAbort, { once: true });
|
|
112301
|
-
});
|
|
112302
|
-
};
|
|
112303
112493
|
isDefinitiveEntryRejection = (error48, entryMutationId) => error48 instanceof HyperliquidExchangeRejectionError && Boolean(entryMutationId) && String(error48.clientMutationId ?? "").trim().toLowerCase() === String(entryMutationId).trim().toLowerCase();
|
|
112304
112494
|
resolveExchangeSizeDecimals = async (symbol2, config2, publicRequestPriority, profileId) => {
|
|
112305
112495
|
const { sz_decimals: sizeDecimals } = await resolveHyperliquidAsset({
|
|
@@ -112341,7 +112531,7 @@ var init_runtime_execution = __esm({
|
|
|
112341
112531
|
if (input.executionMode !== "server" || !decisionSnapshotId || !isDefinitiveEntryRejection(rejection, rejectedMutationId)) return null;
|
|
112342
112532
|
const reason = orderMetadataRetryReason(rejection.message);
|
|
112343
112533
|
if (reason === null) return null;
|
|
112344
|
-
|
|
112534
|
+
throwIfAborted(input.signal);
|
|
112345
112535
|
try {
|
|
112346
112536
|
const asset = await resolveHyperliquidAsset({
|
|
112347
112537
|
symbol: input.executionContext.symbol,
|
|
@@ -112377,12 +112567,12 @@ var init_runtime_execution = __esm({
|
|
|
112377
112567
|
markPrice
|
|
112378
112568
|
};
|
|
112379
112569
|
} catch {
|
|
112380
|
-
|
|
112570
|
+
throwIfAborted(input.signal);
|
|
112381
112571
|
return null;
|
|
112382
112572
|
}
|
|
112383
112573
|
};
|
|
112384
112574
|
resolveCurrentPositionSize = async (input, orderPrice = "decision") => {
|
|
112385
|
-
|
|
112575
|
+
throwIfAborted(input.signal);
|
|
112386
112576
|
const snapshotPositionSize = Number.isFinite(input.executionContext.currentPositionSize) ? Number(input.executionContext.currentPositionSize) : 0;
|
|
112387
112577
|
const decisionPrice = Number.isFinite(input.executionContext.lastPrice) ? Number(input.executionContext.lastPrice) : 0;
|
|
112388
112578
|
const walletAddress = String(input.executionContext.walletAddress || "").trim();
|
|
@@ -112613,7 +112803,7 @@ var init_runtime_execution = __esm({
|
|
|
112613
112803
|
const pending3 = previous.catch(() => void 0).then(async () => {
|
|
112614
112804
|
if (abandoned) return void 0;
|
|
112615
112805
|
startTurn();
|
|
112616
|
-
|
|
112806
|
+
throwIfAborted(request.signal);
|
|
112617
112807
|
if (request.shouldCancelBeforeExchangeOrderDispatch?.()) {
|
|
112618
112808
|
throw new Error(CLIENT_RUNTIME_WINDOW_HANDOFF_BEFORE_PLAN_DISPATCH);
|
|
112619
112809
|
}
|
|
@@ -112684,7 +112874,7 @@ var init_runtime_execution = __esm({
|
|
|
112684
112874
|
}
|
|
112685
112875
|
return judged;
|
|
112686
112876
|
} catch (error48) {
|
|
112687
|
-
|
|
112877
|
+
throwIfAborted(authority.signal);
|
|
112688
112878
|
return plans.map(() => ({ unavailable: error48 }));
|
|
112689
112879
|
}
|
|
112690
112880
|
};
|
|
@@ -112784,7 +112974,8 @@ var init_runtime_execution = __esm({
|
|
|
112784
112974
|
});
|
|
112785
112975
|
} catch (error48) {
|
|
112786
112976
|
const committedClose = getCommittedExecutionReports(error48).find((report) => report.status === "executed" && decisionLegOf(report) === "flip_close");
|
|
112787
|
-
|
|
112977
|
+
const aborted2 = input.signal?.aborted || isAbortLikeError(error48);
|
|
112978
|
+
if (audit.auditId !== null && (!aborted2 || committedClose) && (input.decision === "BUY" || input.decision === "SELL")) {
|
|
112788
112979
|
const reason = String(error48?.reasonCode ?? "");
|
|
112789
112980
|
const orderMayHaveGoneOut = entryDispatched || exitDispatched && !committedClose;
|
|
112790
112981
|
const [status2, reasonCode2] = reason === "outcome_unknown" || !reason && orderMayHaveGoneOut ? ["outcome_unknown", "outcome_unknown"] : ["error", reason === "exchange_rejected" ? "exchange_rejected" : "execution_error"];
|
|
@@ -112803,7 +112994,7 @@ var init_runtime_execution = __esm({
|
|
|
112803
112994
|
...committedClose.execution_metadata,
|
|
112804
112995
|
execution_audit_id: audit.auditId
|
|
112805
112996
|
};
|
|
112806
|
-
await recordAudit(null, {
|
|
112997
|
+
if (!aborted2 || entryDispatched) await recordAudit(null, {
|
|
112807
112998
|
intent: "flip",
|
|
112808
112999
|
side,
|
|
112809
113000
|
requestedUnits: input.units,
|
|
@@ -112884,12 +113075,12 @@ var init_runtime_execution = __esm({
|
|
|
112884
113075
|
const pollMs = Number(input.executionContext.closePositionFreshnessPollMs);
|
|
112885
113076
|
const walletAddress = String(input.executionContext.walletAddress || "").trim();
|
|
112886
113077
|
if (input.executionMode !== "server" || !(pollMs > 0) || !walletAddress) {
|
|
112887
|
-
await
|
|
113078
|
+
await abortableSleep(delayMs, input.signal);
|
|
112888
113079
|
return;
|
|
112889
113080
|
}
|
|
112890
113081
|
const deadline = Date.now() + delayMs;
|
|
112891
113082
|
for (; ; ) {
|
|
112892
|
-
|
|
113083
|
+
throwIfAborted(input.signal);
|
|
112893
113084
|
try {
|
|
112894
113085
|
const snapshot = await fetchBrowserPositionSnapshot(
|
|
112895
113086
|
input.config ?? {},
|
|
@@ -112900,11 +113091,11 @@ var init_runtime_execution = __esm({
|
|
|
112900
113091
|
);
|
|
112901
113092
|
if (Number(snapshot.size) === 0) return;
|
|
112902
113093
|
} catch {
|
|
112903
|
-
|
|
113094
|
+
throwIfAborted(input.signal);
|
|
112904
113095
|
}
|
|
112905
113096
|
const remaining = deadline - Date.now();
|
|
112906
113097
|
if (remaining <= 0) return;
|
|
112907
|
-
await
|
|
113098
|
+
await abortableSleep(Math.min(pollMs, remaining), input.signal);
|
|
112908
113099
|
}
|
|
112909
113100
|
};
|
|
112910
113101
|
maintainClientRuntimeTrailingStops = (request) => withClientProtectivePlanSetMutation(request, request.executionContext.symbol, async () => {
|
|
@@ -113212,7 +113403,7 @@ var init_runtime_execution = __esm({
|
|
|
113212
113403
|
if (!profileId || !walletAddress) return [];
|
|
113213
113404
|
const results = [];
|
|
113214
113405
|
for (const symbol2 of listPendingClientProtectiveSymbols(profileId)) {
|
|
113215
|
-
|
|
113406
|
+
throwIfAborted(input.signal);
|
|
113216
113407
|
const retired = [];
|
|
113217
113408
|
const reports = await withClientProtectivePlanSetMutation({ profileId, signal: input.signal }, symbol2, async () => {
|
|
113218
113409
|
const groups2 = readFreshClientProtectiveGroups(profileId, symbol2);
|
|
@@ -113292,7 +113483,7 @@ var init_runtime_execution = __esm({
|
|
|
113292
113483
|
return carrier;
|
|
113293
113484
|
};
|
|
113294
113485
|
executeClientRuntimeDecisionUnlocked = async (unsizedInput, progress = { committedReports: null }) => {
|
|
113295
|
-
|
|
113486
|
+
throwIfAborted(unsizedInput.signal);
|
|
113296
113487
|
const requestedUnits = Math.max(0, Math.trunc(unsizedInput.units));
|
|
113297
113488
|
appendRuntimeDebugEvent({
|
|
113298
113489
|
label: "execution_start",
|
|
@@ -113341,7 +113532,7 @@ var init_runtime_execution = __esm({
|
|
|
113341
113532
|
{ symbol: unsizedInput.executionContext.symbol, decision: unsizedInput.decision, units: requestedUnits }
|
|
113342
113533
|
], unsizedInput.executionContext.decisionSnapshotCapturedAt))[0];
|
|
113343
113534
|
if ("unavailable" in capacity) {
|
|
113344
|
-
|
|
113535
|
+
throwIfAborted(unsizedInput.signal);
|
|
113345
113536
|
throw capacity.unavailable instanceof Error ? capacity.unavailable : new Error("Positions could not be read before the limit check.");
|
|
113346
113537
|
}
|
|
113347
113538
|
if (!capacity.accepted || !(capacity.units > 0)) {
|
|
@@ -113376,7 +113567,7 @@ var init_runtime_execution = __esm({
|
|
|
113376
113567
|
)
|
|
113377
113568
|
}
|
|
113378
113569
|
};
|
|
113379
|
-
|
|
113570
|
+
throwIfAborted(input.signal);
|
|
113380
113571
|
const decisionSnapshotPositionSize = Number.isFinite(input.executionContext.currentPositionSize) ? Number(input.executionContext.currentPositionSize) : 0;
|
|
113381
113572
|
const decisionSnapshotSignedUnits = signedUnitsFromEntryPosition(
|
|
113382
113573
|
decisionSnapshotPositionSize,
|
|
@@ -113465,7 +113656,7 @@ var init_runtime_execution = __esm({
|
|
|
113465
113656
|
executionSnapshotCapturedAt
|
|
113466
113657
|
} = await resolveCurrentPositionSize(input, serverOrder ? "fresh_mark" : "decision");
|
|
113467
113658
|
let executionPrice = resolvedExecutionPrice;
|
|
113468
|
-
|
|
113659
|
+
throwIfAborted(input.signal);
|
|
113469
113660
|
const currentPosition = buildPositionSnapshot(input.executionContext.symbol, currentPositionSize);
|
|
113470
113661
|
const decisionSnapshotId = String(input.executionContext.decisionSnapshotId ?? "").trim();
|
|
113471
113662
|
const decisionLegMutationId = (leg) => decisionSnapshotId ? clientDecisionMutationId({
|
|
@@ -113607,7 +113798,7 @@ var init_runtime_execution = __esm({
|
|
|
113607
113798
|
};
|
|
113608
113799
|
}
|
|
113609
113800
|
if (input.executionMode === "server") {
|
|
113610
|
-
|
|
113801
|
+
throwIfAborted(input.signal);
|
|
113611
113802
|
const claim = await claimServerHostExecution(
|
|
113612
113803
|
input.profileId,
|
|
113613
113804
|
{
|
|
@@ -113655,7 +113846,7 @@ var init_runtime_execution = __esm({
|
|
|
113655
113846
|
}
|
|
113656
113847
|
}
|
|
113657
113848
|
if (!targetResolution.closeOpposingPosition && classified.reduceOnly !== true && !await serverEntryLeverageAlreadyHeld(input)) {
|
|
113658
|
-
|
|
113849
|
+
throwIfAborted(input.signal);
|
|
113659
113850
|
await executeClientLeverageUpdate({
|
|
113660
113851
|
profileId: input.profileId,
|
|
113661
113852
|
runtimeSessionId: input.sessionId || "__missing_runtime_session__",
|
|
@@ -113670,10 +113861,10 @@ var init_runtime_execution = __esm({
|
|
|
113670
113861
|
leverage: input.executionContext.leverage,
|
|
113671
113862
|
isCross: input.executionContext.marginMode !== "isolated"
|
|
113672
113863
|
});
|
|
113673
|
-
|
|
113864
|
+
throwIfAborted(input.signal);
|
|
113674
113865
|
}
|
|
113675
113866
|
if (classified.intent === "close") {
|
|
113676
|
-
|
|
113867
|
+
throwIfAborted(input.signal);
|
|
113677
113868
|
const closeMutationId = await decisionLegMutationId("close");
|
|
113678
113869
|
const closeResponse = await closeWithServerMetadataRetry("close", closeMutationId, (mutationId, estimatedPrice, assets) => executeClientClosePosition({
|
|
113679
113870
|
mutationId,
|
|
@@ -113761,7 +113952,7 @@ var init_runtime_execution = __esm({
|
|
|
113761
113952
|
];
|
|
113762
113953
|
let flipCloseFillConfirmed = true;
|
|
113763
113954
|
if (targetResolution.closeOpposingPosition) {
|
|
113764
|
-
|
|
113955
|
+
throwIfAborted(input.signal);
|
|
113765
113956
|
const flipCloseMutationId = await decisionLegMutationId("flip_close");
|
|
113766
113957
|
const closeResponse = await closeWithServerMetadataRetry("flip_close", flipCloseMutationId, (mutationId, estimatedPrice, assets) => executeClientClosePosition({
|
|
113767
113958
|
mutationId,
|
|
@@ -113883,7 +114074,7 @@ var init_runtime_execution = __esm({
|
|
|
113883
114074
|
[]
|
|
113884
114075
|
);
|
|
113885
114076
|
await waitForFlipCloseFreshness(input);
|
|
113886
|
-
|
|
114077
|
+
throwIfAborted(input.signal);
|
|
113887
114078
|
await executeClientLeverageUpdate({
|
|
113888
114079
|
profileId: input.profileId,
|
|
113889
114080
|
runtimeSessionId: input.sessionId || "__missing_runtime_session__",
|
|
@@ -113898,7 +114089,7 @@ var init_runtime_execution = __esm({
|
|
|
113898
114089
|
leverage: input.executionContext.leverage,
|
|
113899
114090
|
isCross: input.executionContext.marginMode !== "isolated"
|
|
113900
114091
|
});
|
|
113901
|
-
|
|
114092
|
+
throwIfAborted(input.signal);
|
|
113902
114093
|
if (serverOrder) executionPrice = await readServerOrderMarkPrice(input);
|
|
113903
114094
|
}
|
|
113904
114095
|
const actualUnits = targetResolution.orderUnits;
|
|
@@ -114532,7 +114723,7 @@ var init_runtime_execution = __esm({
|
|
|
114532
114723
|
continue;
|
|
114533
114724
|
}
|
|
114534
114725
|
try {
|
|
114535
|
-
|
|
114726
|
+
throwIfAborted(input.signal);
|
|
114536
114727
|
const liveSnapshot = await fetchBrowserPositionSnapshot(
|
|
114537
114728
|
input.config ?? {},
|
|
114538
114729
|
String(input.executionContext.walletAddress || "").trim(),
|
|
@@ -115196,6 +115387,93 @@ var init_server_protection_sweep = __esm({
|
|
|
115196
115387
|
}
|
|
115197
115388
|
});
|
|
115198
115389
|
|
|
115390
|
+
// lib/runtime/runtime-error-diagnostic-fields.ts
|
|
115391
|
+
var DEVICE_DIAGNOSTICS3, buildRuntimeRequestErrorDiagnosticFields, buildHyperliquidPublicReadDiagnosticFields;
|
|
115392
|
+
var init_runtime_error_diagnostic_fields = __esm({
|
|
115393
|
+
"lib/runtime/runtime-error-diagnostic-fields.ts"() {
|
|
115394
|
+
"use strict";
|
|
115395
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
115396
|
+
init_define_VTX_EXO_POLICY();
|
|
115397
|
+
init_define_VTX_GROK_POLICY();
|
|
115398
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
115399
|
+
init_runtime_policy_generated2();
|
|
115400
|
+
init_constants();
|
|
115401
|
+
init_runtime_redaction();
|
|
115402
|
+
DEVICE_DIAGNOSTICS3 = runtime_policy_generated_default2.trading.engine.client_runtime.device_diagnostics;
|
|
115403
|
+
buildRuntimeRequestErrorDiagnosticFields = (reason) => {
|
|
115404
|
+
if (!reason || typeof reason !== "object" && typeof reason !== "function") {
|
|
115405
|
+
return {};
|
|
115406
|
+
}
|
|
115407
|
+
const record6 = reason;
|
|
115408
|
+
const path = sanitizeRuntimeDiagnosticValue(String(record6.runtimeRequestPath || "")).trim();
|
|
115409
|
+
if (!path) {
|
|
115410
|
+
return {};
|
|
115411
|
+
}
|
|
115412
|
+
const numberOrNull = (value) => {
|
|
115413
|
+
if (value === null || value === void 0 || value === "") {
|
|
115414
|
+
return null;
|
|
115415
|
+
}
|
|
115416
|
+
const parsed = Number(value);
|
|
115417
|
+
return Number.isFinite(parsed) ? parsed : null;
|
|
115418
|
+
};
|
|
115419
|
+
return {
|
|
115420
|
+
runtime_request_path: path.slice(0, DEVICE_DIAGNOSTICS3.request_path_chars),
|
|
115421
|
+
runtime_request_method: sanitizeRuntimeDiagnosticValue(String(record6.runtimeRequestMethod || "")).slice(0, DEVICE_DIAGNOSTICS3.request_method_chars) || null,
|
|
115422
|
+
runtime_request_attempt: numberOrNull(record6.runtimeRequestAttempt),
|
|
115423
|
+
runtime_request_max_attempts: numberOrNull(record6.runtimeRequestMaxAttempts),
|
|
115424
|
+
runtime_request_status: numberOrNull(record6.runtimeRequestStatus),
|
|
115425
|
+
runtime_request_error_kind: sanitizeRuntimeDiagnosticValue(String(record6.runtimeRequestErrorKind || "")).slice(0, DEVICE_DIAGNOSTICS3.error_kind_chars) || null,
|
|
115426
|
+
runtime_request_transient_network: record6.runtimeRequestTransientNetwork === true,
|
|
115427
|
+
runtime_request_deadline_at_ms: numberOrNull(record6.runtimeRequestDeadlineAtMs),
|
|
115428
|
+
runtime_request_deadline_exceeded: record6.runtimeRequestDeadlineExceeded === true,
|
|
115429
|
+
...record6.code === "snapshot_stale" && record6.runtimeRequestStatus === HTTP_STATUS.CONFLICT ? {
|
|
115430
|
+
runtime_rejection_reason_code: "snapshot_stale",
|
|
115431
|
+
snapshot_age_seconds: numberOrNull(record6.runtimeSnapshotAgeSeconds),
|
|
115432
|
+
snapshot_max_age_seconds: numberOrNull(record6.runtimeSnapshotMaxAgeSeconds)
|
|
115433
|
+
} : {},
|
|
115434
|
+
...record6.runtimeRequestId ? {
|
|
115435
|
+
runtime_request_id: sanitizeRuntimeDiagnosticValue(String(record6.runtimeRequestId)).slice(0, DEVICE_DIAGNOSTICS3.request_id_chars)
|
|
115436
|
+
} : {},
|
|
115437
|
+
...record6.runtimeReconciliationAttempted === true ? {
|
|
115438
|
+
runtime_reconciliation_attempted: true,
|
|
115439
|
+
runtime_reconciliation_elapsed_ms: numberOrNull(record6.runtimeReconciliationElapsedMs),
|
|
115440
|
+
runtime_reconciliation_status: numberOrNull(record6.runtimeReconciliationStatus),
|
|
115441
|
+
runtime_reconciliation_error_kind: sanitizeRuntimeDiagnosticValue(String(record6.runtimeReconciliationErrorKind || "")).slice(0, DEVICE_DIAGNOSTICS3.error_kind_chars) || null,
|
|
115442
|
+
runtime_reconciliation_deadline_exceeded: record6.runtimeReconciliationDeadlineExceeded === true,
|
|
115443
|
+
runtime_reconciliation_request_id: sanitizeRuntimeDiagnosticValue(String(record6.runtimeReconciliationRequestId || "")).slice(0, DEVICE_DIAGNOSTICS3.request_id_chars) || null
|
|
115444
|
+
} : {}
|
|
115445
|
+
};
|
|
115446
|
+
};
|
|
115447
|
+
buildHyperliquidPublicReadDiagnosticFields = (reason) => {
|
|
115448
|
+
let current = reason;
|
|
115449
|
+
const seen = /* @__PURE__ */ new Set();
|
|
115450
|
+
for (let depth = 0; depth < DEVICE_DIAGNOSTICS3.error_cause_max_depth; depth += 1) {
|
|
115451
|
+
if (!current || typeof current !== "object" || seen.has(current)) return {};
|
|
115452
|
+
seen.add(current);
|
|
115453
|
+
const record6 = current;
|
|
115454
|
+
if (record6.name === "HyperliquidPublicReadError" && [
|
|
115455
|
+
"public_budget_exhausted",
|
|
115456
|
+
"public_recovery_wait",
|
|
115457
|
+
"public_cooldown_active",
|
|
115458
|
+
"public_rate_limited",
|
|
115459
|
+
"public_network_error",
|
|
115460
|
+
"public_timeout"
|
|
115461
|
+
].includes(String(record6.code))) {
|
|
115462
|
+
const finiteNonnegative = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= Number.MAX_SAFE_INTEGER ? value : null;
|
|
115463
|
+
return {
|
|
115464
|
+
hl_public_read_code: record6.code,
|
|
115465
|
+
hl_public_read_request_type: typeof record6.requestType === "string" ? sanitizeRuntimeDiagnosticValue(record6.requestType).slice(0, CLIENT_RUNTIME_HL_REQUEST_TYPE_MAX_CHARS) : null,
|
|
115466
|
+
hl_public_read_status: finiteNonnegative(record6.status),
|
|
115467
|
+
hl_public_read_retry_after_ms: finiteNonnegative(record6.retryAfterMs)
|
|
115468
|
+
};
|
|
115469
|
+
}
|
|
115470
|
+
current = record6.cause;
|
|
115471
|
+
}
|
|
115472
|
+
return {};
|
|
115473
|
+
};
|
|
115474
|
+
}
|
|
115475
|
+
});
|
|
115476
|
+
|
|
115199
115477
|
// lib/runtime/periodic-schedule.ts
|
|
115200
115478
|
function periodicSlotAtOrAfter(schedule, nowMs2, options = {}) {
|
|
115201
115479
|
if (schedule.phaseMs === null || schedule.intervalMs === null) return null;
|
|
@@ -115352,6 +115630,7 @@ async function invokeProfileModelCascade(input) {
|
|
|
115352
115630
|
if (Array.isArray(observed)) attempts = observed;
|
|
115353
115631
|
if (error48 instanceof Error) error48.runtimeInvocationAttempts = attempts;
|
|
115354
115632
|
const ownAttempts = attempts.filter((attempt2) => !priorIds.has(attempt2.client_invocation_id));
|
|
115633
|
+
if (error48 instanceof Error) Object.assign(error48, { runtimeOwnInvocationAttempts: ownAttempts });
|
|
115355
115634
|
if (error48 instanceof Error) failedModels.push(fallbackAttemptFor(entry, error48, ownAttempts));
|
|
115356
115635
|
if (index === entries.length - 1 || !canAdvanceProfileModel(error48, entry.kind === "external_agent" || entry.source === "external_agent", input.signal, ownAttempts)) surface(error48);
|
|
115357
115636
|
lastFailure = error48;
|
|
@@ -115396,7 +115675,8 @@ var init_profile_model_cascade = __esm({
|
|
|
115396
115675
|
// lib/runtime/model-call-failure.ts
|
|
115397
115676
|
function describeModelCallFailure(error48, options = {}) {
|
|
115398
115677
|
const attempts = failureAttempts(error48);
|
|
115399
|
-
const
|
|
115678
|
+
const ownAttempts = ownFailureAttempts(error48, options.ownAttempts);
|
|
115679
|
+
const last = (ownAttempts ?? attempts).at(-1);
|
|
115400
115680
|
const message = getSanitizedRuntimeErrorMessage(error48) || (error48 instanceof Error ? error48.message : String(error48 ?? "")) || "The model call failed.";
|
|
115401
115681
|
const status = typeof last?.provider_status_code === "number" ? last.provider_status_code : error48?.runtimeProviderStatusCode;
|
|
115402
115682
|
const statusCode = typeof status === "number" && Number.isInteger(status) ? status : null;
|
|
@@ -115415,16 +115695,17 @@ function describeModelCallFailure(error48, options = {}) {
|
|
|
115415
115695
|
detail: typeof diagnostic === "string" && diagnostic ? diagnostic : message,
|
|
115416
115696
|
class: failureClass,
|
|
115417
115697
|
// The provider client marks each failed attempt it would retry (a rate
|
|
115418
|
-
// limit, a server error, a 408, a timeout, a dropped connection).
|
|
115419
|
-
|
|
115420
|
-
|
|
115698
|
+
// limit, a server error, a 408, a timeout, a dropped connection). An empty
|
|
115699
|
+
// reply it has already asked again for, up to its own limit.
|
|
115700
|
+
transient: !cancelled && !emptyReply && last?.status === "failed" && last.retryable === true,
|
|
115701
|
+
model_fallback_safe: !cancelled && canAdvanceProfileModel(error48, Boolean(options.external), options.signal, ownAttempts),
|
|
115421
115702
|
outcome_unknown: attempts.some((attempt2) => attempt2.status !== "succeeded" && attempt2.provider_status_code == null && !isNeverSentInvocation(attempt2)) || /outcome.?unknown|dispatch.?unknown/i.test(message),
|
|
115422
115703
|
partial_output: partialOutput,
|
|
115423
115704
|
retry_after_seconds: retryHintSeconds(last, error48),
|
|
115424
115705
|
status_code: statusCode
|
|
115425
115706
|
};
|
|
115426
115707
|
}
|
|
115427
|
-
var FAILURE_CODE_CLASSES, failureAttempts, retryHintSeconds;
|
|
115708
|
+
var FAILURE_CODE_CLASSES, failureAttempts, ownFailureAttempts, failingModelAttempts, retryHintSeconds;
|
|
115428
115709
|
var init_model_call_failure = __esm({
|
|
115429
115710
|
"lib/runtime/model-call-failure.ts"() {
|
|
115430
115711
|
"use strict";
|
|
@@ -115454,6 +115735,12 @@ var init_model_call_failure = __esm({
|
|
|
115454
115735
|
const attempts = error48?.runtimeInvocationAttempts;
|
|
115455
115736
|
return Array.isArray(attempts) ? attempts : [];
|
|
115456
115737
|
};
|
|
115738
|
+
ownFailureAttempts = (error48, ownAttempts) => {
|
|
115739
|
+
if (ownAttempts) return ownAttempts;
|
|
115740
|
+
const attached = error48?.runtimeOwnInvocationAttempts;
|
|
115741
|
+
return Array.isArray(attached) ? attached : void 0;
|
|
115742
|
+
};
|
|
115743
|
+
failingModelAttempts = (error48) => ownFailureAttempts(error48) ?? failureAttempts(error48);
|
|
115457
115744
|
retryHintSeconds = (attempt2, error48) => {
|
|
115458
115745
|
const diagnostics = attempt2?.provider_diagnostics ?? {};
|
|
115459
115746
|
const hints = [
|
|
@@ -115484,7 +115771,8 @@ function serverModelCallFailure(reason, evidence) {
|
|
|
115484
115771
|
}
|
|
115485
115772
|
if (!terminal || terminal.status !== "failed") return null;
|
|
115486
115773
|
const failure2 = describeModelCallFailure(reason);
|
|
115487
|
-
const
|
|
115774
|
+
const ownTerminal = failingModelAttempts(reason).at(-1);
|
|
115775
|
+
const transient = failure2.class !== "out_of_credit" && (failure2.class === "rate_limit" || failure2.class === "provider_unavailable" || failure2.status_code === HTTP_STATUS.TOO_MANY_REQUESTS || ownTerminal !== void 0 && googleEgressUnreachable(ownTerminal));
|
|
115488
115776
|
return {
|
|
115489
115777
|
report: { class: failure2.class, transient },
|
|
115490
115778
|
overloaded: false,
|
|
@@ -115559,7 +115847,7 @@ var init_browser_observability = __esm({
|
|
|
115559
115847
|
init_define_VTX_GROK_POLICY();
|
|
115560
115848
|
init_define_VTX_PI_MODEL_POLICY();
|
|
115561
115849
|
init_runtime_policy_generated2();
|
|
115562
|
-
CLIENT_SOURCE_VERSION = typeof process !== "undefined" && true && "
|
|
115850
|
+
CLIENT_SOURCE_VERSION = typeof process !== "undefined" && true && "513abd7057f4f450bc3739a147e240268030e1f6".trim() && "513abd7057f4f450bc3739a147e240268030e1f6".trim() !== "unstamped" ? "513abd7057f4f450bc3739a147e240268030e1f6".trim() : null;
|
|
115563
115851
|
listenersInstalled = false;
|
|
115564
115852
|
state = {
|
|
115565
115853
|
loadedAtMs: Date.now(),
|
|
@@ -117913,6 +118201,7 @@ var init_copy_trading_execution = __esm({
|
|
|
117913
118201
|
init_hyperliquid_client();
|
|
117914
118202
|
init_runtime_error_reason_rules();
|
|
117915
118203
|
init_runtime_execution();
|
|
118204
|
+
init_abort();
|
|
117916
118205
|
init_runtime_handoff();
|
|
117917
118206
|
_extractOrderResponseStates = (value) => {
|
|
117918
118207
|
if (value == null || typeof value !== "object" || Array.isArray(value)) {
|
|
@@ -117956,7 +118245,7 @@ var init_copy_trading_execution = __esm({
|
|
|
117956
118245
|
};
|
|
117957
118246
|
executeClientCopyTradingIntent = (input) => executeCopyTradingIntent(input, CLIENT_COPY_TRADING_EXECUTION);
|
|
117958
118247
|
executeCopyTradingIntent = async (input, execution) => {
|
|
117959
|
-
|
|
118248
|
+
throwIfAborted(input.signal);
|
|
117960
118249
|
const intent = input.intent;
|
|
117961
118250
|
if (intent.status !== execution.pendingStatus) {
|
|
117962
118251
|
return {
|
|
@@ -118279,7 +118568,7 @@ var init_copy_trading_execution = __esm({
|
|
|
118279
118568
|
};
|
|
118280
118569
|
executeClientCopyTradingOrderAction = (input) => executeCopyTradingOrderAction(input, CLIENT_COPY_TRADING_EXECUTION);
|
|
118281
118570
|
executeCopyTradingOrderAction = async (input, execution) => {
|
|
118282
|
-
|
|
118571
|
+
throwIfAborted(input.signal);
|
|
118283
118572
|
const action = input.action;
|
|
118284
118573
|
if (action.status !== execution.pendingStatus) {
|
|
118285
118574
|
return {
|
|
@@ -119692,6 +119981,201 @@ var init_ai_settings_helpers = __esm({
|
|
|
119692
119981
|
}
|
|
119693
119982
|
});
|
|
119694
119983
|
|
|
119984
|
+
// lib/executionMode.ts
|
|
119985
|
+
var init_executionMode = __esm({
|
|
119986
|
+
"lib/executionMode.ts"() {
|
|
119987
|
+
"use strict";
|
|
119988
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
119989
|
+
init_define_VTX_EXO_POLICY();
|
|
119990
|
+
init_define_VTX_GROK_POLICY();
|
|
119991
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
119992
|
+
}
|
|
119993
|
+
});
|
|
119994
|
+
|
|
119995
|
+
// lib/run-with-concurrency-limit.ts
|
|
119996
|
+
var init_run_with_concurrency_limit = __esm({
|
|
119997
|
+
"lib/run-with-concurrency-limit.ts"() {
|
|
119998
|
+
"use strict";
|
|
119999
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
120000
|
+
init_define_VTX_EXO_POLICY();
|
|
120001
|
+
init_define_VTX_GROK_POLICY();
|
|
120002
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
120003
|
+
}
|
|
120004
|
+
});
|
|
120005
|
+
|
|
120006
|
+
// lib/runtime/client-panel-reads.ts
|
|
120007
|
+
var exchangeCache, SHARED_RESULT_MS, capacityWaitMs, waitForCapacity, infoRead, readInfoRowsWaitingForCapacity, waitingForCapacity, PANEL_PROFILE_CONCURRENCY;
|
|
120008
|
+
var init_client_panel_reads = __esm({
|
|
120009
|
+
"lib/runtime/client-panel-reads.ts"() {
|
|
120010
|
+
"use strict";
|
|
120011
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
120012
|
+
init_define_VTX_EXO_POLICY();
|
|
120013
|
+
init_define_VTX_GROK_POLICY();
|
|
120014
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
120015
|
+
init_api2();
|
|
120016
|
+
init_constants();
|
|
120017
|
+
init_executionMode();
|
|
120018
|
+
init_runtime_policy_generated2();
|
|
120019
|
+
init_hyperliquid_account_state_adapter();
|
|
120020
|
+
init_hyperliquid_client();
|
|
120021
|
+
init_hyperliquid_market_symbol();
|
|
120022
|
+
init_hyperliquid_public_read();
|
|
120023
|
+
init_history_evidence();
|
|
120024
|
+
init_runtime_error_reason_rules();
|
|
120025
|
+
init_run_with_concurrency_limit();
|
|
120026
|
+
exchangeCache = runtime_policy_generated_default2.exchange.cache;
|
|
120027
|
+
SHARED_RESULT_MS = {
|
|
120028
|
+
open_orders: runtime_policy_generated_default2.trading.engine.client_runtime.panel_reads.device_open_orders_reuse_seconds * MS_PER_SECOND,
|
|
120029
|
+
order_history: exchangeCache.order_history_ttl_seconds * MS_PER_SECOND,
|
|
120030
|
+
twap_orders: exchangeCache.twap_history_ttl_seconds * MS_PER_SECOND,
|
|
120031
|
+
twap_fills: exchangeCache.twap_fills_ttl_seconds * MS_PER_SECOND,
|
|
120032
|
+
funding: exchangeCache.funding_history_ttl_seconds * MS_PER_SECOND
|
|
120033
|
+
};
|
|
120034
|
+
capacityWaitMs = (error48) => {
|
|
120035
|
+
if (!isHyperliquidReadRefusal(error48)) return null;
|
|
120036
|
+
const retryAfter = Number(error48.retryAfterMs);
|
|
120037
|
+
return Number.isFinite(retryAfter) && retryAfter > 0 ? retryAfter : runtime_policy_generated_default2.exchange.hyperliquid.public_recovery.queue_poll_ms;
|
|
120038
|
+
};
|
|
120039
|
+
waitForCapacity = (ms, signal) => new Promise((resolve16, reject) => {
|
|
120040
|
+
if (signal?.aborted) {
|
|
120041
|
+
reject(signal.reason);
|
|
120042
|
+
return;
|
|
120043
|
+
}
|
|
120044
|
+
const done = () => {
|
|
120045
|
+
signal?.removeEventListener("abort", aborted2);
|
|
120046
|
+
resolve16();
|
|
120047
|
+
};
|
|
120048
|
+
const timer = setTimeout(done, Math.max(1, ms));
|
|
120049
|
+
const aborted2 = () => {
|
|
120050
|
+
clearTimeout(timer);
|
|
120051
|
+
reject(signal?.reason);
|
|
120052
|
+
};
|
|
120053
|
+
signal?.addEventListener("abort", aborted2, { once: true });
|
|
120054
|
+
});
|
|
120055
|
+
infoRead = async (config2, body, options) => {
|
|
120056
|
+
const payload = await fetchBrowserHyperliquidInfoPayload(
|
|
120057
|
+
{
|
|
120058
|
+
config: config2 ?? void 0,
|
|
120059
|
+
signal: options.signal,
|
|
120060
|
+
publicRequestPriority: options.priority
|
|
120061
|
+
},
|
|
120062
|
+
body,
|
|
120063
|
+
`hyperliquid.${String(body.type)}`
|
|
120064
|
+
);
|
|
120065
|
+
if (!Array.isArray(payload)) throw new Error(`Malformed Hyperliquid ${String(body.type)} response.`);
|
|
120066
|
+
return payload;
|
|
120067
|
+
};
|
|
120068
|
+
readInfoRowsWaitingForCapacity = (config2, body, options) => waitingForCapacity(() => infoRead(config2, body, options), options.signal);
|
|
120069
|
+
waitingForCapacity = async (read, signal) => {
|
|
120070
|
+
const deadlineMs = Date.now() + runtime_policy_generated_default2.trading.history_reads.device_read_deadline_seconds * MS_PER_SECOND;
|
|
120071
|
+
for (; ; ) {
|
|
120072
|
+
try {
|
|
120073
|
+
return await read();
|
|
120074
|
+
} catch (error48) {
|
|
120075
|
+
const waitMs = capacityWaitMs(error48);
|
|
120076
|
+
const remaining = deadlineMs - Date.now();
|
|
120077
|
+
if (waitMs === null || remaining <= 0) throw error48;
|
|
120078
|
+
await waitForCapacity(Math.min(waitMs, remaining), signal);
|
|
120079
|
+
}
|
|
120080
|
+
}
|
|
120081
|
+
};
|
|
120082
|
+
PANEL_PROFILE_CONCURRENCY = runtime_policy_generated_default2.trading.engine.client_runtime.panel_reads.all_view_profile_concurrency;
|
|
120083
|
+
}
|
|
120084
|
+
});
|
|
120085
|
+
|
|
120086
|
+
// lib/runtime/hyperliquid-candle-reads.ts
|
|
120087
|
+
var decimalText, readHyperliquidCandles;
|
|
120088
|
+
var init_hyperliquid_candle_reads = __esm({
|
|
120089
|
+
"lib/runtime/hyperliquid-candle-reads.ts"() {
|
|
120090
|
+
"use strict";
|
|
120091
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
120092
|
+
init_define_VTX_EXO_POLICY();
|
|
120093
|
+
init_define_VTX_GROK_POLICY();
|
|
120094
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
120095
|
+
init_constants();
|
|
120096
|
+
init_client_panel_reads();
|
|
120097
|
+
init_runtime_error_reason_rules();
|
|
120098
|
+
decimalText = (value) => {
|
|
120099
|
+
if (typeof value === "number") return Number.isFinite(value) ? String(value) : null;
|
|
120100
|
+
return typeof value === "string" && value.trim() !== "" && Number.isFinite(Number(value)) ? value.trim() : null;
|
|
120101
|
+
};
|
|
120102
|
+
readHyperliquidCandles = async (config2, request, options) => {
|
|
120103
|
+
const seconds = CANDLE_TIMEFRAME_SECONDS[request.timeframe];
|
|
120104
|
+
if (!seconds || !request.symbol.trim()) {
|
|
120105
|
+
throw new RuntimeReasonError("A candle read needs a market symbol and a supported timeframe.", "internal_data_error");
|
|
120106
|
+
}
|
|
120107
|
+
const intervalMs = seconds * MS_PER_SECOND;
|
|
120108
|
+
const byOpen = /* @__PURE__ */ new Map();
|
|
120109
|
+
for (const range of request.ranges) {
|
|
120110
|
+
for (let pieceStart = range.startMs; pieceStart <= range.endMs; ) {
|
|
120111
|
+
const pieceEnd = Math.min(range.endMs, pieceStart + (HYPERLIQUID_CANDLE_SNAPSHOT_MAX_ROWS - 1) * intervalMs);
|
|
120112
|
+
options.signal?.throwIfAborted();
|
|
120113
|
+
const rows = await readInfoRowsWaitingForCapacity(config2, {
|
|
120114
|
+
type: "candleSnapshot",
|
|
120115
|
+
req: { coin: request.symbol, interval: request.timeframe, startTime: pieceStart, endTime: pieceEnd }
|
|
120116
|
+
}, options);
|
|
120117
|
+
for (const row of rows) {
|
|
120118
|
+
const candle = row && typeof row === "object" ? row : null;
|
|
120119
|
+
const opened = Number(candle?.t);
|
|
120120
|
+
const ohlcv = ["o", "h", "l", "c", "v"].map((key) => decimalText(candle?.[key]));
|
|
120121
|
+
if (!candle || !Number.isSafeInteger(opened) || ohlcv.some((value) => value === null)) {
|
|
120122
|
+
throw new RuntimeReasonError("Hyperliquid returned a malformed candle.", "hyperliquid_data_unavailable");
|
|
120123
|
+
}
|
|
120124
|
+
if (opened < pieceStart || opened > pieceEnd || opened % intervalMs !== 0) continue;
|
|
120125
|
+
const [o, h, l, c, v] = ohlcv;
|
|
120126
|
+
byOpen.set(opened, { t: opened, o, h, l, c, v });
|
|
120127
|
+
}
|
|
120128
|
+
pieceStart = pieceEnd + intervalMs;
|
|
120129
|
+
}
|
|
120130
|
+
}
|
|
120131
|
+
return [...byOpen.values()].sort((left, right) => left.t - right.t);
|
|
120132
|
+
};
|
|
120133
|
+
}
|
|
120134
|
+
});
|
|
120135
|
+
|
|
120136
|
+
// lib/runtime/client-recent-candles.ts
|
|
120137
|
+
var routeTimestamp, routeCandle, mergeDeviceCandles, readRuntimeRecentCandles;
|
|
120138
|
+
var init_client_recent_candles = __esm({
|
|
120139
|
+
"lib/runtime/client-recent-candles.ts"() {
|
|
120140
|
+
"use strict";
|
|
120141
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
120142
|
+
init_define_VTX_EXO_POLICY();
|
|
120143
|
+
init_define_VTX_GROK_POLICY();
|
|
120144
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
120145
|
+
init_api2();
|
|
120146
|
+
init_constants();
|
|
120147
|
+
init_hyperliquid_candle_reads();
|
|
120148
|
+
routeTimestamp = (openMs2) => new Date(Math.floor(openMs2 / MS_PER_SECOND) * MS_PER_SECOND).toISOString().replace(/\.\d{3}Z$/, "Z");
|
|
120149
|
+
routeCandle = (row, series) => ({
|
|
120150
|
+
...series,
|
|
120151
|
+
timestamp: routeTimestamp(row.t),
|
|
120152
|
+
open: row.o,
|
|
120153
|
+
high: row.h,
|
|
120154
|
+
low: row.l,
|
|
120155
|
+
close: row.c,
|
|
120156
|
+
volume: row.v
|
|
120157
|
+
});
|
|
120158
|
+
mergeDeviceCandles = (stored, rows, series) => {
|
|
120159
|
+
const { limit, ...market } = series;
|
|
120160
|
+
const byOpen = /* @__PURE__ */ new Map();
|
|
120161
|
+
for (const candle of stored) byOpen.set(Date.parse(candle.timestamp), candle);
|
|
120162
|
+
for (const row of rows) byOpen.set(row.t, routeCandle(row, market));
|
|
120163
|
+
return [...byOpen.entries()].filter(([openMs2]) => Number.isFinite(openMs2)).sort(([left], [right]) => right - left).slice(0, limit).map(([, candle]) => candle);
|
|
120164
|
+
};
|
|
120165
|
+
readRuntimeRecentCandles = async (limit, exchange, symbol2, timeframe, signal, context) => {
|
|
120166
|
+
if (!context) return getRecentCandles(limit, exchange, symbol2, timeframe, signal);
|
|
120167
|
+
const { candles, missing: missing2 } = await getRecentCandlesForProfile(context.profileId, limit, exchange, symbol2, timeframe, signal);
|
|
120168
|
+
if (missing2 === null) return candles;
|
|
120169
|
+
const rows = await readHyperliquidCandles(await context.deviceConfig(), {
|
|
120170
|
+
symbol: symbol2,
|
|
120171
|
+
timeframe,
|
|
120172
|
+
ranges: [missing2]
|
|
120173
|
+
}, { priority: context.priority, signal });
|
|
120174
|
+
return mergeDeviceCandles(candles, rows, { exchange, symbol: symbol2, timeframe, limit });
|
|
120175
|
+
};
|
|
120176
|
+
}
|
|
120177
|
+
});
|
|
120178
|
+
|
|
119695
120179
|
// lib/runtime/candle-prompt-contract.ts
|
|
119696
120180
|
var AI_INDICATOR_ROW_COLUMNS, AI_INDICATOR_KEYS, EMA_INDICATOR_KEYS, CANDLE_BASE_ROW_COLUMNS, candlesRowColumns, projectCandlePromptComponent, readCandleNumber, closedCandleCount, calculateRelativeVolumeSeries;
|
|
119697
120181
|
var init_candle_prompt_contract = __esm({
|
|
@@ -121931,6 +122415,29 @@ var init_server_host_prompt_rescue = __esm({
|
|
|
121931
122415
|
}
|
|
121932
122416
|
});
|
|
121933
122417
|
|
|
122418
|
+
// lib/api/inference-pacing.ts
|
|
122419
|
+
async function reserveClientRuntimeInferencePacing(profileId, payload, options) {
|
|
122420
|
+
return postClientRuntime(
|
|
122421
|
+
"/runtime/inference-pacing",
|
|
122422
|
+
profileId,
|
|
122423
|
+
buildClientRuntimeBody(payload, {
|
|
122424
|
+
analysis_run_id: payload.analysisRunId,
|
|
122425
|
+
cycle_id: payload.cycleId
|
|
122426
|
+
}, { includeForceTakeover: false }),
|
|
122427
|
+
options
|
|
122428
|
+
);
|
|
122429
|
+
}
|
|
122430
|
+
var init_inference_pacing = __esm({
|
|
122431
|
+
"lib/api/inference-pacing.ts"() {
|
|
122432
|
+
"use strict";
|
|
122433
|
+
init_define_VTX_CLAUDE_CODE_POLICY();
|
|
122434
|
+
init_define_VTX_EXO_POLICY();
|
|
122435
|
+
init_define_VTX_GROK_POLICY();
|
|
122436
|
+
init_define_VTX_PI_MODEL_POLICY();
|
|
122437
|
+
init_api2();
|
|
122438
|
+
}
|
|
122439
|
+
});
|
|
122440
|
+
|
|
121934
122441
|
// lib/runtime/server-prompt-rescue-snapshot.ts
|
|
121935
122442
|
var accountStateFromServerPromptRescueSnapshot;
|
|
121936
122443
|
var init_server_prompt_rescue_snapshot = __esm({
|
|
@@ -122417,7 +122924,7 @@ var init_provider_client = __esm({
|
|
|
122417
122924
|
emptyProviderContentError = (message, reply) => Object.assign(new Error(message), {
|
|
122418
122925
|
runtimeEmptyProviderContent: true,
|
|
122419
122926
|
// Kept for the in-place retry's own row only (Venice): a model's final
|
|
122420
|
-
// empty reply is recorded with no result and never priced
|
|
122927
|
+
// empty reply is recorded with no result and never priced.
|
|
122421
122928
|
...reply ? { runtimeEmptyProviderReply: reply.result, runtimeEmptyProviderMessage: reply.emptyMessage } : {}
|
|
122422
122929
|
});
|
|
122423
122930
|
isEmptyProviderContentFailure = (error48) => error48?.runtimeEmptyProviderContent === true;
|
|
@@ -123826,7 +124333,7 @@ var init_provider_client = __esm({
|
|
|
123826
124333
|
providerDiagnostics: marker2.providerDiagnostics,
|
|
123827
124334
|
providerRequestId: providerRequestId(response),
|
|
123828
124335
|
errorDetail: getSanitizedRuntimeErrorMessage(error48) || "Provider compatibility dispatch failed.",
|
|
123829
|
-
// An empty reply is an unknown outcome with no status
|
|
124336
|
+
// An empty reply is an unknown outcome with no status.
|
|
123830
124337
|
statusCode: isEmptyProviderContentFailure(error48) ? null : response?.status ?? null,
|
|
123831
124338
|
retryable: isEmptyProviderContentFailure(error48),
|
|
123832
124339
|
response: emptyReplyForInternalAttempt(error48)
|
|
@@ -124607,6 +125114,7 @@ var init_provider_client = __esm({
|
|
|
124607
125114
|
const normalized = detail.toLowerCase();
|
|
124608
125115
|
if (isProviderOutOfCreditText(detail) || isProviderOutOfCreditReply(statusCode, "")) return PROVIDER_OUT_OF_CREDIT_FAILURE_CODE;
|
|
124609
125116
|
if (statusCode === HTTP_STATUS.TOO_MANY_REQUESTS) return "rate_limit";
|
|
125117
|
+
if (isProviderServerErrorStatus(statusCode)) return "provider_error";
|
|
124610
125118
|
if (statusCode === HTTP_STATUS.UNAUTHORIZED || statusCode === HTTP_STATUS.FORBIDDEN || normalized.includes("unauthorized") || normalized.includes("forbidden")) {
|
|
124611
125119
|
return "authorization";
|
|
124612
125120
|
}
|
|
@@ -126765,8 +127273,8 @@ var init_ai_schedule = __esm({
|
|
|
126765
127273
|
function createRecentCandleSeries(read, now = Date.now) {
|
|
126766
127274
|
const held = /* @__PURE__ */ new Map();
|
|
126767
127275
|
const copy4 = (candles) => candles.map((candle) => ({ ...candle }));
|
|
126768
|
-
const readWhole = async (key, limit, exchange, symbol2, timeframe, stepMs, signal) => {
|
|
126769
|
-
const candles = await read(limit, exchange, symbol2, timeframe, signal);
|
|
127276
|
+
const readWhole = async (key, limit, exchange, symbol2, timeframe, stepMs, signal, context) => {
|
|
127277
|
+
const candles = await read(limit, exchange, symbol2, timeframe, signal, context);
|
|
126770
127278
|
if (stepMs != null && candles.length > 0 && contiguous(candles, stepMs)) {
|
|
126771
127279
|
held.set(key, { candles: copy4(candles), fullReadAtMs: now() });
|
|
126772
127280
|
} else {
|
|
@@ -126774,7 +127282,7 @@ function createRecentCandleSeries(read, now = Date.now) {
|
|
|
126774
127282
|
}
|
|
126775
127283
|
return candles;
|
|
126776
127284
|
};
|
|
126777
|
-
const recentCandles = async (limit, exchange, symbol2, timeframe, signal) => {
|
|
127285
|
+
const recentCandles = async (limit, exchange, symbol2, timeframe, signal, context) => {
|
|
126778
127286
|
for (const [heldKey, entry] of held) {
|
|
126779
127287
|
if (now() - entry.fullReadAtMs >= FULL_REFRESH_MS) held.delete(heldKey);
|
|
126780
127288
|
}
|
|
@@ -126783,18 +127291,18 @@ function createRecentCandleSeries(read, now = Date.now) {
|
|
|
126783
127291
|
const stepMs = seconds == null ? null : seconds * MS_PER_SECOND;
|
|
126784
127292
|
const kept = held.get(key);
|
|
126785
127293
|
if (stepMs == null || !kept || now() - kept.fullReadAtMs >= FULL_REFRESH_MS) {
|
|
126786
|
-
return readWhole(key, limit, exchange, symbol2, timeframe, stepMs, signal);
|
|
127294
|
+
return readWhole(key, limit, exchange, symbol2, timeframe, stepMs, signal, context);
|
|
126787
127295
|
}
|
|
126788
127296
|
const newestHeldMs = openMs(kept.candles[0]);
|
|
126789
127297
|
const newCount = Math.max(0, Math.floor((now() - newestHeldMs) / stepMs));
|
|
126790
127298
|
const deltaLimit = newCount + OVERLAP_CANDLES;
|
|
126791
127299
|
if (newCount > DELTA_MAX_CANDLES || deltaLimit >= limit) {
|
|
126792
|
-
return readWhole(key, limit, exchange, symbol2, timeframe, stepMs, signal);
|
|
127300
|
+
return readWhole(key, limit, exchange, symbol2, timeframe, stepMs, signal, context);
|
|
126793
127301
|
}
|
|
126794
|
-
const newest = await read(deltaLimit, exchange, symbol2, timeframe, signal);
|
|
127302
|
+
const newest = await read(deltaLimit, exchange, symbol2, timeframe, signal, context);
|
|
126795
127303
|
const oldestNewMs = newest.length > 0 ? openMs(newest[newest.length - 1]) : Number.NaN;
|
|
126796
127304
|
if (newest.length === 0 || !contiguous(newest, stepMs) || !Number.isFinite(oldestNewMs) || oldestNewMs > newestHeldMs) {
|
|
126797
|
-
return readWhole(key, limit, exchange, symbol2, timeframe, stepMs, signal);
|
|
127305
|
+
return readWhole(key, limit, exchange, symbol2, timeframe, stepMs, signal, context);
|
|
126798
127306
|
}
|
|
126799
127307
|
const heldByOpen = new Map(kept.candles.slice(1).map((candle) => [candle.timestamp, candle]));
|
|
126800
127308
|
const overlapChanged = newest.some((candle) => {
|
|
@@ -126802,11 +127310,11 @@ function createRecentCandleSeries(read, now = Date.now) {
|
|
|
126802
127310
|
return before != null && (before.open !== candle.open || before.high !== candle.high || before.low !== candle.low || before.close !== candle.close || before.volume !== candle.volume);
|
|
126803
127311
|
});
|
|
126804
127312
|
if (overlapChanged) {
|
|
126805
|
-
return readWhole(key, limit, exchange, symbol2, timeframe, stepMs, signal);
|
|
127313
|
+
return readWhole(key, limit, exchange, symbol2, timeframe, stepMs, signal, context);
|
|
126806
127314
|
}
|
|
126807
127315
|
const merged = [...copy4(newest), ...kept.candles.filter((candle) => openMs(candle) < oldestNewMs)].slice(0, limit);
|
|
126808
127316
|
if (!contiguous(merged, stepMs)) {
|
|
126809
|
-
return readWhole(key, limit, exchange, symbol2, timeframe, stepMs, signal);
|
|
127317
|
+
return readWhole(key, limit, exchange, symbol2, timeframe, stepMs, signal, context);
|
|
126810
127318
|
}
|
|
126811
127319
|
held.set(key, { candles: merged, fullReadAtMs: kept.fullReadAtMs });
|
|
126812
127320
|
return copy4(merged);
|
|
@@ -126857,6 +127365,7 @@ __export(local_analysis_exports, {
|
|
|
126857
127365
|
buildServerBehaviorStateArtifacts: () => buildServerBehaviorStateArtifacts,
|
|
126858
127366
|
capacityUnitSize: () => capacityUnitSize,
|
|
126859
127367
|
currentModelOutputJsonText: () => currentModelOutputJsonText,
|
|
127368
|
+
currentModelOutputMatchesContract: () => currentModelOutputMatchesContract,
|
|
126860
127369
|
derivePromptVisibleSections: () => derivePromptVisibleSections,
|
|
126861
127370
|
formatReviewUserPrompt: () => formatReviewUserPrompt,
|
|
126862
127371
|
isClientRuntimeAgentInstructionEmpty: () => isClientRuntimeAgentInstructionEmpty,
|
|
@@ -126892,6 +127401,7 @@ var init_local_analysis = __esm({
|
|
|
126892
127401
|
init_profile_model_fallbacks();
|
|
126893
127402
|
init_api2();
|
|
126894
127403
|
init_ai_settings_helpers();
|
|
127404
|
+
init_client_recent_candles();
|
|
126895
127405
|
init_candle_timeframes();
|
|
126896
127406
|
init_candle_prompt_contract();
|
|
126897
127407
|
init_prompt_candles();
|
|
@@ -126904,6 +127414,7 @@ var init_local_analysis = __esm({
|
|
|
126904
127414
|
init_client_account_report();
|
|
126905
127415
|
init_hyperliquid_public_read();
|
|
126906
127416
|
init_server_host_prompt_rescue();
|
|
127417
|
+
init_inference_pacing();
|
|
126907
127418
|
init_server_prompt_rescue_snapshot();
|
|
126908
127419
|
init_network_debug();
|
|
126909
127420
|
init_abort();
|
|
@@ -126931,7 +127442,7 @@ var init_local_analysis = __esm({
|
|
|
126931
127442
|
init_recent_candle_series();
|
|
126932
127443
|
init_runtime_policy_generated2();
|
|
126933
127444
|
init_constants();
|
|
126934
|
-
cycleCandles = createRecentCandleSeries(
|
|
127445
|
+
cycleCandles = createRecentCandleSeries(readRuntimeRecentCandles);
|
|
126935
127446
|
CYCLE_TIMEOUT_FLOOR_MS = runtime_policy_generated_default2.trading.engine.client_runtime.cycle_timeout_floor_milliseconds;
|
|
126936
127447
|
DECISION_SETTLEMENT_RESERVE_MAX_BUDGET_DIVISOR = runtime_policy_generated_default2.trading.engine.client_runtime.decision_settlement_reserve_max_budget_divisor;
|
|
126937
127448
|
MIN_AGENT_INSTRUCTION_RETRY_AFTER_MS = runtime_policy_generated_default2.trading.engine.client_runtime.request_bounds.min_agent_instruction_retry_after_ms;
|
|
@@ -127538,9 +128049,9 @@ var init_local_analysis = __esm({
|
|
|
127538
128049
|
RUNTIME_SOURCE_DEFINITION_VERSION = "runtime-source-v1";
|
|
127539
128050
|
DECISION_INPUT_DEFINITION_VERSION = "decision-input-v1";
|
|
127540
128051
|
CONTEXT_ENVELOPE_DEFINITION_VERSION = "context-envelope-v2.1";
|
|
127541
|
-
CLIENT_RUNTIME_SOURCE_VERSION = typeof process !== "undefined" && true && "
|
|
127542
|
-
"
|
|
127543
|
-
) ? "
|
|
128052
|
+
CLIENT_RUNTIME_SOURCE_VERSION = typeof process !== "undefined" && true && "513abd7057f4f450bc3739a147e240268030e1f6".trim() && !["unknown", "unstamped", "development"].includes(
|
|
128053
|
+
"513abd7057f4f450bc3739a147e240268030e1f6".trim().toLowerCase()
|
|
128054
|
+
) ? "513abd7057f4f450bc3739a147e240268030e1f6".trim() : null;
|
|
127544
128055
|
CLIENT_MAIN_PROMPT_RENDERER = "client_runtime.buildLocalRuntimePromptArtifacts:v1";
|
|
127545
128056
|
CLIENT_REVIEW_PROMPT_RENDERER = "client_runtime.review_prompt_assembly:v1";
|
|
127546
128057
|
resolveEffectivePromptRuntimeProvenance = (input) => ({
|
|
@@ -130812,6 +131323,20 @@ ${stringifyPromptJson(parts.candlesPayload)}
|
|
|
130812
131323
|
if (input.mode === "trader" && initialPromptMetadata?.main_model_enabled === false) {
|
|
130813
131324
|
return buildMainModelDisabledResult(initialPromptMetadata);
|
|
130814
131325
|
}
|
|
131326
|
+
const pacedMainController = liveModelControllerSchema.safeParse(settings.main_model_controller);
|
|
131327
|
+
if (pacedMainController.success && pacedMainController.data.kind === "external_agent") {
|
|
131328
|
+
await reserveClientRuntimeInferencePacing(profileId, {
|
|
131329
|
+
sessionId,
|
|
131330
|
+
deviceId,
|
|
131331
|
+
schedulerInstanceId: String(input.schedulerInstanceId || "").trim(),
|
|
131332
|
+
mode: input.mode,
|
|
131333
|
+
analysisRunId: input.analysisRunId ?? cycleId,
|
|
131334
|
+
cycleId
|
|
131335
|
+
}, {
|
|
131336
|
+
schedulerInstanceId: String(input.schedulerInstanceId || "").trim(),
|
|
131337
|
+
signal: timeoutController.signal
|
|
131338
|
+
});
|
|
131339
|
+
}
|
|
130815
131340
|
appendRuntimeDebugEvent({
|
|
130816
131341
|
label: "analysis_input",
|
|
130817
131342
|
note: `symbol=${localFallbackSymbol} timeframe=${localFallbackTimeframe} wallet=${walletAddress ? "present" : "missing"}`
|
|
@@ -131016,7 +131541,10 @@ ${stringifyPromptJson(parts.candlesPayload)}
|
|
|
131016
131541
|
"hyperliquid",
|
|
131017
131542
|
marketSymbol,
|
|
131018
131543
|
marketTimeframe,
|
|
131019
|
-
timeoutController.signal
|
|
131544
|
+
timeoutController.signal,
|
|
131545
|
+
// VTX's servers read Hyperliquid only for a Server Mode bot: a
|
|
131546
|
+
// Client Mode bot's candles are stored ones, completed here.
|
|
131547
|
+
input.executionMode === "server" ? void 0 : { profileId, deviceConfig: () => config2, priority: "trading_analysis" }
|
|
131020
131548
|
)
|
|
131021
131549
|
])
|
|
131022
131550
|
)
|
|
@@ -132804,7 +133332,7 @@ ${stringifyPromptJson(parts.candlesPayload)}
|
|
|
132804
133332
|
});
|
|
132805
133333
|
|
|
132806
133334
|
// lib/runtime/engine.ts
|
|
132807
|
-
var
|
|
133335
|
+
var DEVICE_DIAGNOSTICS4, FALLBACK_ERROR_MAX_CHARS, localAnalysis, getExchangeFailureDiagnostics, getRuntimeFallbackAttempts, sentInvocationAttemptCount, boundRuntimeFallbackAttempts, isProviderFailureDiagnosticsCandidate, getEventBoundProviderLabel, getEventBoundProviderTraceId, CLIENT_RUNTIME_POLICY, getRecentProviderFailureDiagnostics, getClientRuntimeErrorProvenance, getRuntimeProviderSetupDiagnostics, buildProviderSetupErrorDiagnosticFields, buildClientRuntimeErrorProvenanceDiagnosticFields, getCycleErrorModelCalls, isReturnedModelCall, hasEventBoundProviderFailureEvidence, endsWithNeverSentAttempt, classifyRuntimeErrorStage, buildRuntimeErrorDiagnostics, positiveNumber, resolveRuntimeEngineOptions, withServerPositionEvents, CLIENT_KILLSWITCH_BLOCK_STORAGE_PREFIX, getClientKillswitchBlockStorageKey, isClientRuntimeKillswitchBlocked, persistClientRuntimeKillswitchBlock, clearClientRuntimeKillswitchBlock, hashRuntimeDebugText2, createRuntimeUuid2, getRuntimeContractIdentityToken, getRuntimeStatusContractIdentityToken, getRuntimeContractBindingTokenFromCycleResult, getRuntimeContractBindingTupleToken, getRuntimeStatusContractBindingTupleToken, isTransientRuntimeConflictError, createRuntimeStartCancelledError, isRuntimeContractMismatchError, isClientExecutionModeMismatchError, isClientRuntimeSessionStoppedError, isClientRuntimeLeaseAuthError, isClientRuntimeReleasedError, deriveFailedStartCleanupOwnershipLossReason, isRuntimeAbortError, isExplicitClientExecutionMode, createStopAbortError, isRuntimeContractIdentityAdvancedAbort, CLIENT_RUNTIME_NO_DECISION_RECOVERY_REASON, CLIENT_RUNTIME_NO_DECISION_MESSAGE, sanitizeSettingsSnapshotForFallback, preflightClientRuntime, onCadenceGridPoint, ClientExecutionEngine, createStoppedRuntimeSnapshot, ClientRuntimeRegistry, botEngine;
|
|
132808
133336
|
var init_engine = __esm({
|
|
132809
133337
|
"lib/runtime/engine.ts"() {
|
|
132810
133338
|
"use strict";
|
|
@@ -132816,6 +133344,7 @@ var init_engine = __esm({
|
|
|
132816
133344
|
init_hyperliquid_public_read();
|
|
132817
133345
|
init_runtime_policy_generated2();
|
|
132818
133346
|
init_constants();
|
|
133347
|
+
init_runtime_error_diagnostic_fields();
|
|
132819
133348
|
init_periodic_schedule();
|
|
132820
133349
|
init_host_storage();
|
|
132821
133350
|
init_vault();
|
|
@@ -132857,7 +133386,7 @@ var init_engine = __esm({
|
|
|
132857
133386
|
init_runtime_error_reason_rules();
|
|
132858
133387
|
init_host_wake_schedule();
|
|
132859
133388
|
init_copy_trading_evidence();
|
|
132860
|
-
|
|
133389
|
+
DEVICE_DIAGNOSTICS4 = runtime_policy_generated_default2.trading.engine.client_runtime.device_diagnostics;
|
|
132861
133390
|
FALLBACK_ERROR_MAX_CHARS = runtime_policy_generated_default2.trading.engine.client_runtime.request_bounds.max_fallback_error_length;
|
|
132862
133391
|
getExchangeFailureDiagnostics = (error48) => {
|
|
132863
133392
|
if (error48 instanceof HyperliquidExchangeRejectionError) {
|
|
@@ -132871,7 +133400,7 @@ var init_engine = __esm({
|
|
|
132871
133400
|
let attempts = null;
|
|
132872
133401
|
let current = error48;
|
|
132873
133402
|
const seen = /* @__PURE__ */ new Set();
|
|
132874
|
-
for (let depth = 0; depth <
|
|
133403
|
+
for (let depth = 0; depth < DEVICE_DIAGNOSTICS4.error_cause_max_depth && current && typeof current === "object" && !seen.has(current); depth += 1) {
|
|
132875
133404
|
seen.add(current);
|
|
132876
133405
|
const candidate = current.runtimeFallbackAttempts;
|
|
132877
133406
|
if (Array.isArray(candidate)) {
|
|
@@ -132956,7 +133485,7 @@ var init_engine = __esm({
|
|
|
132956
133485
|
getEventBoundProviderTraceId = (reason) => {
|
|
132957
133486
|
let current = reason;
|
|
132958
133487
|
const seen = /* @__PURE__ */ new Set();
|
|
132959
|
-
for (let depth = 0; depth <
|
|
133488
|
+
for (let depth = 0; depth < DEVICE_DIAGNOSTICS4.error_cause_max_depth; depth += 1) {
|
|
132960
133489
|
if (!current || typeof current !== "object" && typeof current !== "function" || seen.has(current)) {
|
|
132961
133490
|
return null;
|
|
132962
133491
|
}
|
|
@@ -132993,7 +133522,7 @@ var init_engine = __esm({
|
|
|
132993
133522
|
getClientRuntimeErrorProvenance = (reason) => {
|
|
132994
133523
|
let current = reason;
|
|
132995
133524
|
const seen = /* @__PURE__ */ new Set();
|
|
132996
|
-
for (let depth = 0; depth <
|
|
133525
|
+
for (let depth = 0; depth < DEVICE_DIAGNOSTICS4.error_cause_max_depth; depth += 1) {
|
|
132997
133526
|
if (!current || typeof current !== "object" && typeof current !== "function" || seen.has(current)) {
|
|
132998
133527
|
return null;
|
|
132999
133528
|
}
|
|
@@ -133060,50 +133589,6 @@ var init_engine = __esm({
|
|
|
133060
133589
|
error_provenance_model_source: provenance.modelSource
|
|
133061
133590
|
};
|
|
133062
133591
|
};
|
|
133063
|
-
buildRuntimeRequestErrorDiagnosticFields = (reason) => {
|
|
133064
|
-
if (!reason || typeof reason !== "object" && typeof reason !== "function") {
|
|
133065
|
-
return {};
|
|
133066
|
-
}
|
|
133067
|
-
const record6 = reason;
|
|
133068
|
-
const path = sanitizeRuntimeDiagnosticValue(String(record6.runtimeRequestPath || "")).trim();
|
|
133069
|
-
if (!path) {
|
|
133070
|
-
return {};
|
|
133071
|
-
}
|
|
133072
|
-
const numberOrNull = (value) => {
|
|
133073
|
-
if (value === null || value === void 0 || value === "") {
|
|
133074
|
-
return null;
|
|
133075
|
-
}
|
|
133076
|
-
const parsed = Number(value);
|
|
133077
|
-
return Number.isFinite(parsed) ? parsed : null;
|
|
133078
|
-
};
|
|
133079
|
-
return {
|
|
133080
|
-
runtime_request_path: path.slice(0, DEVICE_DIAGNOSTICS3.request_path_chars),
|
|
133081
|
-
runtime_request_method: sanitizeRuntimeDiagnosticValue(String(record6.runtimeRequestMethod || "")).slice(0, DEVICE_DIAGNOSTICS3.request_method_chars) || null,
|
|
133082
|
-
runtime_request_attempt: numberOrNull(record6.runtimeRequestAttempt),
|
|
133083
|
-
runtime_request_max_attempts: numberOrNull(record6.runtimeRequestMaxAttempts),
|
|
133084
|
-
runtime_request_status: numberOrNull(record6.runtimeRequestStatus),
|
|
133085
|
-
runtime_request_error_kind: sanitizeRuntimeDiagnosticValue(String(record6.runtimeRequestErrorKind || "")).slice(0, DEVICE_DIAGNOSTICS3.error_kind_chars) || null,
|
|
133086
|
-
runtime_request_transient_network: record6.runtimeRequestTransientNetwork === true,
|
|
133087
|
-
runtime_request_deadline_at_ms: numberOrNull(record6.runtimeRequestDeadlineAtMs),
|
|
133088
|
-
runtime_request_deadline_exceeded: record6.runtimeRequestDeadlineExceeded === true,
|
|
133089
|
-
...record6.code === "snapshot_stale" && record6.runtimeRequestStatus === HTTP_STATUS.CONFLICT ? {
|
|
133090
|
-
runtime_rejection_reason_code: "snapshot_stale",
|
|
133091
|
-
snapshot_age_seconds: numberOrNull(record6.runtimeSnapshotAgeSeconds),
|
|
133092
|
-
snapshot_max_age_seconds: numberOrNull(record6.runtimeSnapshotMaxAgeSeconds)
|
|
133093
|
-
} : {},
|
|
133094
|
-
...record6.runtimeRequestId ? {
|
|
133095
|
-
runtime_request_id: sanitizeRuntimeDiagnosticValue(String(record6.runtimeRequestId)).slice(0, DEVICE_DIAGNOSTICS3.request_id_chars)
|
|
133096
|
-
} : {},
|
|
133097
|
-
...record6.runtimeReconciliationAttempted === true ? {
|
|
133098
|
-
runtime_reconciliation_attempted: true,
|
|
133099
|
-
runtime_reconciliation_elapsed_ms: numberOrNull(record6.runtimeReconciliationElapsedMs),
|
|
133100
|
-
runtime_reconciliation_status: numberOrNull(record6.runtimeReconciliationStatus),
|
|
133101
|
-
runtime_reconciliation_error_kind: sanitizeRuntimeDiagnosticValue(String(record6.runtimeReconciliationErrorKind || "")).slice(0, DEVICE_DIAGNOSTICS3.error_kind_chars) || null,
|
|
133102
|
-
runtime_reconciliation_deadline_exceeded: record6.runtimeReconciliationDeadlineExceeded === true,
|
|
133103
|
-
runtime_reconciliation_request_id: sanitizeRuntimeDiagnosticValue(String(record6.runtimeReconciliationRequestId || "")).slice(0, DEVICE_DIAGNOSTICS3.request_id_chars) || null
|
|
133104
|
-
} : {}
|
|
133105
|
-
};
|
|
133106
|
-
};
|
|
133107
133592
|
getCycleErrorModelCalls = (reason) => {
|
|
133108
133593
|
if (!reason || typeof reason !== "object" && typeof reason !== "function") return [];
|
|
133109
133594
|
const record6 = reason;
|
|
@@ -133165,33 +133650,6 @@ var init_engine = __esm({
|
|
|
133165
133650
|
}
|
|
133166
133651
|
return "runtime";
|
|
133167
133652
|
};
|
|
133168
|
-
buildHyperliquidPublicReadDiagnosticFields = (reason) => {
|
|
133169
|
-
let current = reason;
|
|
133170
|
-
const seen = /* @__PURE__ */ new Set();
|
|
133171
|
-
for (let depth = 0; depth < DEVICE_DIAGNOSTICS3.error_cause_max_depth; depth += 1) {
|
|
133172
|
-
if (!current || typeof current !== "object" || seen.has(current)) return {};
|
|
133173
|
-
seen.add(current);
|
|
133174
|
-
const record6 = current;
|
|
133175
|
-
if (record6.name === "HyperliquidPublicReadError" && [
|
|
133176
|
-
"public_budget_exhausted",
|
|
133177
|
-
"public_recovery_wait",
|
|
133178
|
-
"public_cooldown_active",
|
|
133179
|
-
"public_rate_limited",
|
|
133180
|
-
"public_network_error",
|
|
133181
|
-
"public_timeout"
|
|
133182
|
-
].includes(String(record6.code))) {
|
|
133183
|
-
const finiteNonnegative = (value) => typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= Number.MAX_SAFE_INTEGER ? value : null;
|
|
133184
|
-
return {
|
|
133185
|
-
hl_public_read_code: record6.code,
|
|
133186
|
-
hl_public_read_request_type: typeof record6.requestType === "string" ? sanitizeRuntimeDiagnosticValue(record6.requestType).slice(0, CLIENT_RUNTIME_HL_REQUEST_TYPE_MAX_CHARS) : null,
|
|
133187
|
-
hl_public_read_status: finiteNonnegative(record6.status),
|
|
133188
|
-
hl_public_read_retry_after_ms: finiteNonnegative(record6.retryAfterMs)
|
|
133189
|
-
};
|
|
133190
|
-
}
|
|
133191
|
-
current = record6.cause;
|
|
133192
|
-
}
|
|
133193
|
-
return {};
|
|
133194
|
-
};
|
|
133195
133653
|
buildRuntimeErrorDiagnostics = (reason) => {
|
|
133196
133654
|
const existing = getRecentProviderFailureDiagnostics(reason);
|
|
133197
133655
|
if (existing) {
|
|
@@ -133340,7 +133798,7 @@ var init_engine = __esm({
|
|
|
133340
133798
|
};
|
|
133341
133799
|
isTransientRuntimeConflictError = (error48) => {
|
|
133342
133800
|
const structured = error48;
|
|
133343
|
-
return Number(structured?.status) === HTTP_STATUS.CONFLICT && structured?.retryable === true && (structured?.code === "profile_runtime_contract_busy" || structured?.code === "runtime_decision_finalizing" || structured?.code === "runtime_trade_sync_finalizing");
|
|
133801
|
+
return Number(structured?.status) === HTTP_STATUS.CONFLICT && structured?.retryable === true && (structured?.code === "profile_runtime_contract_busy" || structured?.code === "runtime_decision_finalizing" || structured?.code === "runtime_trade_sync_finalizing" || structured?.code === "provider_paced");
|
|
133344
133802
|
};
|
|
133345
133803
|
createRuntimeStartCancelledError = (reason, detail) => Object.assign(new Error(AI_RUNTIME_START_CANCELLED_MESSAGE), {
|
|
133346
133804
|
runtimeStartCancelReason: reason,
|
|
@@ -133952,7 +134410,7 @@ var init_engine = __esm({
|
|
|
133952
134410
|
}
|
|
133953
134411
|
appendRuntimeDebugEvent({
|
|
133954
134412
|
label: "runtime_contract_invalidated",
|
|
133955
|
-
note: `source=${source} previous=${previousToken.slice(0,
|
|
134413
|
+
note: `source=${source} previous=${previousToken.slice(0, DEVICE_DIAGNOSTICS4.contract_token_prefix_chars)} next=${nextToken.slice(0, DEVICE_DIAGNOSTICS4.contract_token_prefix_chars)}`
|
|
133956
134414
|
});
|
|
133957
134415
|
this._lastError = "Runtime contract updated. Rebinding to latest server identity...";
|
|
133958
134416
|
if (!this._executionFinalizationRequired && this._analysisAbortController && !this._analysisAbortController.signal.aborted) {
|
|
@@ -136045,6 +136503,7 @@ var init_engine = __esm({
|
|
|
136045
136503
|
let aiSchedulePauseMs = null;
|
|
136046
136504
|
let aiSchedulePauseHasNext = false;
|
|
136047
136505
|
let providerRetryDelayMs = null;
|
|
136506
|
+
let pacedTurnDelayMs = null;
|
|
136048
136507
|
const ignoreAiSchedule = this._manualRunRequested;
|
|
136049
136508
|
this._manualRunRequested = false;
|
|
136050
136509
|
const pausedBeforeSlot = this._aiSchedulePaused && this._nextRunAtMs != null && Date.now() < this._nextRunAtMs;
|
|
@@ -136444,7 +136903,7 @@ var init_engine = __esm({
|
|
|
136444
136903
|
this._lastError = "Local analysis is stale against latest runtime contract. Rebinding.";
|
|
136445
136904
|
appendRuntimeDebugEvent({
|
|
136446
136905
|
label: "runtime_contract_checkpoint_block",
|
|
136447
|
-
note: `checkpoint=${checkpoint} reason=binding_mismatch latest=${latestBindingTupleToken.slice(0,
|
|
136906
|
+
note: `checkpoint=${checkpoint} reason=binding_mismatch latest=${latestBindingTupleToken.slice(0, DEVICE_DIAGNOSTICS4.contract_token_prefix_chars)} cycle=${cycleContractBindingToken.slice(0, DEVICE_DIAGNOSTICS4.contract_token_prefix_chars)}`
|
|
136448
136907
|
});
|
|
136449
136908
|
this._notifyListeners();
|
|
136450
136909
|
return true;
|
|
@@ -136712,6 +137171,20 @@ var init_engine = __esm({
|
|
|
136712
137171
|
})), capacityPlans[0]?.plan.executionContext.decisionSnapshotCapturedAt);
|
|
136713
137172
|
capacityPlans.forEach(({ planIndex }, index) => serverCapacityByPlan.set(planIndex, allocations[index]));
|
|
136714
137173
|
}
|
|
137174
|
+
const endPlansAfterEarlierOrder = (planIndex, symbol2, reason) => {
|
|
137175
|
+
cycleOutcome = "interrupted";
|
|
137176
|
+
cycleReason = reason;
|
|
137177
|
+
appendRuntimeDebugEvent({
|
|
137178
|
+
label: "execution_plans_ended_after_earlier_order",
|
|
137179
|
+
note: [
|
|
137180
|
+
`cycle_id=${result.cycleId}`,
|
|
137181
|
+
`index=${planIndex + 1}/${executionPlans.length}`,
|
|
137182
|
+
`symbol=${symbol2}`,
|
|
137183
|
+
`reason=${reason}`
|
|
137184
|
+
].join(" "),
|
|
137185
|
+
outcome: "error"
|
|
137186
|
+
});
|
|
137187
|
+
};
|
|
136715
137188
|
const runPlan = async (plan, planIndex) => {
|
|
136716
137189
|
const withPlanCapacityTrim = (planResult) => {
|
|
136717
137190
|
if (plan.capacityTrim) {
|
|
@@ -136731,6 +137204,7 @@ var init_engine = __esm({
|
|
|
136731
137204
|
};
|
|
136732
137205
|
let planEntryOrderDispatched = false;
|
|
136733
137206
|
let planExitOrderDispatched = false;
|
|
137207
|
+
const finalizationOwedBeforePlan = this._executionFinalizationRequired;
|
|
136734
137208
|
const decisionWallet = String(
|
|
136735
137209
|
plan.executionContext.walletAddress || ""
|
|
136736
137210
|
).trim().toLowerCase();
|
|
@@ -136744,13 +137218,23 @@ var init_engine = __esm({
|
|
|
136744
137218
|
plan.executionContext.symbol
|
|
136745
137219
|
);
|
|
136746
137220
|
if (actionablePlan || trailingHoldCanMutate || protectiveHoldCanMutate) {
|
|
136747
|
-
|
|
136748
|
-
|
|
136749
|
-
|
|
136750
|
-
|
|
136751
|
-
|
|
136752
|
-
|
|
137221
|
+
try {
|
|
137222
|
+
await this._assertFreshClientWalletAssignment(
|
|
137223
|
+
profileId,
|
|
137224
|
+
decisionWallet,
|
|
137225
|
+
analysisAbortController.signal,
|
|
137226
|
+
actionablePlan ? "decision execution" : trailingHoldCanMutate ? "trailing stop maintenance" : "protective order reconciliation"
|
|
137227
|
+
);
|
|
137228
|
+
} catch (walletCheckError) {
|
|
137229
|
+
if (!finalizationOwedBeforePlan) throw walletCheckError;
|
|
137230
|
+
endPlansAfterEarlierOrder(planIndex, plan.executionContext.symbol, isTransientRuntimeConflictError(walletCheckError) ? "runtime_conflict" : isRuntimeContractMismatchError(walletCheckError) ? "runtime_contract_changed" : "runtime_interrupted");
|
|
137231
|
+
return { control: "break" };
|
|
137232
|
+
}
|
|
136753
137233
|
if (shouldAbortForContractInvalidation("post_execution_preferences_refresh")) {
|
|
137234
|
+
if (finalizationOwedBeforePlan) {
|
|
137235
|
+
endPlansAfterEarlierOrder(planIndex, plan.executionContext.symbol, "runtime_contract_changed");
|
|
137236
|
+
return { control: "break" };
|
|
137237
|
+
}
|
|
136754
137238
|
return { control: "return" };
|
|
136755
137239
|
}
|
|
136756
137240
|
}
|
|
@@ -136820,6 +137304,9 @@ var init_engine = __esm({
|
|
|
136820
137304
|
if (this._windowHandoffRequested && (dispatchKind !== "protection" || !planEntryOrderDispatched)) {
|
|
136821
137305
|
throw new Error(CLIENT_RUNTIME_WINDOW_HANDOFF_BEFORE_PLAN_DISPATCH);
|
|
136822
137306
|
}
|
|
137307
|
+
if (this._isStopping && this._executionFinalizationRequired && (dispatchKind === "entry" || dispatchKind === "exit")) {
|
|
137308
|
+
throw createStopAbortError("stopping_after_order");
|
|
137309
|
+
}
|
|
136823
137310
|
if (dispatchKind === "entry") {
|
|
136824
137311
|
planEntryOrderDispatched = true;
|
|
136825
137312
|
}
|
|
@@ -136858,6 +137345,15 @@ var init_engine = __esm({
|
|
|
136858
137345
|
return { control: "break" };
|
|
136859
137346
|
}
|
|
136860
137347
|
const abortedAfterCommittedOrder = committedReports.length > 0 && (analysisAbortController.signal.aborted || isRuntimeAbortError(executionError));
|
|
137348
|
+
const stoppedAfterEarlierPlanOrder = finalizationOwedBeforePlan && committedReports.length === 0 && !planEntryOrderDispatched && !planExitOrderDispatched;
|
|
137349
|
+
if (stoppedAfterEarlierPlanOrder) {
|
|
137350
|
+
const conflict = isTransientRuntimeConflictError(executionError);
|
|
137351
|
+
const contractChanged = isRuntimeContractMismatchError(executionError);
|
|
137352
|
+
if (conflict || contractChanged || analysisAbortController.signal.aborted || isRuntimeAbortError(executionError)) {
|
|
137353
|
+
endPlansAfterEarlierOrder(planIndex, plan.executionContext.symbol, conflict ? executionError.code === "provider_paced" ? "provider_paced" : "runtime_conflict" : contractChanged ? "runtime_contract_changed" : "runtime_interrupted");
|
|
137354
|
+
return { control: "break" };
|
|
137355
|
+
}
|
|
137356
|
+
}
|
|
136861
137357
|
if (!abortedAfterCommittedOrder && (analysisAbortController.signal.aborted || isRuntimeAbortError(executionError)) || isRuntimeContractMismatchError(executionError) || isClientExecutionModeMismatchError(executionError) || isClientRuntimeSessionStoppedError(executionError) || isClientRuntimeLeaseAuthError(executionError) || isTransientRuntimeConflictError(executionError) && committedReports.length === 0) {
|
|
136862
137358
|
throw executionError;
|
|
136863
137359
|
}
|
|
@@ -137024,6 +137520,10 @@ var init_engine = __esm({
|
|
|
137024
137520
|
if (dispatched > 0 && this._windowHandoffRequested) {
|
|
137025
137521
|
break;
|
|
137026
137522
|
}
|
|
137523
|
+
if (this._executionFinalizationRequired && this._isStopping) {
|
|
137524
|
+
endPlansAfterEarlierOrder(planIndex, executionPlans[planIndex].executionContext.symbol, "runtime_interrupted");
|
|
137525
|
+
break;
|
|
137526
|
+
}
|
|
137027
137527
|
const outcome = await runPlan(executionPlans[planIndex], planIndex);
|
|
137028
137528
|
if (outcome.control === "return") {
|
|
137029
137529
|
await settleUnsentAgentDecision("plan_ended_cycle");
|
|
@@ -137187,7 +137687,7 @@ var init_engine = __esm({
|
|
|
137187
137687
|
if (this._windowHandoffRequested) {
|
|
137188
137688
|
return;
|
|
137189
137689
|
}
|
|
137190
|
-
await checkInCopyTrading(config2);
|
|
137690
|
+
if (!this._isStopping) await checkInCopyTrading(config2);
|
|
137191
137691
|
this._executionModeMismatchConsecutiveCount = 0;
|
|
137192
137692
|
if (executionFailures.length > 0) {
|
|
137193
137693
|
cycleOutcome = "failed";
|
|
@@ -137252,7 +137752,7 @@ var init_engine = __esm({
|
|
|
137252
137752
|
cycleReason = "execution_mode_changed";
|
|
137253
137753
|
} else if (isTransientRuntimeConflictError(error48)) {
|
|
137254
137754
|
cycleOutcome = "interrupted";
|
|
137255
|
-
cycleReason = "runtime_conflict";
|
|
137755
|
+
cycleReason = error48.code === "provider_paced" ? "provider_paced" : "runtime_conflict";
|
|
137256
137756
|
}
|
|
137257
137757
|
if (this._state === "stopped" || this._analysisRequestId !== requestId) {
|
|
137258
137758
|
this._lastError = null;
|
|
@@ -137310,6 +137810,9 @@ var init_engine = __esm({
|
|
|
137310
137810
|
}
|
|
137311
137811
|
if (isTransientRuntimeConflictError(error48)) {
|
|
137312
137812
|
this._lastError = null;
|
|
137813
|
+
if (error48.code === "provider_paced") {
|
|
137814
|
+
pacedTurnDelayMs = readRetryableRuntimeRefusalDelayMs(error48);
|
|
137815
|
+
}
|
|
137313
137816
|
this._notifyListeners();
|
|
137314
137817
|
return;
|
|
137315
137818
|
}
|
|
@@ -137424,6 +137927,17 @@ var init_engine = __esm({
|
|
|
137424
137927
|
if (this._state === "running" && this._sessionId === sessionId) {
|
|
137425
137928
|
this._agentInstructionPollActive = agentPollDelayMs !== null;
|
|
137426
137929
|
}
|
|
137930
|
+
if (
|
|
137931
|
+
// Stale and offline runtimes run too (active); recovery re-arms none owing a settlement.
|
|
137932
|
+
(this._state === "running" || this._state === "stale" || this._state === "offline") && !this._killswitchLatched && !this._isStopping && !this._scheduledSuspendPromise && !this._windowHandoffRequested && this._executionFinalizationRequired
|
|
137933
|
+
) {
|
|
137934
|
+
appendRuntimeDebugEvent({
|
|
137935
|
+
label: "engine_execution_finalization_unsettled",
|
|
137936
|
+
note: `request_id=${requestId} outcome=${cycleOutcome} reason=${cycleReason ?? "none"}`,
|
|
137937
|
+
outcome: "error"
|
|
137938
|
+
});
|
|
137939
|
+
this._scheduleRecoverableSuspendAfterExecutionLoop({ reason: "execution_finalization_unsettled" });
|
|
137940
|
+
}
|
|
137427
137941
|
if (this._state === "running" && !this._killswitchLatched && !this._isStopping && !this._scheduledSuspendPromise && !this._executionFinalizationRequired) {
|
|
137428
137942
|
if (executedExchangeOrderInCycle) {
|
|
137429
137943
|
const previousNextRunAtMs2 = this._nextRunAtMs;
|
|
@@ -137450,16 +137964,19 @@ var init_engine = __esm({
|
|
|
137450
137964
|
const providerRetryWake = providerRetryDelayMs !== null && aiSchedulePauseMs === null && agentPollDelayMs === null ? providerRetryDelayMs : null;
|
|
137451
137965
|
if (providerRetryWake !== null) this._nextRunAtMs = Date.now() + providerRetryWake;
|
|
137452
137966
|
const windowEndsAtMs = this._aiScheduleWindowEndsAtMs;
|
|
137967
|
+
const pacedTurnAtMs = pacedTurnDelayMs === null ? null : Date.now() + pacedTurnDelayMs;
|
|
137968
|
+
const pacedTurnWake = pacedTurnAtMs !== null && aiSchedulePauseMs === null && agentPollDelayMs === null && providerRetryWake === null && this._nextRunAtMs != null && pacedTurnAtMs < this._nextRunAtMs && (windowEndsAtMs == null || pacedTurnAtMs < windowEndsAtMs) ? pacedTurnDelayMs : null;
|
|
137969
|
+
if (pacedTurnWake !== null && this._periodicSchedule) this._nextRunAtMs = Date.now() + pacedTurnWake;
|
|
137453
137970
|
const nextWorkAtMs = this._primaryAnalysisDisabled && this._loopIntervalMs != null ? Date.now() + this._loopIntervalMs : this._nextRunAtMs;
|
|
137454
|
-
const windowEndWake = aiSchedulePauseMs === null && agentPollDelayMs === null && providerRetryWake === null && windowEndsAtMs != null && windowEndsAtMs > Date.now() && (nextWorkAtMs == null || windowEndsAtMs < nextWorkAtMs) ? windowEndsAtMs - Date.now() : null;
|
|
137971
|
+
const windowEndWake = aiSchedulePauseMs === null && agentPollDelayMs === null && providerRetryWake === null && pacedTurnWake === null && windowEndsAtMs != null && windowEndsAtMs > Date.now() && (nextWorkAtMs == null || windowEndsAtMs < nextWorkAtMs) ? windowEndsAtMs - Date.now() : null;
|
|
137455
137972
|
this._aiScheduleCheckPending = windowEndWake !== null;
|
|
137456
137973
|
const manualRunWake = this._manualRunRequested ? 0 : null;
|
|
137457
137974
|
this._firstCycleEndedAtMs ??= Date.now();
|
|
137458
137975
|
if (cycleAgentDriven !== null) this._agentDrivenCycles = cycleAgentDriven;
|
|
137459
137976
|
this._armExecutionLoopTimer({
|
|
137460
137977
|
alignToNextRun: agentPollDelayMs === null,
|
|
137461
|
-
delayOverrideMs: manualRunWake ?? aiSchedulePauseMs ?? agentPollDelayMs ?? providerRetryWake ?? windowEndWake,
|
|
137462
|
-
reason: manualRunWake !== null ? "manual_run_requested" : aiSchedulePauseMs !== null ? "ai_schedule_paused" : agentPollDelayMs !== null ? "agent_instruction_poll" : providerRetryWake !== null ? "provider_failure_retry" : windowEndWake !== null ? "ai_schedule_window_end" : this._primaryAnalysisDisabled ? "main_model_disabled_copy_poll" : "cycle_finally",
|
|
137978
|
+
delayOverrideMs: manualRunWake ?? aiSchedulePauseMs ?? agentPollDelayMs ?? providerRetryWake ?? pacedTurnWake ?? windowEndWake,
|
|
137979
|
+
reason: manualRunWake !== null ? "manual_run_requested" : aiSchedulePauseMs !== null ? "ai_schedule_paused" : agentPollDelayMs !== null ? "agent_instruction_poll" : providerRetryWake !== null ? "provider_failure_retry" : pacedTurnWake !== null ? "provider_paced_retry" : windowEndWake !== null ? "ai_schedule_window_end" : this._primaryAnalysisDisabled ? "main_model_disabled_copy_poll" : "cycle_finally",
|
|
137463
137980
|
suppressNextRunProjection: aiSchedulePauseMs !== null && !aiSchedulePauseHasNext || agentPollDelayMs === null && aiSchedulePauseMs === null && this._primaryAnalysisDisabled
|
|
137464
137981
|
});
|
|
137465
137982
|
}
|
|
@@ -137683,7 +138200,7 @@ var init_engine = __esm({
|
|
|
137683
138200
|
origin: provenance?.origin ?? null,
|
|
137684
138201
|
providerNotConfigured: getRuntimeProviderSetupDiagnostics(reason)?.reason === "provider_not_configured",
|
|
137685
138202
|
attempts: getCycleErrorModelCalls(reason),
|
|
137686
|
-
causeMaxDepth:
|
|
138203
|
+
causeMaxDepth: DEVICE_DIAGNOSTICS4.error_cause_max_depth
|
|
137687
138204
|
});
|
|
137688
138205
|
if (failure2?.overloaded && provenance?.lane === "main") this._serverOverloadStreak += 1;
|
|
137689
138206
|
return failure2;
|
|
@@ -138690,7 +139207,7 @@ var init_engine = __esm({
|
|
|
138690
139207
|
* account_evidence_status, which is logged here.
|
|
138691
139208
|
*/
|
|
138692
139209
|
async _sendClientCopyTradingAccountEvidence(input) {
|
|
138693
|
-
const requestId = String(input.request.request_id ?? "").trim().slice(0,
|
|
139210
|
+
const requestId = String(input.request.request_id ?? "").trim().slice(0, DEVICE_DIAGNOSTICS4.copy_trading_request_id_chars) || "none";
|
|
138694
139211
|
const evidence = await readClientCopyTradingAccountEvidence({
|
|
138695
139212
|
request: input.request,
|
|
138696
139213
|
trustedWalletAddress: input.trustedWalletAddress,
|
|
@@ -138714,7 +139231,7 @@ var init_engine = __esm({
|
|
|
138714
139231
|
if (status !== "applied") {
|
|
138715
139232
|
appendRuntimeDebugEvent({
|
|
138716
139233
|
label: "copy_trading_account_evidence_rejected",
|
|
138717
|
-
note: `profile_id=${input.profileId} request_id=${requestId} reason=${String(status ?? "missing").slice(0,
|
|
139234
|
+
note: `profile_id=${input.profileId} request_id=${requestId} reason=${String(status ?? "missing").slice(0, DEVICE_DIAGNOSTICS4.copy_trading_status_chars)}`,
|
|
138718
139235
|
outcome: "error"
|
|
138719
139236
|
});
|
|
138720
139237
|
}
|
|
@@ -138722,7 +139239,7 @@ var init_engine = __esm({
|
|
|
138722
139239
|
if (evidence.read.source && sourceStatus !== "accepted") {
|
|
138723
139240
|
appendRuntimeDebugEvent({
|
|
138724
139241
|
label: "copy_trading_source_evidence_rejected",
|
|
138725
|
-
note: `profile_id=${input.profileId} request_id=${requestId} reason=${String(sourceStatus ?? "missing").slice(0,
|
|
139242
|
+
note: `profile_id=${input.profileId} request_id=${requestId} reason=${String(sourceStatus ?? "missing").slice(0, DEVICE_DIAGNOSTICS4.copy_trading_status_chars)}`,
|
|
138726
139243
|
outcome: "error"
|
|
138727
139244
|
});
|
|
138728
139245
|
}
|
|
@@ -139276,7 +139793,7 @@ var init_local_ai_preflight = __esm({
|
|
|
139276
139793
|
|
|
139277
139794
|
// lib/agent-core/headless-runtime.ts
|
|
139278
139795
|
import { randomUUID as randomUUID16 } from "node:crypto";
|
|
139279
|
-
import { setTimeout as
|
|
139796
|
+
import { setTimeout as sleep2 } from "node:timers/promises";
|
|
139280
139797
|
function objectOrNull2(value) {
|
|
139281
139798
|
return value && typeof value === "object" && !Array.isArray(value) ? value : null;
|
|
139282
139799
|
}
|
|
@@ -139325,7 +139842,7 @@ async function claimRuntime(options, engine, identity2, kind, signal) {
|
|
|
139325
139842
|
}
|
|
139326
139843
|
if (claim.outcome === "wait" && waits < maxWaits) {
|
|
139327
139844
|
waits += 1;
|
|
139328
|
-
await
|
|
139845
|
+
await sleep2(Math.max(1, Number(claim.retry_after_seconds) || 1) * MS_PER_SECOND, void 0, { signal });
|
|
139329
139846
|
continue;
|
|
139330
139847
|
}
|
|
139331
139848
|
if (kind === "auto" && claim.outcome === "blocked") return null;
|
|
@@ -139617,7 +140134,7 @@ async function runHeadlessRuntime(options) {
|
|
|
139617
140134
|
status = read === "retry" ? null : read.status;
|
|
139618
140135
|
if (status || attempt2 >= BACKUP_FIRST_READ_RETRY_MS.length || stopController.signal.aborted) break;
|
|
139619
140136
|
try {
|
|
139620
|
-
await
|
|
140137
|
+
await sleep2(BACKUP_FIRST_READ_RETRY_MS[attempt2], void 0, { signal: stopController.signal });
|
|
139621
140138
|
} catch {
|
|
139622
140139
|
break;
|
|
139623
140140
|
}
|
|
@@ -139659,7 +140176,7 @@ async function runHeadlessRuntime(options) {
|
|
|
139659
140176
|
return "yielded_for_update";
|
|
139660
140177
|
}
|
|
139661
140178
|
try {
|
|
139662
|
-
await
|
|
140179
|
+
await sleep2(options.serverBackupWaitMs ?? BACKUP_WAIT_TICK_MS, void 0, { signal: stopController.signal });
|
|
139663
140180
|
} catch {
|
|
139664
140181
|
await withdraw();
|
|
139665
140182
|
return "stopped";
|
|
@@ -139812,7 +140329,7 @@ async function runHeadlessRuntime(options) {
|
|
|
139812
140329
|
try {
|
|
139813
140330
|
const backoff = options.resumeBackoffMs?.length ? options.resumeBackoffMs : RESUME_BACKOFF_MS;
|
|
139814
140331
|
if (event.kind !== "resume" || !event.immediate) {
|
|
139815
|
-
await
|
|
140332
|
+
await sleep2(backoff[Math.min(resumesWithoutCycle, backoff.length - 1)], void 0, {
|
|
139816
140333
|
signal: stopController.signal
|
|
139817
140334
|
});
|
|
139818
140335
|
}
|
|
@@ -140013,7 +140530,7 @@ function parsePositiveNumber(value, flag) {
|
|
|
140013
140530
|
}
|
|
140014
140531
|
return parsed;
|
|
140015
140532
|
}
|
|
140016
|
-
function
|
|
140533
|
+
function parseExecutionMode2(value) {
|
|
140017
140534
|
const normalized = value.trim().toLowerCase();
|
|
140018
140535
|
if (normalized !== "client" && normalized !== "server") {
|
|
140019
140536
|
throw new Error("--mode must be client or server");
|
|
@@ -140367,7 +140884,7 @@ async function runVtxCli(argv2, env = process.env) {
|
|
|
140367
140884
|
}
|
|
140368
140885
|
if (group === "profiles" && command === "set-mode") {
|
|
140369
140886
|
const profileId = requireProfileId(parsed.profileId, config2.activeProfileId);
|
|
140370
|
-
const mode =
|
|
140887
|
+
const mode = parseExecutionMode2(requireValue(args, "--mode"));
|
|
140371
140888
|
return { exitCode: 0, stdout: render3(await client.setProfileExecutionMode(profileId, mode), json2), stderr: "" };
|
|
140372
140889
|
}
|
|
140373
140890
|
if (group === "bots" && command === "start") {
|