@vtxmacro/cli 2026.8.51 → 2026.8.52

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.
Files changed (2) hide show
  1. package/bin/vtx.js +701 -73
  2. package/package.json +1 -1
package/bin/vtx.js CHANGED
@@ -5,11 +5,20 @@ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
5
  var __getOwnPropNames = Object.getOwnPropertyNames;
6
6
  var __getProtoOf = Object.getPrototypeOf;
7
7
  var __hasOwnProp = Object.prototype.hasOwnProperty;
8
- var __esm = (fn, res) => function __init() {
9
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
8
+ var __esm = (fn, res, err) => function __init() {
9
+ if (err) throw err[0];
10
+ try {
11
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
12
+ } catch (e) {
13
+ throw err = [e], e;
14
+ }
10
15
  };
11
16
  var __commonJS = (cb, mod2) => function __require() {
12
- return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports;
17
+ try {
18
+ return mod2 || (0, cb[__getOwnPropNames(cb)[0]])((mod2 = { exports: {} }).exports, mod2), mod2.exports;
19
+ } catch (e) {
20
+ throw mod2 = 0, e;
21
+ }
13
22
  };
14
23
  var __export = (target, all) => {
15
24
  for (var name in all)
@@ -38,7 +47,7 @@ var init_agent_cli_release = __esm({
38
47
  "agent-cli-release.json"() {
39
48
  agent_cli_release_default = {
40
49
  package_name: "@vtxmacro/cli",
41
- package_version: "2026.8.51",
50
+ package_version: "2026.8.52",
42
51
  codex_package_name: "@openai/codex",
43
52
  codex_version: "0.147.0",
44
53
  copilot_sdk_package_name: "@github/copilot-sdk",
@@ -16535,6 +16544,25 @@ async function syncInferenceDirectory(path, platform = process.platform) {
16535
16544
  await handle.close();
16536
16545
  }
16537
16546
  }
16547
+ async function replaceAtomicInferencePrivateFile(temporaryPath, destinationPath, options = {}) {
16548
+ const platform = options.platform ?? process.platform;
16549
+ const renameFile = options.renameFile ?? rename;
16550
+ const sleep4 = options.sleep ?? ((milliseconds) => new Promise((resolve6) => setTimeout(resolve6, milliseconds)));
16551
+ const maxAttempts = Math.max(1, options.maxAttempts ?? 40);
16552
+ const retryDelayMs = Math.max(0, options.retryDelayMs ?? 25);
16553
+ for (let attempt = 0; attempt < maxAttempts; attempt += 1) {
16554
+ try {
16555
+ await renameFile(temporaryPath, destinationPath);
16556
+ return;
16557
+ } catch (error48) {
16558
+ const code = String(error48.code ?? "");
16559
+ if (platform !== "win32" || !WINDOWS_PRIVATE_FILE_REPLACE_ERROR_CODES.has(code) || attempt === maxAttempts - 1) {
16560
+ throw error48;
16561
+ }
16562
+ await sleep4(retryDelayMs);
16563
+ }
16564
+ }
16565
+ }
16538
16566
  async function writeAtomicInferencePrivateFile(path, contents, dependencies = {}) {
16539
16567
  const platform = dependencies.platform ?? process.platform;
16540
16568
  const runner = dependencies.runner ?? runWindowsPrivateAcl;
@@ -16571,7 +16599,13 @@ async function writeAtomicInferencePrivateFile(path, contents, dependencies = {}
16571
16599
  }
16572
16600
  try {
16573
16601
  invalidateWindowsAclCache(path);
16574
- await rename(temporary, path);
16602
+ await replaceAtomicInferencePrivateFile(temporary, path, {
16603
+ platform,
16604
+ renameFile: dependencies.renameFile,
16605
+ sleep: dependencies.sleep,
16606
+ maxAttempts: dependencies.replaceMaxAttempts,
16607
+ retryDelayMs: dependencies.replaceRetryDelayMs
16608
+ });
16575
16609
  if (platform === "win32" && hardenedIdentity) {
16576
16610
  await rebindHardenedWindowsAclAfterRename(
16577
16611
  temporary,
@@ -16838,7 +16872,7 @@ async function acquireInferenceHostProcessLock(path, dependencies = {}) {
16838
16872
  }
16839
16873
  };
16840
16874
  }
16841
- var 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, processLockObservationCache, inferenceProcessIdentitiesMatch, DEFAULT_INFERENCE_HOST_INSTANCE, SAFE_INFERENCE_HOST_INSTANCE, requireNamedInstancePath, credentialStoreIdentity, inferenceHostCredentialContextPath, inferenceHostCredentialContextTransitionPath, credentialContextForConfig;
16875
+ var 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, processLockObservationCache, inferenceProcessIdentitiesMatch, DEFAULT_INFERENCE_HOST_INSTANCE, SAFE_INFERENCE_HOST_INSTANCE, requireNamedInstancePath, credentialStoreIdentity, inferenceHostCredentialContextPath, inferenceHostCredentialContextTransitionPath, credentialContextForConfig, WINDOWS_PRIVATE_FILE_REPLACE_ERROR_CODES;
16842
16876
  var init_config = __esm({
16843
16877
  "lib/inference-host/config.ts"() {
16844
16878
  "use strict";
@@ -17413,6 +17447,13 @@ while(($line=[Console]::In.ReadLine()) -ne $null) {
17413
17447
  credential_store_mode: config2.credentialStoreMode,
17414
17448
  credential_file_path: config2.credentialStoreMode === "file" ? resolve(config2.credentialFilePath) : null
17415
17449
  });
17450
+ WINDOWS_PRIVATE_FILE_REPLACE_ERROR_CODES = /* @__PURE__ */ new Set([
17451
+ "EACCES",
17452
+ "EBUSY",
17453
+ "EEXIST",
17454
+ "ENOTEMPTY",
17455
+ "EPERM"
17456
+ ]);
17416
17457
  }
17417
17458
  });
17418
17459
 
@@ -38220,7 +38261,18 @@ var init_sort_utils = __esm({
38220
38261
  });
38221
38262
 
38222
38263
  // lib/runtime/hyperliquid-account-mode-contract.ts
38223
- var UNIFIED_MODE_ALIASES, normalizeAccountMode, extractAccountModeFromPayload, extractAccountModeCandidateFromPayload, isUnifiedAccountMode;
38264
+ function resolveExactHyperliquidAccountMode(userAbstraction, ...dexEvidence) {
38265
+ const mode = extractCanonicalHyperliquidAccountMode(userAbstraction);
38266
+ if (!mode) {
38267
+ throw new Error("Exact Hyperliquid userAbstraction response is invalid.");
38268
+ }
38269
+ if (mode !== "default" && mode !== "disabled") return mode;
38270
+ if (dexEvidence.length < 1) {
38271
+ throw new Error("Exact Hyperliquid userDexAbstraction response is unavailable.");
38272
+ }
38273
+ return parseExactDexAbstractionEnabled(dexEvidence[0]) ? "dexAbstraction" : mode;
38274
+ }
38275
+ var UNIFIED_MODE_ALIASES, CANONICAL_ACCOUNT_MODE_ALIASES, EXACT_MODE_KEYS, EXACT_MODE_BOOLEAN_KEYS, isExactTruthyFlag, normalizeCanonicalHyperliquidAccountMode, extractCanonicalHyperliquidAccountMode, parseExactDexAbstractionEnabled, normalizeAccountMode, extractAccountModeFromPayload, extractAccountModeCandidateFromPayload, isUnifiedAccountMode;
38224
38276
  var init_hyperliquid_account_mode_contract = __esm({
38225
38277
  "lib/runtime/hyperliquid-account-mode-contract.ts"() {
38226
38278
  "use strict";
@@ -38231,6 +38283,89 @@ var init_hyperliquid_account_mode_contract = __esm({
38231
38283
  "unified",
38232
38284
  "pm"
38233
38285
  ]);
38286
+ CANONICAL_ACCOUNT_MODE_ALIASES = /* @__PURE__ */ new Map([
38287
+ ["default", "default"],
38288
+ ["standard", "default"],
38289
+ ["classic", "default"],
38290
+ ["disabled", "disabled"],
38291
+ ["unifiedaccount", "unifiedAccount"],
38292
+ ["unified", "unifiedAccount"],
38293
+ ["portfoliomargin", "portfolioMargin"],
38294
+ ["pm", "portfolioMargin"],
38295
+ ["dexabstraction", "dexAbstraction"]
38296
+ ]);
38297
+ EXACT_MODE_KEYS = [
38298
+ "accountMode",
38299
+ "account_mode",
38300
+ "accountType",
38301
+ "account_type",
38302
+ "accountUnificationMode",
38303
+ "account_unification_mode",
38304
+ "abstractionMode",
38305
+ "abstraction_mode",
38306
+ "abstraction",
38307
+ "abstractionState",
38308
+ "dexAbstractionState",
38309
+ "marginMode",
38310
+ "state",
38311
+ "mode",
38312
+ "value"
38313
+ ];
38314
+ EXACT_MODE_BOOLEAN_KEYS = [
38315
+ ["unifiedAccount", ["isUnifiedAccount", "unifiedAccount", "isUnified", "unified", "is_unified_account"]],
38316
+ ["portfolioMargin", ["isPortfolioMargin", "portfolioMargin", "isPm", "pm", "is_portfolio_margin"]],
38317
+ ["dexAbstraction", ["isDexAbstraction", "dexAbstraction", "dexAbstractionEnabled", "is_dex_abstraction"]],
38318
+ ["default", ["isClassic", "classic", "isStandard", "standard"]]
38319
+ ];
38320
+ isExactTruthyFlag = (value) => value === true || value === 1 || typeof value === "string" && value.trim().toLowerCase() === "true";
38321
+ normalizeCanonicalHyperliquidAccountMode = (value) => {
38322
+ if (typeof value !== "string") return null;
38323
+ const key = value.trim().replace(/[_\s-]/g, "").toLowerCase();
38324
+ return CANONICAL_ACCOUNT_MODE_ALIASES.get(key) ?? null;
38325
+ };
38326
+ extractCanonicalHyperliquidAccountMode = (payload, depth = 0) => {
38327
+ if (depth > 6) return null;
38328
+ const direct = normalizeCanonicalHyperliquidAccountMode(payload);
38329
+ if (direct) return direct;
38330
+ if (Array.isArray(payload)) {
38331
+ for (const item of payload) {
38332
+ const mode = extractCanonicalHyperliquidAccountMode(item, depth + 1);
38333
+ if (mode) return mode;
38334
+ }
38335
+ return null;
38336
+ }
38337
+ if (!payload || typeof payload !== "object") return null;
38338
+ const source = payload;
38339
+ for (const key of EXACT_MODE_KEYS) {
38340
+ if (!(key in source)) continue;
38341
+ const mode = normalizeCanonicalHyperliquidAccountMode(source[key]);
38342
+ if (mode) return mode;
38343
+ }
38344
+ for (const [mode, keys] of EXACT_MODE_BOOLEAN_KEYS) {
38345
+ for (const key of keys) {
38346
+ if (isExactTruthyFlag(source[key])) return mode;
38347
+ }
38348
+ }
38349
+ for (const value of Object.values(source)) {
38350
+ const mode = extractCanonicalHyperliquidAccountMode(value, depth + 1);
38351
+ if (mode) return mode;
38352
+ }
38353
+ return null;
38354
+ };
38355
+ parseExactDexAbstractionEnabled = (payload) => {
38356
+ if (payload == null || payload === false) return false;
38357
+ if (payload === true) return true;
38358
+ if (typeof payload === "string") {
38359
+ const normalized = payload.trim().toLowerCase();
38360
+ if (normalized === "true") return true;
38361
+ if (normalized === "false") return false;
38362
+ }
38363
+ if (typeof payload === "number" && Number.isFinite(payload)) {
38364
+ if (payload === 1) return true;
38365
+ if (payload === 0) return false;
38366
+ }
38367
+ throw new Error("Exact Hyperliquid userDexAbstraction response is invalid.");
38368
+ };
38234
38369
  normalizeAccountMode = (mode) => String(mode ?? "").trim().toLowerCase().replace(/[_\s-]/g, "");
38235
38370
  extractAccountModeFromPayload = (payload) => {
38236
38371
  const candidate = extractAccountModeCandidateFromPayload(payload);
@@ -38455,6 +38590,229 @@ var init_hyperliquid_active_asset_contract = __esm({
38455
38590
  }
38456
38591
  });
38457
38592
 
38593
+ // lib/runtime/server-prompt-rescue-account-contract.ts
38594
+ var STABLE_SYMBOLS, toNumber2, firstNumber2, firstTruthy, spotContainers, extractCanonicalSpotMetrics, sumBalanceValueUsd, approximatelyEqual, balancesMirrorUnifiedAccountValue, computeEffectiveAccountValue, equityFormula, buildServerPromptRescueAccountSummary;
38595
+ var init_server_prompt_rescue_account_contract = __esm({
38596
+ "lib/runtime/server-prompt-rescue-account-contract.ts"() {
38597
+ "use strict";
38598
+ init_hyperliquid_account_mode_contract();
38599
+ STABLE_SYMBOLS = /* @__PURE__ */ new Set(["USDC", "USD", "USDT"]);
38600
+ toNumber2 = (value, fallback = 0) => {
38601
+ const numeric = Number(value);
38602
+ return Number.isFinite(numeric) ? numeric : fallback;
38603
+ };
38604
+ firstNumber2 = (values, fallback = 0) => {
38605
+ for (const value of values) {
38606
+ if (value == null || value === "") continue;
38607
+ const numeric = Number(value);
38608
+ if (Number.isFinite(numeric)) return numeric;
38609
+ }
38610
+ return fallback;
38611
+ };
38612
+ firstTruthy = (values, fallback) => {
38613
+ for (const value of values) {
38614
+ if (value) return value;
38615
+ }
38616
+ return fallback;
38617
+ };
38618
+ spotContainers = (spotResponse) => {
38619
+ if (!spotResponse || typeof spotResponse !== "object" || Array.isArray(spotResponse)) return [];
38620
+ const response = spotResponse;
38621
+ const containers = [response];
38622
+ for (const key of ["spotState", "userState", "clearinghouseState", "state", "data"]) {
38623
+ const child = response[key];
38624
+ if (child && typeof child === "object" && !Array.isArray(child)) containers.push(child);
38625
+ }
38626
+ return containers;
38627
+ };
38628
+ extractCanonicalSpotMetrics = (spotResponse) => {
38629
+ const response = spotResponse && typeof spotResponse === "object" && !Array.isArray(spotResponse) ? spotResponse : {};
38630
+ const containers = spotContainers(response);
38631
+ let accountValue = 0;
38632
+ let totalMarginUsed = 0;
38633
+ let withdrawable = 0;
38634
+ for (const container of containers) {
38635
+ const marginSummary = container.marginSummary && typeof container.marginSummary === "object" && !Array.isArray(container.marginSummary) ? container.marginSummary : {};
38636
+ accountValue = Math.max(accountValue, toNumber2(marginSummary.accountValue));
38637
+ totalMarginUsed = Math.max(totalMarginUsed, toNumber2(marginSummary.totalMarginUsed));
38638
+ withdrawable = Math.max(withdrawable, toNumber2(container.withdrawable));
38639
+ }
38640
+ if (accountValue <= 0) {
38641
+ for (const key of ["accountValue", "totalValue", "equity", "totalRawUsd", "usdValue", "usdcValue"]) {
38642
+ accountValue = Math.max(accountValue, toNumber2(response[key]));
38643
+ }
38644
+ }
38645
+ const balances = [];
38646
+ const listKeys = ["balances", "tokenBalances", "spotBalances", "assets"];
38647
+ for (const container of containers) {
38648
+ for (const listKey of listKeys) {
38649
+ const bucket = container[listKey];
38650
+ if (!Array.isArray(bucket)) continue;
38651
+ let stableTotal = 0;
38652
+ let anyTotal = 0;
38653
+ for (const rawEntry of bucket) {
38654
+ if (!rawEntry || typeof rawEntry !== "object" || Array.isArray(rawEntry)) continue;
38655
+ const entry = rawEntry;
38656
+ const coin = String(firstTruthy([
38657
+ entry.coin,
38658
+ entry.token,
38659
+ entry.asset,
38660
+ entry.symbol
38661
+ ], "")).trim().toUpperCase();
38662
+ if (!coin) continue;
38663
+ const total = toNumber2(firstTruthy([entry.total, entry.balance, entry.amount], "0"));
38664
+ const hold = toNumber2(firstTruthy([entry.hold, entry.locked], "0"));
38665
+ const available = Math.max(
38666
+ 0,
38667
+ toNumber2(firstTruthy([entry.available, entry.free, total - hold], "0"))
38668
+ );
38669
+ let valueUsd = toNumber2(firstTruthy([entry.usdValue, entry.usdcValue], "0"));
38670
+ if (valueUsd <= 0 && STABLE_SYMBOLS.has(coin)) {
38671
+ valueUsd = available > 0 ? available : total;
38672
+ }
38673
+ balances.push({ coin, total, hold, available, value_usd: valueUsd });
38674
+ const entryValue = valueUsd > 0 ? valueUsd : total;
38675
+ if (entryValue > 0) {
38676
+ anyTotal += entryValue;
38677
+ if (STABLE_SYMBOLS.has(coin)) stableTotal += entryValue;
38678
+ }
38679
+ }
38680
+ if (accountValue <= 0) {
38681
+ if (stableTotal > 0) accountValue = stableTotal;
38682
+ else if (anyTotal > 0) accountValue = anyTotal;
38683
+ }
38684
+ }
38685
+ if (balances.length > 0) break;
38686
+ }
38687
+ return { accountValue, totalMarginUsed, withdrawable, balances };
38688
+ };
38689
+ sumBalanceValueUsd = (balances) => balances.reduce((total, balance) => {
38690
+ let valueUsd = toNumber2(balance.value_usd);
38691
+ if (valueUsd <= 0 && STABLE_SYMBOLS.has(String(balance.coin || "").trim().toUpperCase())) {
38692
+ valueUsd = toNumber2(balance.total);
38693
+ }
38694
+ return total + Math.max(valueUsd, 0);
38695
+ }, 0);
38696
+ approximatelyEqual = (left, right, absoluteToleranceUsd, relativeTolerance) => {
38697
+ const reference = Math.max(Math.abs(left), Math.abs(right), 1);
38698
+ return Math.abs(left - right) <= Math.max(absoluteToleranceUsd, reference * relativeTolerance);
38699
+ };
38700
+ balancesMirrorUnifiedAccountValue = (input) => input.perpsEquity > 0 && input.spotEquity > 0 && input.balancesEquity > 0 && approximatelyEqual(
38701
+ input.perpsEquity,
38702
+ input.spotEquity,
38703
+ input.absoluteToleranceUsd,
38704
+ input.relativeTolerance
38705
+ ) && approximatelyEqual(
38706
+ input.spotEquity,
38707
+ input.balancesEquity,
38708
+ input.absoluteToleranceUsd,
38709
+ input.relativeTolerance
38710
+ );
38711
+ computeEffectiveAccountValue = (input) => {
38712
+ if (!input.unifiedLike) return input.perpsEquity;
38713
+ if (input.balancesEquity > 0) {
38714
+ if (input.mirrored) {
38715
+ return Math.max(input.perpsEquity, input.spotEquity, input.balancesEquity);
38716
+ }
38717
+ return Math.max(
38718
+ input.perpsEquity + input.balancesEquity,
38719
+ input.spotEquity,
38720
+ input.balancesEquity
38721
+ );
38722
+ }
38723
+ return Math.max(input.perpsEquity, input.spotEquity);
38724
+ };
38725
+ equityFormula = (input) => {
38726
+ if (!input.unifiedLike) return "perps_account_value";
38727
+ if (input.balancesEquity > 0) {
38728
+ if (input.mirrored) return "unified_mirrored_balances_equity";
38729
+ if (input.perpsEquity + input.balancesEquity >= Math.max(input.spotEquity, input.balancesEquity)) return "unified_perps_plus_balances";
38730
+ if (input.spotEquity >= input.balancesEquity) return "unified_spot_account_value";
38731
+ return "unified_balances_equity";
38732
+ }
38733
+ return input.perpsEquity >= input.spotEquity ? "unified_perps_account_value" : "unified_spot_account_value";
38734
+ };
38735
+ buildServerPromptRescueAccountSummary = (perpsResponse, spotResponse, accountMode, options = {}) => {
38736
+ const perps = perpsResponse && typeof perpsResponse === "object" && !Array.isArray(perpsResponse) ? perpsResponse : {};
38737
+ const marginSummary = perps.marginSummary && typeof perps.marginSummary === "object" && !Array.isArray(perps.marginSummary) ? perps.marginSummary : {};
38738
+ const crossMarginSummary = perps.crossMarginSummary && typeof perps.crossMarginSummary === "object" && !Array.isArray(perps.crossMarginSummary) ? perps.crossMarginSummary : {};
38739
+ const rawPerpsAccountValue = toNumber2(marginSummary.accountValue);
38740
+ const perpsAccountValue = Math.max(0, rawPerpsAccountValue);
38741
+ const crossMarginAccountValue = toNumber2(crossMarginSummary.accountValue);
38742
+ let totalMarginUsed = toNumber2(marginSummary.totalMarginUsed);
38743
+ let withdrawable = toNumber2(perps.withdrawable);
38744
+ const spot = accountMode === "disabled" ? { accountValue: 0, totalMarginUsed: 0, withdrawable: 0, balances: [] } : extractCanonicalSpotMetrics(spotResponse);
38745
+ const balances = spot.balances;
38746
+ const balancesEquity = sumBalanceValueUsd(balances);
38747
+ const unifiedLike = isUnifiedAccountMode(accountMode);
38748
+ if (unifiedLike) {
38749
+ totalMarginUsed = Math.max(totalMarginUsed, spot.totalMarginUsed);
38750
+ withdrawable = Math.max(withdrawable, spot.withdrawable);
38751
+ }
38752
+ const absoluteToleranceUsd = firstNumber2([
38753
+ options.mirroredAccountValueAbsoluteToleranceUsd,
38754
+ options.mirrored_account_value_absolute_tolerance_usd
38755
+ ]);
38756
+ const relativeTolerance = firstNumber2([
38757
+ options.mirroredAccountValueRelativeTolerance,
38758
+ options.mirrored_account_value_relative_tolerance
38759
+ ]);
38760
+ const mirrored = balancesMirrorUnifiedAccountValue({
38761
+ perpsEquity: perpsAccountValue,
38762
+ spotEquity: Math.max(spot.accountValue, 0),
38763
+ balancesEquity,
38764
+ absoluteToleranceUsd,
38765
+ relativeTolerance
38766
+ });
38767
+ const formulaInput = {
38768
+ perpsEquity: perpsAccountValue,
38769
+ spotEquity: Math.max(spot.accountValue, 0),
38770
+ balancesEquity,
38771
+ unifiedLike,
38772
+ mirrored
38773
+ };
38774
+ const accountValue = computeEffectiveAccountValue(formulaInput);
38775
+ const maintenanceMargin = toNumber2(perps.crossMaintenanceMarginUsed);
38776
+ const calculatedAvailable = accountValue - totalMarginUsed;
38777
+ const availableMargin = maintenanceMargin > 0 ? Math.max(
38778
+ calculatedAvailable,
38779
+ Math.max(0, accountValue - 4 * maintenanceMargin),
38780
+ withdrawable
38781
+ ) : Math.max(calculatedAvailable, withdrawable);
38782
+ let totalNotional = 0;
38783
+ let totalUnrealizedPnl = 0;
38784
+ const positions = Array.isArray(perps.assetPositions) ? perps.assetPositions : [];
38785
+ for (const entry of positions) {
38786
+ const position = entry && typeof entry === "object" && !Array.isArray(entry) ? entry.position : null;
38787
+ if (!position || typeof position !== "object" || Array.isArray(position)) continue;
38788
+ const size = toNumber2(position.szi);
38789
+ const unrealizedPnl = toNumber2(position.unrealizedPnl);
38790
+ totalUnrealizedPnl += unrealizedPnl;
38791
+ totalNotional += Math.abs(size * toNumber2(position.entryPx) + unrealizedPnl);
38792
+ }
38793
+ return {
38794
+ account_value: accountValue,
38795
+ total_margin_used: totalMarginUsed,
38796
+ available_margin: availableMargin,
38797
+ withdrawable,
38798
+ cross_margin_ratio: accountValue > 0 ? maintenanceMargin / accountValue : 0,
38799
+ maintenance_margin: maintenanceMargin,
38800
+ cross_account_leverage: accountValue > 0 ? totalNotional / accountValue : 0,
38801
+ total_unrealized_pnl: totalUnrealizedPnl,
38802
+ account_mode: accountMode,
38803
+ mode_source: "canonical",
38804
+ balances,
38805
+ raw_account_value: rawPerpsAccountValue,
38806
+ cross_margin_account_value: crossMarginAccountValue,
38807
+ spot_account_value: spot.accountValue,
38808
+ balances_equity: balancesEquity,
38809
+ equity_formula: equityFormula(formulaInput),
38810
+ balance_trust_classification: "trusted_canonical"
38811
+ };
38812
+ };
38813
+ }
38814
+ });
38815
+
38458
38816
  // lib/runtime/abort.ts
38459
38817
  var ABORT_MESSAGE_TOKENS, readAbortLikeMessage, isAbortLikeError;
38460
38818
  var init_abort = __esm({
@@ -39021,6 +39379,8 @@ var init_hyperliquid_account_state_adapter = __esm({
39021
39379
  init_sort_utils();
39022
39380
  init_hyperliquid_account_contract();
39023
39381
  init_hyperliquid_active_asset_contract();
39382
+ init_hyperliquid_account_mode_contract();
39383
+ init_server_prompt_rescue_account_contract();
39024
39384
  init_hyperliquid_market_symbol();
39025
39385
  init_network_debug();
39026
39386
  unsupportedUserActiveAssetCache = /* @__PURE__ */ new Set();
@@ -39136,13 +39496,15 @@ var init_hyperliquid_account_state_adapter = __esm({
39136
39496
  buildUserFillsStorageKey = (cacheKey) => {
39137
39497
  return `${USER_FILLS_CACHE_STORAGE_PREFIX}${cacheKey}`;
39138
39498
  };
39139
- buildAccountStateCacheKey = (apiUrl, walletAddress, symbol2, aggregatePerpDexs, dexNames, includeEffectiveTakerRate) => {
39499
+ buildAccountStateCacheKey = (apiUrl, walletAddress, symbol2, aggregatePerpDexs, dexNames, includeEffectiveTakerRate, includeExactAccountMode, includeActiveAssetData) => {
39140
39500
  return [
39141
39501
  apiUrl.replace(/\/$/, "").toLowerCase(),
39142
39502
  walletAddress.trim().toLowerCase(),
39143
39503
  normalizeHyperliquidMarketSymbol(symbol2),
39144
39504
  aggregatePerpDexs ? "aggregate" : "selected",
39145
39505
  includeEffectiveTakerRate ? "with-effective-taker-rate" : "without-effective-taker-rate",
39506
+ includeExactAccountMode ? "with-exact-account-mode" : "without-exact-account-mode",
39507
+ includeActiveAssetData ? "with-active-asset" : "without-active-asset",
39146
39508
  ...dexNames.map(normalizePerpDexName).sort()
39147
39509
  ].join("::");
39148
39510
  };
@@ -39352,7 +39714,8 @@ var init_hyperliquid_account_state_adapter = __esm({
39352
39714
  accountSummary: { ...result2.accountSummary },
39353
39715
  availableToTrade: { ...result2.availableToTrade },
39354
39716
  positions: result2.positions.map((position) => ({ ...position })),
39355
- ...result2.takerRate == null ? {} : { takerRate: result2.takerRate }
39717
+ ...result2.takerRate == null ? {} : { takerRate: result2.takerRate },
39718
+ ...result2.promptRescueEvidence == null ? {} : { promptRescueEvidence: { ...result2.promptRescueEvidence } }
39356
39719
  });
39357
39720
  readBrowserAccountStateCache = (cacheKey) => {
39358
39721
  const memoryEntry = browserAccountStateCache.get(cacheKey);
@@ -39382,7 +39745,8 @@ var init_hyperliquid_account_state_adapter = __esm({
39382
39745
  accountSummary: { ...result2.accountSummary || {} },
39383
39746
  availableToTrade: { ...result2.availableToTrade || {} },
39384
39747
  positions: Array.isArray(result2.positions) ? result2.positions.filter((position) => position !== null && typeof position === "object" && !Array.isArray(position)).map((position) => ({ ...position })) : [],
39385
- ...result2.takerRate == null ? {} : { takerRate: Number(result2.takerRate) }
39748
+ ...result2.takerRate == null ? {} : { takerRate: Number(result2.takerRate) },
39749
+ ...result2.promptRescueEvidence == null ? {} : { promptRescueEvidence: { ...result2.promptRescueEvidence } }
39386
39750
  }
39387
39751
  };
39388
39752
  if (entry.result.takerRate != null && (!Number.isFinite(entry.result.takerRate) || entry.result.takerRate < 0 || entry.result.takerRate >= 1)) {
@@ -39810,6 +40174,8 @@ var init_hyperliquid_account_state_adapter = __esm({
39810
40174
  const activeAssetRequestTypes = getBrowserActiveAssetTypeCandidates(apiUrl, walletAddress, symbol2);
39811
40175
  const aggregatePerpDexs = input.aggregatePerpDexs !== false;
39812
40176
  const includeEffectiveTakerRate = input.includeEffectiveTakerRate === true;
40177
+ const includeExactAccountMode = input.includeExactAccountMode === true;
40178
+ const includeActiveAssetData = input.includeActiveAssetData !== false;
39813
40179
  const dexNames = listPerpDexsForAccountState(input.config, dex, aggregatePerpDexs);
39814
40180
  const cacheKey = buildAccountStateCacheKey(
39815
40181
  apiUrl,
@@ -39817,7 +40183,9 @@ var init_hyperliquid_account_state_adapter = __esm({
39817
40183
  symbol2,
39818
40184
  aggregatePerpDexs,
39819
40185
  dexNames,
39820
- includeEffectiveTakerRate
40186
+ includeEffectiveTakerRate,
40187
+ includeExactAccountMode,
40188
+ includeActiveAssetData
39821
40189
  );
39822
40190
  const now = Date.now();
39823
40191
  const cached2 = readBrowserAccountStateCache(cacheKey);
@@ -39828,7 +40196,8 @@ var init_hyperliquid_account_state_adapter = __esm({
39828
40196
  "clearinghouseState",
39829
40197
  "spotClearinghouseState",
39830
40198
  ...includeEffectiveTakerRate ? ["userFees"] : [],
39831
- ...activeAssetRequestTypes
40199
+ ...includeExactAccountMode ? ["userAbstraction", "userDexAbstraction"] : [],
40200
+ ...includeActiveAssetData ? activeAssetRequestTypes : []
39832
40201
  ], now)) {
39833
40202
  return cloneBrowserAccountStateResult(cached2.result);
39834
40203
  }
@@ -39906,20 +40275,29 @@ var init_hyperliquid_account_state_adapter = __esm({
39906
40275
  return prefixHip3PositionCoins(response, dexName);
39907
40276
  })
39908
40277
  );
39909
- return aggregateClearinghouseResponses([defaultResponse, ...dexResponses]);
40278
+ return {
40279
+ payload: aggregateClearinghouseResponses([defaultResponse, ...dexResponses]),
40280
+ capturedAt: (/* @__PURE__ */ new Date()).toISOString()
40281
+ };
39910
40282
  })();
39911
- const spotPromise = fetchHyperliquidInfoPayload(
39912
- apiUrl,
39913
- { type: "spotClearinghouseState", user: walletAddress },
39914
- input.signal
39915
- ).catch((error48) => {
39916
- recordInfoRateLimitCooldownFromError(apiUrl, error48, staleIf429MaxAgeMs);
39917
- if (input.forceRefresh || input.includeEffectiveTakerRate === true) {
39918
- throw error48;
40283
+ const spotPromise = (async () => {
40284
+ let payload;
40285
+ try {
40286
+ payload = await fetchHyperliquidInfoPayload(
40287
+ apiUrl,
40288
+ { type: "spotClearinghouseState", user: walletAddress },
40289
+ input.signal
40290
+ );
40291
+ } catch (error48) {
40292
+ recordInfoRateLimitCooldownFromError(apiUrl, error48, staleIf429MaxAgeMs);
40293
+ if (input.forceRefresh || input.includeEffectiveTakerRate === true) {
40294
+ throw error48;
40295
+ }
40296
+ payload = {};
39919
40297
  }
39920
- return {};
39921
- });
39922
- const activeAssetPromise = (async () => {
40298
+ return { payload, capturedAt: (/* @__PURE__ */ new Date()).toISOString() };
40299
+ })();
40300
+ const activeAssetPromise = input.includeActiveAssetData === false ? Promise.resolve(null) : (async () => {
39923
40301
  let lastError = null;
39924
40302
  for (const typeName of activeAssetRequestTypes) {
39925
40303
  try {
@@ -39939,17 +40317,50 @@ var init_hyperliquid_account_state_adapter = __esm({
39939
40317
  }
39940
40318
  throw lastError instanceof Error ? lastError : new Error("Failed to fetch browser active asset data.");
39941
40319
  })();
39942
- const userFeesPromise = input.includeEffectiveTakerRate === true ? fetchHyperliquidInfoPayload(
39943
- apiUrl,
39944
- { type: "userFees", user: walletAddress },
39945
- input.signal
39946
- ) : Promise.resolve(null);
39947
- const [perpsResponse, spotResponse, activeAssetResult, userFeesResponse] = await Promise.all([
40320
+ const userFeesPromise = input.includeEffectiveTakerRate === true ? (async () => ({
40321
+ payload: await fetchHyperliquidInfoPayload(
40322
+ apiUrl,
40323
+ { type: "userFees", user: walletAddress },
40324
+ input.signal
40325
+ ),
40326
+ capturedAt: (/* @__PURE__ */ new Date()).toISOString()
40327
+ }))() : Promise.resolve(null);
40328
+ const exactAccountModePromise = input.includeExactAccountMode === true ? (async () => {
40329
+ const userAbstraction = await fetchHyperliquidInfoPayload(
40330
+ apiUrl,
40331
+ { type: "userAbstraction", user: walletAddress },
40332
+ input.signal
40333
+ );
40334
+ const preliminaryMode = extractCanonicalHyperliquidAccountMode(userAbstraction);
40335
+ if (!preliminaryMode) {
40336
+ throw new Error("Exact Hyperliquid userAbstraction response is invalid.");
40337
+ }
40338
+ let userDexAbstraction;
40339
+ if (preliminaryMode === "default" || preliminaryMode === "disabled") {
40340
+ userDexAbstraction = await fetchHyperliquidInfoPayload(
40341
+ apiUrl,
40342
+ { type: "userDexAbstraction", user: walletAddress },
40343
+ input.signal
40344
+ );
40345
+ }
40346
+ return {
40347
+ accountMode: resolveExactHyperliquidAccountMode(
40348
+ userAbstraction,
40349
+ userDexAbstraction
40350
+ ),
40351
+ capturedAt: (/* @__PURE__ */ new Date()).toISOString()
40352
+ };
40353
+ })() : Promise.resolve(null);
40354
+ const [perpsResult, spotResult, activeAssetResult, userFeesResult, exactAccountMode] = await Promise.all([
39948
40355
  perpsPromise,
39949
40356
  spotPromise,
39950
40357
  activeAssetPromise,
39951
- userFeesPromise
40358
+ userFeesPromise,
40359
+ exactAccountModePromise
39952
40360
  ]);
40361
+ const perpsResponse = perpsResult.payload;
40362
+ const spotResponse = spotResult.payload;
40363
+ const userFeesResponse = userFeesResult?.payload ?? null;
39953
40364
  if (input.includeEffectiveTakerRate === true) {
39954
40365
  requirePromptSpotState(spotResponse);
39955
40366
  }
@@ -39969,20 +40380,32 @@ var init_hyperliquid_account_state_adapter = __esm({
39969
40380
  takerRate = parsedUserCrossRate;
39970
40381
  }
39971
40382
  const accountStateConfig = input.config.client_runtime_hyperliquid_account_state;
39972
- const normalizedSummary = buildAccountSummaryFromInfoResponses(perpsResponse, spotResponse, {
40383
+ const summaryPerpsResponse = exactAccountMode ? { ...perpsResponse, accountMode: exactAccountMode.accountMode } : perpsResponse;
40384
+ const accountSummaryOptions = {
39973
40385
  spotDominatesMinTotalUsd: accountStateConfig?.spot_dominates_min_total_usd,
39974
40386
  spotDominatesPerpsMultiplier: accountStateConfig?.spot_dominates_perps_multiplier,
39975
40387
  mirroredAccountValueAbsoluteToleranceUsd: accountStateConfig?.mirrored_account_value_absolute_tolerance_usd,
39976
40388
  mirroredAccountValueRelativeTolerance: accountStateConfig?.mirrored_account_value_relative_tolerance
39977
- });
40389
+ };
40390
+ const normalizedSummary = exactAccountMode ? buildServerPromptRescueAccountSummary(
40391
+ perpsResponse,
40392
+ spotResponse,
40393
+ exactAccountMode.accountMode,
40394
+ accountSummaryOptions
40395
+ ) : buildAccountSummaryFromInfoResponses(
40396
+ summaryPerpsResponse,
40397
+ spotResponse,
40398
+ accountSummaryOptions
40399
+ );
39978
40400
  const accountSummary = {
39979
40401
  ...normalizedSummary,
40402
+ ...exactAccountMode == null ? {} : { account_mode: exactAccountMode.accountMode, mode_source: "canonical" },
39980
40403
  address: walletAddress,
39981
40404
  dex: "all",
39982
40405
  market_type: "perp"
39983
40406
  };
39984
- const activeAssetPayload = activeAssetResult.payload;
39985
- const activeAssetType = activeAssetResult.type;
40407
+ const activeAssetPayload = activeAssetResult?.payload ?? null;
40408
+ const activeAssetType = activeAssetResult?.type ?? "promptAccountState";
39986
40409
  const normalizedActiveAsset = normalizeActiveAssetData(activeAssetPayload, symbol2);
39987
40410
  const markPrice = toPositiveFinite(normalizedActiveAsset.mark_price, toPositiveFinite(input.tickerPrice));
39988
40411
  const fallbackLeverage = toPositiveFinite(input.leverage, 1);
@@ -40000,7 +40423,17 @@ var init_hyperliquid_account_state_adapter = __esm({
40000
40423
  accountSummary,
40001
40424
  availableToTrade,
40002
40425
  positions: parseInfoPositions(perpsResponse),
40003
- ...takerRate == null ? {} : { takerRate }
40426
+ ...takerRate == null ? {} : { takerRate },
40427
+ ...exactAccountMode == null || userFeesResult == null ? {} : {
40428
+ promptRescueEvidence: {
40429
+ capturedAt: (/* @__PURE__ */ new Date()).toISOString(),
40430
+ perpsCapturedAt: perpsResult.capturedAt,
40431
+ spotCapturedAt: spotResult.capturedAt,
40432
+ feesCapturedAt: userFeesResult.capturedAt,
40433
+ accountModeCapturedAt: exactAccountMode.capturedAt,
40434
+ accountModeSource: "canonical"
40435
+ }
40436
+ }
40004
40437
  };
40005
40438
  };
40006
40439
  fetchBrowserUserFills = async (input) => {
@@ -51158,6 +51591,145 @@ var init_runtime_handoff = __esm({
51158
51591
  }
51159
51592
  });
51160
51593
 
51594
+ // lib/runtime/status-contract.ts
51595
+ var init_status_contract = __esm({
51596
+ "lib/runtime/status-contract.ts"() {
51597
+ "use strict";
51598
+ }
51599
+ });
51600
+
51601
+ // lib/runtime/error-surface-contract.ts
51602
+ var SENSITIVE_DB_TOKENS, SCHEMA_DISCLOSURE_TOKENS, SQL_STATEMENT_PATTERN, TRACEBACK_PATTERN, DB_SESSION_STATE_PATTERNS, isSensitiveRuntimeErrorDetail, EXECUTION_ERROR_DEFAULTS, isExecutionErrorReasonCode, RuntimeExecutionError, projectExecutionErrorContract;
51603
+ var init_error_surface_contract = __esm({
51604
+ "lib/runtime/error-surface-contract.ts"() {
51605
+ "use strict";
51606
+ init_status_contract();
51607
+ init_runtime_redaction();
51608
+ SENSITIVE_DB_TOKENS = [
51609
+ "sqlalchemy",
51610
+ "asyncpg",
51611
+ "psycopg",
51612
+ "dbapi",
51613
+ "programmingerror",
51614
+ "undefinedcolumnerror",
51615
+ "integrityerror",
51616
+ "statementerror",
51617
+ "queuepool",
51618
+ "postgresql",
51619
+ "sqlite"
51620
+ ];
51621
+ SCHEMA_DISCLOSURE_TOKENS = [
51622
+ " column ",
51623
+ " table ",
51624
+ " schema ",
51625
+ " relation ",
51626
+ " constraint "
51627
+ ];
51628
+ SQL_STATEMENT_PATTERN = /\b(select|insert|update|delete)\b[\s\S]{0,300}\bfrom\b/i;
51629
+ TRACEBACK_PATTERN = /traceback \(most recent call last\):/i;
51630
+ DB_SESSION_STATE_PATTERNS = [
51631
+ /\bthis session is in ['"]?\w+['"]? state\b/i,
51632
+ /\bno further sql can be emitted within this transaction\b/i,
51633
+ /\bcan(?:not|'t) reconnect until (?:the )?invalid transaction is rolled back\b/i,
51634
+ /\bthis session(?:'s)? transaction has been rolled back due to a previous exception\b/i,
51635
+ /\bthis transaction is (?:closed|inactive)\b/i,
51636
+ /\bthis session is provisioning a new connection; concurrent operations are not permitted\b/i,
51637
+ /\bthis session has been permanently closed\b/i,
51638
+ /\binvalid savepoint transaction\b/i
51639
+ ];
51640
+ isSensitiveRuntimeErrorDetail = (error48) => {
51641
+ const message = String(error48 || "").trim();
51642
+ if (!message) {
51643
+ return false;
51644
+ }
51645
+ const lowered = message.toLowerCase();
51646
+ if (TRACEBACK_PATTERN.test(lowered) || lowered.includes("[sql:")) {
51647
+ return true;
51648
+ }
51649
+ if (SENSITIVE_DB_TOKENS.some((token) => lowered.includes(token))) {
51650
+ return true;
51651
+ }
51652
+ if (DB_SESSION_STATE_PATTERNS.some((pattern) => pattern.test(message))) {
51653
+ return true;
51654
+ }
51655
+ return SQL_STATEMENT_PATTERN.test(lowered) && SCHEMA_DISCLOSURE_TOKENS.some((token) => ` ${lowered} `.includes(token));
51656
+ };
51657
+ EXECUTION_ERROR_DEFAULTS = {
51658
+ private_node_stale: ["preflight", "not_dispatched"],
51659
+ signer_validation_unavailable: ["preflight", "not_dispatched"],
51660
+ wallet_not_authorized: ["preflight", "not_dispatched"],
51661
+ credentials_missing: ["preflight", "not_dispatched"],
51662
+ local_safety_block: ["preflight", "not_dispatched"],
51663
+ redis_unavailable: ["coordination", "not_dispatched"],
51664
+ exchange_rejected: ["exchange_response", "confirmed_dispatched"],
51665
+ outcome_unknown: ["transport", "outcome_unknown"],
51666
+ internal_execution_error: ["execution", "unknown"]
51667
+ };
51668
+ isExecutionErrorReasonCode = (value) => Object.prototype.hasOwnProperty.call(EXECUTION_ERROR_DEFAULTS, value);
51669
+ RuntimeExecutionError = class extends Error {
51670
+ constructor(message, reasonCode) {
51671
+ super(message);
51672
+ this.name = "RuntimeExecutionError";
51673
+ this.reasonCode = reasonCode;
51674
+ this.executionStage = EXECUTION_ERROR_DEFAULTS[reasonCode][0];
51675
+ this.dispatchOutcome = EXECUTION_ERROR_DEFAULTS[reasonCode][1];
51676
+ }
51677
+ };
51678
+ projectExecutionErrorContract = (input) => {
51679
+ const {
51680
+ error: error48,
51681
+ symbol: symbol2 = null,
51682
+ reasonCode = null
51683
+ } = input;
51684
+ const typed = error48;
51685
+ const rawReason = String(reasonCode || typed?.reasonCode || "internal_execution_error").trim().toLowerCase();
51686
+ const resolvedReason = isExecutionErrorReasonCode(rawReason) ? rawReason : "internal_execution_error";
51687
+ const defaults = EXECUTION_ERROR_DEFAULTS[resolvedReason];
51688
+ const resolvedStage = defaults[0];
51689
+ const resolvedDispatch = defaults[1];
51690
+ const normalizedSymbol = String(symbol2 || "").trim();
51691
+ const orderLabel = normalizedSymbol ? `${normalizedSymbol} order` : "order";
51692
+ const rawMessage = sanitizeRuntimeDiagnosticValue(
51693
+ error48 instanceof Error ? error48.message : String(error48 || "").trim()
51694
+ );
51695
+ let message;
51696
+ if (resolvedReason === "private_node_stale") {
51697
+ message = `\u26A0\uFE0F The ${orderLabel} was not sent: Hyperliquid private account data was too stale to validate the signing key.`;
51698
+ } else if (resolvedReason === "signer_validation_unavailable") {
51699
+ message = `\u26A0\uFE0F The ${orderLabel} was not sent: Hyperliquid's private account service could not validate the signing key.`;
51700
+ } else if (resolvedReason === "wallet_not_authorized") {
51701
+ message = `\u26A0\uFE0F The ${orderLabel} was not sent: the signing key is not authorized for the configured wallet.`;
51702
+ } else if (resolvedReason === "credentials_missing") {
51703
+ message = `\u26A0\uFE0F The ${orderLabel} was not sent: a wallet address and authorized signing key are required for trading.`;
51704
+ } else if (resolvedReason === "local_safety_block") {
51705
+ const detail = isSensitiveRuntimeErrorDetail(rawMessage) ? "Local preflight validation failed." : rawMessage || "Local preflight validation failed.";
51706
+ const canonicalDetail = detail.replace(/^⚠️?\s*The (?:.+ )?order was not sent before exchange dispatch:\s*/i, "").trim() || "Local preflight validation failed.";
51707
+ message = `\u26A0\uFE0F The ${orderLabel} was not sent before exchange dispatch: ${canonicalDetail}`;
51708
+ } else if (resolvedReason === "redis_unavailable") {
51709
+ message = `\u26A0\uFE0F The ${orderLabel} was not sent because execution coordination was unavailable.`;
51710
+ } else if (resolvedReason === "exchange_rejected") {
51711
+ let detail = isSensitiveRuntimeErrorDetail(rawMessage) ? "The exchange did not provide safe rejection details." : rawMessage || "The exchange did not provide safe rejection details.";
51712
+ detail = detail.replace(/^⚠️?\s*Hyperliquid rejected the (?:.+ )?order:\s*/i, "").trim();
51713
+ detail = detail.replace(/^(?:Hyperliquid rejected order:|Order execution failed:|order execution failed:)\s*/, "");
51714
+ detail = detail.replace(/\s+asset=\d+\b\.?/g, "").trim() || "The exchange did not provide safe rejection details.";
51715
+ message = `\u26A0\uFE0F Hyperliquid rejected the ${orderLabel}: ${detail}`;
51716
+ } else if (resolvedReason === "outcome_unknown") {
51717
+ message = `\u26A0\uFE0F VTX could not confirm whether the ${orderLabel} was applied. Check open orders and the current position before retrying.`;
51718
+ } else {
51719
+ const detail = isSensitiveRuntimeErrorDetail(rawMessage) ? "VTX could not complete the exchange operation." : rawMessage || "VTX could not complete the exchange operation.";
51720
+ const canonicalDetail = detail.replace(/^⚠️?\s*VTX could not complete the (?:.+ )?order:\s*/i, "").trim() || "VTX could not complete the exchange operation.";
51721
+ message = `\u26A0\uFE0F VTX could not complete the ${orderLabel}: ${canonicalDetail}`;
51722
+ }
51723
+ return {
51724
+ reason_code: resolvedReason,
51725
+ execution_stage: resolvedStage,
51726
+ dispatch_outcome: resolvedDispatch,
51727
+ message
51728
+ };
51729
+ };
51730
+ }
51731
+ });
51732
+
51161
51733
  // lib/runtime/hyperliquid-client.ts
51162
51734
  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, submitHyperliquidExchangePayload;
51163
51735
  var init_hyperliquid_client = __esm({
@@ -51171,9 +51743,10 @@ var init_hyperliquid_client = __esm({
51171
51743
  init_runtime_redaction();
51172
51744
  init_exchange_mutation_fence();
51173
51745
  init_runtime_handoff();
51174
- HyperliquidExchangeRejectionError = class extends Error {
51746
+ init_error_surface_contract();
51747
+ HyperliquidExchangeRejectionError = class extends RuntimeExecutionError {
51175
51748
  constructor(message, orderDiagnostics, clientMutationId = null) {
51176
- super(message);
51749
+ super(message, "exchange_rejected");
51177
51750
  this.name = "HyperliquidExchangeRejectionError";
51178
51751
  this.orderDiagnostics = orderDiagnostics;
51179
51752
  this.clientMutationId = clientMutationId;
@@ -52871,8 +53444,9 @@ var init_hyperliquid_client = __esm({
52871
53444
  ...durableMutationAuthorityArgs(durableMutation)
52872
53445
  );
52873
53446
  if (beginResult.dispatch_authorized !== true) {
52874
- throw new Error(
52875
- "This exchange mutation was already recorded and will not be dispatched again. Durable reconciliation is required before retrying."
53447
+ throw new RuntimeExecutionError(
53448
+ "This exchange mutation was already recorded and will not be dispatched again. Durable reconciliation is required before retrying.",
53449
+ "local_safety_block"
52876
53450
  );
52877
53451
  }
52878
53452
  }
@@ -52895,8 +53469,9 @@ var init_hyperliquid_client = __esm({
52895
53469
  ...durableMutationAuthorityArgs(durableMutation)
52896
53470
  );
52897
53471
  } catch {
52898
- throw new Error(
52899
- "Exchange submission may have completed; durable reconciliation is pending."
53472
+ throw new RuntimeExecutionError(
53473
+ "Exchange submission may have completed; durable reconciliation is pending.",
53474
+ "outcome_unknown"
52900
53475
  );
52901
53476
  }
52902
53477
  };
@@ -52980,7 +53555,10 @@ var init_hyperliquid_client = __esm({
52980
53555
  assertFreshPreparedExecutionContext(input.preparedContext);
52981
53556
  } catch (preparedContextError) {
52982
53557
  await settleDurableMutation("rejected");
52983
- throw preparedContextError;
53558
+ throw new RuntimeExecutionError(
53559
+ preparedContextError instanceof Error ? preparedContextError.message : "Prepared exchange context expired before dispatch.",
53560
+ "local_safety_block"
53561
+ );
52984
53562
  }
52985
53563
  if (input.signal?.aborted) {
52986
53564
  await settleDurableMutation("rejected");
@@ -53012,8 +53590,9 @@ var init_hyperliquid_client = __esm({
53012
53590
  const payload = await response.json().catch(() => ({}));
53013
53591
  if (!response.ok) {
53014
53592
  await settleDurableMutation("transport_ambiguous");
53015
- throw new Error(
53016
- "Exchange submission may have completed; durable reconciliation is pending."
53593
+ throw new RuntimeExecutionError(
53594
+ "Exchange submission may have completed; durable reconciliation is pending.",
53595
+ "outcome_unknown"
53017
53596
  );
53018
53597
  }
53019
53598
  const exchangeError = extractHyperliquidExchangeError(payload);
@@ -53022,8 +53601,9 @@ var init_hyperliquid_client = __esm({
53022
53601
  exchangeError.partial ? "transport_ambiguous" : "rejected"
53023
53602
  );
53024
53603
  if (exchangeError.partial) {
53025
- throw new Error(
53026
- "Hyperliquid returned a partially applied exchange response; durable reconciliation is pending."
53604
+ throw new RuntimeExecutionError(
53605
+ "Hyperliquid returned a partially applied exchange response; durable reconciliation is pending.",
53606
+ "outcome_unknown"
53027
53607
  );
53028
53608
  }
53029
53609
  throw new HyperliquidExchangeRejectionError(
@@ -53037,8 +53617,9 @@ var init_hyperliquid_client = __esm({
53037
53617
  input.payload.action
53038
53618
  )) {
53039
53619
  await settleDurableMutation("transport_ambiguous");
53040
- throw new Error(
53041
- "Hyperliquid returned an incomplete exchange response; durable reconciliation is pending."
53620
+ throw new RuntimeExecutionError(
53621
+ "Hyperliquid returned an incomplete exchange response; durable reconciliation is pending.",
53622
+ "outcome_unknown"
53042
53623
  );
53043
53624
  }
53044
53625
  const exactExchangeOrderId = durableMutation?.operationKind === "order" ? extractDefinitiveHyperliquidOrderId(payload, input.payload.action) : null;
@@ -53060,12 +53641,14 @@ var init_hyperliquid_client = __esm({
53060
53641
  try {
53061
53642
  await settleDurableMutation("transport_ambiguous");
53062
53643
  } catch {
53063
- throw new Error(
53064
- "Exchange submission may have completed; durable reconciliation is pending."
53644
+ throw new RuntimeExecutionError(
53645
+ "Exchange submission may have completed; durable reconciliation is pending.",
53646
+ "outcome_unknown"
53065
53647
  );
53066
53648
  }
53067
- throw new Error(
53068
- "Exchange submission may have completed; durable reconciliation is pending."
53649
+ throw new RuntimeExecutionError(
53650
+ "Exchange submission may have completed; durable reconciliation is pending.",
53651
+ "outcome_unknown"
53069
53652
  );
53070
53653
  }
53071
53654
  throw error48;
@@ -53087,6 +53670,7 @@ var init_hyperliquid_signer_binding = __esm({
53087
53670
  "use strict";
53088
53671
  init_lib2();
53089
53672
  init_hyperliquid_client();
53673
+ init_error_surface_contract();
53090
53674
  normalizeAddress = (value, label) => {
53091
53675
  const normalized = String(value || "").trim().toLowerCase();
53092
53676
  if (!/^0x[0-9a-f]{40}$/.test(normalized)) {
@@ -53109,7 +53693,15 @@ var init_hyperliquid_signer_binding = __esm({
53109
53693
  return null;
53110
53694
  };
53111
53695
  assertBrowserHyperliquidSignerWalletBinding = async (input) => {
53112
- const walletAddress = normalizeAddress(input.walletAddress, "wallet address");
53696
+ let walletAddress;
53697
+ try {
53698
+ walletAddress = normalizeAddress(input.walletAddress, "wallet address");
53699
+ } catch {
53700
+ throw new RuntimeExecutionError(
53701
+ "A valid Hyperliquid wallet address is required for trading.",
53702
+ "credentials_missing"
53703
+ );
53704
+ }
53113
53705
  let signerAddress;
53114
53706
  try {
53115
53707
  signerAddress = normalizeAddress(
@@ -53117,13 +53709,25 @@ var init_hyperliquid_signer_binding = __esm({
53117
53709
  "signer address"
53118
53710
  );
53119
53711
  } catch {
53120
- throw new Error("Invalid Hyperliquid signing key.");
53712
+ throw new RuntimeExecutionError(
53713
+ "Invalid Hyperliquid signing key.",
53714
+ "credentials_missing"
53715
+ );
53716
+ }
53717
+ let roleResponse;
53718
+ try {
53719
+ roleResponse = await fetchBrowserUserRole({
53720
+ config: input.config ?? null,
53721
+ walletAddress: signerAddress,
53722
+ signal: input.signal
53723
+ });
53724
+ } catch (error48) {
53725
+ if (input.signal?.aborted) throw error48;
53726
+ throw new RuntimeExecutionError(
53727
+ "Hyperliquid's private account service could not validate the signing key.",
53728
+ "signer_validation_unavailable"
53729
+ );
53121
53730
  }
53122
- const roleResponse = await fetchBrowserUserRole({
53123
- config: input.config ?? null,
53124
- walletAddress: signerAddress,
53125
- signal: input.signal
53126
- });
53127
53731
  const signerRole = String(roleResponse.role || "").trim().toLowerCase();
53128
53732
  if (signerRole === "user" && signerAddress === walletAddress) {
53129
53733
  return {
@@ -53145,8 +53749,9 @@ var init_hyperliquid_signer_binding = __esm({
53145
53749
  };
53146
53750
  }
53147
53751
  }
53148
- throw new Error(
53149
- "The device Hyperliquid signing key is not authorized for this profile wallet. Stop the runtime and reconnect the wallet."
53752
+ throw new RuntimeExecutionError(
53753
+ "The device Hyperliquid signing key is not authorized for this profile wallet. Stop the runtime and reconnect the wallet.",
53754
+ "wallet_not_authorized"
53150
53755
  );
53151
53756
  };
53152
53757
  }
@@ -53881,6 +54486,7 @@ var init_browser_trading = __esm({
53881
54486
  "use strict";
53882
54487
  init_hyperliquid_client();
53883
54488
  init_hyperliquid_signer_binding();
54489
+ init_error_surface_contract();
53884
54490
  init_vault();
53885
54491
  resolveProfileId = (value) => {
53886
54492
  const profileId = String(value).trim();
@@ -53966,7 +54572,10 @@ var init_browser_trading = __esm({
53966
54572
  }
53967
54573
  }
53968
54574
  if (!signingKey) {
53969
- throw new Error("Missing required device-local Hyperliquid signing key for this profile. Configure it in System for this device.");
54575
+ throw new RuntimeExecutionError(
54576
+ "Missing required device-local Hyperliquid signing key for this profile. Configure it in System for this device.",
54577
+ "credentials_missing"
54578
+ );
53970
54579
  }
53971
54580
  return signingKey;
53972
54581
  };
@@ -53975,7 +54584,10 @@ var init_browser_trading = __esm({
53975
54584
  const signingKey = explicit || await loadSigningKey(resolveProfileId(input.profileId));
53976
54585
  const walletAddress = String(input.walletAddress || "").trim();
53977
54586
  if (!walletAddress) {
53978
- throw new Error("Missing wallet address for client Hyperliquid signing.");
54587
+ throw new RuntimeExecutionError(
54588
+ "Missing wallet address for client Hyperliquid signing.",
54589
+ "credentials_missing"
54590
+ );
53979
54591
  }
53980
54592
  await assertBrowserHyperliquidSignerWalletBinding({
53981
54593
  signingKey,
@@ -54484,6 +55096,7 @@ var init_runtime_execution = __esm({
54484
55096
  init_hyperliquid_market_symbol();
54485
55097
  init_network_debug();
54486
55098
  init_runtime_redaction();
55099
+ init_error_surface_contract();
54487
55100
  init_runtime_handoff();
54488
55101
  fetchClientRuntimeOpenOrders = async (request) => {
54489
55102
  const normalizedSymbol = normalizeHyperliquidMarketSymbol(
@@ -55961,6 +56574,7 @@ var init_runtime_execution = __esm({
55961
56574
  }
55962
56575
  }
55963
56576
  for (const candidate of candidates) {
56577
+ const rejectionProjection = error48 instanceof HyperliquidExchangeRejectionError ? projectExecutionErrorContract({ error: error48, symbol: symbol2 }) : null;
55964
56578
  reports.push({
55965
56579
  order_id: null,
55966
56580
  client_mutation_id: error48 instanceof HyperliquidExchangeRejectionError ? error48.clientMutationId ?? candidate.mutationId : candidate.mutationId,
@@ -55968,10 +56582,12 @@ var init_runtime_execution = __esm({
55968
56582
  action: candidate.kind === "sl" ? "AUTO_SL" : "AUTO_TP",
55969
56583
  status: error48 instanceof HyperliquidExchangeRejectionError ? "failed" : "blocked",
55970
56584
  execution_metadata: {
55971
- reason_code: error48 instanceof HyperliquidExchangeRejectionError ? "execution_error" : "protective_trigger_ack_unresolved",
55972
- error: getSanitizedRuntimeErrorMessage(error48) || "Protective trigger submission is unresolved.",
56585
+ reason_code: error48 instanceof HyperliquidExchangeRejectionError ? rejectionProjection?.reason_code : "protective_trigger_ack_unresolved",
56586
+ error: rejectionProjection?.message ?? getSanitizedRuntimeErrorMessage(error48) ?? "Protective trigger submission is unresolved.",
55973
56587
  ...error48 instanceof HyperliquidExchangeRejectionError ? {
55974
- execution_stage: "protective_trigger_order",
56588
+ execution_stage: rejectionProjection?.execution_stage,
56589
+ dispatch_outcome: rejectionProjection?.dispatch_outcome,
56590
+ operation_stage: "protective_trigger_order",
55975
56591
  entry_order_id: fill.orderId,
55976
56592
  order_diagnostics: error48.orderDiagnostics
55977
56593
  } : {}
@@ -59030,15 +59646,21 @@ var init_runtime_execution = __esm({
59030
59646
  execution_metadata: _toExecutionMetadata(marketOrderResponse)
59031
59647
  });
59032
59648
  const appendPostEntryProtectionFailure = (error48) => {
59033
- const message = getSanitizedRuntimeErrorMessage(error48) || "Unknown post-entry protection error.";
59649
+ const projection = projectExecutionErrorContract({
59650
+ error: error48,
59651
+ symbol: input.executionContext.symbol
59652
+ });
59653
+ const message = projection.message;
59034
59654
  executionReports.push({
59035
59655
  order_id: null,
59036
59656
  symbol: input.executionContext.symbol,
59037
59657
  action: "PROTECTIVE_RECONCILIATION",
59038
59658
  status: "failed",
59039
59659
  execution_metadata: {
59040
- reason_code: "execution_error",
59041
- execution_stage: "post_entry_protection",
59660
+ reason_code: projection.reason_code,
59661
+ execution_stage: projection.execution_stage,
59662
+ dispatch_outcome: projection.dispatch_outcome,
59663
+ operation_stage: "post_entry_protection",
59042
59664
  entry_order_id: _extractOrderId(marketOrderResponse),
59043
59665
  error: message
59044
59666
  }
@@ -59443,7 +60065,11 @@ var init_runtime_execution = __esm({
59443
60065
  );
59444
60066
  }
59445
60067
  } catch (triggerError) {
59446
- const message = getSanitizedRuntimeErrorMessage(triggerError) || "Unknown protective trigger order error.";
60068
+ const projection = projectExecutionErrorContract({
60069
+ error: triggerError,
60070
+ symbol: input.executionContext.symbol
60071
+ });
60072
+ const message = projection.message;
59447
60073
  const rejection = triggerError instanceof HyperliquidExchangeRejectionError ? triggerError : null;
59448
60074
  executionReports.push({
59449
60075
  order_id: null,
@@ -59454,8 +60080,10 @@ var init_runtime_execution = __esm({
59454
60080
  execution_metadata: {
59455
60081
  trigger_price: triggerInput.triggerPrice,
59456
60082
  is_take_profit: triggerInput.isTakeProfit,
59457
- reason_code: "execution_error",
59458
- execution_stage: "protective_trigger_order",
60083
+ reason_code: projection.reason_code,
60084
+ execution_stage: projection.execution_stage,
60085
+ dispatch_outcome: projection.dispatch_outcome,
60086
+ operation_stage: "protective_trigger_order",
59459
60087
  entry_order_id: _extractOrderId(marketOrderResponse),
59460
60088
  error: message,
59461
60089
  ...rejection ? { order_diagnostics: rejection.orderDiagnostics } : {}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@vtxmacro/cli",
3
- "version": "2026.8.51",
3
+ "version": "2026.8.52",
4
4
  "description": "VTX Macro CLI, MCP server, and durable subscription inference host.",
5
5
  "type": "module",
6
6
  "license": "UNLICENSED",