@vtxmacro/cli 2026.9.69 → 2026.10.2

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.js CHANGED
@@ -77,7 +77,7 @@ var init_agent_cli_release = __esm({
77
77
  "agent-cli-release.json"() {
78
78
  agent_cli_release_default = {
79
79
  package_name: "@vtxmacro/cli",
80
- package_version: "2026.9.69",
80
+ package_version: "2026.10.2",
81
81
  codex_package_name: "@openai/codex",
82
82
  codex_version: "0.155.0",
83
83
  copilot_sdk_package_name: "@github/copilot-sdk",
@@ -17607,9 +17607,9 @@ var init_mcp_transport_config = __esm({
17607
17607
  import { randomBytes } from "node:crypto";
17608
17608
  import { spawn } from "node:child_process";
17609
17609
  import { constants } from "node:fs";
17610
- import { lstat, mkdir, open, readFile, realpath, rename, rm } from "node:fs/promises";
17610
+ import { lstat, mkdir, open, readdir, readFile, realpath, rename, rm } from "node:fs/promises";
17611
17611
  import { homedir } from "node:os";
17612
- import { dirname, isAbsolute as isAbsolute2, join, relative, resolve, win32 as windowsPath } from "node:path";
17612
+ import { basename, dirname, isAbsolute as isAbsolute2, join, relative, resolve, win32 as windowsPath } from "node:path";
17613
17613
  function inferenceBaseDir(env) {
17614
17614
  const configured = String(env.VTX_INFERENCE_HOST_HOME || "").trim();
17615
17615
  return configured || join(homedir(), ".vtx", "inference-host");
@@ -18012,146 +18012,65 @@ async function acquireInferenceHostProcessLock(path, dependencies = {}) {
18012
18012
  const directory2 = dirname(path);
18013
18013
  await ensureInferencePrivateDirectory(directory2);
18014
18014
  const ownerToken = randomBytes(24).toString("base64url");
18015
- const observeIdentity = dependencies.processIdentity ?? defaultProcessIdentity;
18016
- const currentBootIdentity = dependencies.currentBootIdentity ?? (() => readInferenceSystemBootIdentity());
18017
- const isProcessAlive = dependencies.processAlive ?? ((pid) => {
18018
- try {
18019
- process.kill(pid, 0);
18020
- return true;
18021
- } catch (error48) {
18022
- if (error48.code === "ESRCH") return false;
18023
- throw error48;
18024
- }
18025
- });
18026
- let handle;
18027
- for (let acquisition = 0; acquisition < 2; acquisition += 1) {
18028
- try {
18029
- handle = await open(
18030
- path,
18031
- constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW,
18032
- 384
18033
- );
18034
- break;
18035
- } catch (error48) {
18036
- if (error48.code !== "EEXIST") throw error48;
18037
- if (acquisition > 0) {
18038
- throw new InferenceHostProcessLockBusyError();
18039
- }
18040
- let before;
18015
+ const probes = {
18016
+ currentBootIdentity: dependencies.currentBootIdentity ?? (() => readInferenceSystemBootIdentity()),
18017
+ observeIdentity: dependencies.processIdentity ?? defaultProcessIdentity,
18018
+ isProcessAlive: dependencies.processAlive ?? ((pid) => {
18041
18019
  try {
18042
- before = await lstat(path);
18043
- } catch (error49) {
18044
- if (error49.code === "ENOENT") continue;
18045
- throw error49;
18046
- }
18047
- if (before.isSymbolicLink() || !before.isFile() || process.platform !== "win32" && (before.mode & 63) !== 0 || typeof process.getuid === "function" && before.uid !== process.getuid()) {
18048
- throw new Error("Inference host process lock is unsafe.");
18049
- }
18050
- const reclaimPublicationResidue = async () => {
18051
- let current2;
18052
- try {
18053
- current2 = await lstat(path);
18054
- } catch (error49) {
18055
- if (error49.code === "ENOENT") return false;
18056
- throw error49;
18057
- }
18058
- if (current2.isSymbolicLink() || !current2.isFile() || current2.dev !== before.dev || current2.ino !== before.ino || process.platform !== "win32" && (current2.mode & 63) !== 0 || typeof process.getuid === "function" && current2.uid !== process.getuid()) {
18059
- throw new Error("Inference host process lock publication residue changed or is unsafe.");
18060
- }
18061
- try {
18062
- await rm(path);
18063
- } catch (error49) {
18064
- if (error49.code === "ENOENT") return false;
18065
- throw error49;
18066
- }
18067
- processLockObservationCache.delete(resolve(path));
18068
- await syncInferenceDirectory(directory2);
18020
+ process.kill(pid, 0);
18069
18021
  return true;
18070
- };
18071
- try {
18072
- await secureExistingWindowsPath(path, "file");
18073
- } catch (error49) {
18074
- if (error49.code === "ENOENT") continue;
18075
- throw error49;
18022
+ } catch (error48) {
18023
+ if (error48.code === "ESRCH") return false;
18024
+ throw error48;
18076
18025
  }
18077
- let staleOwner;
18026
+ })
18027
+ };
18028
+ const [ownerIdentity, bootIdentity] = await Promise.all([
18029
+ (dependencies.currentProcessIdentity ?? defaultCurrentProcessIdentity)(),
18030
+ probes.currentBootIdentity()
18031
+ ]);
18032
+ const ownerRecord = (token) => `${JSON.stringify({
18033
+ schema_version: 2,
18034
+ pid: process.pid,
18035
+ owner_token: token,
18036
+ process_identity: ownerIdentity,
18037
+ boot_identity: bootIdentity
18038
+ })}
18039
+ `;
18040
+ let handle = await openExclusiveProcessLockFile(path);
18041
+ if (!handle) {
18042
+ const inspection = await inspectProcessLockFile(path, PROCESS_LOCK_LABEL, probes);
18043
+ if (inspection.state === "busy") throw new InferenceHostProcessLockBusyError();
18044
+ if (inspection.state === "stale") {
18045
+ await inspection.handle.close();
18046
+ const guard = await acquireProcessLockReclaimGuard(path, ownerRecord, probes);
18078
18047
  try {
18079
- staleOwner = JSON.parse(await readFile(path, "utf8"));
18080
- } catch (error49) {
18081
- if (error49.code === "ENOENT") continue;
18082
- if (Date.now() - before.mtimeMs < 1e4) {
18083
- throw new InferenceHostProcessLockBusyError();
18084
- }
18085
- await reclaimPublicationResidue();
18086
- continue;
18087
- }
18088
- if (staleOwner.schema_version !== 2 || !Number.isSafeInteger(staleOwner.pid) || Number(staleOwner.pid) < 1 || typeof staleOwner.owner_token !== "string" || !staleOwner.owner_token || typeof staleOwner.process_identity !== "string" || !staleOwner.process_identity || typeof staleOwner.boot_identity !== "string" || !staleOwner.boot_identity) {
18089
- if (Date.now() - before.mtimeMs < 1e4) {
18090
- throw new InferenceHostProcessLockBusyError();
18091
- }
18092
- await reclaimPublicationResidue();
18093
- continue;
18094
- }
18095
- const stalePid = Number(staleOwner.pid);
18096
- const bootIdentity2 = await currentBootIdentity();
18097
- if (bootIdentity2 === staleOwner.boot_identity && isProcessAlive(stalePid)) {
18098
- const cached2 = processLockObservationCache.get(resolve(path));
18099
- const observedIdentity = cached2 && cached2.dev === before.dev && cached2.ino === before.ino && cached2.pid === stalePid && cached2.storedIdentity === staleOwner.process_identity && Date.now() - cached2.observedAtMs < 5e3 ? cached2.observedIdentity : await observeIdentity(stalePid);
18100
- if (!observedIdentity) {
18101
- throw new Error("Inference host could not verify the existing lock owner identity.");
18102
- }
18103
- processLockObservationCache.set(resolve(path), {
18104
- dev: before.dev,
18105
- ino: before.ino,
18106
- pid: stalePid,
18107
- storedIdentity: staleOwner.process_identity,
18108
- observedIdentity,
18109
- observedAtMs: Date.now()
18110
- });
18111
- if (inferenceProcessIdentitiesMatch(staleOwner.process_identity, observedIdentity)) {
18112
- throw new InferenceHostProcessLockBusyError();
18048
+ const guarded = await inspectProcessLockFile(path, PROCESS_LOCK_LABEL, probes);
18049
+ if (guarded.state === "busy") throw new InferenceHostProcessLockBusyError();
18050
+ if (guarded.state === "stale") {
18051
+ await removeVerifiedStaleProcessLockFile(path, guarded, guard.assertHeld);
18113
18052
  }
18053
+ handle = await openExclusiveProcessLockFile(path);
18054
+ } finally {
18055
+ await guard.release();
18114
18056
  }
18115
- let current;
18116
- try {
18117
- current = await lstat(path);
18118
- } catch (error49) {
18119
- if (error49.code === "ENOENT") continue;
18120
- throw error49;
18121
- }
18122
- if (current.dev !== before.dev || current.ino !== before.ino) {
18123
- throw new Error("Inference host process lock ownership changed.");
18124
- }
18125
- await rm(path);
18126
- processLockObservationCache.delete(resolve(path));
18127
- await syncInferenceDirectory(directory2);
18057
+ } else {
18058
+ handle = await openExclusiveProcessLockFile(path);
18128
18059
  }
18060
+ if (!handle) throw new InferenceHostProcessLockBusyError();
18129
18061
  }
18130
- if (!handle) throw new Error("Inference host process lock could not be acquired.");
18131
- let ownerIdentity;
18132
- let bootIdentity;
18133
18062
  try {
18134
- [ownerIdentity, bootIdentity] = await Promise.all([
18135
- (dependencies.currentProcessIdentity ?? defaultCurrentProcessIdentity)(),
18136
- currentBootIdentity()
18137
- ]);
18063
+ await handle.writeFile(ownerRecord(ownerToken), "utf8");
18064
+ await handle.sync();
18138
18065
  } catch (error48) {
18066
+ const created = await handle.stat().catch(() => null);
18139
18067
  await handle.close().catch(() => void 0);
18140
- await rm(path, { force: true }).catch(() => void 0);
18068
+ const current = await lstat(path).catch(() => null);
18069
+ if (created && current && current.dev === created.dev && current.ino === created.ino) {
18070
+ await rm(path, { force: true }).catch(() => void 0);
18071
+ }
18141
18072
  throw error48;
18142
18073
  }
18143
- await handle.writeFile(
18144
- `${JSON.stringify({
18145
- schema_version: 2,
18146
- pid: process.pid,
18147
- owner_token: ownerToken,
18148
- process_identity: ownerIdentity,
18149
- boot_identity: bootIdentity
18150
- })}
18151
- `,
18152
- "utf8"
18153
- );
18154
- await handle.sync();
18155
18074
  await handle.close();
18156
18075
  await secureWindowsPrivatePath(path, "file", "harden");
18157
18076
  await syncInferenceDirectory(directory2);
@@ -18176,7 +18095,7 @@ async function acquireInferenceHostProcessLock(path, dependencies = {}) {
18176
18095
  }
18177
18096
  };
18178
18097
  }
18179
- var loadInferenceReceiptDurabilityTimeoutMs, loadInferenceAgentDataRequestTimeoutMs, loadInferenceAgentCommandLockPolicy, InferenceHostProcessLockBusyError, INFERENCE_CREDENTIAL_NAMESPACE, MAX_INFERENCE_PRIVATE_FILE_BYTES, WINDOWS_PRIVATE_ACL_BROKER_SCRIPT, WINDOWS_IDENTITY_COMMAND_TIMEOUT_MS, WINDOWS_PRIVATE_ACL_BROKER_STARTUP_TIMEOUT_MS, SMALL_IDENTITY_COMMAND_TIMEOUT_MS, windowsPowerShellEnvironment, windowsPrivateAclBrokerInvocation, WindowsPrivateAclBroker, defaultWindowsPrivateAclBroker, runWindowsPrivateAcl, windowsAclCache, windowsAclIdentity, aclCacheKey, secureWindowsPrivatePath, invalidateWindowsAclCache, rebindHardenedWindowsAclAfterRename, rebindHardenedWindowsDirectoryAfterOwnedMutation, isDefaultWindowsPrivatePath, secureExistingWindowsPath, linuxProcessIdentity, windowsProcessIdentityInvocation, windowsBootIdentityInvocation, windowsProcessIdentity, darwinProcessIdentity, runSmallIdentityCommand, cachedSystemBootIdentity, readInferenceSystemBootIdentity, defaultProcessIdentity, defaultCurrentProcessIdentity, readInferenceHostProcessLockStatus, processLockObservationCache, inferenceProcessIdentitiesMatch, DEFAULT_INFERENCE_HOST_INSTANCE, SAFE_INFERENCE_HOST_INSTANCE, requireNamedInstancePath, credentialStoreIdentity, inferenceHostCredentialContextPath, inferenceHostCredentialContextTransitionPath, credentialContextForConfig, WINDOWS_PRIVATE_FILE_REPLACE_ERROR_CODES;
18098
+ var loadInferenceReceiptDurabilityTimeoutMs, loadInferenceAgentDataRequestTimeoutMs, loadInferenceAgentCommandLockPolicy, InferenceHostProcessLockBusyError, INFERENCE_CREDENTIAL_NAMESPACE, MAX_INFERENCE_PRIVATE_FILE_BYTES, WINDOWS_PRIVATE_ACL_BROKER_SCRIPT, WINDOWS_IDENTITY_COMMAND_TIMEOUT_MS, WINDOWS_PRIVATE_ACL_BROKER_STARTUP_TIMEOUT_MS, SMALL_IDENTITY_COMMAND_TIMEOUT_MS, windowsPowerShellEnvironment, windowsPrivateAclBrokerInvocation, WindowsPrivateAclBroker, defaultWindowsPrivateAclBroker, runWindowsPrivateAcl, windowsAclCache, windowsAclIdentity, aclCacheKey, secureWindowsPrivatePath, invalidateWindowsAclCache, rebindHardenedWindowsAclAfterRename, rebindHardenedWindowsDirectoryAfterOwnedMutation, isDefaultWindowsPrivatePath, secureExistingWindowsPath, linuxProcessIdentity, windowsProcessIdentityInvocation, windowsBootIdentityInvocation, windowsProcessIdentity, darwinProcessIdentity, runSmallIdentityCommand, cachedSystemBootIdentity, readInferenceSystemBootIdentity, defaultProcessIdentity, cachedCurrentProcessIdentity, defaultCurrentProcessIdentity, readInferenceHostProcessLockStatus, processLockObservationCache, inferenceProcessIdentitiesMatch, DEFAULT_INFERENCE_HOST_INSTANCE, SAFE_INFERENCE_HOST_INSTANCE, requireNamedInstancePath, credentialStoreIdentity, inferenceHostCredentialContextPath, inferenceHostCredentialContextTransitionPath, credentialContextForConfig, WINDOWS_PRIVATE_FILE_REPLACE_ERROR_CODES, PROCESS_LOCK_PUBLICATION_GRACE_MS, PROCESS_LOCK_MAX_RECORD_BYTES, PROCESS_LOCK_GUARD_ELECTION_LEASE_MS, PROCESS_LOCK_GUARD_ELECTION_STALE_MS, PROCESS_LOCK_GUARD_ELECTION_ATTEMPTS, PROCESS_LOCK_GUARD_ELECTION_BACKOFF_MS, PROCESS_LOCK_LABEL, PROCESS_LOCK_GUARD_LABEL, sameProcessLockFile, openExclusiveProcessLockFile, inspectProcessLockFile, removeVerifiedStaleProcessLockFile, removeStaleProcessLockReclaimGuard, acquireProcessLockReclaimGuard;
18180
18099
  var init_config = __esm({
18181
18100
  "lib/inference-host/config.ts"() {
18182
18101
  "use strict";
@@ -18770,10 +18689,22 @@ while(($line=[Console]::In.ReadLine()) -ne $null) {
18770
18689
  if (process.platform === "darwin") return await darwinProcessIdentity(pid);
18771
18690
  return null;
18772
18691
  };
18692
+ cachedCurrentProcessIdentity = null;
18773
18693
  defaultCurrentProcessIdentity = async () => {
18774
- const identity2 = await defaultProcessIdentity(process.pid);
18775
- if (!identity2) throw new Error("Inference host could not establish its process-start identity.");
18776
- return identity2;
18694
+ if (!cachedCurrentProcessIdentity) {
18695
+ cachedCurrentProcessIdentity = (async () => {
18696
+ const identity2 = await defaultProcessIdentity(process.pid);
18697
+ if (!identity2) throw new Error("Inference host could not establish its process-start identity.");
18698
+ return identity2;
18699
+ })();
18700
+ }
18701
+ const pending3 = cachedCurrentProcessIdentity;
18702
+ try {
18703
+ return await pending3;
18704
+ } catch (error48) {
18705
+ if (cachedCurrentProcessIdentity === pending3) cachedCurrentProcessIdentity = null;
18706
+ throw error48;
18707
+ }
18777
18708
  };
18778
18709
  readInferenceHostProcessLockStatus = async (path) => {
18779
18710
  const raw = await readInferencePrivateFile(path, "Inference host process lock");
@@ -18836,6 +18767,242 @@ while(($line=[Console]::In.ReadLine()) -ne $null) {
18836
18767
  "ENOTEMPTY",
18837
18768
  "EPERM"
18838
18769
  ]);
18770
+ PROCESS_LOCK_PUBLICATION_GRACE_MS = 1e4;
18771
+ PROCESS_LOCK_MAX_RECORD_BYTES = 64 * 1024;
18772
+ PROCESS_LOCK_GUARD_ELECTION_LEASE_MS = 5e3;
18773
+ PROCESS_LOCK_GUARD_ELECTION_STALE_MS = 3e4;
18774
+ PROCESS_LOCK_GUARD_ELECTION_ATTEMPTS = 8;
18775
+ PROCESS_LOCK_GUARD_ELECTION_BACKOFF_MS = 10;
18776
+ PROCESS_LOCK_LABEL = "Inference host process lock";
18777
+ PROCESS_LOCK_GUARD_LABEL = "Inference host process lock reclamation guard";
18778
+ sameProcessLockFile = (left, right) => left.dev === right.dev && left.ino === right.ino && left.size === right.size && left.mtimeMs === right.mtimeMs && left.ctimeMs === right.ctimeMs;
18779
+ openExclusiveProcessLockFile = async (path) => {
18780
+ try {
18781
+ return await open(
18782
+ path,
18783
+ constants.O_CREAT | constants.O_EXCL | constants.O_WRONLY | constants.O_NOFOLLOW,
18784
+ 384
18785
+ );
18786
+ } catch (error48) {
18787
+ if (error48.code === "EEXIST") return null;
18788
+ throw error48;
18789
+ }
18790
+ };
18791
+ inspectProcessLockFile = async (path, label, probes) => {
18792
+ let before;
18793
+ try {
18794
+ before = await lstat(path);
18795
+ } catch (error48) {
18796
+ if (error48.code === "ENOENT") return { state: "missing" };
18797
+ throw error48;
18798
+ }
18799
+ if (before.isSymbolicLink() || !before.isFile() || process.platform !== "win32" && (before.mode & 63) !== 0 || typeof process.getuid === "function" && before.uid !== process.getuid()) {
18800
+ throw new Error(`${label} is unsafe.`);
18801
+ }
18802
+ let handle;
18803
+ try {
18804
+ await secureExistingWindowsPath(path, "file");
18805
+ handle = await open(path, constants.O_RDONLY | constants.O_NOFOLLOW);
18806
+ } catch (error48) {
18807
+ if (error48.code === "ENOENT") return { state: "missing" };
18808
+ throw error48;
18809
+ }
18810
+ let stale = false;
18811
+ try {
18812
+ const opened = await handle.stat();
18813
+ if (!opened.isFile() || opened.dev !== before.dev || opened.ino !== before.ino) {
18814
+ return { state: "busy" };
18815
+ }
18816
+ const raw = opened.size > PROCESS_LOCK_MAX_RECORD_BYTES ? "" : await handle.readFile("utf8");
18817
+ const stat = await handle.stat();
18818
+ if (!sameProcessLockFile(opened, stat)) return { state: "busy" };
18819
+ let record5 = null;
18820
+ try {
18821
+ const parsed = JSON.parse(raw);
18822
+ if (parsed && typeof parsed === "object") record5 = parsed;
18823
+ } catch {
18824
+ record5 = null;
18825
+ }
18826
+ if (!record5 || record5.schema_version !== 2 || !Number.isSafeInteger(record5.pid) || Number(record5.pid) < 1 || typeof record5.owner_token !== "string" || !record5.owner_token || typeof record5.process_identity !== "string" || !record5.process_identity || typeof record5.boot_identity !== "string" || !record5.boot_identity) {
18827
+ if (Date.now() - stat.mtimeMs < PROCESS_LOCK_PUBLICATION_GRACE_MS) return { state: "busy" };
18828
+ stale = true;
18829
+ return { state: "stale", handle, stat };
18830
+ }
18831
+ const ownerPid = Number(record5.pid);
18832
+ const storedIdentity = record5.process_identity;
18833
+ const cacheKey = resolve(path);
18834
+ if (await probes.currentBootIdentity() === record5.boot_identity && probes.isProcessAlive(ownerPid)) {
18835
+ const cached2 = processLockObservationCache.get(cacheKey);
18836
+ const observedIdentity = cached2 && cached2.dev === stat.dev && cached2.ino === stat.ino && cached2.pid === ownerPid && cached2.storedIdentity === storedIdentity && Date.now() - cached2.observedAtMs < 5e3 ? cached2.observedIdentity : await probes.observeIdentity(ownerPid);
18837
+ if (!observedIdentity) {
18838
+ throw new Error("Inference host could not verify the existing lock owner identity.");
18839
+ }
18840
+ processLockObservationCache.set(cacheKey, {
18841
+ dev: stat.dev,
18842
+ ino: stat.ino,
18843
+ pid: ownerPid,
18844
+ storedIdentity,
18845
+ observedIdentity,
18846
+ observedAtMs: Date.now()
18847
+ });
18848
+ if (inferenceProcessIdentitiesMatch(storedIdentity, observedIdentity)) {
18849
+ return { state: "busy" };
18850
+ }
18851
+ }
18852
+ stale = true;
18853
+ return { state: "stale", handle, stat };
18854
+ } finally {
18855
+ if (!stale) await handle.close().catch(() => void 0);
18856
+ }
18857
+ };
18858
+ removeVerifiedStaleProcessLockFile = async (path, inspection, assertExclusive) => {
18859
+ try {
18860
+ await assertExclusive();
18861
+ let current;
18862
+ try {
18863
+ current = await lstat(path);
18864
+ } catch (error48) {
18865
+ if (error48.code === "ENOENT") return;
18866
+ throw error48;
18867
+ }
18868
+ const opened = await inspection.handle.stat();
18869
+ if (current.isSymbolicLink() || !sameProcessLockFile(current, opened) || !sameProcessLockFile(opened, inspection.stat)) {
18870
+ throw new InferenceHostProcessLockBusyError();
18871
+ }
18872
+ if (process.platform === "win32") await inspection.handle.close();
18873
+ try {
18874
+ await rm(path);
18875
+ } catch (error48) {
18876
+ if (error48.code !== "ENOENT") throw error48;
18877
+ }
18878
+ } finally {
18879
+ await inspection.handle.close().catch(() => void 0);
18880
+ }
18881
+ processLockObservationCache.delete(resolve(path));
18882
+ invalidateWindowsAclCache(path);
18883
+ await syncInferenceDirectory(dirname(path));
18884
+ };
18885
+ removeStaleProcessLockReclaimGuard = async (lockPath, guardPath, inspection) => {
18886
+ const directory2 = dirname(lockPath);
18887
+ const prefix = `${basename(lockPath)}.reclaim-ballot.`;
18888
+ try {
18889
+ for (let attempt = 0; attempt < PROCESS_LOCK_GUARD_ELECTION_ATTEMPTS; attempt += 1) {
18890
+ if (attempt > 0) {
18891
+ await new Promise((resolvePromise) => setTimeout(
18892
+ resolvePromise,
18893
+ Math.floor(Math.random() * PROCESS_LOCK_GUARD_ELECTION_BACKOFF_MS * 2 ** Math.min(attempt, 4))
18894
+ ));
18895
+ let current;
18896
+ try {
18897
+ current = await lstat(guardPath);
18898
+ } catch (error48) {
18899
+ if (error48.code === "ENOENT") return;
18900
+ throw error48;
18901
+ }
18902
+ if (!sameProcessLockFile(current, inspection.stat)) return;
18903
+ }
18904
+ const ballotName = `${prefix}${randomBytes(16).toString("hex")}`;
18905
+ const ballotPath = join(directory2, ballotName);
18906
+ const ballot = await openExclusiveProcessLockFile(ballotPath);
18907
+ if (!ballot) continue;
18908
+ await ballot.close();
18909
+ const electedAt = performance.now();
18910
+ try {
18911
+ let contested = false;
18912
+ for (const name of await readdir(directory2)) {
18913
+ if (!name.startsWith(prefix) || name === ballotName) continue;
18914
+ const otherPath = join(directory2, name);
18915
+ let other;
18916
+ try {
18917
+ other = await lstat(otherPath);
18918
+ } catch (error48) {
18919
+ if (error48.code === "ENOENT") continue;
18920
+ throw error48;
18921
+ }
18922
+ if (!other.isDirectory() && Date.now() - other.mtimeMs > PROCESS_LOCK_GUARD_ELECTION_STALE_MS) {
18923
+ await rm(otherPath, { force: true });
18924
+ continue;
18925
+ }
18926
+ contested = true;
18927
+ }
18928
+ if (contested) continue;
18929
+ await removeVerifiedStaleProcessLockFile(guardPath, inspection, async () => {
18930
+ if (performance.now() - electedAt > PROCESS_LOCK_GUARD_ELECTION_LEASE_MS) {
18931
+ throw new InferenceHostProcessLockBusyError();
18932
+ }
18933
+ });
18934
+ return;
18935
+ } finally {
18936
+ await rm(ballotPath, { force: true }).catch(() => void 0);
18937
+ }
18938
+ }
18939
+ throw new InferenceHostProcessLockBusyError();
18940
+ } finally {
18941
+ await inspection.handle.close().catch(() => void 0);
18942
+ }
18943
+ };
18944
+ acquireProcessLockReclaimGuard = async (lockPath, ownerRecord, probes) => {
18945
+ const guardPath = `${lockPath}.reclaim`;
18946
+ const guardToken = randomBytes(24).toString("base64url");
18947
+ for (let attempt = 0; attempt < 2; attempt += 1) {
18948
+ const handle = await openExclusiveProcessLockFile(guardPath);
18949
+ if (handle) {
18950
+ try {
18951
+ await handle.writeFile(ownerRecord(guardToken), "utf8");
18952
+ } catch (error48) {
18953
+ await handle.close().catch(() => void 0);
18954
+ await rm(guardPath, { force: true }).catch(() => void 0);
18955
+ throw error48;
18956
+ }
18957
+ await handle.close();
18958
+ await secureWindowsPrivatePath(guardPath, "file", "harden");
18959
+ const isHeld = async () => {
18960
+ let reader;
18961
+ try {
18962
+ reader = await open(guardPath, constants.O_RDONLY | constants.O_NOFOLLOW);
18963
+ } catch (error48) {
18964
+ if (error48.code === "ENOENT") return false;
18965
+ throw error48;
18966
+ }
18967
+ try {
18968
+ const [opened, current] = await Promise.all([reader.stat(), lstat(guardPath)]);
18969
+ if (current.isSymbolicLink() || current.dev !== opened.dev || current.ino !== opened.ino) {
18970
+ return false;
18971
+ }
18972
+ const parsed = JSON.parse(await reader.readFile("utf8"));
18973
+ return parsed.owner_token === guardToken;
18974
+ } catch {
18975
+ return false;
18976
+ } finally {
18977
+ await reader.close().catch(() => void 0);
18978
+ }
18979
+ };
18980
+ return {
18981
+ assertHeld: async () => {
18982
+ if (!await isHeld()) throw new InferenceHostProcessLockBusyError();
18983
+ },
18984
+ // Best effort: a guard left behind carries this live process identity
18985
+ // and becomes reclaimable once this process exits.
18986
+ release: async () => {
18987
+ try {
18988
+ if (!await isHeld()) return;
18989
+ await rm(guardPath);
18990
+ processLockObservationCache.delete(resolve(guardPath));
18991
+ invalidateWindowsAclCache(guardPath);
18992
+ } catch {
18993
+ }
18994
+ }
18995
+ };
18996
+ }
18997
+ if (attempt > 0) break;
18998
+ const inspection = await inspectProcessLockFile(guardPath, PROCESS_LOCK_GUARD_LABEL, probes);
18999
+ if (inspection.state === "busy") break;
19000
+ if (inspection.state === "stale") {
19001
+ await removeStaleProcessLockReclaimGuard(lockPath, guardPath, inspection);
19002
+ }
19003
+ }
19004
+ throw new InferenceHostProcessLockBusyError();
19005
+ };
18839
19006
  }
18840
19007
  });
18841
19008
 
@@ -35964,7 +36131,7 @@ import {
35964
36131
  lstat as lstat3,
35965
36132
  mkdir as mkdir2,
35966
36133
  mkdtemp,
35967
- readdir,
36134
+ readdir as readdir2,
35968
36135
  readFile as readFile4,
35969
36136
  realpath as realpath3,
35970
36137
  rm as rm3
@@ -36402,7 +36569,7 @@ var init_codex_adapter = __esm({
36402
36569
  if (!directoryState.isDirectory() || directoryState.isSymbolicLink() || typeof process.getuid === "function" && directoryState.uid !== process.getuid()) {
36403
36570
  throw new Error("Codex recovery home contains an unsafe directory.");
36404
36571
  }
36405
- const entries = await readdir(current.path, { withFileTypes: true });
36572
+ const entries = await readdir2(current.path, { withFileTypes: true });
36406
36573
  for (const entry of entries) {
36407
36574
  entriesSeen += 1;
36408
36575
  if (entriesSeen > 2e4) {
@@ -38497,7 +38664,7 @@ var init_deepseek_transport_proxy = __esm({
38497
38664
  import { randomUUID as randomUUID4 } from "node:crypto";
38498
38665
  import { mkdtemp as mkdtemp3, realpath as realpath4, rm as rm5 } from "node:fs/promises";
38499
38666
  import { tmpdir as tmpdir4 } from "node:os";
38500
- import { basename, dirname as dirname4, join as join6 } from "node:path";
38667
+ import { basename as basename2, dirname as dirname4, join as join6 } from "node:path";
38501
38668
  import { Context } from "@deepseek-ai/cordis";
38502
38669
  import * as AgentSpine from "@deepseek-ai/dsh-agent-spine-demo";
38503
38670
  import {
@@ -39155,7 +39322,7 @@ ${JSON.stringify(input.outputSchema)}`,
39155
39322
  }
39156
39323
  const resolved = await realpath4(thread.threadPath);
39157
39324
  const temporaryRoot = await realpath4(tmpdir4());
39158
- if (dirname4(resolved) !== temporaryRoot || !basename(resolved).startsWith("vtx-deepseek-harness-")) throw new Error("deepseek_harness_thread_path_not_owned");
39325
+ if (dirname4(resolved) !== temporaryRoot || !basename2(resolved).startsWith("vtx-deepseek-harness-")) throw new Error("deepseek_harness_thread_path_not_owned");
39159
39326
  await rm5(resolved, { recursive: true, force: true });
39160
39327
  }
39161
39328
  async close() {
@@ -39361,8 +39528,8 @@ var init_pi_transport = __esm({
39361
39528
 
39362
39529
  // lib/inference-host/pi-adapter.ts
39363
39530
  import { randomUUID as randomUUID5 } from "node:crypto";
39364
- import { lstat as lstat4, realpath as realpath5, rm as rm6, readdir as readdir2 } from "node:fs/promises";
39365
- import { basename as basename2, dirname as dirname5, join as join7, resolve as resolve4 } from "node:path";
39531
+ import { lstat as lstat4, realpath as realpath5, rm as rm6, readdir as readdir3 } from "node:fs/promises";
39532
+ import { basename as basename3, dirname as dirname5, join as join7, resolve as resolve4 } from "node:path";
39366
39533
  import {
39367
39534
  createAgentSession,
39368
39535
  DefaultResourceLoader,
@@ -39525,7 +39692,7 @@ var init_pi_adapter = __esm({
39525
39692
  async ownedThread(thread) {
39526
39693
  const root = await realpath5(this.dependencies.stateRoot);
39527
39694
  const supplied = resolve4(thread.threadPath);
39528
- if (dirname5(supplied) !== root || basename2(supplied) !== `agent-${thread.threadId}` || !/^[a-f0-9-]{36}$/u.test(thread.threadId)) throw fail("pi_thread_not_owned");
39695
+ if (dirname5(supplied) !== root || basename3(supplied) !== `agent-${thread.threadId}` || !/^[a-f0-9-]{36}$/u.test(thread.threadId)) throw fail("pi_thread_not_owned");
39529
39696
  const info = await lstat4(supplied);
39530
39697
  if (info.isSymbolicLink() || !info.isDirectory()) throw fail("pi_thread_not_owned");
39531
39698
  if (await realpath5(supplied) !== supplied) throw fail("pi_thread_not_owned");
@@ -39608,7 +39775,7 @@ var init_pi_adapter = __esm({
39608
39775
  const selection = manager.buildSessionContext().model;
39609
39776
  if (!selection || selection.provider !== model.provider || selection.modelId !== model.id) throw fail("pi_thread_binding_changed", "model");
39610
39777
  } else if (agent) {
39611
- const initial = SessionManager.inMemory(cwd, { id: basename2(cwd).slice("agent-".length) });
39778
+ const initial = SessionManager.inMemory(cwd, { id: basename3(cwd).slice("agent-".length) });
39612
39779
  await writeAtomicInferencePrivateFile(sessionFile, `${JSON.stringify(initial.getHeader())}
39613
39780
  `);
39614
39781
  manager = SessionManager.open(sessionFile, cwd, cwd);
@@ -39679,7 +39846,7 @@ var init_pi_adapter = __esm({
39679
39846
  if (created.modelFallbackMessage || session.model?.id !== model.id || session.model.provider !== model.provider || session.thinkingLevel !== thinkingLevel) throw fail("pi_effective_selection_mismatch", "model");
39680
39847
  if (session.getActiveToolNames().sort().join(",") !== (agent ? [...CODEX_AGENT_DYNAMIC_TOOLS].sort().join(",") : "")) throw fail("pi_tool_isolation_failed");
39681
39848
  if (agent) {
39682
- const threadId = basename2(cwd).slice("agent-".length);
39849
+ const threadId = basename3(cwd).slice("agent-".length);
39683
39850
  thread = { threadId, threadPath: cwd, effectiveModel: input.requestedModel, effectiveReasoningEffort: input.requestedReasoningEffort };
39684
39851
  await agent.onThreadReady?.(thread);
39685
39852
  published = true;
@@ -39874,11 +40041,11 @@ var init_pi_adapter = __esm({
39874
40041
  if (metadata.isSymbolicLink() || !metadata.isDirectory()) throw fail("pi_state_not_owned");
39875
40042
  await ensureInferencePrivateDirectory(stateRoot);
39876
40043
  const root = await realpath5(stateRoot);
39877
- const entries = await readdir2(root, { withFileTypes: true });
40044
+ const entries = await readdir3(root, { withFileTypes: true });
39878
40045
  for (const entry of entries) {
39879
40046
  if (entry.isSymbolicLink() || !entry.isDirectory() || entry.name !== "provider" && !/^agent-[a-f0-9-]{36}$/u.test(entry.name)) throw fail("pi_state_not_owned");
39880
40047
  const path = join7(root, entry.name);
39881
- for (const child of await readdir2(path, { withFileTypes: true })) {
40048
+ for (const child of await readdir3(path, { withFileTypes: true })) {
39882
40049
  if (child.isSymbolicLink() || !child.isFile() || entry.name === "provider" || child.name !== "session.jsonl") throw fail("pi_state_not_owned");
39883
40050
  const contents = await readInferencePrivateFile(join7(path, child.name), "Pi session");
39884
40051
  const header = contents === null ? null : object2(JSON.parse(contents.split("\n", 1)[0]));
@@ -40859,8 +41026,8 @@ var init_grok_runtime = __esm({
40859
41026
 
40860
41027
  // lib/inference-host/grok-state.ts
40861
41028
  import { constants as constants2 } from "node:fs";
40862
- import { lstat as lstat7, mkdtemp as mkdtemp4, open as open3, readdir as readdir3, realpath as realpath6, rm as rm9, rmdir, unlink, writeFile as writeFile3 } from "node:fs/promises";
40863
- import { basename as basename3, dirname as dirname8, join as join10, resolve as resolve6 } from "node:path";
41029
+ import { lstat as lstat7, mkdtemp as mkdtemp4, open as open3, readdir as readdir4, realpath as realpath6, rm as rm9, rmdir, unlink, writeFile as writeFile3 } from "node:fs/promises";
41030
+ import { basename as basename4, dirname as dirname8, join as join10, resolve as resolve6 } from "node:path";
40864
41031
  var markerName, ownedName, invalid, missing, sessionIdValid, directory, nativeDirectory, roots, owner, nativeFile, encodedCwd, nativeSession, removeEmptyNativeGroup, createGrokOwnedWorkspace, bindGrokOwnedSession, validateGrokOwnedThread, releaseGrokOwnedWorkspace, cleanupGrokOwnedState;
40865
41032
  var init_grok_state = __esm({
40866
41033
  "lib/inference-host/grok-state.ts"() {
@@ -40897,7 +41064,7 @@ var init_grok_state = __esm({
40897
41064
  };
40898
41065
  owner = async (options, workspace) => {
40899
41066
  const scope = await roots(options);
40900
- if (workspace !== resolve6(workspace) || dirname8(workspace) !== scope.workspaceRoot || !ownedName.test(basename3(workspace))) throw invalid();
41067
+ if (workspace !== resolve6(workspace) || dirname8(workspace) !== scope.workspaceRoot || !ownedName.test(basename4(workspace))) throw invalid();
40901
41068
  await directory(scope.workspaceRoot);
40902
41069
  await directory(workspace);
40903
41070
  const raw = await readInferencePrivateFile(join10(workspace, markerName), "Grok workspace owner");
@@ -40940,7 +41107,7 @@ var init_grok_state = __esm({
40940
41107
  if (encoded.length <= 255) groups = [join10(sessions, encoded)];
40941
41108
  else {
40942
41109
  groups = [];
40943
- for (const entry of await readdir3(sessions, { withFileTypes: true })) {
41110
+ for (const entry of await readdir4(sessions, { withFileTypes: true })) {
40944
41111
  if (!entry.isDirectory() || entry.isSymbolicLink()) continue;
40945
41112
  const group = join10(sessions, entry.name);
40946
41113
  if (await realpath6(group) !== resolve6(group)) throw invalid();
@@ -40987,7 +41154,7 @@ var init_grok_state = __esm({
40987
41154
  if (missing(error48)) return;
40988
41155
  throw error48;
40989
41156
  }
40990
- const entries = await readdir3(group);
41157
+ const entries = await readdir4(group);
40991
41158
  let cwdMarker = null;
40992
41159
  if (entries.length === 1 && entries[0] === ".cwd") {
40993
41160
  cwdMarker = await nativeFile(join10(group, ".cwd"), 32768);
@@ -41047,7 +41214,7 @@ var init_grok_state = __esm({
41047
41214
  };
41048
41215
  releaseGrokOwnedWorkspace = async (options, workspace, expectedSessionId) => {
41049
41216
  const scope = await roots(options);
41050
- if (workspace !== resolve6(workspace) || dirname8(workspace) !== scope.workspaceRoot || !ownedName.test(basename3(workspace))) throw invalid();
41217
+ if (workspace !== resolve6(workspace) || dirname8(workspace) !== scope.workspaceRoot || !ownedName.test(basename4(workspace))) throw invalid();
41051
41218
  await directory(scope.workspaceRoot);
41052
41219
  try {
41053
41220
  await lstat7(workspace);
@@ -41081,7 +41248,7 @@ var init_grok_state = __esm({
41081
41248
  if (missing(error48)) return;
41082
41249
  throw error48;
41083
41250
  }
41084
- for (const entry of await readdir3(scope.workspaceRoot, { withFileTypes: true })) {
41251
+ for (const entry of await readdir4(scope.workspaceRoot, { withFileTypes: true })) {
41085
41252
  if (!ownedName.test(entry.name)) continue;
41086
41253
  const workspace = join10(scope.workspaceRoot, entry.name);
41087
41254
  try {
@@ -41650,8 +41817,8 @@ var init_grok_auth = __esm({
41650
41817
  import { spawn as spawn9 } from "node:child_process";
41651
41818
  import { randomUUID as randomUUID9, timingSafeEqual as timingSafeEqual2 } from "node:crypto";
41652
41819
  import { createServer as createServer5 } from "node:http";
41653
- import { access as access3, lstat as lstat8, readdir as readdir4, realpath as realpath7, rm as rm10 } from "node:fs/promises";
41654
- import { basename as basename4, dirname as dirname9, join as join12, resolve as resolve7 } from "node:path";
41820
+ import { access as access3, lstat as lstat8, readdir as readdir5, realpath as realpath7, rm as rm10 } from "node:fs/promises";
41821
+ import { basename as basename5, dirname as dirname9, join as join12, resolve as resolve7 } from "node:path";
41655
41822
  import { fileURLToPath as fileURLToPath2 } from "node:url";
41656
41823
  var import_ajv3, failure, object4, validModel, receiptUsage, assertOwnedRuntime, cleanupExoOwnedState, ExoForegroundAdapter;
41657
41824
  var init_exo_adapter = __esm({
@@ -41707,7 +41874,7 @@ var init_exo_adapter = __esm({
41707
41874
  }
41708
41875
  await ensureInferencePrivateDirectory(stateRoot);
41709
41876
  const root = await realpath7(stateRoot);
41710
- for (const entry of await readdir4(root, { withFileTypes: true })) {
41877
+ for (const entry of await readdir5(root, { withFileTypes: true })) {
41711
41878
  const match = /^(?:agent|attempt)-([a-f0-9-]{36})$/u.exec(entry.name);
41712
41879
  if (!match || !entry.isDirectory() || entry.isSymbolicLink()) throw failure("exo_state_not_owned");
41713
41880
  await assertOwnedRuntime(join12(root, entry.name), match[1]);
@@ -41821,7 +41988,7 @@ var init_exo_adapter = __esm({
41821
41988
  async ownedRoot(thread) {
41822
41989
  const parent = await realpath7(this.options.stateRoot);
41823
41990
  const root = resolve7(thread.threadPath);
41824
- if (!/^[a-f0-9-]{36}$/u.test(thread.threadId) || dirname9(root) !== parent || basename4(root) !== `agent-${thread.threadId}`) throw failure("exo_thread_not_owned");
41991
+ if (!/^[a-f0-9-]{36}$/u.test(thread.threadId) || dirname9(root) !== parent || basename5(root) !== `agent-${thread.threadId}`) throw failure("exo_thread_not_owned");
41825
41992
  await assertOwnedRuntime(root, thread.threadId);
41826
41993
  return root;
41827
41994
  }
@@ -48165,7 +48332,8 @@ async function parseError(response, fallback) {
48165
48332
  detail = null;
48166
48333
  }
48167
48334
  const rawDetail = detail && typeof detail === "object" && "detail" in detail ? detail.detail : detail;
48168
- const message = typeof rawDetail === "string" ? rawDetail : fallback;
48335
+ const detailMessage = rawDetail && typeof rawDetail === "object" && typeof rawDetail.message === "string" ? String(rawDetail.message).trim() : "";
48336
+ const message = typeof rawDetail === "string" ? rawDetail : detailMessage || fallback;
48169
48337
  const code = rawDetail && typeof rawDetail === "object" && "code" in rawDetail ? String(rawDetail.code || "") : void 0;
48170
48338
  return new AgentClientError({
48171
48339
  status: response.status,
@@ -50153,7 +50321,7 @@ var init_hyperliquid_account_mode_contract = __esm({
50153
50321
  });
50154
50322
 
50155
50323
  // lib/runtime/hyperliquid-account-contract.ts
50156
- var toNumber, firstNumber, roundTo, normalizeSpotBalancesFromInfoResponse, sumBalanceHoldUsd, sumPositionUnrealizedPnl, resolveTotalUnrealizedPnl, approximatelyEqualAccountValues, buildAccountSummaryFromInfoResponses;
50324
+ var toNumber, firstNumber, roundTo, STABLE_SPOT_SYMBOLS, spotBalanceValueUsd, normalizeSpotBalancesFromInfoResponse, sumBalanceHoldUsd, sumPositionUnrealizedPnl, resolveTotalUnrealizedPnl, approximatelyEqualAccountValues, buildAccountSummaryFromInfoResponses;
50157
50325
  var init_hyperliquid_account_contract = __esm({
50158
50326
  "lib/runtime/hyperliquid-account-contract.ts"() {
50159
50327
  "use strict";
@@ -50178,6 +50346,14 @@ var init_hyperliquid_account_contract = __esm({
50178
50346
  return fallback;
50179
50347
  };
50180
50348
  roundTo = (value, digits = 12) => Number(value.toFixed(digits));
50349
+ STABLE_SPOT_SYMBOLS = /* @__PURE__ */ new Set(["USDC", "USD", "USDT"]);
50350
+ spotBalanceValueUsd = (balance, coin, total) => {
50351
+ const explicit = firstNumber([balance?.value_usd, balance?.usdValue, balance?.usdcValue], Number.NaN);
50352
+ if (Number.isFinite(explicit)) {
50353
+ return explicit;
50354
+ }
50355
+ return STABLE_SPOT_SYMBOLS.has(coin) ? total : 0;
50356
+ };
50181
50357
  normalizeSpotBalancesFromInfoResponse = (spotResponse) => {
50182
50358
  const containers = [];
50183
50359
  if (spotResponse && typeof spotResponse === "object") {
@@ -50196,7 +50372,7 @@ var init_hyperliquid_account_contract = __esm({
50196
50372
  const total = toNumber(balance?.total, 0);
50197
50373
  const hold = toNumber(balance?.hold, 0);
50198
50374
  const available = roundTo(Math.max(0, total - hold));
50199
- const value_usd = toNumber(balance?.value_usd, total);
50375
+ const value_usd = spotBalanceValueUsd(balance, coin, total);
50200
50376
  return {
50201
50377
  coin,
50202
50378
  total,
@@ -50358,7 +50534,7 @@ var init_hyperliquid_active_asset_contract = __esm({
50358
50534
  });
50359
50535
 
50360
50536
  // lib/runtime/server-prompt-rescue-account-contract.ts
50361
- var STABLE_SYMBOLS, toNumber2, firstNumber2, firstTruthy, spotContainers, extractCanonicalSpotMetrics, sumBalanceValueUsd, approximatelyEqual, balancesMirrorUnifiedAccountValue, computeEffectiveAccountValue, equityFormula, buildServerPromptRescueAccountSummary;
50537
+ var toNumber2, firstNumber2, firstTruthy, spotContainers, extractCanonicalSpotMetrics, sumBalanceValueUsd, approximatelyEqual, balancesMirrorUnifiedAccountValue, computeEffectiveAccountValue, equityFormula, buildServerPromptRescueAccountSummary;
50362
50538
  var init_server_prompt_rescue_account_contract = __esm({
50363
50539
  "lib/runtime/server-prompt-rescue-account-contract.ts"() {
50364
50540
  "use strict";
@@ -50366,7 +50542,7 @@ var init_server_prompt_rescue_account_contract = __esm({
50366
50542
  init_define_VTX_GROK_POLICY();
50367
50543
  init_define_VTX_PI_MODEL_POLICY();
50368
50544
  init_hyperliquid_account_mode_contract();
50369
- STABLE_SYMBOLS = /* @__PURE__ */ new Set(["USDC", "USD", "USDT"]);
50545
+ init_hyperliquid_account_contract();
50370
50546
  toNumber2 = (value, fallback = 0) => {
50371
50547
  const numeric2 = Number(value);
50372
50548
  return Number.isFinite(numeric2) ? numeric2 : fallback;
@@ -50437,14 +50613,14 @@ var init_server_prompt_rescue_account_contract = __esm({
50437
50613
  toNumber2(firstTruthy([entry.available, entry.free, total - hold], "0"))
50438
50614
  );
50439
50615
  let valueUsd = toNumber2(firstTruthy([entry.usdValue, entry.usdcValue], "0"));
50440
- if (valueUsd <= 0 && STABLE_SYMBOLS.has(coin)) {
50616
+ if (valueUsd <= 0 && STABLE_SPOT_SYMBOLS.has(coin)) {
50441
50617
  valueUsd = available > 0 ? available : total;
50442
50618
  }
50443
50619
  balances.push({ coin, total, hold, available, value_usd: valueUsd });
50444
50620
  const entryValue = valueUsd > 0 ? valueUsd : total;
50445
50621
  if (entryValue > 0) {
50446
50622
  anyTotal += entryValue;
50447
- if (STABLE_SYMBOLS.has(coin)) stableTotal += entryValue;
50623
+ if (STABLE_SPOT_SYMBOLS.has(coin)) stableTotal += entryValue;
50448
50624
  }
50449
50625
  }
50450
50626
  if (accountValue <= 0) {
@@ -50458,7 +50634,7 @@ var init_server_prompt_rescue_account_contract = __esm({
50458
50634
  };
50459
50635
  sumBalanceValueUsd = (balances) => balances.reduce((total, balance) => {
50460
50636
  let valueUsd = toNumber2(balance.value_usd);
50461
- if (valueUsd <= 0 && STABLE_SYMBOLS.has(String(balance.coin || "").trim().toUpperCase())) {
50637
+ if (valueUsd <= 0 && STABLE_SPOT_SYMBOLS.has(String(balance.coin || "").trim().toUpperCase())) {
50462
50638
  valueUsd = toNumber2(balance.total);
50463
50639
  }
50464
50640
  return total + Math.max(valueUsd, 0);
@@ -50870,7 +51046,13 @@ var init_hyperliquid_account_state_adapter = __esm({
50870
51046
  }
50871
51047
  const parsedProviderRowCount = Number(parsed?.providerRowCount);
50872
51048
  const providerRowCount = Number.isInteger(parsedProviderRowCount) && parsedProviderRowCount >= rawFills.length ? parsedProviderRowCount : rawFills.length;
50873
- const entry = { fetchedAtMs, rawFills, providerRowCount };
51049
+ const parsedOldestFillTimeMs = Number(parsed?.oldestFillTimeMs);
51050
+ const entry = {
51051
+ fetchedAtMs,
51052
+ rawFills,
51053
+ providerRowCount,
51054
+ oldestFillTimeMs: Number.isSafeInteger(parsedOldestFillTimeMs) && parsedOldestFillTimeMs > 0 ? parsedOldestFillTimeMs : null
51055
+ };
50874
51056
  browserUserFillsCache.set(cacheKey, entry);
50875
51057
  return entry;
50876
51058
  } catch {
@@ -51763,6 +51945,7 @@ var init_hyperliquid_account_state_adapter = __esm({
51763
51945
  fetchedAtMs: cached2.fetchedAtMs,
51764
51946
  providerRowCount: cached2.providerRowCount,
51765
51947
  providerPageCap: HYPERLIQUID_USER_FILLS_PROVIDER_PAGE_CAP,
51948
+ oldestFillTimeMs: cached2.oldestFillTimeMs ?? null,
51766
51949
  exactTerminalFillEvidenceComplete: false
51767
51950
  }
51768
51951
  };
@@ -51778,12 +51961,14 @@ var init_hyperliquid_account_state_adapter = __esm({
51778
51961
  fetchedAtMs: cached2.fetchedAtMs,
51779
51962
  providerRowCount: cached2.providerRowCount,
51780
51963
  providerPageCap: HYPERLIQUID_USER_FILLS_PROVIDER_PAGE_CAP,
51964
+ oldestFillTimeMs: cached2.oldestFillTimeMs ?? null,
51781
51965
  exactTerminalFillEvidenceComplete: false
51782
51966
  }
51783
51967
  };
51784
51968
  }
51785
51969
  let rawWalletFills;
51786
51970
  let providerRowCount = 0;
51971
+ let oldestFillTimeMs = null;
51787
51972
  let evidenceSource = "live";
51788
51973
  let fetchedAtMs = now;
51789
51974
  const olderInFlight = browserUserFillsInFlight.get(cacheKey);
@@ -51812,12 +51997,15 @@ var init_hyperliquid_account_state_adapter = __esm({
51812
51997
  ).then((payload) => {
51813
51998
  const providerRowCount2 = Array.isArray(payload) ? payload.length : 0;
51814
51999
  const rawFills2 = Array.isArray(payload) ? payload.filter(isPerpFill).map((fill) => ({ ...fill })) : [];
51815
- writeBrowserUserFillsCache(cacheKey, {
52000
+ const fillTimes = Array.isArray(payload) ? payload.map((fill) => Number(fill?.time)).filter((time3) => Number.isSafeInteger(time3) && time3 > 0) : [];
52001
+ const entry = {
51816
52002
  fetchedAtMs: Date.now(),
51817
52003
  rawFills: rawFills2,
51818
- providerRowCount: providerRowCount2
51819
- });
51820
- return { fetchedAtMs: Date.now(), rawFills: rawFills2, providerRowCount: providerRowCount2 };
52004
+ providerRowCount: providerRowCount2,
52005
+ oldestFillTimeMs: fillTimes.length > 0 ? Math.min(...fillTimes) : null
52006
+ };
52007
+ writeBrowserUserFillsCache(cacheKey, entry);
52008
+ return entry;
51821
52009
  }).finally(() => {
51822
52010
  if (browserUserFillsInFlight.get(cacheKey)?.promise === freshRequest) {
51823
52011
  browserUserFillsInFlight.delete(cacheKey);
@@ -51831,6 +52019,7 @@ var init_hyperliquid_account_state_adapter = __esm({
51831
52019
  rawWalletFills = liveResult.rawFills;
51832
52020
  providerRowCount = liveResult.providerRowCount;
51833
52021
  fetchedAtMs = liveResult.fetchedAtMs;
52022
+ oldestFillTimeMs = liveResult.oldestFillTimeMs ?? null;
51834
52023
  } catch (error48) {
51835
52024
  const staleCache = readBrowserUserFillsCache(cacheKey);
51836
52025
  if (isRateLimitError(error48) && !input.forceRefresh) {
@@ -51838,6 +52027,7 @@ var init_hyperliquid_account_state_adapter = __esm({
51838
52027
  rawWalletFills = staleCache && Date.now() - staleCache.fetchedAtMs <= staleIf429MaxAgeMs ? staleCache.rawFills : [];
51839
52028
  providerRowCount = staleCache?.providerRowCount ?? 0;
51840
52029
  fetchedAtMs = staleCache?.fetchedAtMs ?? Date.now();
52030
+ oldestFillTimeMs = staleCache?.oldestFillTimeMs ?? null;
51841
52031
  } else {
51842
52032
  throw error48;
51843
52033
  }
@@ -51852,6 +52042,7 @@ var init_hyperliquid_account_state_adapter = __esm({
51852
52042
  fetchedAtMs,
51853
52043
  providerRowCount,
51854
52044
  providerPageCap: HYPERLIQUID_USER_FILLS_PROVIDER_PAGE_CAP,
52045
+ oldestFillTimeMs,
51855
52046
  exactTerminalFillEvidenceComplete: evidenceSource === "live" && providerRowCount < HYPERLIQUID_USER_FILLS_PROVIDER_PAGE_CAP
51856
52047
  }
51857
52048
  };
@@ -52534,6 +52725,28 @@ var init_client_host_commands = __esm({
52534
52725
  }
52535
52726
  });
52536
52727
 
52728
+ // lib/api/insights-access-center.ts
52729
+ var init_insights_access_center = __esm({
52730
+ "lib/api/insights-access-center.ts"() {
52731
+ "use strict";
52732
+ init_define_VTX_EXO_POLICY();
52733
+ init_define_VTX_GROK_POLICY();
52734
+ init_define_VTX_PI_MODEL_POLICY();
52735
+ init_shared();
52736
+ }
52737
+ });
52738
+
52739
+ // lib/api/updates.ts
52740
+ var init_updates = __esm({
52741
+ "lib/api/updates.ts"() {
52742
+ "use strict";
52743
+ init_define_VTX_EXO_POLICY();
52744
+ init_define_VTX_GROK_POLICY();
52745
+ init_define_VTX_PI_MODEL_POLICY();
52746
+ init_shared();
52747
+ }
52748
+ });
52749
+
52537
52750
  // lib/runtime/server-runtime-lease.ts
52538
52751
  var CLIENT_RUNTIME_SERVER_LEASE_STORAGE_KEY, canUseStorage, normalizeProfileId, normalizeLeaseGeneration, parseLeaseRecord, readPersistedLeaseMap, writePersistedLeaseMap, isLeaseExpired, getPersistedClientRuntimeServerLease, persistExistingClientRuntimeServerLease, persistClientRuntimeServerLease, clearPersistedClientRuntimeServerLease;
52539
52752
  var init_server_runtime_lease = __esm({
@@ -53243,6 +53456,8 @@ var init_api2 = __esm({
53243
53456
  init_market_data();
53244
53457
  init_screener();
53245
53458
  init_client_host_commands();
53459
+ init_insights_access_center();
53460
+ init_updates();
53246
53461
  init_server_runtime_lease();
53247
53462
  preferencesWriteQueue = Promise.resolve();
53248
53463
  CLIENT_SUPPORTED_PROMPT_CONTRACT_VERSION = String(
@@ -71146,8 +71361,8 @@ var init_network = __esm({
71146
71361
  * Gets a list of all plugins that match %%name%%, with otr without
71147
71362
  * a fragment.
71148
71363
  */
71149
- getPlugins(basename5) {
71150
- return this.plugins.filter((p) => p.name.split("#")[0] === basename5);
71364
+ getPlugins(basename6) {
71365
+ return this.plugins.filter((p) => p.name.split("#")[0] === basename6);
71151
71366
  }
71152
71367
  /**
71153
71368
  * Create a copy of this Network.
@@ -84477,7 +84692,7 @@ var init_hyperliquid_signer = __esm({
84477
84692
  });
84478
84693
 
84479
84694
  // lib/runtime/hyperliquid-client.ts
84480
- var HyperliquidExchangeRejectionError, durableMutationAuthorityArgs, assertFreshPreparedExecutionContext, HYPERLIQUID_TERMINAL_ORDER_STATUSES, normalizeSymbol, HYPERLIQUID_NONCE_STORAGE_KEY, HYPERLIQUID_NONCE_LOCK_NAME, lastGeneratedNonce, readBrowserStoredHyperliquidNonce, writeBrowserStoredHyperliquidNonce, browserNonceCoordinator, allocateHyperliquidNonce, generateHyperliquidNonce, roundToSigFigs, normalizeDecimalString, toPlainDecimalString, roundDirectionalDecimalString, formatHyperliquidPerpPriceWire, formatHyperliquidTriggerPriceWire, countSignificantDigits, countDecimalPlaces, validateHyperliquidPerpPriceWire, validateHyperliquidSizeWire, formatSizeWire, inferApiUrl, inferIsTestnet, postHyperliquidInfo, toFiniteNumber, OPEN_ORDER_NUMERIC_STRING, OPEN_ORDER_ID_STRING, parseCanonicalOpenOrderId, parseOpenOrderFiniteNumber, parseOpenOrderPositiveNumber, parseOpenOrderPresentationNumber, readOpenOrderField, firstFiniteNumber2, parseFundingUsdcFromInfoPosition2, isExchangeIsolatedOnly, computeHip3AssetId, getPerpDexIndexMap, buildAssetInfosFromMetaResponse, requireWalletAddress2, assertPositiveInteger, assertPositiveNumber, normalizeOrderSide, normalizeHyperliquidClientOrderId, resolveAssets, findResolvedAsset, normalizeExecutionAssetMetadata, resolveHyperliquidAsset, resolveHyperliquidAssetIndex, fetchBrowserAvailableAssets, fetchBrowserAllMids, fetchBrowserSymbolMidPrice, fetchBrowserOpenOrders, parseCanonicalHyperliquidOrderStatusEvidence, fetchBrowserOrderStatusEvidence, fetchBrowserUserRole, fetchBrowserAccountState2, fetchBrowserPosition, buildHyperliquidOrderWire, buildHyperliquidTriggerOrderWire, signHyperliquidPayload, buildHyperliquidCancelPayload, buildHyperliquidUpdateLeveragePayload, buildHyperliquidMarketOrderPayload, buildHyperliquidTriggerOrderPayload, buildHyperliquidOrderBatchPayload, buildHyperliquidModifyOrderPayload, extractHyperliquidExchangeError, isDefinitiveHyperliquidExchangeResponse, extractDefinitiveHyperliquidOrderId, CANONICAL_POSITIVE_DECIMAL_PATTERN, extractCanonicalHyperliquidOrderStateAcknowledgement, extractCanonicalHyperliquidOrderStateAcknowledgements, extractCanonicalHyperliquidFilledOrderAcknowledgement, extractDefinitiveHyperliquidOrderMemberResults, buildHyperliquidOrderDiagnostics, loadClientExecutionReferenceEvidence, sha256Hex, extractSignedPayloadClientOrderId, extractSignedPayloadMutationCorrelation, assertDurableMutationMatchesSignedAction, exchangeRejectionReason, exchangeActionPriority, submitHyperliquidExchangePayload;
84695
+ var HyperliquidExchangeRejectionError, durableMutationAuthorityArgs, assertFreshPreparedExecutionContext, HYPERLIQUID_TERMINAL_ORDER_STATUSES, normalizeSymbol, HYPERLIQUID_NONCE_STORAGE_KEY, HYPERLIQUID_NONCE_LOCK_NAME, lastGeneratedNonce, readBrowserStoredHyperliquidNonce, writeBrowserStoredHyperliquidNonce, browserNonceCoordinator, allocateHyperliquidNonce, generateHyperliquidNonce, roundToSigFigs, normalizeDecimalString, toPlainDecimalString, roundDirectionalDecimalString, formatHyperliquidPerpPriceWire, formatHyperliquidTriggerPriceWire, countSignificantDigits, countDecimalPlaces, validateHyperliquidPerpPriceWire, validateHyperliquidSizeWire, formatSizeWire, inferApiUrl, inferIsTestnet, postHyperliquidInfo, toFiniteNumber, OPEN_ORDER_NUMERIC_STRING, OPEN_ORDER_ID_STRING, parseCanonicalOpenOrderId, parseOpenOrderFiniteNumber, parseOpenOrderPositiveNumber, parseOpenOrderPresentationNumber, readOpenOrderField, firstFiniteNumber2, parseFundingUsdcFromInfoPosition2, isExchangeIsolatedOnly, computeHip3AssetId, getPerpDexIndexMap, buildAssetInfosFromMetaResponse, requireWalletAddress2, assertPositiveInteger, assertPositiveNumber, normalizeOrderSide, normalizeHyperliquidClientOrderId, resolveAssets, findResolvedAsset, normalizeExecutionAssetMetadata, resolveHyperliquidAsset, resolveHyperliquidAssetIndex, fetchBrowserAvailableAssets, fetchBrowserAllMids, fetchBrowserSymbolMidPrice, fetchBrowserOpenOrders, parseCanonicalHyperliquidOrderStatusEvidence, fetchBrowserOrderStatusEvidence, fetchBrowserUserRole, fetchBrowserAccountState2, fetchBrowserPosition, buildHyperliquidOrderWire, buildHyperliquidTriggerOrderWire, signHyperliquidPayload, buildHyperliquidCancelPayload, buildHyperliquidUpdateLeveragePayload, buildHyperliquidMarketOrderPayload, buildHyperliquidTriggerOrderPayload, buildHyperliquidOrderBatchPayload, buildHyperliquidModifyOrderPayload, extractHyperliquidExchangeError, resolveHyperliquidTriggerAcknowledgements, isDefinitiveHyperliquidExchangeResponse, extractDefinitiveHyperliquidOrderId, CANONICAL_POSITIVE_DECIMAL_PATTERN, extractCanonicalHyperliquidOrderStateAcknowledgement, extractCanonicalHyperliquidOrderStateAcknowledgements, extractCanonicalHyperliquidFilledOrderAcknowledgement, extractDefinitiveHyperliquidOrderMemberResults, buildHyperliquidOrderDiagnostics, loadClientExecutionReferenceEvidence, sha256Hex, extractSignedPayloadClientOrderId, extractSignedPayloadMutationCorrelation, assertDurableMutationMatchesSignedAction, exchangeRejectionReason, exchangeActionPriority, submitHyperliquidExchangePayload;
84481
84696
  var init_hyperliquid_client = __esm({
84482
84697
  "lib/runtime/hyperliquid-client.ts"() {
84483
84698
  "use strict";
@@ -85713,6 +85928,40 @@ var init_hyperliquid_client = __esm({
85713
85928
  }
85714
85929
  return null;
85715
85930
  };
85931
+ resolveHyperliquidTriggerAcknowledgements = async (payload, action, lookup) => {
85932
+ if (action.type !== "order" || action.grouping !== "normalTpsl" && action.grouping !== "positionTpsl" || !Array.isArray(action.orders) || payload == null || typeof payload !== "object" || Array.isArray(payload)) {
85933
+ return payload;
85934
+ }
85935
+ const root = payload;
85936
+ const response = root.response;
85937
+ const data4 = response && typeof response === "object" ? response.data : void 0;
85938
+ const statuses = data4 && typeof data4 === "object" && Array.isArray(data4.statuses) ? data4.statuses : null;
85939
+ if (root.status !== "ok" || response?.type !== "order" || statuses == null || statuses.length !== action.orders.length || !statuses.includes("waitingForTrigger")) {
85940
+ return payload;
85941
+ }
85942
+ const resolved = [...statuses];
85943
+ for (let index = 0; index < statuses.length; index += 1) {
85944
+ if (statuses[index] !== "waitingForTrigger") continue;
85945
+ const order = action.orders[index];
85946
+ const trigger = order && typeof order === "object" ? order.t : void 0;
85947
+ const clientOrderId = String(order?.c ?? "").trim().toLowerCase();
85948
+ if (!trigger || typeof trigger !== "object" || !("trigger" in trigger) || !/^0x[0-9a-f]{32}$/.test(clientOrderId)) {
85949
+ return payload;
85950
+ }
85951
+ let evidence;
85952
+ try {
85953
+ evidence = await lookup(clientOrderId);
85954
+ } catch {
85955
+ return payload;
85956
+ }
85957
+ const orderId = Number(evidence.orderId);
85958
+ if (!evidence.responseValid || !evidence.orderMatches || evidence.orderStatus !== "open" || evidence.isTrigger !== true || !Number.isSafeInteger(orderId) || orderId <= 0) {
85959
+ return payload;
85960
+ }
85961
+ resolved[index] = { resting: { oid: orderId, cloid: clientOrderId } };
85962
+ }
85963
+ return { ...root, response: { ...response, data: { ...data4, statuses: resolved } } };
85964
+ };
85716
85965
  isDefinitiveHyperliquidExchangeResponse = (payload, action) => {
85717
85966
  if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
85718
85967
  return false;
@@ -86419,6 +86668,18 @@ var init_hyperliquid_client = __esm({
86419
86668
  "outcome_unknown"
86420
86669
  );
86421
86670
  }
86671
+ const triggerWallet = String(input.triggerAcknowledgementWalletAddress ?? "").trim();
86672
+ if (triggerWallet) {
86673
+ payload = await resolveHyperliquidTriggerAcknowledgements(
86674
+ payload,
86675
+ input.payload.action,
86676
+ (clientOrderId) => fetchBrowserOrderStatusEvidence({
86677
+ ...input,
86678
+ walletAddress: triggerWallet,
86679
+ orderId: clientOrderId
86680
+ })
86681
+ );
86682
+ }
86422
86683
  const exchangeError = extractHyperliquidExchangeError(payload);
86423
86684
  if (exchangeError) {
86424
86685
  await settleDurableMutation(
@@ -86737,7 +86998,7 @@ var init_openai_compatible_capabilities = __esm({
86737
86998
  });
86738
86999
 
86739
87000
  // lib/local-ai.ts
86740
- var LOCAL_CONTEXT_CACHE_TTL_MS, LOCAL_AI_SERVER_TYPE_ALIASES, normalizeLocalAiServerType;
87001
+ var LOCAL_CONTEXT_CACHE_TTL_MS, LOCAL_AI_SERVER_TYPE_ALIASES, normalizeLocalAiServerType, endpointOrigin, sameEndpointOriginKey;
86741
87002
  var init_local_ai = __esm({
86742
87003
  "lib/local-ai.ts"() {
86743
87004
  "use strict";
@@ -86761,6 +87022,17 @@ var init_local_ai = __esm({
86761
87022
  }
86762
87023
  return Object.prototype.hasOwnProperty.call(LOCAL_AI_SERVER_TYPE_ALIASES, normalized) ? "openai-compatible" : null;
86763
87024
  };
87025
+ endpointOrigin = (value) => {
87026
+ try {
87027
+ return value ? new URL(value).origin : null;
87028
+ } catch {
87029
+ return null;
87030
+ }
87031
+ };
87032
+ sameEndpointOriginKey = (saved, targetBaseUrl) => {
87033
+ const savedOrigin = endpointOrigin(saved?.baseUrl);
87034
+ return savedOrigin !== null && savedOrigin === endpointOrigin(targetBaseUrl) ? saved?.apiKey || void 0 : void 0;
87035
+ };
86764
87036
  }
86765
87037
  });
86766
87038
 
@@ -87130,7 +87402,10 @@ var init_vault = __esm({
87130
87402
  serverType: localNormalized?.localAi?.serverType ?? remoteNormalized?.localAi?.serverType
87131
87403
  }) : normalizeLocalAiSecrets({
87132
87404
  baseUrl: remoteNormalized?.localAi?.baseUrl,
87133
- apiKey: remoteNormalized?.localAi?.apiKey ?? localNormalized?.localAi?.apiKey,
87405
+ apiKey: remoteNormalized?.localAi?.apiKey ?? sameEndpointOriginKey(
87406
+ localNormalized?.localAi,
87407
+ remoteNormalized?.localAi?.baseUrl
87408
+ ),
87134
87409
  serverType: remoteNormalized?.localAi?.serverType ?? localNormalized?.localAi?.serverType
87135
87410
  });
87136
87411
  const mergedOpenAiCompatible = storage2.byok === "device" ? normalizeOpenAiCompatibleSecrets({
@@ -87138,7 +87413,10 @@ var init_vault = __esm({
87138
87413
  apiKey: localNormalized?.openaiCompatible?.apiKey
87139
87414
  }) : normalizeOpenAiCompatibleSecrets({
87140
87415
  baseUrl: remoteNormalized?.openaiCompatible?.baseUrl,
87141
- apiKey: remoteNormalized?.openaiCompatible?.apiKey ?? localNormalized?.openaiCompatible?.apiKey
87416
+ apiKey: remoteNormalized?.openaiCompatible?.apiKey ?? sameEndpointOriginKey(
87417
+ localNormalized?.openaiCompatible,
87418
+ remoteNormalized?.openaiCompatible?.baseUrl
87419
+ )
87142
87420
  });
87143
87421
  return validateDeviceSecrets({
87144
87422
  hyperliquidSigningKey: storage2.hyperliquid === "device" ? localNormalized?.hyperliquidSigningKey : remoteNormalized?.hyperliquidSigningKey,
@@ -87157,8 +87435,15 @@ var init_vault = __esm({
87157
87435
  return null;
87158
87436
  }
87159
87437
  const storage2 = normalizeDeviceSecretStorage(normalized.storage);
87160
- const localAi = storage2.byok === "device" ? normalizeLocalAiSecrets(normalized.localAi) : normalizeLocalAiSecrets({ apiKey: normalized.localAi?.apiKey, serverType: normalized.localAi?.serverType });
87161
- const openaiCompatible = storage2.byok === "device" ? normalizeOpenAiCompatibleSecrets(normalized.openaiCompatible) : normalizeOpenAiCompatibleSecrets({ apiKey: normalized.openaiCompatible?.apiKey });
87438
+ const localAi = storage2.byok === "device" ? normalizeLocalAiSecrets(normalized.localAi) : normalizeLocalAiSecrets({
87439
+ apiKey: normalized.localAi?.apiKey,
87440
+ baseUrl: normalized.localAi?.apiKey ? normalized.localAi?.baseUrl : void 0,
87441
+ serverType: normalized.localAi?.serverType
87442
+ });
87443
+ const openaiCompatible = storage2.byok === "device" ? normalizeOpenAiCompatibleSecrets(normalized.openaiCompatible) : normalizeOpenAiCompatibleSecrets({
87444
+ apiKey: normalized.openaiCompatible?.apiKey,
87445
+ baseUrl: normalized.openaiCompatible?.apiKey ? normalized.openaiCompatible?.baseUrl : void 0
87446
+ });
87162
87447
  return validateDeviceSecrets({
87163
87448
  hyperliquidSigningKey: storage2.hyperliquid === "device" ? normalized.hyperliquidSigningKey : void 0,
87164
87449
  providerKeys: storage2.byok === "device" ? { ...normalized.providerKeys } : {},
@@ -87744,7 +88029,8 @@ var init_browser_trading = __esm({
87744
88029
  symbol: input.symbol,
87745
88030
  clientOrderIds: input.members.map((member) => member.clientOrderId),
87746
88031
  onExchangeOrderDispatched: input.onExchangeOrderDispatched
87747
- }
88032
+ },
88033
+ triggerAcknowledgementWalletAddress: input.walletAddress ?? null
87748
88034
  });
87749
88035
  };
87750
88036
  executeClientModifyOrder = async (input) => {
@@ -88109,7 +88395,7 @@ var init_execution_guard_contract = __esm({
88109
88395
  });
88110
88396
 
88111
88397
  // lib/runtime/runtime-execution.ts
88112
- var executionReadPriority, fetchClientRuntimeOpenOrders, createRuntimeId, _extractOrderId, _toExecutionMetadata, _extractClientMutationId, trailingStopMemory, protectiveGroupMemory, protectiveGroupReadFailures, windowHandoffCleanupAttempts, clientRuntimeProtectionStorage, resolveClientRuntimeProtectionStorage, setClientRuntimeProtectionStorage, trailingStopStorageKey, readTrackedTrailingStops, writeTrackedTrailingStops, rememberTrailingStop, protectiveGroupStorageKey, readClientProtectiveGroups, writeClientProtectiveGroups, hasClientProtectiveGroupReadFailure, readFreshClientProtectiveGroups, stableProtectionSnapshot, exactClientProtectiveGroupSnapshot, exactClientProtectiveGroupSetSnapshot, replaceExactClientProtectiveGroup, replaceExactClientProtectiveGroupSet, isClientRuntimeLeaseOwnershipError, hasClientRuntimeProtectionState, clearClientRuntimeVetoedProtectiveIntent, rethrowWindowHandoffAfterProtectiveReplacementVeto, canPersistClientProtectiveGroups, removeTrackedTrailingStop, replaceTrackedTrailingStop, replaceProtectiveLeg, replacementJournalEntryOrderId, buildProtectiveReplacementJournalGroup, isProtectiveReplacementJournalGroup, reserveProtectiveLegReplacement, ensureProtectiveReplacementJournalCompanion, buildVetoedProtectiveReplacementCleanup, assertExactProtectiveReplacementDispatchAuthority, transitionProtectiveReplacementAcknowledgement, transitionTerminalProtectiveReplacement, pendingProtectiveReplacementReport, toPositiveNumber, resolveRiskPct, buildTriggerPrice, isConfiguredProtectionRequested, protectiveAction, isExactClientPositionTpslPair, hasAmbiguousClientPositionTpslAuthority, protectiveStableShapeMatches, protectiveLiveShapeMatches, protectiveTerminalShapeMatches, cancelClientProtectiveLeg, buildPendingProtectivePlan, attachClientProtectivePlan, resolveJournaledAttachmentContinuity, recoverJournaledClientProtectiveAttachments, recoverPendingClientProtectiveGroups, recoverPendingProtectiveReplacements, reconcileClientProtectiveGroups, cancelAllClientProtectiveGroups, tightenClientTrailingStops, throwIfAborted2, sleep3, roundAssetSize, resolvePositionSize, resolveCurrentPositionSize, buildPositionSnapshot, signedRemainingExposureAfterConfirmedReduction, verifyNoLiveClientProtectiveTriggers, clientExecutionMutations, withClientExecutionMutation, executeClientRuntimeDecision, maintainClientRuntimeTrailingStops, executeClientRuntimeDecisionUnlocked;
88398
+ var clientProtectiveMutationAuthority, executionReadPriority, fetchClientRuntimeOpenOrders, createRuntimeId, _extractOrderId, _toExecutionMetadata, _extractClientMutationId, trailingStopMemory, protectiveGroupMemory, protectiveGroupReadFailures, windowHandoffCleanupAttempts, clientRuntimeProtectionStorage, resolveClientRuntimeProtectionStorage, setClientRuntimeProtectionStorage, trailingStopStorageKey, readTrackedTrailingStops, writeTrackedTrailingStops, rememberTrailingStop, protectiveGroupStorageKey, readClientProtectiveGroups, writeClientProtectiveGroups, hasClientProtectiveGroupReadFailure, readFreshClientProtectiveGroups, stableProtectionSnapshot, exactClientProtectiveGroupSnapshot, exactClientProtectiveGroupSetSnapshot, replaceExactClientProtectiveGroup, replaceExactClientProtectiveGroupSet, isClientRuntimeLeaseOwnershipError, hasClientRuntimeProtectionState, clearClientRuntimeVetoedProtectiveIntent, rethrowWindowHandoffAfterProtectiveReplacementVeto, canPersistClientProtectiveGroups, removeTrackedTrailingStop, replaceTrackedTrailingStop, replaceProtectiveLeg, replacementJournalEntryOrderId, buildProtectiveReplacementJournalGroup, isProtectiveReplacementJournalGroup, reserveProtectiveLegReplacement, ensureProtectiveReplacementJournalCompanion, buildVetoedProtectiveReplacementCleanup, assertExactProtectiveReplacementDispatchAuthority, transitionProtectiveReplacementAcknowledgement, transitionTerminalProtectiveReplacement, pendingProtectiveReplacementReport, toPositiveNumber, resolveRiskPct, buildTriggerPrice, isConfiguredProtectionRequested, protectiveAction, isExactClientPositionTpslPair, hasAmbiguousClientPositionTpslAuthority, protectiveStableShapeMatches, protectiveLiveShapeMatches, protectiveTerminalShapeMatches, cancelClientProtectiveLeg, buildPendingProtectivePlan, persistPendingClientProtectiveGroup, attachClientProtectivePlan, resolveJournaledAttachmentContinuity, recoverJournaledClientProtectiveAttachments, recoverPendingClientProtectiveGroups, recoverPendingProtectiveReplacements, reconcileClientProtectiveGroups, cancelAllClientProtectiveGroups, tightenClientTrailingStops, throwIfAborted2, sleep3, roundAssetSize, resolvePositionSize, resolveCurrentPositionSize, buildPositionSnapshot, signedRemainingExposureAfterConfirmedReduction, verifyNoLiveClientProtectiveTriggers, clientExecutionMutations, withClientExecutionMutation, executeClientRuntimeDecision, maintainClientRuntimeTrailingStops, executeClientRuntimeDecisionUnlocked;
88113
88399
  var init_runtime_execution = __esm({
88114
88400
  "lib/runtime/runtime-execution.ts"() {
88115
88401
  "use strict";
@@ -88125,6 +88411,12 @@ var init_runtime_execution = __esm({
88125
88411
  init_runtime_redaction();
88126
88412
  init_error_surface_contract();
88127
88413
  init_runtime_handoff();
88414
+ clientProtectiveMutationAuthority = (request) => request.mutationAuthority === "manual_session" ? {} : {
88415
+ runtimeSessionId: request.sessionId || "__missing_runtime_session__",
88416
+ runtimeLeaseToken: request.runtimeLeaseToken,
88417
+ runtimeDeviceId: request.runtimeDeviceId,
88418
+ schedulerInstanceId: request.schedulerInstanceId
88419
+ };
88128
88420
  executionReadPriority = (input) => {
88129
88421
  const context = input.executionContext;
88130
88422
  const classified = classifyExecutionIntent(
@@ -89138,10 +89430,7 @@ var init_runtime_execution = __esm({
89138
89430
  await executeClientCancelOrder({
89139
89431
  publicRequestPriority: "trading_reduce",
89140
89432
  profileId: request.profileId,
89141
- runtimeSessionId: request.sessionId || "__missing_runtime_session__",
89142
- runtimeLeaseToken: request.runtimeLeaseToken,
89143
- runtimeDeviceId: request.runtimeDeviceId,
89144
- schedulerInstanceId: request.schedulerInstanceId,
89433
+ ...clientProtectiveMutationAuthority(request),
89145
89434
  walletAddress: request.executionContext.walletAddress,
89146
89435
  config: request.config ?? null,
89147
89436
  signal: request.signal,
@@ -89174,24 +89463,58 @@ var init_runtime_execution = __esm({
89174
89463
  };
89175
89464
  }
89176
89465
  };
89177
- buildPendingProtectivePlan = (request, input) => ({
89466
+ buildPendingProtectivePlan = (settings, input) => ({
89178
89467
  ...input,
89179
89468
  stopLoss: {
89180
- enabled: request.executionContext.stopLossEnabled !== false,
89181
- mode: request.executionContext.stopLossMode === "usdc" ? "usdc" : "percent",
89469
+ enabled: settings.stopLossEnabled !== false,
89470
+ mode: settings.stopLossMode === "usdc" ? "usdc" : "percent",
89182
89471
  value: toPositiveNumber(
89183
- request.executionContext.stopLossMode === "usdc" ? request.executionContext.stopLossUsdc : request.executionContext.stopLossPct
89472
+ settings.stopLossMode === "usdc" ? settings.stopLossUsdc : settings.stopLossPct
89184
89473
  ),
89185
- isTrailing: request.executionContext.stopLossType === "trailing"
89474
+ isTrailing: settings.stopLossType === "trailing"
89186
89475
  },
89187
89476
  takeProfit: {
89188
- enabled: request.executionContext.takeProfitEnabled !== false,
89189
- mode: request.executionContext.takeProfitMode === "usdc" ? "usdc" : "percent",
89477
+ enabled: settings.takeProfitEnabled !== false,
89478
+ mode: settings.takeProfitMode === "usdc" ? "usdc" : "percent",
89190
89479
  value: toPositiveNumber(
89191
- request.executionContext.takeProfitMode === "usdc" ? request.executionContext.takeProfitUsdc : request.executionContext.takeProfitPct
89480
+ settings.takeProfitMode === "usdc" ? settings.takeProfitUsdc : settings.takeProfitPct
89192
89481
  )
89193
89482
  }
89194
89483
  });
89484
+ persistPendingClientProtectiveGroup = (input) => {
89485
+ const { profileId, symbol: symbol2 } = input;
89486
+ const group = {
89487
+ version: 2,
89488
+ profileId,
89489
+ symbol: symbol2.trim().toUpperCase(),
89490
+ walletAddress: String(input.walletAddress || "").trim().toLowerCase(),
89491
+ entryOrderId: input.entryClientOrderId,
89492
+ isLong: input.entrySide === "buy",
89493
+ legs: [],
89494
+ pendingEntry: buildPendingProtectivePlan(input.settings, {
89495
+ entryMutationId: input.entryMutationId,
89496
+ entryClientOrderId: input.entryClientOrderId,
89497
+ entrySide: input.entrySide,
89498
+ requestedSize: input.requestedSize
89499
+ })
89500
+ };
89501
+ const cleanup = {
89502
+ kind: "vetoed_protective_intent",
89503
+ profileId,
89504
+ symbol: symbol2,
89505
+ entryOrderId: group.entryOrderId,
89506
+ pendingGroupSnapshot: exactClientProtectiveGroupSnapshot(group)
89507
+ };
89508
+ const existingGroups = readFreshClientProtectiveGroups(profileId, symbol2);
89509
+ const nextGroups = [...existingGroups, group];
89510
+ const persistenceFailed = hasClientProtectiveGroupReadFailure(profileId, symbol2) || !replaceExactClientProtectiveGroupSet(
89511
+ profileId,
89512
+ symbol2,
89513
+ existingGroups,
89514
+ nextGroups
89515
+ );
89516
+ return { group, cleanup, persistedGroupSet: persistenceFailed ? null : nextGroups };
89517
+ };
89195
89518
  attachClientProtectivePlan = async (request, group, fill) => {
89196
89519
  const reports = [];
89197
89520
  const plan = group.pendingEntry;
@@ -89255,8 +89578,7 @@ var init_runtime_execution = __esm({
89255
89578
  "trading_reduce"
89256
89579
  );
89257
89580
  const livePositionSize = Number(snapshot.size);
89258
- const directionMatches = Number.isFinite(livePositionSize) && (isLong ? livePositionSize > 0 : livePositionSize < 0);
89259
- if (!directionMatches) {
89581
+ if (!Number.isFinite(livePositionSize)) {
89260
89582
  reports.push({
89261
89583
  order_id: fill.orderId,
89262
89584
  symbol: symbol2,
@@ -89266,6 +89588,26 @@ var init_runtime_execution = __esm({
89266
89588
  });
89267
89589
  return reports;
89268
89590
  }
89591
+ const directionMatches = isLong ? livePositionSize > 0 : livePositionSize < 0;
89592
+ if (!directionMatches) {
89593
+ const flat = livePositionSize === 0;
89594
+ const retired = replaceExactClientProtectiveGroupSet(
89595
+ profileId,
89596
+ symbol2,
89597
+ observedGroups,
89598
+ existingGroups
89599
+ );
89600
+ reports.push({
89601
+ order_id: fill.orderId,
89602
+ symbol: symbol2,
89603
+ action: "PROTECTIVE_RECONCILIATION",
89604
+ status: "failed",
89605
+ execution_metadata: {
89606
+ reason_code: !retired ? "protective_lifecycle_persistence_failed" : flat ? "protective_position_flat" : "protective_position_drift"
89607
+ }
89608
+ });
89609
+ return reports;
89610
+ }
89269
89611
  const liveExposure = Math.abs(livePositionSize);
89270
89612
  const allocatedCandidates = planned.flatMap((candidate) => {
89271
89613
  const allocated = existingGroups.flatMap((existing) => existing.legs).filter((leg) => leg.kind === candidate.kind).reduce((total, leg) => total + leg.size, 0);
@@ -89273,7 +89615,22 @@ var init_runtime_execution = __esm({
89273
89615
  Math.min(fill.filledSize, Math.max(0, liveExposure - allocated)),
89274
89616
  request.executionContext.sizeDecimals
89275
89617
  );
89276
- if (!Number.isFinite(size) || size <= 0) return [];
89618
+ if (!Number.isFinite(size) || size <= 0) {
89619
+ reports.push({
89620
+ order_id: null,
89621
+ symbol: symbol2,
89622
+ action: candidate.kind === "sl" ? "AUTO_SL" : "AUTO_TP",
89623
+ status: "blocked",
89624
+ execution_metadata: {
89625
+ reason_code: "protective_exposure_already_covered",
89626
+ entry_order_id: fill.orderId,
89627
+ entry_filled_size: fill.filledSize,
89628
+ entry_average_price: fill.averagePrice,
89629
+ live_position_size: livePositionSize
89630
+ }
89631
+ });
89632
+ return [];
89633
+ }
89277
89634
  const triggerPrice = buildTriggerPrice(
89278
89635
  fill.averagePrice,
89279
89636
  resolveRiskPct(
@@ -89315,7 +89672,7 @@ var init_runtime_execution = __esm({
89315
89672
  (candidate) => candidate.triggerPrice <= 0
89316
89673
  );
89317
89674
  if (invalidCandidates.length > 0) {
89318
- for (const candidate of invalidCandidates) {
89675
+ for (const candidate of allocatedCandidates) {
89319
89676
  reports.push({
89320
89677
  order_id: fill.orderId,
89321
89678
  symbol: symbol2,
@@ -89323,6 +89680,7 @@ var init_runtime_execution = __esm({
89323
89680
  status: "failed",
89324
89681
  execution_metadata: {
89325
89682
  reason_code: "protective_trigger_invalid",
89683
+ ...candidate.triggerPrice > 0 ? { invalid_sibling: true } : {},
89326
89684
  entry_filled_size: fill.filledSize,
89327
89685
  entry_average_price: fill.averagePrice
89328
89686
  }
@@ -89540,10 +89898,7 @@ var init_runtime_execution = __esm({
89540
89898
  if (positionTpsl) {
89541
89899
  response = await executeClientOrderBatch({
89542
89900
  profileId: request.profileId,
89543
- runtimeSessionId: request.sessionId || "__missing_runtime_session__",
89544
- runtimeLeaseToken: request.runtimeLeaseToken,
89545
- runtimeDeviceId: request.runtimeDeviceId,
89546
- schedulerInstanceId: request.schedulerInstanceId,
89901
+ ...clientProtectiveMutationAuthority(request),
89547
89902
  walletAddress: request.executionContext.walletAddress,
89548
89903
  config: request.config ?? null,
89549
89904
  signal: request.signal,
@@ -89573,10 +89928,7 @@ var init_runtime_execution = __esm({
89573
89928
  const candidate = candidates[0];
89574
89929
  response = await executeClientTriggerOrder({
89575
89930
  profileId: request.profileId,
89576
- runtimeSessionId: request.sessionId || "__missing_runtime_session__",
89577
- runtimeLeaseToken: request.runtimeLeaseToken,
89578
- runtimeDeviceId: request.runtimeDeviceId,
89579
- schedulerInstanceId: request.schedulerInstanceId,
89931
+ ...clientProtectiveMutationAuthority(request),
89580
89932
  walletAddress: request.executionContext.walletAddress,
89581
89933
  config: request.config ?? null,
89582
89934
  signal: request.signal,
@@ -89649,14 +90001,15 @@ var init_runtime_execution = __esm({
89649
90001
  return acknowledgement == null ? null : [acknowledgement];
89650
90002
  })();
89651
90003
  if (acknowledgements == null) {
89652
- return candidates.map((candidate) => ({
90004
+ reports.push(...candidates.map((candidate) => ({
89653
90005
  order_id: null,
89654
90006
  client_mutation_id: candidate.mutationId,
89655
90007
  symbol: symbol2,
89656
90008
  action: candidate.kind === "sl" ? "AUTO_SL" : "AUTO_TP",
89657
90009
  status: "blocked",
89658
90010
  execution_metadata: { reason_code: "protective_trigger_ack_unresolved" }
89659
- }));
90011
+ })));
90012
+ return reports;
89660
90013
  }
89661
90014
  const acknowledgedLegs = acknowledgements.map((acknowledgement, index) => ({
89662
90015
  ...provisionalLegs[index],
@@ -90452,7 +90805,9 @@ var init_runtime_execution = __esm({
90452
90805
  execution_metadata: {
90453
90806
  reason_code: "protective_replacement_terminal_reconciled",
90454
90807
  previous_order_id: replacement.previousOrderId,
90455
- order_status: evidence.orderStatus
90808
+ order_status: evidence.orderStatus,
90809
+ protected_size: replacementLeg.size,
90810
+ position_tpsl: replacementLeg.positionTpsl === true
90456
90811
  }
90457
90812
  });
90458
90813
  continue;
@@ -90508,7 +90863,8 @@ var init_runtime_execution = __esm({
90508
90863
  reason_code: exactLivePositionTpsl ? "protective_replacement_reconciled_for_cleanup" : "protective_replacement_reconciled",
90509
90864
  previous_order_id: replacement.previousOrderId,
90510
90865
  trigger_price: replacement.triggerPrice,
90511
- protected_size: replacement.size
90866
+ protected_size: replacement.size,
90867
+ position_tpsl: recoveredLeg.positionTpsl === true
90512
90868
  }
90513
90869
  });
90514
90870
  continue;
@@ -90553,7 +90909,8 @@ var init_runtime_execution = __esm({
90553
90909
  reason_code: "protective_replacement_fulfilled_reconciled",
90554
90910
  previous_order_id: replacement.previousOrderId,
90555
90911
  trigger_price: replacement.triggerPrice,
90556
- protected_size: replacement.size
90912
+ protected_size: replacement.size,
90913
+ position_tpsl: leg.positionTpsl === true
90557
90914
  }
90558
90915
  });
90559
90916
  continue;
@@ -90656,7 +91013,8 @@ var init_runtime_execution = __esm({
90656
91013
  reason_code: acknowledgement.state === "fulfilled" ? "protective_replacement_fulfilled_reconciled" : "protective_replacement_reconciled",
90657
91014
  previous_order_id: replacement.previousOrderId,
90658
91015
  trigger_price: replacement.triggerPrice,
90659
- protected_size: replacement.size
91016
+ protected_size: replacement.size,
91017
+ position_tpsl: effectiveLeg.positionTpsl === true
90660
91018
  }
90661
91019
  });
90662
91020
  continue;
@@ -90694,7 +91052,8 @@ var init_runtime_execution = __esm({
90694
91052
  reason_code: "protective_replacement_reconciled",
90695
91053
  previous_order_id: replacement.previousOrderId,
90696
91054
  trigger_price: replacement.triggerPrice,
90697
- protected_size: replacement.size
91055
+ protected_size: replacement.size,
91056
+ position_tpsl: canonicalReplacementLeg.positionTpsl === true
90698
91057
  }
90699
91058
  });
90700
91059
  } catch (error48) {
@@ -90770,7 +91129,9 @@ var init_runtime_execution = __esm({
90770
91129
  status: "executed",
90771
91130
  execution_metadata: {
90772
91131
  reason_code: "protective_replacement_terminal_reconciled",
90773
- order_status: evidence.orderStatus
91132
+ order_status: evidence.orderStatus,
91133
+ protected_size: journalLeg.size,
91134
+ position_tpsl: journalLeg.positionTpsl === true || evidence.isPositionTpsl === true
90774
91135
  }
90775
91136
  });
90776
91137
  continue;
@@ -91394,7 +91755,8 @@ var init_runtime_execution = __esm({
91394
91755
  execution_metadata: {
91395
91756
  reason_code: "protective_resized_to_live_exposure",
91396
91757
  previous_order_id: leg.orderId,
91397
- protected_size: allowedSize
91758
+ protected_size: allowedSize,
91759
+ position_tpsl: replacementLeg.positionTpsl === true
91398
91760
  }
91399
91761
  });
91400
91762
  if (fulfilledDuringResize) {
@@ -91857,7 +92219,9 @@ var init_runtime_execution = __esm({
91857
92219
  execution_metadata: {
91858
92220
  trigger_price: replacementTriggerPrice,
91859
92221
  previous_trigger_price: record5.triggerPrice,
91860
- previous_order_id: record5.orderId
92222
+ previous_order_id: record5.orderId,
92223
+ protected_size: effectiveSize,
92224
+ position_tpsl: record5.positionTpsl === true
91861
92225
  }
91862
92226
  });
91863
92227
  } catch (error48) {
@@ -92614,41 +92978,19 @@ var init_runtime_execution = __esm({
92614
92978
  if (shouldAttachSlTp) {
92615
92979
  entryMutationId = createRuntimeId().toLowerCase();
92616
92980
  entryClientOrderId = `0x${entryMutationId.replaceAll("-", "")}`;
92617
- const profileId2 = String(input.profileId).trim();
92618
- pendingProtectiveGroup = {
92619
- version: 2,
92620
- profileId: profileId2,
92621
- symbol: input.executionContext.symbol.trim().toUpperCase(),
92622
- walletAddress: String(input.executionContext.walletAddress || "").trim().toLowerCase(),
92623
- entryOrderId: entryClientOrderId,
92624
- isLong: classified.side === "buy",
92625
- legs: [],
92626
- pendingEntry: buildPendingProtectivePlan(input, {
92627
- entryMutationId,
92628
- entryClientOrderId,
92629
- entrySide: classified.side,
92630
- requestedSize: sizeAsset
92631
- })
92632
- };
92633
- pendingProtectiveCleanup = {
92634
- kind: "vetoed_protective_intent",
92635
- profileId: profileId2,
92981
+ const pendingProtection = persistPendingClientProtectiveGroup({
92982
+ profileId: String(input.profileId).trim(),
92636
92983
  symbol: input.executionContext.symbol,
92637
- entryOrderId: pendingProtectiveGroup.entryOrderId,
92638
- pendingGroupSnapshot: exactClientProtectiveGroupSnapshot(pendingProtectiveGroup)
92639
- };
92640
- const existingGroups = readFreshClientProtectiveGroups(
92641
- profileId2,
92642
- input.executionContext.symbol
92643
- );
92644
- const nextGroups = [...existingGroups, pendingProtectiveGroup];
92645
- const persistenceFailed = hasClientProtectiveGroupReadFailure(profileId2, input.executionContext.symbol) || !replaceExactClientProtectiveGroupSet(
92646
- profileId2,
92647
- input.executionContext.symbol,
92648
- existingGroups,
92649
- nextGroups
92650
- );
92651
- if (persistenceFailed) {
92984
+ walletAddress: input.executionContext.walletAddress,
92985
+ settings: input.executionContext,
92986
+ entryMutationId,
92987
+ entryClientOrderId,
92988
+ entrySide: classified.side,
92989
+ requestedSize: sizeAsset
92990
+ });
92991
+ pendingProtectiveGroup = pendingProtection.group;
92992
+ pendingProtectiveCleanup = pendingProtection.cleanup;
92993
+ if (pendingProtection.persistedGroupSet == null) {
92652
92994
  const cleanupComplete = clearClientRuntimeVetoedProtectiveIntent(
92653
92995
  pendingProtectiveCleanup
92654
92996
  );
@@ -92679,7 +93021,7 @@ var init_runtime_execution = __esm({
92679
93021
  executionSnapshotCapturedAt
92680
93022
  };
92681
93023
  }
92682
- persistedProtectiveGroupSet = nextGroups;
93024
+ persistedProtectiveGroupSet = pendingProtection.persistedGroupSet;
92683
93025
  }
92684
93026
  let marketOrderResponse;
92685
93027
  let entryDispatchBoundaryPassed = false;
@@ -93089,6 +93431,7 @@ var init_runtime_execution = __esm({
93089
93431
  is_take_profit: triggerInput.isTakeProfit,
93090
93432
  entry_filled_size: protectionSize,
93091
93433
  protected_size: legSize,
93434
+ position_tpsl: leg.positionTpsl === true,
93092
93435
  entry_average_price: protectionEntryPrice,
93093
93436
  ..._toExecutionMetadata(triggerResponse)
93094
93437
  }
@@ -95057,8 +95400,34 @@ function parseMarketOrderPayload(args) {
95057
95400
  if (estimatedPriceTimestampMs) {
95058
95401
  payload.estimated_price_timestamp_ms = parsePositiveInt(estimatedPriceTimestampMs, "--estimated-price-timestamp-ms");
95059
95402
  }
95403
+ if (args.includes("--reduce-only")) {
95404
+ payload.reduce_only = true;
95405
+ }
95406
+ const protection = parseMarketOrderProtection(args);
95407
+ if (protection) {
95408
+ payload.protection = protection;
95409
+ }
95060
95410
  return payload;
95061
95411
  }
95412
+ function parseMarketOrderProtection(args) {
95413
+ const leg = (name) => {
95414
+ const percent = optionalValue(args, `--${name}-percent`);
95415
+ const usdc = optionalValue(args, `--${name}-usdc`);
95416
+ if (percent && usdc) {
95417
+ throw new Error(`Use either --${name}-percent or --${name}-usdc, not both`);
95418
+ }
95419
+ if (percent) return { mode: "percent", value: parsePositiveNumber(percent, `--${name}-percent`) };
95420
+ if (usdc) return { mode: "usdc", value: parsePositiveNumber(usdc, `--${name}-usdc`) };
95421
+ return null;
95422
+ };
95423
+ const takeProfit = leg("take-profit");
95424
+ const stopLoss = leg("stop-loss");
95425
+ if (!takeProfit && !stopLoss) return null;
95426
+ return {
95427
+ ...takeProfit ? { take_profit: takeProfit } : {},
95428
+ ...stopLoss ? { stop_loss: { ...stopLoss, stop_type: "fixed" } } : {}
95429
+ };
95430
+ }
95062
95431
  function parseLimitOrderPayload(args) {
95063
95432
  return {
95064
95433
  symbol: normalizeHyperliquidMarketSymbol(requireValue(args, "--symbol")),
@@ -95417,6 +95786,17 @@ Common commands:
95417
95786
  runtime events Read recent runtime events and errors
95418
95787
  inference-host --help Set up an automated or agent-driven inference host
95419
95788
 
95789
+ Trading commands (Server Mode profiles):
95790
+ trade market-order --symbol <s> --side buy|sell --size <n>
95791
+ [--slippage <fraction>] [--estimated-price <n>] [--reduce-only]
95792
+ [--take-profit-percent <n> | --take-profit-usdc <n>]
95793
+ [--stop-loss-percent <n> | --stop-loss-usdc <n>]
95794
+ Fixed TP/SL as reduce-only market triggers from the
95795
+ average fill, within the AI page's Auto SL/TP limits;
95796
+ not allowed with --reduce-only; no trailing stops
95797
+ trade limit-order --symbol <s> --side buy|sell --size <n> --limit-price <n> [--reduce-only]
95798
+ trade cancel-order --symbol <s> --oid <n>
95799
+
95420
95800
  Global options:
95421
95801
  --json Emit machine-readable JSON
95422
95802
  --profile <id> Select one VTX profile