@vtxmacro/cli 2026.10.62 → 2026.10.64

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
@@ -122,7 +122,7 @@ var init_routing = __esm({
122
122
  var agent_cli_release_default;
123
123
  var init_agent_cli_release = __esm({
124
124
  "agent-cli-release.json"() {
125
- agent_cli_release_default = { package_name: "@vtxmacro/cli", package_version: "2026.10.62", codex_package_name: "@openai/codex", codex_version: "0.155.0", copilot_sdk_package_name: "@github/copilot-sdk", copilot_sdk_version: "1.0.0-beta.8", copilot_cli_package_name: "@github/copilot", copilot_cli_version: "1.0.80", deepseek_harness_version: "0.1.1-rc.2", deepseek_harness_packages: ["@deepseek-ai/dsh-agent", "@deepseek-ai/dsh-agent-instructions", "@deepseek-ai/dsh-agent-loop", "@deepseek-ai/dsh-agent-spine-demo", "@deepseek-ai/dsh-anonymous-user-id", "@deepseek-ai/dsh-atomic-write", "@deepseek-ai/dsh-attachment", "@deepseek-ai/dsh-brand", "@deepseek-ai/dsh-code-runtime", "@deepseek-ai/dsh-credentials", "@deepseek-ai/dsh-fs", "@deepseek-ai/dsh-goal", "@deepseek-ai/dsh-goal-round-driver", "@deepseek-ai/dsh-home-paths", "@deepseek-ai/dsh-invariants", "@deepseek-ai/dsh-jobs", "@deepseek-ai/dsh-jobs-local", "@deepseek-ai/dsh-launch-environment", "@deepseek-ai/dsh-llm", "@deepseek-ai/dsh-llm-deepseek", "@deepseek-ai/dsh-llm-retry", "@deepseek-ai/dsh-output-retention", "@deepseek-ai/dsh-sandbox", "@deepseek-ai/dsh-sandbox-policy", "@deepseek-ai/dsh-scope", "@deepseek-ai/dsh-session", "@deepseek-ai/dsh-session-checkpoint-policy", "@deepseek-ai/dsh-session-persistence", "@deepseek-ai/dsh-session-persistence-jsonl", "@deepseek-ai/dsh-session-projection", "@deepseek-ai/dsh-session-title", "@deepseek-ai/dsh-settings", "@deepseek-ai/dsh-shell", "@deepseek-ai/dsh-shell-env", "@deepseek-ai/dsh-skill", "@deepseek-ai/dsh-skill-filesystem", "@deepseek-ai/dsh-subprocess", "@deepseek-ai/dsh-system-prompt", "@deepseek-ai/dsh-timeout", "@deepseek-ai/dsh-tool-bash", "@deepseek-ai/dsh-tool-goal", "@deepseek-ai/dsh-tool-jobs", "@deepseek-ai/dsh-tool-skill", "@deepseek-ai/dsh-tools", "@deepseek-ai/dsh-typert-protocol", "@deepseek-ai/dsh-user-approval"], deepseek_cordis_package_name: "@deepseek-ai/cordis", deepseek_cordis_version: "4.0.1", deepseek_support_packages: { "@deepseek-ai/cordis-plugin-timer": "1.1.3" }, platforms: { "linux-x64": { package_name: "@openai/codex-linux-x64", target: "x86_64-unknown-linux-musl", binary_name: "codex", sha256: "660e159a49e823ac8e5986cb238f73158ce4b957d40d9292f8de90862644b501" }, "win32-x64": { package_name: "@openai/codex-win32-x64", target: "x86_64-pc-windows-msvc", binary_name: "codex.exe", sha256: "e4c11374bd9de8ad5c3b7617fd4654bb7839901edb0863f9930666863c7a021b" } }, pi_coding_agent_package_name: "@earendil-works/pi-coding-agent", pi_ai_package_name: "@earendil-works/pi-ai", pi_version: "0.85.1", pi_support_packages: ["@earendil-works/pi-agent-core", "@earendil-works/pi-telemetry", "@earendil-works/pi-tui", "@earendil-works/chord"], grok_version: "1.0.30", grok_platforms: { "linux-x64": { package_name: "@xai-official/grok-linux-x64", binary_name: "grok", sha256: "504dd6546ab991b75d36698242875ce461489cd1f8cd84285873cb55bd5c7d54" }, "win32-x64": { package_name: "@xai-official/grok-win32-x64", binary_name: "grok.exe", sha256: "48736d1a4342a801ea26d0ecde4c516b653f791399065adaa55973f83abd8867" } } };
125
+ agent_cli_release_default = { package_name: "@vtxmacro/cli", package_version: "2026.10.64", codex_package_name: "@openai/codex", codex_version: "0.155.0", copilot_sdk_package_name: "@github/copilot-sdk", copilot_sdk_version: "1.0.0-beta.8", copilot_cli_package_name: "@github/copilot", copilot_cli_version: "1.0.80", deepseek_harness_version: "0.1.1-rc.2", deepseek_harness_packages: ["@deepseek-ai/dsh-agent", "@deepseek-ai/dsh-agent-instructions", "@deepseek-ai/dsh-agent-loop", "@deepseek-ai/dsh-agent-spine-demo", "@deepseek-ai/dsh-anonymous-user-id", "@deepseek-ai/dsh-atomic-write", "@deepseek-ai/dsh-attachment", "@deepseek-ai/dsh-brand", "@deepseek-ai/dsh-code-runtime", "@deepseek-ai/dsh-credentials", "@deepseek-ai/dsh-fs", "@deepseek-ai/dsh-goal", "@deepseek-ai/dsh-goal-round-driver", "@deepseek-ai/dsh-home-paths", "@deepseek-ai/dsh-invariants", "@deepseek-ai/dsh-jobs", "@deepseek-ai/dsh-jobs-local", "@deepseek-ai/dsh-launch-environment", "@deepseek-ai/dsh-llm", "@deepseek-ai/dsh-llm-deepseek", "@deepseek-ai/dsh-llm-retry", "@deepseek-ai/dsh-output-retention", "@deepseek-ai/dsh-sandbox", "@deepseek-ai/dsh-sandbox-policy", "@deepseek-ai/dsh-scope", "@deepseek-ai/dsh-session", "@deepseek-ai/dsh-session-checkpoint-policy", "@deepseek-ai/dsh-session-persistence", "@deepseek-ai/dsh-session-persistence-jsonl", "@deepseek-ai/dsh-session-projection", "@deepseek-ai/dsh-session-title", "@deepseek-ai/dsh-settings", "@deepseek-ai/dsh-shell", "@deepseek-ai/dsh-shell-env", "@deepseek-ai/dsh-skill", "@deepseek-ai/dsh-skill-filesystem", "@deepseek-ai/dsh-subprocess", "@deepseek-ai/dsh-system-prompt", "@deepseek-ai/dsh-timeout", "@deepseek-ai/dsh-tool-bash", "@deepseek-ai/dsh-tool-goal", "@deepseek-ai/dsh-tool-jobs", "@deepseek-ai/dsh-tool-skill", "@deepseek-ai/dsh-tools", "@deepseek-ai/dsh-typert-protocol", "@deepseek-ai/dsh-user-approval"], deepseek_cordis_package_name: "@deepseek-ai/cordis", deepseek_cordis_version: "4.0.1", deepseek_support_packages: { "@deepseek-ai/cordis-plugin-timer": "1.1.3" }, platforms: { "linux-x64": { package_name: "@openai/codex-linux-x64", target: "x86_64-unknown-linux-musl", binary_name: "codex", sha256: "660e159a49e823ac8e5986cb238f73158ce4b957d40d9292f8de90862644b501" }, "win32-x64": { package_name: "@openai/codex-win32-x64", target: "x86_64-pc-windows-msvc", binary_name: "codex.exe", sha256: "e4c11374bd9de8ad5c3b7617fd4654bb7839901edb0863f9930666863c7a021b" } }, pi_coding_agent_package_name: "@earendil-works/pi-coding-agent", pi_ai_package_name: "@earendil-works/pi-ai", pi_version: "0.85.1", pi_support_packages: ["@earendil-works/pi-agent-core", "@earendil-works/pi-telemetry", "@earendil-works/pi-tui", "@earendil-works/chord"], grok_version: "1.0.30", grok_platforms: { "linux-x64": { package_name: "@xai-official/grok-linux-x64", binary_name: "grok", sha256: "504dd6546ab991b75d36698242875ce461489cd1f8cd84285873cb55bd5c7d54" }, "win32-x64": { package_name: "@xai-official/grok-win32-x64", binary_name: "grok.exe", sha256: "48736d1a4342a801ea26d0ecde4c516b653f791399065adaa55973f83abd8867" } } };
126
126
  }
127
127
  });
128
128
 
@@ -636,6 +636,54 @@ var init_runtime_policy_generated = __esm({
636
636
  arena_leaderboard_entries: 3,
637
637
  data_revalidate_seconds: 60
638
638
  },
639
+ google_analytics: {
640
+ excluded_country_codes: [
641
+ "AT",
642
+ "BE",
643
+ "BG",
644
+ "HR",
645
+ "CY",
646
+ "CZ",
647
+ "DK",
648
+ "EE",
649
+ "FI",
650
+ "FR",
651
+ "DE",
652
+ "GR",
653
+ "HU",
654
+ "IE",
655
+ "IT",
656
+ "LV",
657
+ "LT",
658
+ "LU",
659
+ "MT",
660
+ "NL",
661
+ "PL",
662
+ "PT",
663
+ "RO",
664
+ "SK",
665
+ "SI",
666
+ "ES",
667
+ "SE",
668
+ "GF",
669
+ "GP",
670
+ "MQ",
671
+ "RE",
672
+ "YT",
673
+ "MF",
674
+ "AX",
675
+ "IS",
676
+ "LI",
677
+ "NO",
678
+ "GB",
679
+ "CH",
680
+ "EU"
681
+ ],
682
+ unresolved_country_codes: [
683
+ "XX",
684
+ "T1"
685
+ ]
686
+ },
639
687
  calendar: {
640
688
  event_highlight_window_minutes: 60,
641
689
  search_save_debounce_ms: 250
@@ -1542,6 +1590,14 @@ var init_runtime_policy_generated = __esm({
1542
1590
  posts: {
1543
1591
  list_default_limit: 20,
1544
1592
  list_max_limit: 100
1593
+ },
1594
+ comments: {
1595
+ max_length: 2e3
1596
+ }
1597
+ },
1598
+ community: {
1599
+ reports: {
1600
+ details_max_length: 1e3
1545
1601
  }
1546
1602
  },
1547
1603
  security: {
@@ -22351,6 +22407,54 @@ var init_runtime_policy_generated2 = __esm({
22351
22407
  arena_leaderboard_entries: 3,
22352
22408
  data_revalidate_seconds: 60
22353
22409
  },
22410
+ google_analytics: {
22411
+ excluded_country_codes: [
22412
+ "AT",
22413
+ "BE",
22414
+ "BG",
22415
+ "HR",
22416
+ "CY",
22417
+ "CZ",
22418
+ "DK",
22419
+ "EE",
22420
+ "FI",
22421
+ "FR",
22422
+ "DE",
22423
+ "GR",
22424
+ "HU",
22425
+ "IE",
22426
+ "IT",
22427
+ "LV",
22428
+ "LT",
22429
+ "LU",
22430
+ "MT",
22431
+ "NL",
22432
+ "PL",
22433
+ "PT",
22434
+ "RO",
22435
+ "SK",
22436
+ "SI",
22437
+ "ES",
22438
+ "SE",
22439
+ "GF",
22440
+ "GP",
22441
+ "MQ",
22442
+ "RE",
22443
+ "YT",
22444
+ "MF",
22445
+ "AX",
22446
+ "IS",
22447
+ "LI",
22448
+ "NO",
22449
+ "GB",
22450
+ "CH",
22451
+ "EU"
22452
+ ],
22453
+ unresolved_country_codes: [
22454
+ "XX",
22455
+ "T1"
22456
+ ]
22457
+ },
22354
22458
  calendar: {
22355
22459
  event_highlight_window_minutes: 60,
22356
22460
  search_save_debounce_ms: 250
@@ -23257,6 +23361,14 @@ var init_runtime_policy_generated2 = __esm({
23257
23361
  posts: {
23258
23362
  list_default_limit: 20,
23259
23363
  list_max_limit: 100
23364
+ },
23365
+ comments: {
23366
+ max_length: 2e3
23367
+ }
23368
+ },
23369
+ community: {
23370
+ reports: {
23371
+ details_max_length: 1e3
23260
23372
  }
23261
23373
  },
23262
23374
  security: {
@@ -26685,6 +26797,9 @@ async function refreshInferenceCredential(options) {
26685
26797
  timeoutMs: options.requestTimeoutMs
26686
26798
  }
26687
26799
  );
26800
+ if (tokens.refreshToken === credential.refresh_token) {
26801
+ return { accessToken: tokens.accessToken, expiresIn: tokens.expiresIn, credential, accountKey: accountKey2 };
26802
+ }
26688
26803
  const rotated = validateInferenceHostCredential({
26689
26804
  ...credential,
26690
26805
  refresh_token: tokens.refreshToken,
@@ -61578,6 +61693,17 @@ var init_market_data = __esm({
61578
61693
  }
61579
61694
  });
61580
61695
 
61696
+ // lib/api/open-orders.ts
61697
+ var init_open_orders = __esm({
61698
+ "lib/api/open-orders.ts"() {
61699
+ "use strict";
61700
+ init_define_VTX_CLAUDE_CODE_POLICY();
61701
+ init_define_VTX_EXO_POLICY();
61702
+ init_define_VTX_GROK_POLICY();
61703
+ init_define_VTX_PI_MODEL_POLICY();
61704
+ }
61705
+ });
61706
+
61581
61707
  // lib/api/screener.ts
61582
61708
  var init_screener = __esm({
61583
61709
  "lib/api/screener.ts"() {
@@ -61867,6 +61993,19 @@ var init_insights_access_center = __esm({
61867
61993
  }
61868
61994
  });
61869
61995
 
61996
+ // lib/api/community.ts
61997
+ var init_community = __esm({
61998
+ "lib/api/community.ts"() {
61999
+ "use strict";
62000
+ init_define_VTX_CLAUDE_CODE_POLICY();
62001
+ init_define_VTX_EXO_POLICY();
62002
+ init_define_VTX_GROK_POLICY();
62003
+ init_define_VTX_PI_MODEL_POLICY();
62004
+ init_shared();
62005
+ init_constants();
62006
+ }
62007
+ });
62008
+
61870
62009
  // lib/api/updates.ts
61871
62010
  var init_updates = __esm({
61872
62011
  "lib/api/updates.ts"() {
@@ -61876,6 +62015,7 @@ var init_updates = __esm({
61876
62015
  init_define_VTX_GROK_POLICY();
61877
62016
  init_define_VTX_PI_MODEL_POLICY();
61878
62017
  init_shared();
62018
+ init_community();
61879
62019
  init_constants();
61880
62020
  }
61881
62021
  });
@@ -62025,6 +62165,19 @@ var init_admin_signups = __esm({
62025
62165
  }
62026
62166
  });
62027
62167
 
62168
+ // lib/api/admin-accounts.ts
62169
+ var init_admin_accounts = __esm({
62170
+ "lib/api/admin-accounts.ts"() {
62171
+ "use strict";
62172
+ init_define_VTX_CLAUDE_CODE_POLICY();
62173
+ init_define_VTX_EXO_POLICY();
62174
+ init_define_VTX_GROK_POLICY();
62175
+ init_define_VTX_PI_MODEL_POLICY();
62176
+ init_community();
62177
+ init_shared();
62178
+ }
62179
+ });
62180
+
62028
62181
  // lib/api/client-exchange-reconciliation.ts
62029
62182
  var init_client_exchange_reconciliation = __esm({
62030
62183
  "lib/api/client-exchange-reconciliation.ts"() {
@@ -62612,7 +62765,7 @@ var init_hyperliquid_account_contract = __esm({
62612
62765
  });
62613
62766
 
62614
62767
  // lib/runtime/order-identity.ts
62615
- var clientOrderIdForMutation, mutationIdForClientOrderId, clientDecisionMutationId;
62768
+ var clientOrderIdForMutation, mutationIdForClientOrderId, listedClientOrderId, clientDecisionMutationId;
62616
62769
  var init_order_identity = __esm({
62617
62770
  "lib/runtime/order-identity.ts"() {
62618
62771
  "use strict";
@@ -62628,6 +62781,12 @@ var init_order_identity = __esm({
62628
62781
  const hex4 = cloid.slice("0x".length);
62629
62782
  return UUID_HEX_GROUP_ENDS.map((end, index) => hex4.slice(index === 0 ? 0 : UUID_HEX_GROUP_ENDS[index - 1], end)).join("-");
62630
62783
  };
62784
+ listedClientOrderId = (row) => {
62785
+ const value = row.cloid;
62786
+ if (value == null) return null;
62787
+ const cloid = typeof value === "string" ? value.trim().toLowerCase() : "";
62788
+ return /^0x[0-9a-f]{32}$/.test(cloid) ? cloid : void 0;
62789
+ };
62631
62790
  clientDecisionMutationId = async (input) => {
62632
62791
  const key = [
62633
62792
  "client-decision:v1",
@@ -62644,6 +62803,79 @@ var init_order_identity = __esm({
62644
62803
  }
62645
62804
  });
62646
62805
 
62806
+ // lib/runtime/hyperliquid-open-order-fields.ts
62807
+ var OPEN_ORDER_NUMERIC_STRING, OPEN_ORDER_ID_STRING, malformed, parseCanonicalOpenOrderId, parseOpenOrderFiniteNumber, parseOpenOrderNonNegativeNumber, parseOpenOrderPositiveNumber, parseOpenOrderPresentationNumber, readOpenOrderField;
62808
+ var init_hyperliquid_open_order_fields = __esm({
62809
+ "lib/runtime/hyperliquid-open-order-fields.ts"() {
62810
+ "use strict";
62811
+ init_define_VTX_CLAUDE_CODE_POLICY();
62812
+ init_define_VTX_EXO_POLICY();
62813
+ init_define_VTX_GROK_POLICY();
62814
+ init_define_VTX_PI_MODEL_POLICY();
62815
+ init_runtime_error_reason_rules();
62816
+ OPEN_ORDER_NUMERIC_STRING = /^[+-]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:[eE][+-]?\d+)?$/;
62817
+ OPEN_ORDER_ID_STRING = /^[1-9]\d*$/;
62818
+ malformed = () => new RuntimeReasonError("Malformed Hyperliquid frontendOpenOrders member.", "internal_data_error");
62819
+ parseCanonicalOpenOrderId = (value) => {
62820
+ if (typeof value === "number") {
62821
+ if (Number.isSafeInteger(value) && value > 0) {
62822
+ return value;
62823
+ }
62824
+ throw malformed();
62825
+ }
62826
+ if (typeof value !== "string" || !OPEN_ORDER_ID_STRING.test(value)) {
62827
+ throw malformed();
62828
+ }
62829
+ const parsed = Number(value);
62830
+ if (!Number.isSafeInteger(parsed) || parsed <= 0) {
62831
+ throw malformed();
62832
+ }
62833
+ return parsed;
62834
+ };
62835
+ parseOpenOrderFiniteNumber = (value) => {
62836
+ if (typeof value !== "number" && (typeof value !== "string" || value.trim() === "" || !OPEN_ORDER_NUMERIC_STRING.test(value.trim()))) {
62837
+ throw malformed();
62838
+ }
62839
+ const parsed = typeof value === "number" ? value : Number(value.trim());
62840
+ if (!Number.isFinite(parsed)) {
62841
+ throw malformed();
62842
+ }
62843
+ return parsed;
62844
+ };
62845
+ parseOpenOrderNonNegativeNumber = (value) => {
62846
+ const parsed = parseOpenOrderFiniteNumber(value);
62847
+ if (parsed < 0) {
62848
+ throw malformed();
62849
+ }
62850
+ return parsed;
62851
+ };
62852
+ parseOpenOrderPositiveNumber = (value) => {
62853
+ const parsed = parseOpenOrderFiniteNumber(value);
62854
+ if (parsed <= 0) {
62855
+ throw malformed();
62856
+ }
62857
+ return parsed;
62858
+ };
62859
+ parseOpenOrderPresentationNumber = (value, fallback, options = {}) => {
62860
+ if (value == null || typeof value === "boolean" || typeof value === "string" && value.trim() === "") {
62861
+ return fallback;
62862
+ }
62863
+ const number6 = typeof value === "number" ? value : Number(value);
62864
+ const parsed = Number.isFinite(number6) ? number6 : fallback;
62865
+ return options.positive && parsed <= 0 ? fallback : parsed;
62866
+ };
62867
+ readOpenOrderField = (order, camel, snake) => {
62868
+ if (Object.prototype.hasOwnProperty.call(order, camel)) {
62869
+ return { present: true, value: order[camel] };
62870
+ }
62871
+ if (snake != null && Object.prototype.hasOwnProperty.call(order, snake)) {
62872
+ return { present: true, value: order[snake] };
62873
+ }
62874
+ return { present: false, value: void 0 };
62875
+ };
62876
+ }
62877
+ });
62878
+
62647
62879
  // lib/runtime/hyperliquid-order-status.ts
62648
62880
  var HYPERLIQUID_PENDING_TRIGGER_REASON_CODE, HYPERLIQUID_TERMINAL_UNFILLED_ORDER_STATUSES, classifyHyperliquidOrderStatus;
62649
62881
  var init_hyperliquid_order_status = __esm({
@@ -63667,7 +63899,7 @@ var init_hyperliquid_exchange_rejections = __esm({
63667
63899
  });
63668
63900
 
63669
63901
  // lib/runtime/hyperliquid-market-catalog.ts
63670
- var DEFAULT_DEX, DEFAULT_DEX_INDEX, ISOLATED_ONLY_MARGIN_MODES, malformed, perpDexIndexes, integer3, marketIdentityRow, listedMarketRows;
63902
+ var DEFAULT_DEX, DEFAULT_DEX_INDEX, ISOLATED_ONLY_MARGIN_MODES, malformed2, perpDexIndexes, integer3, marketIdentityRow, listedMarketRows;
63671
63903
  var init_hyperliquid_market_catalog = __esm({
63672
63904
  "lib/runtime/hyperliquid-market-catalog.ts"() {
63673
63905
  "use strict";
@@ -63681,10 +63913,10 @@ var init_hyperliquid_market_catalog = __esm({
63681
63913
  DEFAULT_DEX = "";
63682
63914
  DEFAULT_DEX_INDEX = 0;
63683
63915
  ISOLATED_ONLY_MARGIN_MODES = /* @__PURE__ */ new Set(["nocross", "strictisolated"]);
63684
- malformed = (message) => new RuntimeReasonError(message, "hyperliquid_data_unavailable");
63916
+ malformed2 = (message) => new RuntimeReasonError(message, "hyperliquid_data_unavailable");
63685
63917
  perpDexIndexes = (perpDexs) => {
63686
63918
  if (!Array.isArray(perpDexs) || perpDexs.length === 0 || perpDexs.some((item) => item !== null && (!item || typeof item !== "object" || Array.isArray(item) || !String(item.name ?? "").trim()))) {
63687
- throw malformed("Hyperliquid returned a malformed perpDexs list.");
63919
+ throw malformed2("Hyperliquid returned a malformed perpDexs list.");
63688
63920
  }
63689
63921
  const indexes = /* @__PURE__ */ new Map([[DEFAULT_DEX, DEFAULT_DEX_INDEX]]);
63690
63922
  perpDexs.forEach((item, index) => {
@@ -63699,14 +63931,14 @@ var init_hyperliquid_market_catalog = __esm({
63699
63931
  };
63700
63932
  marketIdentityRow = (input) => {
63701
63933
  const symbol2 = normalizeHyperliquidMarketSymbol(input.asset.name);
63702
- if (!symbol2) throw malformed("A Hyperliquid market entry has no name.");
63934
+ if (!symbol2) throw malformed2("A Hyperliquid market entry has no name.");
63703
63935
  const dex = getHyperliquidMarketDex(symbol2);
63704
- if (dex !== String(input.dex ?? "").trim().toLowerCase()) throw malformed(`Hyperliquid listed ${symbol2} under another DEX.`);
63936
+ if (dex !== String(input.dex ?? "").trim().toLowerCase()) throw malformed2(`Hyperliquid listed ${symbol2} under another DEX.`);
63705
63937
  const baseSymbol = dex ? symbol2.slice(dex.length + 1) : symbol2;
63706
63938
  const szDecimals = integer3(input.asset.szDecimals);
63707
- if (szDecimals === null || szDecimals < 0) throw malformed(`Hyperliquid's entry for ${symbol2} has no size precision.`);
63939
+ if (szDecimals === null || szDecimals < 0) throw malformed2(`Hyperliquid's entry for ${symbol2} has no size precision.`);
63708
63940
  const leverage = input.asset.maxLeverage ? integer3(input.asset.maxLeverage) : 1;
63709
- if (leverage === null) throw malformed(`Hyperliquid's entry for ${symbol2} has an invalid max leverage.`);
63941
+ if (leverage === null) throw malformed2(`Hyperliquid's entry for ${symbol2} has an invalid max leverage.`);
63710
63942
  const rawMarginMode = input.asset.marginMode;
63711
63943
  const marginMode = rawMarginMode === null || rawMarginMode === void 0 ? null : String(rawMarginMode).trim() || null;
63712
63944
  const assetId = input.perpDexIndex === DEFAULT_DEX_INDEX ? input.indexInMeta : HYPERLIQUID_EXCHANGE_SPECIFICATION.hip3_asset_id_base + input.perpDexIndex * HYPERLIQUID_EXCHANGE_SPECIFICATION.hip3_asset_id_dex_stride + input.indexInMeta;
@@ -63735,10 +63967,10 @@ var init_hyperliquid_market_catalog = __esm({
63735
63967
  for (const [dex, response] of Object.entries(metas)) {
63736
63968
  const universe = response && typeof response === "object" ? response.universe : null;
63737
63969
  if (!Array.isArray(universe) || universe.length === 0 || universe.some((asset) => !asset || typeof asset !== "object" || !String(asset.name ?? "").trim())) {
63738
- throw malformed(`Hyperliquid returned malformed market metadata for ${dex || "the default DEX"}.`);
63970
+ throw malformed2(`Hyperliquid returned malformed market metadata for ${dex || "the default DEX"}.`);
63739
63971
  }
63740
63972
  const perpDexIndex = dex === DEFAULT_DEX ? DEFAULT_DEX_INDEX : dexIndexes.get(dex);
63741
- if (perpDexIndex === void 0) throw malformed(`Hyperliquid does not list the perp DEX ${dex}.`);
63973
+ if (perpDexIndex === void 0) throw malformed2(`Hyperliquid does not list the perp DEX ${dex}.`);
63742
63974
  universe.forEach((asset, indexInMeta) => {
63743
63975
  const symbol2 = normalizeHyperliquidMarketSymbol(asset.name);
63744
63976
  const delisted = asset.isDelisted === true;
@@ -84761,7 +84993,7 @@ function showThrottleMessage(service) {
84761
84993
  console.log("==========================");
84762
84994
  }
84763
84995
  var shown;
84764
- var init_community = __esm({
84996
+ var init_community2 = __esm({
84765
84997
  "node_modules/ethers/lib.esm/providers/community.js"() {
84766
84998
  init_define_VTX_CLAUDE_CODE_POLICY();
84767
84999
  init_define_VTX_EXO_POLICY();
@@ -85853,7 +86085,7 @@ var init_provider_ankr = __esm({
85853
86085
  init_define_VTX_GROK_POLICY();
85854
86086
  init_define_VTX_PI_MODEL_POLICY();
85855
86087
  init_utils();
85856
- init_community();
86088
+ init_community2();
85857
86089
  init_network();
85858
86090
  init_provider_jsonrpc();
85859
86091
  defaultApiKey = "9f7d929b018cdffb338517efa06f58359e86ff1ffd350bc889738523659e7972";
@@ -85965,7 +86197,7 @@ var init_provider_alchemy = __esm({
85965
86197
  init_define_VTX_GROK_POLICY();
85966
86198
  init_define_VTX_PI_MODEL_POLICY();
85967
86199
  init_utils();
85968
- init_community();
86200
+ init_community2();
85969
86201
  init_network();
85970
86202
  init_provider_jsonrpc();
85971
86203
  defaultApiKey2 = "_gg7wSSi0KMBsdKnGVfHDueq6xMB9EkC";
@@ -86078,7 +86310,7 @@ var init_provider_chainstack = __esm({
86078
86310
  init_define_VTX_GROK_POLICY();
86079
86311
  init_define_VTX_PI_MODEL_POLICY();
86080
86312
  init_utils();
86081
- init_community();
86313
+ init_community2();
86082
86314
  init_network();
86083
86315
  init_provider_jsonrpc();
86084
86316
  ChainstackProvider = class _ChainstackProvider extends JsonRpcProvider {
@@ -86175,7 +86407,7 @@ var init_provider_etherscan = __esm({
86175
86407
  init_abstract_provider();
86176
86408
  init_network();
86177
86409
  init_plugins_network();
86178
- init_community();
86410
+ init_community2();
86179
86411
  Supported = "1 11155111 17000 560048 2741 11124 33111 33139 42170 42161 421614 43114 43113 8453 84532 80069 80094 199 1029 81457 168587773 56 97 42220 11142220 252 2523 100 999 737373 747474 59144 59141 5000 5003 43521 143 10143 1287 1284 1285 10 11155420 204 5611 80002 137 534352 534351 1329 1328 146 14601 988 2201 1923 1924 167013 167000 130 1301 480 4801 51 50 324 300".split(/ /g);
86180
86412
  THROTTLE = 2e3;
86181
86413
  EtherscanPluginId = "org.ethers.plugins.provider.Etherscan";
@@ -90840,7 +91072,7 @@ var init_provider_infura = __esm({
90840
91072
  init_define_VTX_GROK_POLICY();
90841
91073
  init_define_VTX_PI_MODEL_POLICY();
90842
91074
  init_utils();
90843
- init_community();
91075
+ init_community2();
90844
91076
  init_network();
90845
91077
  init_provider_jsonrpc();
90846
91078
  init_provider_websocket();
@@ -90999,7 +91231,7 @@ var init_provider_quicknode = __esm({
90999
91231
  init_define_VTX_GROK_POLICY();
91000
91232
  init_define_VTX_PI_MODEL_POLICY();
91001
91233
  init_utils();
91002
- init_community();
91234
+ init_community2();
91003
91235
  init_network();
91004
91236
  init_provider_jsonrpc();
91005
91237
  defaultToken = "919b412a057b5e9c9b6dce193c5a60242d6efadb";
@@ -92146,7 +92378,7 @@ var init_provider_pocket = __esm({
92146
92378
  init_define_VTX_GROK_POLICY();
92147
92379
  init_define_VTX_PI_MODEL_POLICY();
92148
92380
  init_utils();
92149
- init_community();
92381
+ init_community2();
92150
92382
  init_network();
92151
92383
  init_provider_jsonrpc();
92152
92384
  defaultApplicationId = "62e1ad51b37b8e00394bda3b";
@@ -92297,7 +92529,7 @@ var init_providers = __esm({
92297
92529
  init_define_VTX_PI_MODEL_POLICY();
92298
92530
  init_abstract_provider();
92299
92531
  init_abstract_signer();
92300
- init_community();
92532
+ init_community2();
92301
92533
  init_default_provider();
92302
92534
  init_ens_resolver();
92303
92535
  init_network();
@@ -96203,7 +96435,7 @@ var init_hyperliquid_signer = __esm({
96203
96435
  });
96204
96436
 
96205
96437
  // lib/runtime/hyperliquid-client.ts
96206
- var HyperliquidExchangeRejectionError, assertFreshPreparedExecutionContext, normalizeSymbol, normalizeBotMarket, HYPERLIQUID_NONCE_STORAGE_KEY, HYPERLIQUID_NONCE_LOCK_NAME, lastGeneratedNonce, readBrowserStoredHyperliquidNonce, writeBrowserStoredHyperliquidNonce, browserNonceCoordinator, allocateHyperliquidNonce, hostNonceAllocator, allocateActionNonce, generateHyperliquidNonce, normalizeDecimalString, HYPERLIQUID_PRICE_SIGNIFICANT_FIGURES, HYPERLIQUID_INTEGER_PRICE_MINIMUM, shortestDecimalParts, formatHyperliquidPerpPriceGrid, formatHyperliquidTriggerPriceWire, hyperliquidOrderPriceRounding, formatHyperliquidOrderPriceWire, countSignificantDigits, countDecimalPlaces, validateHyperliquidPerpPriceWire, validateHyperliquidSizeWire, formatSizeWire, inferApiUrl, inferIsTestnet, postHyperliquidInfoRead, postHyperliquidInfo, fetchBrowserHyperliquidInfoPayload, fetchBrowserHyperliquidInfoRead, fetchBrowserHyperliquidInfoText, toFiniteNumber, OPEN_ORDER_NUMERIC_STRING, OPEN_ORDER_ID_STRING, parseCanonicalOpenOrderId, parseOpenOrderFiniteNumber, parseOpenOrderNonNegativeNumber, NATIVE_FIRED_TRIGGER_CONDITION, parseOpenOrderPositiveNumber, parseOpenOrderPresentationNumber, readOpenOrderField, firstFiniteNumber, parseFundingUsdcFromInfoPosition, isExchangeIsolatedOnly, resolveLeverageTarget, computeHip3AssetId, buildAssetInfosFromMetaResponse, requireWalletAddress, assertPositiveInteger, assertPositiveNumber, normalizeOrderSide, normalizeHyperliquidClientOrderId, resolveAssets, findResolvedAsset, normalizeExecutionAssetMetadata, readDeviceExecutionAssetMetadata, requireBotProfileId, executionAssetMetadataFor, resolveHyperliquidAsset, resolveHyperliquidAssetIndex, decimalUnits, quantizeHyperliquidOrderSizeValue, hyperliquidSignedSizeMatchesRequestedSize, finitePositive, readDevicePrivateExecutionContext, quantizeHyperliquidOrderSize, listBrowserMarketListDexes, browserMarketListMaxMarkets, cutBrowserMarketList, readBrowserPerpDexIndexes, readBrowserMarketListDex, fetchBrowserAvailableAssets, fetchBrowserAllMids, fetchBrowserSymbolMidPrice, fetchBrowserOpenOrders, parseCanonicalHyperliquidOrderStatusEvidence, fetchBrowserOrderStatusEvidence, fetchBrowserUserRole, fetchBrowserAccountState, fetchBrowserPosition, buildHyperliquidOrderWire, buildHyperliquidTriggerOrderWire, signHyperliquidPayload, signHyperliquidPreparedAction, buildHyperliquidCancelAction, buildHyperliquidCancelPayload, buildHyperliquidUpdateLeverageAction, buildHyperliquidUpdateLeveragePayload, buildHyperliquidMarketOrderAction, buildHyperliquidMarketOrderPayload, buildHyperliquidLimitOrderAction, buildHyperliquidLimitOrderPayload, buildHyperliquidTriggerOrderAction, buildHyperliquidTriggerOrderPayload, buildHyperliquidOrderBatchAction, buildHyperliquidOrderBatchPayload, buildHyperliquidModifyOrderAction, buildHyperliquidModifyOrderPayload, TRAILING_PCT_PATTERN, buildHyperliquidTrailingStopAction, buildHyperliquidTrailingStopPayload, extractHyperliquidExchangeError, acknowledgementLookupPacing, lookupUntilListed, resolveHyperliquidTriggerAcknowledgements, readHyperliquidTrailingStopAcknowledgement, resolveHyperliquidModifyAcknowledgement, isDefinitiveHyperliquidExchangeResponse, extractDefinitiveHyperliquidOrderId, CANONICAL_POSITIVE_DECIMAL_PATTERN, extractCanonicalHyperliquidOrderStateAcknowledgement, extractCanonicalHyperliquidOrderStateAcknowledgements, extractCanonicalHyperliquidFilledOrderAcknowledgement, extractDefinitiveHyperliquidOrderMemberResults, buildHyperliquidOrderDiagnostics, loadClientExecutionReferenceEvidence, sha256Hex, extractSignedPayloadClientOrderId, extractSignedPayloadMutationCorrelation, assertDurableMutationMatchesSignedAction, exchangeRejectionReason, exchangeActionPriority, submitHyperliquidExchangePayload;
96438
+ var HyperliquidExchangeRejectionError, assertFreshPreparedExecutionContext, normalizeSymbol, normalizeBotMarket, HYPERLIQUID_NONCE_STORAGE_KEY, HYPERLIQUID_NONCE_LOCK_NAME, lastGeneratedNonce, readBrowserStoredHyperliquidNonce, writeBrowserStoredHyperliquidNonce, browserNonceCoordinator, allocateHyperliquidNonce, hostNonceAllocator, allocateActionNonce, generateHyperliquidNonce, normalizeDecimalString, HYPERLIQUID_PRICE_SIGNIFICANT_FIGURES, HYPERLIQUID_INTEGER_PRICE_MINIMUM, shortestDecimalParts, formatHyperliquidPerpPriceGrid, formatHyperliquidTriggerPriceWire, hyperliquidOrderPriceRounding, formatHyperliquidOrderPriceWire, countSignificantDigits, countDecimalPlaces, validateHyperliquidPerpPriceWire, validateHyperliquidSizeWire, formatSizeWire, inferApiUrl, inferIsTestnet, postHyperliquidInfoRead, postHyperliquidInfo, fetchBrowserHyperliquidInfoPayload, fetchBrowserHyperliquidInfoRead, fetchBrowserHyperliquidInfoText, toFiniteNumber, NATIVE_FIRED_TRIGGER_CONDITION, firstFiniteNumber, parseFundingUsdcFromInfoPosition, isExchangeIsolatedOnly, resolveLeverageTarget, computeHip3AssetId, buildAssetInfosFromMetaResponse, requireWalletAddress, assertPositiveInteger, assertPositiveNumber, normalizeOrderSide, normalizeHyperliquidClientOrderId, resolveAssets, findResolvedAsset, normalizeExecutionAssetMetadata, readDeviceExecutionAssetMetadata, requireBotProfileId, executionAssetMetadataFor, resolveHyperliquidAsset, resolveHyperliquidAssetIndex, decimalUnits, quantizeHyperliquidOrderSizeValue, hyperliquidSignedSizeMatchesRequestedSize, finitePositive, readDevicePrivateExecutionContext, quantizeHyperliquidOrderSize, listBrowserMarketListDexes, browserMarketListMaxMarkets, cutBrowserMarketList, readBrowserPerpDexIndexes, readBrowserMarketListDex, fetchBrowserAvailableAssets, fetchBrowserAllMids, fetchBrowserSymbolMidPrice, fetchBrowserOpenOrders, parseCanonicalHyperliquidOrderStatusEvidence, fetchBrowserOrderStatusEvidence, fetchBrowserUserRole, fetchBrowserAccountState, fetchBrowserPosition, buildHyperliquidOrderWire, buildHyperliquidTriggerOrderWire, signHyperliquidPayload, signHyperliquidPreparedAction, buildHyperliquidCancelAction, buildHyperliquidCancelPayload, buildHyperliquidUpdateLeverageAction, buildHyperliquidUpdateLeveragePayload, buildHyperliquidMarketOrderAction, buildHyperliquidMarketOrderPayload, buildHyperliquidLimitOrderAction, buildHyperliquidLimitOrderPayload, buildHyperliquidTriggerOrderAction, buildHyperliquidTriggerOrderPayload, buildHyperliquidOrderBatchAction, buildHyperliquidOrderBatchPayload, buildHyperliquidModifyOrderAction, buildHyperliquidModifyOrderPayload, TRAILING_PCT_PATTERN, buildHyperliquidTrailingStopAction, buildHyperliquidTrailingStopPayload, extractHyperliquidExchangeError, acknowledgementLookupPacing, lookupUntilListed, resolveHyperliquidTriggerAcknowledgements, readHyperliquidTrailingStopAcknowledgement, resolveHyperliquidModifyAcknowledgement, isDefinitiveHyperliquidExchangeResponse, extractDefinitiveHyperliquidOrderId, CANONICAL_POSITIVE_DECIMAL_PATTERN, extractCanonicalHyperliquidOrderStateAcknowledgement, extractCanonicalHyperliquidOrderStateAcknowledgements, extractCanonicalHyperliquidFilledOrderAcknowledgement, extractDefinitiveHyperliquidOrderMemberResults, buildHyperliquidOrderDiagnostics, loadClientExecutionReferenceEvidence, sha256Hex, extractSignedPayloadClientOrderId, extractSignedPayloadMutationCorrelation, assertDurableMutationMatchesSignedAction, exchangeRejectionReason, exchangeActionPriority, submitHyperliquidExchangePayload;
96207
96439
  var init_hyperliquid_client = __esm({
96208
96440
  "lib/runtime/hyperliquid-client.ts"() {
96209
96441
  "use strict";
@@ -96213,6 +96445,7 @@ var init_hyperliquid_client = __esm({
96213
96445
  init_define_VTX_PI_MODEL_POLICY();
96214
96446
  init_hyperliquid_account_contract();
96215
96447
  init_order_identity();
96448
+ init_hyperliquid_open_order_fields();
96216
96449
  init_hyperliquid_order_status();
96217
96450
  init_runtime_policy_generated2();
96218
96451
  init_constants();
@@ -96480,65 +96713,7 @@ var init_hyperliquid_client = __esm({
96480
96713
  const parsed = typeof value === "number" ? value : Number(value);
96481
96714
  return Number.isFinite(parsed) ? parsed : fallback;
96482
96715
  };
96483
- OPEN_ORDER_NUMERIC_STRING = /^[+-]?(?:(?:\d+(?:\.\d*)?)|(?:\.\d+))(?:[eE][+-]?\d+)?$/;
96484
- OPEN_ORDER_ID_STRING = /^[1-9]\d*$/;
96485
- parseCanonicalOpenOrderId = (value) => {
96486
- if (typeof value === "number") {
96487
- if (Number.isSafeInteger(value) && value > 0) {
96488
- return value;
96489
- }
96490
- throw new Error("Malformed Hyperliquid frontendOpenOrders member.");
96491
- }
96492
- if (typeof value !== "string" || !OPEN_ORDER_ID_STRING.test(value)) {
96493
- throw new Error("Malformed Hyperliquid frontendOpenOrders member.");
96494
- }
96495
- const parsed = Number(value);
96496
- if (!Number.isSafeInteger(parsed) || parsed <= 0) {
96497
- throw new Error("Malformed Hyperliquid frontendOpenOrders member.");
96498
- }
96499
- return parsed;
96500
- };
96501
- parseOpenOrderFiniteNumber = (value) => {
96502
- if (typeof value !== "number" && (typeof value !== "string" || value.trim() === "" || !OPEN_ORDER_NUMERIC_STRING.test(value.trim()))) {
96503
- throw new Error("Malformed Hyperliquid frontendOpenOrders member.");
96504
- }
96505
- const parsed = typeof value === "number" ? value : Number(value.trim());
96506
- if (!Number.isFinite(parsed)) {
96507
- throw new Error("Malformed Hyperliquid frontendOpenOrders member.");
96508
- }
96509
- return parsed;
96510
- };
96511
- parseOpenOrderNonNegativeNumber = (value) => {
96512
- const parsed = parseOpenOrderFiniteNumber(value);
96513
- if (parsed < 0) {
96514
- throw new Error("Malformed Hyperliquid frontendOpenOrders member.");
96515
- }
96516
- return parsed;
96517
- };
96518
96716
  NATIVE_FIRED_TRIGGER_CONDITION = "Triggered";
96519
- parseOpenOrderPositiveNumber = (value) => {
96520
- const parsed = parseOpenOrderFiniteNumber(value);
96521
- if (parsed <= 0) {
96522
- throw new Error("Malformed Hyperliquid frontendOpenOrders member.");
96523
- }
96524
- return parsed;
96525
- };
96526
- parseOpenOrderPresentationNumber = (value, fallback, options = {}) => {
96527
- if (value == null || typeof value === "boolean" || typeof value === "string" && value.trim() === "") {
96528
- return fallback;
96529
- }
96530
- const parsed = toFiniteNumber(value, fallback);
96531
- return options.positive && parsed <= 0 ? fallback : parsed;
96532
- };
96533
- readOpenOrderField = (order, camel, snake) => {
96534
- if (Object.prototype.hasOwnProperty.call(order, camel)) {
96535
- return { present: true, value: order[camel] };
96536
- }
96537
- if (snake != null && Object.prototype.hasOwnProperty.call(order, snake)) {
96538
- return { present: true, value: order[snake] };
96539
- }
96540
- return { present: false, value: void 0 };
96541
- };
96542
96717
  firstFiniteNumber = (values, fallback = 0) => {
96543
96718
  for (const value of values) {
96544
96719
  if (value == null || typeof value === "string" && value.trim() === "") {
@@ -97079,7 +97254,8 @@ var init_hyperliquid_client = __esm({
97079
97254
  "triggerCondition",
97080
97255
  "trigger_condition"
97081
97256
  );
97082
- if (!coin || !side || !Number.isFinite(size) || !rawOrderType.present || !orderType || typeof reduceOnly !== "boolean" || typeof isTrigger !== "boolean" || typeof isPositionTpsl !== "boolean" || (isTrigger ? triggerKind == null : normalizedOrderType !== "limit" && !(triggerKind != null && triggerConditionField.value === NATIVE_FIRED_TRIGGER_CONDITION)) || isTrigger && (triggerPrice == null || triggerPrice <= 0)) {
97257
+ const clientOrderId = listedClientOrderId(order);
97258
+ if (!coin || !side || !Number.isFinite(size) || clientOrderId === void 0 || !rawOrderType.present || !orderType || typeof reduceOnly !== "boolean" || typeof isTrigger !== "boolean" || typeof isPositionTpsl !== "boolean" || (isTrigger ? triggerKind == null : normalizedOrderType !== "limit" && !(triggerKind != null && triggerConditionField.value === NATIVE_FIRED_TRIGGER_CONDITION)) || isTrigger && (triggerPrice == null || triggerPrice <= 0)) {
97083
97259
  throw new Error("Malformed Hyperliquid frontendOpenOrders member.");
97084
97260
  }
97085
97261
  return {
@@ -97097,7 +97273,8 @@ var init_hyperliquid_client = __esm({
97097
97273
  is_position_tpsl: isPositionTpsl,
97098
97274
  trigger_px: triggerPrice,
97099
97275
  ...triggerKind ? { trigger_kind: triggerKind } : {},
97100
- order_value: orderValue
97276
+ order_value: orderValue,
97277
+ ...clientOrderId ? { cloid: clientOrderId } : {}
97101
97278
  };
97102
97279
  };
97103
97280
  if (input.includeChildren !== true) {
@@ -97197,7 +97374,7 @@ var init_hyperliquid_client = __esm({
97197
97374
  }
97198
97375
  const orderRecord = nested;
97199
97376
  const orderId = orderRecord.oid == null ? null : String(orderRecord.oid);
97200
- const clientOrderId = orderRecord.cloid == null ? null : String(orderRecord.cloid);
97377
+ const clientOrderId = listedClientOrderId(orderRecord) ?? null;
97201
97378
  const coin = typeof orderRecord.coin === "string" ? orderRecord.coin.trim() : null;
97202
97379
  const side = typeof orderRecord.side === "string" ? orderRecord.side.trim() : null;
97203
97380
  const originalSizeRaw = orderRecord.origSz;
@@ -100110,6 +100287,7 @@ var init_api2 = __esm({
100110
100287
  init_client_runtime_bootstrap();
100111
100288
  init_billing();
100112
100289
  init_market_data();
100290
+ init_open_orders();
100113
100291
  init_screener();
100114
100292
  init_client_host_commands();
100115
100293
  init_client_exchange_mutation_begin();
@@ -100129,6 +100307,7 @@ var init_api2 = __esm({
100129
100307
  init_mobile_notifications();
100130
100308
  init_server_prompt_rescue();
100131
100309
  init_admin_signups();
100310
+ init_admin_accounts();
100132
100311
  init_client_exchange_reconciliation();
100133
100312
  init_client_protective_evidence();
100134
100313
  init_server_runtime_lease();
@@ -108601,7 +108780,7 @@ var init_protective_leg_evidence = __esm({
108601
108780
  });
108602
108781
 
108603
108782
  // lib/runtime/protective-market-evidence.ts
108604
- var policy2, CLOCK_MARGIN_MS, FRESH_EVIDENCE_WARN_AFTER_MS, ProtectiveEvidenceUnavailableError, fetchClientRuntimeOpenOrders, provenFromMs, nodeAnswerProves, freshEvidenceWait, storedFreshEvidenceWait, waitFor, readProtectiveMarket, PROTECTIVE_FRESH_EVIDENCE_UNAVAILABLE;
108783
+ var policy2, CLOCK_MARGIN_MS, FRESH_EVIDENCE_WARN_AFTER_MS, ProtectiveEvidenceUnavailableError, fetchClientRuntimeOpenOrders, provenFromMs, nodeAnswerProves, readAfter, freshEvidenceWait, storedFreshEvidenceWait, waitFor, readProtectiveMarket, PROTECTIVE_FRESH_EVIDENCE_UNAVAILABLE;
108605
108784
  var init_protective_market_evidence = __esm({
108606
108785
  "lib/runtime/protective-market-evidence.ts"() {
108607
108786
  "use strict";
@@ -108650,6 +108829,7 @@ var init_protective_market_evidence = __esm({
108650
108829
  const fromMs = provenFromMs(notBefore);
108651
108830
  return fromMs == null || stateMs != null && Number.isFinite(stateMs) && stateMs >= fromMs;
108652
108831
  };
108832
+ readAfter = (market) => (hostMs) => market.orders != null && market.pageSentMs != null && market.pageSentMs > hostMs && (!market.viaNode || nodeAnswerProves(market.position.stateTimeMs, { hostMs }));
108653
108833
  freshEvidenceWait = (sinceMs, nowMs2) => {
108654
108834
  const since = typeof sinceMs === "number" && Number.isFinite(sinceMs) && sinceMs <= nowMs2 ? sinceMs : nowMs2;
108655
108835
  return { sinceMs: since, overdue: nowMs2 - since >= FRESH_EVIDENCE_WARN_AFTER_MS };
@@ -109120,30 +109300,25 @@ var init_protective_entry_cover = __esm({
109120
109300
  const { symbol: symbol2, orders } = input;
109121
109301
  const entries = input.groups.flatMap((group) => group.legs.map((leg) => ({ group, leg })));
109122
109302
  const knownId = ({ leg }) => input.lookedUp?.get(String(leg.orderId)) ?? (typeof leg.orderId === "number" ? leg.orderId : null);
109303
+ const clientId = ({ leg }) => typeof leg.orderId === "string" ? leg.orderId.trim().toLowerCase() : null;
109123
109304
  const pendingIds = new Set(entries.flatMap(({ leg }) => leg.replacement?.clientOrderId ? [leg.replacement.clientOrderId] : []));
109124
- const unbound = (entry) => knownId(entry) == null && !pendingIds.has(String(entry.leg.orderId)) && (input.canStillExist ?? ownLegCanStillExist)(entry.group, entry.leg);
109305
+ const companion = (entry) => pendingIds.has(String(entry.leg.orderId));
109125
109306
  const claims = /* @__PURE__ */ new Map();
109126
- const claimed = /* @__PURE__ */ new Set();
109127
- const claim = (entry, order) => {
109128
- if (order == null || claimed.has(order) || claims.has(entry)) return;
109129
- claims.set(entry, order);
109130
- claimed.add(order);
109131
- };
109132
- const byShape = (entry, leg) => orders.find((order) => !claimed.has(order) && protectiveLiveShapeMatches({
109133
- shape: liveProtectiveOrderShape(order),
109134
- symbol: symbol2,
109135
- isLong: entry.group.isLong,
109136
- leg
109137
- }));
109138
- for (const entry of entries) claim(entry, pageOrderById(orders, knownId(entry)));
109139
- const named = new Set(claimed);
109140
- const leaving = new Set(input.groups.filter((group) => group.cleanupRequired === true || entries.some((entry) => entry.group === group && knownId(entry) != null && !claims.has(entry))));
109141
- const waiting = entries.filter(unbound);
109142
- const unread = (entry) => input.unresolved?.has(String(entry.leg.orderId)) === true;
109143
- const staying = waiting.filter((entry) => !leaving.has(entry.group));
109144
- for (const entry of [...waiting.filter((entry2) => leaving.has(entry2.group)), ...staying.filter(unread), ...staying.filter((entry2) => !unread(entry2))]) {
109145
- claim(entry, byShape(entry, entry.leg));
109146
- }
109307
+ for (const entry of entries) {
109308
+ const id2 = knownId(entry);
109309
+ const cloid = companion(entry) ? null : clientId(entry);
109310
+ const order = orders.find((candidate) => id2 != null && String(candidate.oid) === String(id2) || cloid != null && typeof candidate.cloid === "string" && candidate.cloid.toLowerCase() === cloid);
109311
+ if (order != null && ![...claims.values()].includes(order)) claims.set(entry, order);
109312
+ }
109313
+ const placedAs = (entry) => input.placed?.get(String(entry.leg.orderId)) ?? (knownId(entry) == null ? void 0 : input.placed?.get(String(knownId(entry))));
109314
+ const unknown2 = (entry) => {
109315
+ const placed = placedAs(entry);
109316
+ if (placed != null) return placed === "unknown";
109317
+ if (knownId(entry) != null || companion(entry)) return false;
109318
+ const journaledAtMs = entry.leg.replaceJournal?.createdAtMs ?? entry.group.attachmentJournal?.createdAtMs;
109319
+ return journaledAtMs == null || input.provesGone?.(journaledAtMs) !== true;
109320
+ };
109321
+ const leaving = new Set(input.groups.filter((group) => group.cleanupRequired === true || entries.some((entry) => entry.group === group && knownId(entry) != null && !claims.has(entry) && !unknown2(entry))));
109147
109322
  const byKey = /* @__PURE__ */ new Map();
109148
109323
  for (const entry of entries) {
109149
109324
  byKey.set(String(entry.leg.orderId), entry);
@@ -109155,7 +109330,7 @@ var init_protective_entry_cover = __esm({
109155
109330
  const size = Number(order?.sz);
109156
109331
  return entry != null && size > 0 ? protectiveLegCoverSize(entry.leg, Math.min(entry.leg.size, size)) : 0;
109157
109332
  };
109158
- const inFlightOf = (entry) => entry == null || leaving.has(entry.group) || claims.has(entry) || !unbound(entry) ? 0 : protectiveLegCoverSize(entry.leg);
109333
+ const inFlightOf = (entry) => entry == null || leaving.has(entry.group) || claims.has(entry) || !unknown2(entry) || !(input.canStillExist ?? ownLegCanStillExist)(entry.group, entry.leg) ? 0 : protectiveLegCoverSize(entry.leg);
109159
109334
  return {
109160
109335
  /** The leg is on its way out: it covers nothing and takes no share. */
109161
109336
  leaving: (leg) => {
@@ -109164,15 +109339,13 @@ var init_protective_entry_cover = __esm({
109164
109339
  },
109165
109340
  /** What the leg's order on the page covers (nothing on its way out or off the page). */
109166
109341
  cover: (leg) => coverOf(entryOf(leg)),
109167
- /** What a leg whose order is on no page may still cover: its size while it is in flight. */
109342
+ /** What a leg whose order the page does not list may still cover: its size while it is unknown. */
109168
109343
  inFlight: (leg) => inFlightOf(entryOf(leg)),
109169
- /** Whether an order of exactly the leg's shape that no stored leg names rests on the page. */
109170
- restsUnnamed: (group, leg) => orders.some((order) => !named.has(order) && protectiveLiveShapeMatches({
109171
- shape: liveProtectiveOrderShape(order),
109172
- symbol: symbol2,
109173
- isLong: group.isLong,
109174
- leg
109175
- })),
109344
+ /** Whether the page lists the order carrying the leg's id. */
109345
+ lists: (leg) => {
109346
+ const entry = entryOf(leg);
109347
+ return entry != null && claims.has(entry);
109348
+ },
109176
109349
  /** What the legs of one direction cover, by kind (a new entry's attach). */
109177
109350
  directionCover: (isLong) => {
109178
109351
  const cover = { sl: 0, tp: 0 };
@@ -109182,21 +109355,21 @@ var init_protective_entry_cover = __esm({
109182
109355
  return cover;
109183
109356
  },
109184
109357
  /**
109185
- * For a lost stop: the stop losses on the page closing the position, other
109186
- * than the orders a status proved ended (`lost`) and those this pass placed
109187
- * (`placed`, counted where they were placed), an order no leg names whole;
109188
- * and, unseen, what the legs this pass could not read may still cover.
109358
+ * For a lost stop: the stop losses on the page closing the position,
109359
+ * other than the orders a status proved ended (`ended`), each at its
109360
+ * owning leg's cover, and an order no leg owns whole; and, unseen, what
109361
+ * the legs this pass could not read, and the stops it re-placed, may
109362
+ * still cover while unknown.
109189
109363
  */
109190
- lostStopCover: (positionSize, excluded) => {
109364
+ lostStopCover: (positionSize) => {
109191
109365
  const isLong = positionSize > 0;
109192
109366
  const owners = new Map([...claims].map(([entry, order]) => [order, entry]));
109193
- const placed = (entry) => excluded.placed.has(String(entry.leg.orderId)) || excluded.placed.has(String(knownId(entry)));
109194
- const onPage = orders.filter((order) => !excluded.lost.has(String(order.oid)) && !excluded.placed.has(String(order.oid)) && String(order.coin).trim().toUpperCase() === symbol2.trim().toUpperCase() && order.reduce_only && order.is_trigger && order.trigger_kind === "sl" && (isLong ? ["a", "sell"] : ["b", "buy"]).includes(String(order.side).trim().toLowerCase())).reduce((total, order) => {
109367
+ const onPage = orders.filter((order) => input.ended?.has(String(order.oid)) !== true && String(order.coin).trim().toUpperCase() === symbol2.trim().toUpperCase() && order.reduce_only && order.is_trigger && order.trigger_kind === "sl" && (isLong ? ["a", "sell"] : ["b", "buy"]).includes(String(order.side).trim().toLowerCase())).reduce((total, order) => {
109195
109368
  const owner2 = owners.get(order);
109196
109369
  const size = Number(order.sz);
109197
- return total + (owner2 != null ? placed(owner2) ? 0 : coverOf(owner2) : size > 0 ? size : 0);
109370
+ return total + (owner2 != null ? coverOf(owner2) : size > 0 ? size : 0);
109198
109371
  }, 0);
109199
- const unseen = entries.filter((entry) => entry.leg.kind === "sl" && entry.group.isLong === isLong && !placed(entry) && input.unresolved?.has(String(entry.leg.orderId)) === true).reduce((total, entry) => total + inFlightOf(entry), 0);
109372
+ const unseen = entries.filter((entry) => entry.leg.kind === "sl" && entry.group.isLong === isLong && (input.unresolved?.has(String(entry.leg.orderId)) === true || placedAs(entry) != null)).reduce((total, entry) => total + inFlightOf(entry), 0);
109200
109373
  return { onPage, unseen };
109201
109374
  }
109202
109375
  };
@@ -109205,6 +109378,102 @@ var init_protective_entry_cover = __esm({
109205
109378
  }
109206
109379
  });
109207
109380
 
109381
+ // lib/runtime/protective-placed-stops.ts
109382
+ var passPlacedStops;
109383
+ var init_protective_placed_stops = __esm({
109384
+ "lib/runtime/protective-placed-stops.ts"() {
109385
+ "use strict";
109386
+ init_define_VTX_CLAUDE_CODE_POLICY();
109387
+ init_define_VTX_EXO_POLICY();
109388
+ init_define_VTX_GROK_POLICY();
109389
+ init_define_VTX_PI_MODEL_POLICY();
109390
+ init_protective_leg_evidence();
109391
+ init_protective_market_evidence();
109392
+ passPlacedStops = () => {
109393
+ const stops = [];
109394
+ const pages = /* @__PURE__ */ new WeakMap();
109395
+ let pagesSeen = 0;
109396
+ const pageOrder = (market) => {
109397
+ if (!pages.has(market)) {
109398
+ pagesSeen += 1;
109399
+ pages.set(market, pagesSeen);
109400
+ }
109401
+ return pages.get(market);
109402
+ };
109403
+ return {
109404
+ /** A stop about to be sent, under its client order id. */
109405
+ add: (leg) => {
109406
+ const stop = { ids: [String(leg.orderId)], sentMs: protectiveReadStampMs(), pagesBefore: pagesSeen, filled: false };
109407
+ stops.push(stop);
109408
+ return stop;
109409
+ },
109410
+ /**
109411
+ * The newest stop this pass sent and still holds, if any: the lost-stop
109412
+ * count reads its market again, proven past this stop's stamp, before it
109413
+ * counts a lost stop after it (runtime-execution.ts readLostLegMarket).
109414
+ */
109415
+ latest: () => stops[stops.length - 1] ?? null,
109416
+ /** A stop never sent, or refused: forgotten. */
109417
+ drop: (stop) => {
109418
+ stops.splice(stops.indexOf(stop), 1);
109419
+ },
109420
+ /** Its answer (extractCanonicalHyperliquidOrderStateAcknowledgement): its exchange order id, and whether it filled. */
109421
+ answered: (stop, answer) => {
109422
+ stop.ids.push(answer.orderId);
109423
+ stop.filled = answer.state === "fulfilled";
109424
+ },
109425
+ /** What this market's page tells of each, by its client and exchange order ids, when it does not list it. */
109426
+ on: (market) => {
109427
+ const read = pageOrder(market);
109428
+ return new Map(stops.flatMap((stop) => {
109429
+ const after = market.orders != null && read > stop.pagesBefore;
109430
+ const proven = !market.viaNode || nodeAnswerProves(market.position.stateTimeMs, { hostMs: stop.sentMs });
109431
+ const told = after && (stop.filled || proven) ? "gone" : "unknown";
109432
+ return stop.ids.map((id2) => [id2, told]);
109433
+ }));
109434
+ }
109435
+ };
109436
+ };
109437
+ }
109438
+ });
109439
+
109440
+ // lib/runtime/client-order-landing.ts
109441
+ var clientOrderNeverLandsAfterMs, requireClientRuntimeConfigSeconds, pageProvesGone;
109442
+ var init_client_order_landing = __esm({
109443
+ "lib/runtime/client-order-landing.ts"() {
109444
+ "use strict";
109445
+ init_define_VTX_CLAUDE_CODE_POLICY();
109446
+ init_define_VTX_EXO_POLICY();
109447
+ init_define_VTX_GROK_POLICY();
109448
+ init_define_VTX_PI_MODEL_POLICY();
109449
+ init_constants();
109450
+ init_protective_market_evidence();
109451
+ init_runtime_error_reason_rules();
109452
+ clientOrderNeverLandsAfterMs = (config2, ledger) => {
109453
+ const marginMs = requireClientRuntimeConfigSeconds(
109454
+ config2,
109455
+ "client_pending_entry_never_landed_margin_seconds"
109456
+ ) * MS_PER_SECOND;
109457
+ if (ledger.kind === "found") return ledger.expiresAfterMs + marginMs;
109458
+ const signedLifetimeSeconds = Number(
109459
+ config2?.client_runtime_exchange_mutation?.expires_after_seconds
109460
+ );
109461
+ if (!Number.isInteger(signedLifetimeSeconds) || signedLifetimeSeconds <= 0) {
109462
+ throw new RuntimeReasonError("Missing required client runtime config: client_runtime_exchange_mutation.expires_after_seconds", "runtime_config_missing");
109463
+ }
109464
+ return ledger.ageStartMs + signedLifetimeSeconds * MS_PER_SECOND + marginMs;
109465
+ };
109466
+ requireClientRuntimeConfigSeconds = (config2, key) => {
109467
+ const value = Number(config2?.[key]);
109468
+ if (!Number.isFinite(value) || value < 0) {
109469
+ throw new RuntimeReasonError(`Missing required client runtime config: ${String(key)}`, "runtime_config_missing");
109470
+ }
109471
+ return value;
109472
+ };
109473
+ pageProvesGone = (market, config2) => ((journaledAtMs) => readAfter(market)(clientOrderNeverLandsAfterMs(config2, { kind: "absent", ageStartMs: journaledAtMs })));
109474
+ }
109475
+ });
109476
+
109208
109477
  // lib/runtime/protective-oversized-leg.ts
109209
109478
  var OVERSIZED_LEG_GROUP_PREFIX, splitOversizedProtectiveLeg;
109210
109479
  var init_protective_oversized_leg = __esm({
@@ -109276,6 +109545,7 @@ var init_native_position_protection = __esm({
109276
109545
  init_hyperliquid_client();
109277
109546
  init_hyperliquid_market_symbol();
109278
109547
  init_hyperliquid_order_status();
109548
+ init_order_identity();
109279
109549
  init_protective_stop_replacement();
109280
109550
  nativeProtectionSettings = (resolved) => ({
109281
109551
  stopLoss: resolved.tpSlEnabled && resolved.stopLossEnabled ? {
@@ -109439,7 +109709,7 @@ var init_native_position_protection = __esm({
109439
109709
  if (orderType === TRAILING_ORDER_TYPE && rowOrderId != null && ownTrailing.has(rowOrderId)) continue;
109440
109710
  const rowKind = orderType.includes("take profit") ? "tp" : orderType.includes("stop") ? "sl" : null;
109441
109711
  if (rowKind !== input.kind) continue;
109442
- if (own.has(String(row.cloid ?? "").trim().toLowerCase())) {
109712
+ if (own.has(listedClientOrderId(row) ?? "")) {
109443
109713
  return { decision: "adopt", order_id: Number(row.oid) };
109444
109714
  }
109445
109715
  const size = String(row.sz ?? "").trim();
@@ -111341,7 +111611,7 @@ var init_native_protection_device = __esm({
111341
111611
  });
111342
111612
 
111343
111613
  // lib/runtime/runtime-execution.ts
111344
- var clientProtectiveMutationAuthority, executionReadPriority, serverEntryLeverageAlreadyHeld, createRuntimeId, _extractFilledSize, firstMemberAcknowledgement, _extractOrderId, _toExecutionMetadata, _extractClientMutationId, _stableMutationIdentity, trailingStopMemory, protectiveGroupMemory, protectiveGroupReadFailures, windowHandoffCleanupAttempts, clientRuntimeProtectionStorage, resolveClientRuntimeProtectionStorage, setClientRuntimeProtectionStorage, trailingStopStorageKey, readTrackedTrailingStops, writeTrackedTrailingStops, rememberTrailingStop, protectiveGroupStorageKey, LOST_LEG_EVIDENCE_MAX_AGE_MS, EPISODE_END_FILL_LOOKBACK_MS, withClientProtectivePlanSetLock, readClientProtectiveGroups, writeClientProtectiveGroups, hasClientProtectiveGroupReadFailure, readFreshClientProtectiveGroups, stableProtectionSnapshot, exactClientProtectiveGroupSnapshot, exactClientProtectiveGroupSetSnapshot, storableClientProtectiveGroup, replaceExactClientProtectiveGroup, replaceExactClientProtectiveGroupSet, isClientRuntimeLeaseOwnershipError, hasClientRuntimeProtectionState, clearClientRuntimeVetoedProtectiveIntent, rethrowWindowHandoffAfterProtectiveReplacementVeto, canPersistClientProtectiveGroups, removeTrackedTrailingStop, replaceTrackedTrailingStop, replacementJournalEntryOrderId, buildProtectiveReplacementJournalGroup, isProtectiveReplacementJournalGroup, reserveProtectiveLegReplacement, ensureProtectiveReplacementJournalCompanion, buildVetoedProtectiveReplacementCleanup, assertExactProtectiveReplacementDispatchAuthority, transitionProtectiveReplacementAcknowledgement, transitionTerminalProtectiveReplacement, isConfiguredProtectionRequested, protectiveAction, isExactClientPositionTpslPair, deviceOwnsClientProtectiveLegKind, isAdoptionNarrowedPositionTpslLeg, hasAmbiguousClientPositionTpslAuthority, protectiveTerminalShapeMatches, cancelClientProtectiveLeg, buildPendingProtectivePlan, persistPendingClientProtectiveGroup, readAttachEvidence, attachClientProtectivePlan, resolveJournaledAttachmentContinuity, protectiveMemberRested, ledgerOrderIdsByClientOrderId, journaledAttachmentNeverLanded, recoverJournaledClientProtectiveAttachments, readClientOrderMutation, readPendingEntryMutation, clientOrderNeverLandsAfterMs, requireClientRuntimeConfigSeconds, replacePendingEntryRecovery, recoverPendingClientProtectiveGroups, recoverPendingProtectiveReplacements, observedStandaloneProtectiveGroup, migrateTrackedTrailingStopsToStandalone, nativeSettingsOf, nativePassEnded, nativeProtectionIo, nativeStorageReport, readNativeRecord, reconcileNativeProtectionForDecision, reconcileClientProtectiveGroups, cancelAllClientProtectiveGroups, modifyClientTrailingLeg, trailingRatchetIo, isDefinitiveEntryRejection, resolveExchangeSizeDecimals, readServerOrderMarkPrice, serverOrderMetadataRetry, resolveCurrentPositionSize, buildPositionSnapshot, runtimeProtectionAuthority, runtimeProtectionListings, runtimeProtectionListing, resolveServerNativeEntry, SERVER_NATIVE_LEGACY_REFUSAL, isServerNativeLegacyRefusal, serverUserCancelLookup, passUserCancelsFor, serverModeProtectionOwner, runtimeProtectionOwners, resolveRuntimeProtectionOwner, drainServerProtectionForRuntime, drainServerProtectionIfOwned, verifyNoLiveClientProtectiveTriggers, clientExecutionMutations, CLIENT_EXECUTION_QUEUE_TIMEOUT_MESSAGE, withClientExecutionMutation, withClientProtectivePlanSetMutation, allocateServerExecutionCapacity, withClientProtectiveAdoptionMutation, executeClientRuntimeDecisionLocked, unsentDecisionOrderReport, SERVER_AUDIT_RECORDED_ELSEWHERE, serverExecutionAuditOutcome, decisionLegOf, withExecutionAuditId, executeClientRuntimeDecision, waitForFlipCloseFreshness, nextClientTrailingStopDueAtMs, ratchetClientTrailingStopsBetweenCycles, handedOverPlan, listPendingClientProtectiveSymbols, listStoredClientProtectiveSymbols, hasUnresolvedClientProtectiveIdentity, resolveClientProtectiveIdentitiesForAdoption, exportClientProtectiveGroupsForAdoption, adoptionGroupKey, applyClientProtectiveAdoptionOutcomes, hasStoredClientProtectiveGroupsForWallet, hasPendingClientProtectiveGroups, recoverManualClientProtectiveGroups, listStoredClientProtectionSymbols, clientRuntimeDecisionSizesOrders, COMMITTED_EXECUTION_REPORTS, COMMITTED_DECISION_ORDER, getCommittedExecutionReports, getCommittedDecisionOrder, withCommittedExecutionReports, executeClientRuntimeDecisionUnlocked;
111614
+ var clientProtectiveMutationAuthority, executionReadPriority, serverEntryLeverageAlreadyHeld, createRuntimeId, _extractFilledSize, firstMemberAcknowledgement, _extractOrderId, _toExecutionMetadata, _extractClientMutationId, _stableMutationIdentity, trailingStopMemory, protectiveGroupMemory, protectiveGroupReadFailures, windowHandoffCleanupAttempts, clientRuntimeProtectionStorage, resolveClientRuntimeProtectionStorage, setClientRuntimeProtectionStorage, trailingStopStorageKey, readTrackedTrailingStops, writeTrackedTrailingStops, rememberTrailingStop, protectiveGroupStorageKey, LOST_LEG_EVIDENCE_MAX_AGE_MS, EPISODE_END_FILL_LOOKBACK_MS, withClientProtectivePlanSetLock, readClientProtectiveGroups, writeClientProtectiveGroups, hasClientProtectiveGroupReadFailure, readFreshClientProtectiveGroups, stableProtectionSnapshot, exactClientProtectiveGroupSnapshot, exactClientProtectiveGroupSetSnapshot, storableClientProtectiveGroup, replaceExactClientProtectiveGroup, replaceExactClientProtectiveGroupSet, isClientRuntimeLeaseOwnershipError, hasClientRuntimeProtectionState, clearClientRuntimeVetoedProtectiveIntent, rethrowWindowHandoffAfterProtectiveReplacementVeto, canPersistClientProtectiveGroups, removeTrackedTrailingStop, replaceTrackedTrailingStop, replacementJournalEntryOrderId, buildProtectiveReplacementJournalGroup, isProtectiveReplacementJournalGroup, reserveProtectiveLegReplacement, ensureProtectiveReplacementJournalCompanion, buildVetoedProtectiveReplacementCleanup, assertExactProtectiveReplacementDispatchAuthority, transitionProtectiveReplacementAcknowledgement, transitionTerminalProtectiveReplacement, isConfiguredProtectionRequested, protectiveAction, isExactClientPositionTpslPair, deviceOwnsClientProtectiveLegKind, isAdoptionNarrowedPositionTpslLeg, hasAmbiguousClientPositionTpslAuthority, protectiveTerminalShapeMatches, cancelClientProtectiveLeg, buildPendingProtectivePlan, persistPendingClientProtectiveGroup, readAttachEvidence, attachClientProtectivePlan, resolveJournaledAttachmentContinuity, protectiveMemberRested, ledgerOrderIdsByClientOrderId, journaledAttachmentNeverLanded, recoverJournaledClientProtectiveAttachments, readClientOrderMutation, readPendingEntryMutation, replacePendingEntryRecovery, recoverPendingClientProtectiveGroups, recoverPendingProtectiveReplacements, observedStandaloneProtectiveGroup, migrateTrackedTrailingStopsToStandalone, nativeSettingsOf, nativePassEnded, nativeProtectionIo, nativeStorageReport, readNativeRecord, reconcileNativeProtectionForDecision, reconcileClientProtectiveGroups, cancelAllClientProtectiveGroups, modifyClientTrailingLeg, trailingRatchetIo, isDefinitiveEntryRejection, resolveExchangeSizeDecimals, readServerOrderMarkPrice, serverOrderMetadataRetry, resolveCurrentPositionSize, buildPositionSnapshot, runtimeProtectionAuthority, runtimeProtectionListings, runtimeProtectionListing, resolveServerNativeEntry, SERVER_NATIVE_LEGACY_REFUSAL, isServerNativeLegacyRefusal, serverUserCancelLookup, passUserCancelsFor, serverModeProtectionOwner, runtimeProtectionOwners, resolveRuntimeProtectionOwner, drainServerProtectionForRuntime, drainServerProtectionIfOwned, verifyNoLiveClientProtectiveTriggers, clientExecutionMutations, CLIENT_EXECUTION_QUEUE_TIMEOUT_MESSAGE, withClientExecutionMutation, withClientProtectivePlanSetMutation, allocateServerExecutionCapacity, withClientProtectiveAdoptionMutation, executeClientRuntimeDecisionLocked, unsentDecisionOrderReport, SERVER_AUDIT_RECORDED_ELSEWHERE, serverExecutionAuditOutcome, decisionLegOf, withExecutionAuditId, executeClientRuntimeDecision, waitForFlipCloseFreshness, nextClientTrailingStopDueAtMs, ratchetClientTrailingStopsBetweenCycles, handedOverPlan, listPendingClientProtectiveSymbols, listStoredClientProtectiveSymbols, hasUnresolvedClientProtectiveIdentity, resolveClientProtectiveIdentitiesForAdoption, exportClientProtectiveGroupsForAdoption, adoptionGroupKey, applyClientProtectiveAdoptionOutcomes, hasStoredClientProtectiveGroupsForWallet, hasPendingClientProtectiveGroups, recoverManualClientProtectiveGroups, listStoredClientProtectionSymbols, clientRuntimeDecisionSizesOrders, COMMITTED_EXECUTION_REPORTS, COMMITTED_DECISION_ORDER, getCommittedExecutionReports, getCommittedDecisionOrder, withCommittedExecutionReports, executeClientRuntimeDecisionUnlocked;
111345
111615
  var init_runtime_execution = __esm({
111346
111616
  "lib/runtime/runtime-execution.ts"() {
111347
111617
  "use strict";
@@ -111381,6 +111651,8 @@ var init_runtime_execution = __esm({
111381
111651
  init_protective_leg_evidence();
111382
111652
  init_protective_stop_replacement();
111383
111653
  init_protective_entry_cover();
111654
+ init_protective_placed_stops();
111655
+ init_client_order_landing();
111384
111656
  init_protective_oversized_leg();
111385
111657
  init_protective_report_entry();
111386
111658
  init_error_surface_contract();
@@ -112591,7 +112863,8 @@ var init_runtime_execution = __esm({
112591
112863
  const cover = resolveOwnStops({
112592
112864
  symbol: request.executionContext.symbol,
112593
112865
  groups: candidates,
112594
- orders: market.orders ?? []
112866
+ orders: market.orders ?? [],
112867
+ provesGone: pageProvesGone(market, request.config)
112595
112868
  }).directionCover(entryIsLong);
112596
112869
  return { position: market.position, cover };
112597
112870
  };
@@ -113343,8 +113616,7 @@ var init_runtime_execution = __esm({
113343
113616
  throw new Error("Journaled protective order identity is unresolved.");
113344
113617
  }
113345
113618
  } else {
113346
- const mayRestUnseen = ownStops.restsUnnamed(group, provisionalLeg);
113347
- if (ledgerVerdict.proven && !mayRestUnseen) {
113619
+ if (ledgerVerdict.proven && !ownStops.lists(provisionalLeg)) {
113348
113620
  newlyNeverLanded.add(provisionalLeg.orderId);
113349
113621
  inspected.push({ leg: provisionalLeg, state: "terminal", rested: false, neverLanded: true });
113350
113622
  continue;
@@ -113754,27 +114026,6 @@ var init_runtime_execution = __esm({
113754
114026
  }
113755
114027
  };
113756
114028
  readPendingEntryMutation = (request, plan) => readClientOrderMutation(request, plan.entryMutationId, plan.entryClientOrderId);
113757
- clientOrderNeverLandsAfterMs = (config2, ledger) => {
113758
- const marginMs = requireClientRuntimeConfigSeconds(
113759
- config2,
113760
- "client_pending_entry_never_landed_margin_seconds"
113761
- ) * MS_PER_SECOND;
113762
- if (ledger.kind === "found") return ledger.expiresAfterMs + marginMs;
113763
- const signedLifetimeSeconds = Number(
113764
- config2?.client_runtime_exchange_mutation?.expires_after_seconds
113765
- );
113766
- if (!Number.isInteger(signedLifetimeSeconds) || signedLifetimeSeconds <= 0) {
113767
- throw new Error("Missing required client runtime config: client_runtime_exchange_mutation.expires_after_seconds");
113768
- }
113769
- return ledger.ageStartMs + signedLifetimeSeconds * MS_PER_SECOND + marginMs;
113770
- };
113771
- requireClientRuntimeConfigSeconds = (config2, key) => {
113772
- const value = Number(config2?.[key]);
113773
- if (!Number.isFinite(value) || value < 0) {
113774
- throw new Error(`Missing required client runtime config: ${String(key)}`);
113775
- }
113776
- return value;
113777
- };
113778
114029
  replacePendingEntryRecovery = (profileId, symbol2, group, recovery) => {
113779
114030
  const plan = group.pendingEntry;
113780
114031
  if (plan == null) throw new Error("Pending entry plan is unavailable.");
@@ -114926,9 +115177,9 @@ var init_runtime_execution = __esm({
114926
115177
  let livePositionSize;
114927
115178
  let liveOrders;
114928
115179
  try {
114929
- const paired = await market.withPage();
114930
- livePositionSize = Number(paired.position.size);
114931
- const fetchedOrders = paired.orders;
115180
+ market = await market.withPage();
115181
+ livePositionSize = Number(market.position.size);
115182
+ const fetchedOrders = market.orders;
114932
115183
  if (!Array.isArray(fetchedOrders)) {
114933
115184
  throw new Error("Malformed live protective-order snapshot.");
114934
115185
  }
@@ -115195,8 +115446,7 @@ var init_runtime_execution = __esm({
115195
115446
  tp: exposure
115196
115447
  };
115197
115448
  const retainedGroups = expectedGroupSet.filter((group) => group.pendingEntry != null || isProtectiveReplacementJournalGroup(group));
115198
- let stopSizePlacedThisPass = 0;
115199
- const placedThisPass = /* @__PURE__ */ new Set();
115449
+ const placedStops = passPlacedStops();
115200
115450
  const unresolvedLegIds = new Set(inspectedGroups.flatMap((candidate) => candidate.legs).filter((entry) => entry.state === "unresolved").map((entry) => String(entry.leg.orderId)));
115201
115451
  const lostOrderIds = new Set(inspectedGroups.flatMap((candidate) => candidate.legs).filter((entry) => entry.state === "terminal").flatMap(({ leg }) => [String(leg.orderId), String(lookedUp.get(String(leg.orderId)) ?? leg.orderId)]));
115202
115452
  const statusOnlyOrders = () => inspectedGroups.flatMap((candidate) => candidate.legs).filter((entry) => entry.openOrder == null).map((entry) => ({ receivedMs: entry.statusReceivedMs ?? legsLiveSinceMs, atMs: entry.terminalStatus?.statusTimestampMs ?? entry.statusAtMs }));
@@ -115208,11 +115458,13 @@ var init_runtime_execution = __esm({
115208
115458
  });
115209
115459
  const qualifyingRead = (read) => {
115210
115460
  let current = null;
115461
+ let placedBefore = placedStops.latest();
115211
115462
  return async () => {
115212
115463
  if (current != null) {
115213
115464
  const previous = await current;
115214
- if (readQualifies(previous.sentMs)) return previous;
115465
+ if (readQualifies(previous.sentMs) && placedBefore === placedStops.latest()) return previous;
115215
115466
  }
115467
+ placedBefore = placedStops.latest();
115216
115468
  current = read();
115217
115469
  const fresh = await current;
115218
115470
  if (!readQualifies(fresh.sentMs)) {
@@ -115223,8 +115475,9 @@ var init_runtime_execution = __esm({
115223
115475
  };
115224
115476
  const readLostLegMarket = qualifyingRead(async () => {
115225
115477
  const statuses = statusOnlyOrders();
115478
+ const placed = placedStops.latest();
115226
115479
  const market2 = await readProtectiveMarket(request, {
115227
- notBefore: statuses.every((status) => typeof status.atMs === "number" && status.atMs > 0) ? { exchangeMs: Math.max(...statuses.map((status) => status.atMs)) } : { hostMs: Math.max(...statuses.map((status) => status.receivedMs)) },
115480
+ notBefore: placed == null && statuses.every((status) => typeof status.atMs === "number" && status.atMs > 0) ? { exchangeMs: Math.max(...statuses.map((status) => status.atMs)) } : { hostMs: Math.max(placed?.sentMs ?? 0, ...statuses.map((status) => status.receivedMs)) },
115228
115481
  priority: "trading_reconcile"
115229
115482
  });
115230
115483
  return { sentMs: market2.positionSentMs, market: market2 };
@@ -115325,18 +115578,23 @@ var init_runtime_execution = __esm({
115325
115578
  const market2 = reachable(sizeOf(lost.position)) ? await lost.withPage() : lost;
115326
115579
  const positionSize = sizeOf(market2.position);
115327
115580
  const replaceReachable = reachable(positionSize) && market2.orders != null;
115328
- const stops = replaceReachable ? resolveOwnStops({
115581
+ const own = replaceReachable ? resolveOwnStops({
115329
115582
  symbol: symbol2,
115330
115583
  groups: expectedGroupSet,
115331
115584
  orders: market2.orders ?? [],
115332
115585
  lookedUp,
115333
- unresolved: unresolvedLegIds
115334
- }).lostStopCover(positionSize, { lost: lostOrderIds, placed: placedThisPass }) : null;
115586
+ unresolved: unresolvedLegIds,
115587
+ placed: placedStops.on(market2),
115588
+ ended: lostOrderIds,
115589
+ provesGone: pageProvesGone(market2, request.config)
115590
+ }) : null;
115591
+ const stops = own?.lostStopCover(positionSize);
115335
115592
  const markPrice = Number(market2.position.markPrice);
115336
115593
  evidence2 = {
115337
115594
  positionSize,
115338
115595
  liveStopSize: stops?.onPage ?? 0,
115339
- unseenStopSize: stops?.unseen ?? 0,
115596
+ // What the legs this pass could not read, and its own re-placed stops, may still cover.
115597
+ inFlightStopSize: stops?.unseen ?? 0,
115340
115598
  markPrice: replaceReachable && Number.isFinite(markPrice) && markPrice > 0 ? markPrice : null
115341
115599
  };
115342
115600
  } catch (error48) {
@@ -115349,7 +115607,7 @@ var init_runtime_execution = __esm({
115349
115607
  positionSize: evidence2.positionSize,
115350
115608
  legSize: leg.size,
115351
115609
  otherLiveStopSize: evidence2.liveStopSize,
115352
- inFlightStopSize: evidence2.unseenStopSize + stopSizePlacedThisPass,
115610
+ inFlightStopSize: evidence2.inFlightStopSize,
115353
115611
  sizeDecimals: request.executionContext.sizeDecimals,
115354
115612
  triggerPrice: leg.triggerPrice,
115355
115613
  alreadyReplaced: leg.replacedOrderId != null,
@@ -115457,8 +115715,7 @@ var init_runtime_execution = __esm({
115457
115715
  }]
115458
115716
  };
115459
115717
  }
115460
- stopSizePlacedThisPass += decision.size;
115461
- placedThisPass.add(clientOrderId);
115718
+ const placedStop = placedStops.add(provisionalLeg);
115462
115719
  let dispatchMayHaveStarted = false;
115463
115720
  let response;
115464
115721
  try {
@@ -115489,8 +115746,7 @@ var init_runtime_execution = __esm({
115489
115746
  } catch (error48) {
115490
115747
  if (error48 instanceof ExchangeRejectionError) {
115491
115748
  const rejectionProjection = projectExecutionErrorContract({ error: error48, symbol: symbol2 });
115492
- stopSizePlacedThisPass -= decision.size;
115493
- placedThisPass.delete(clientOrderId);
115749
+ placedStops.drop(placedStop);
115494
115750
  const rejectedGroup = {
115495
115751
  ...provisionalGroup,
115496
115752
  legs: provisionalGroup.legs.filter((candidate) => candidate.orderId !== clientOrderId)
@@ -115521,8 +115777,7 @@ var init_runtime_execution = __esm({
115521
115777
  };
115522
115778
  }
115523
115779
  if (!dispatchMayHaveStarted) {
115524
- stopSizePlacedThisPass -= decision.size;
115525
- placedThisPass.delete(clientOrderId);
115780
+ placedStops.drop(placedStop);
115526
115781
  const restored = transitionExactGroup(provisionalGroup, group);
115527
115782
  if (restored && isClientRuntimeWindowHandoffBeforePlanDispatch(error48)) {
115528
115783
  throw error48;
@@ -115578,7 +115833,7 @@ var init_runtime_execution = __esm({
115578
115833
  }]
115579
115834
  };
115580
115835
  }
115581
- placedThisPass.add(String(placedOrderId));
115836
+ placedStops.answered(placedStop, acknowledgement);
115582
115837
  const { replaceJournal: _landedJournal, ...landedLeg } = provisionalLeg;
115583
115838
  const placedLeg = { ...landedLeg, orderId: placedOrderId };
115584
115839
  const placedGroup = {
@@ -115631,7 +115886,8 @@ var init_runtime_execution = __esm({
115631
115886
  groups: expectedGroupSet,
115632
115887
  orders: liveOrders,
115633
115888
  lookedUp,
115634
- unresolved: unresolvedLegIds
115889
+ unresolved: unresolvedLegIds,
115890
+ provesGone: pageProvesGone(market, request.config)
115635
115891
  });
115636
115892
  const userCancels = passUserCancelsFor(request);
115637
115893
  await userCancels?.prefetch(inspectedGroups.flatMap((candidate) => candidate.group.cleanupRequired === true || exposure <= 0 || candidate.legs.some((entry) => entry.state === "fulfilled") ? [] : candidate.legs.filter((entry) => entry.state === "terminal" && entry.leg.replacement == null).map((entry) => entry.leg.orderId)));
@@ -119838,7 +120094,7 @@ var init_browser_observability = __esm({
119838
120094
  init_define_VTX_GROK_POLICY();
119839
120095
  init_define_VTX_PI_MODEL_POLICY();
119840
120096
  init_runtime_policy_generated2();
119841
- CLIENT_SOURCE_VERSION = typeof process !== "undefined" && true && "3ff286d7fc6667e818cc519c84b33e40f68d2161".trim() && "3ff286d7fc6667e818cc519c84b33e40f68d2161".trim() !== "unstamped" ? "3ff286d7fc6667e818cc519c84b33e40f68d2161".trim() : null;
120097
+ CLIENT_SOURCE_VERSION = typeof process !== "undefined" && true && "455c2035586f6d2a0253fb8dabb4418c3f06b04c".trim() && "455c2035586f6d2a0253fb8dabb4418c3f06b04c".trim() !== "unstamped" ? "455c2035586f6d2a0253fb8dabb4418c3f06b04c".trim() : null;
119842
120098
  listenersInstalled = false;
119843
120099
  state = {
119844
120100
  loadedAtMs: Date.now(),
@@ -121888,6 +122144,7 @@ var init_copy_trading_evidence = __esm({
121888
122144
  init_hyperliquid_account_mode_contract();
121889
122145
  init_hyperliquid_client();
121890
122146
  init_monotonic_clock();
122147
+ init_order_identity();
121891
122148
  init_protective_evidence();
121892
122149
  ACCOUNT_MODE_CACHE_MS = runtime_policy_generated_default2.exchange.hyperliquid.client_public_read_budget.account_mode_ttl_seconds * MS_PER_SECOND;
121893
122150
  dexList2 = (value) => {
@@ -121924,9 +122181,10 @@ var init_copy_trading_evidence = __esm({
121924
122181
  const refs = /* @__PURE__ */ new Set();
121925
122182
  for (const order of response) {
121926
122183
  if (!order || typeof order !== "object") continue;
121927
- const { oid, cloid } = order;
122184
+ const { oid } = order;
122185
+ const cloid = listedClientOrderId(order);
121928
122186
  if (oid != null && oid !== "") refs.add(String(oid).trim().toLowerCase());
121929
- if (typeof cloid === "string" && cloid.trim()) refs.add(cloid.trim().toLowerCase());
122187
+ if (cloid) refs.add(cloid);
121930
122188
  }
121931
122189
  return refs;
121932
122190
  };
@@ -123328,33 +123586,33 @@ var init_history_evidence = __esm({
123328
123586
  isDecimalText = (value) => typeof value === "string" && DECIMAL_TEXT.test(value.trim());
123329
123587
  isRecord6 = (value) => typeof value === "object" && value !== null && !Array.isArray(value);
123330
123588
  parseHistoryPage = (stream, body, startMs, endMs) => {
123331
- const malformed2 = (detail) => new HistoryPageError(`The ${stream} page is not a valid Hyperliquid response: ${detail}`);
123589
+ const malformed3 = (detail) => new HistoryPageError(`The ${stream} page is not a valid Hyperliquid response: ${detail}`);
123332
123590
  if (!STREAMS.has(stream)) throw new HistoryPageError(`Unknown history stream ${stream}.`);
123333
- if (!isInt(startMs) || !isInt(endMs) || startMs < 0 || endMs < startMs) throw malformed2("the window is invalid");
123334
- if (typeof body !== "string") throw malformed2("the body must be the raw response text");
123591
+ if (!isInt(startMs) || !isInt(endMs) || startMs < 0 || endMs < startMs) throw malformed3("the window is invalid");
123592
+ if (typeof body !== "string") throw malformed3("the body must be the raw response text");
123335
123593
  let rows;
123336
123594
  try {
123337
123595
  rows = JSON.parse(body);
123338
123596
  } catch {
123339
- throw malformed2("the body is not JSON");
123597
+ throw malformed3("the body is not JSON");
123340
123598
  }
123341
- if (!Array.isArray(rows)) throw malformed2("the body is not a list");
123599
+ if (!Array.isArray(rows)) throw malformed3("the body is not a list");
123342
123600
  for (const row of rows) {
123343
- if (!isRecord6(row)) throw malformed2("a row is not an object");
123601
+ if (!isRecord6(row)) throw malformed3("a row is not an object");
123344
123602
  const time3 = row.time;
123345
- if (!isInt(time3)) throw malformed2("a row has no millisecond time");
123346
- if (time3 < startMs || time3 > endMs) throw malformed2("a row lies outside the requested window");
123347
- if (!isText(row.hash)) throw malformed2("a row has no hash");
123603
+ if (!isInt(time3)) throw malformed3("a row has no millisecond time");
123604
+ if (time3 < startMs || time3 > endMs) throw malformed3("a row lies outside the requested window");
123605
+ if (!isText(row.hash)) throw malformed3("a row has no hash");
123348
123606
  if (stream === "fills") {
123349
123607
  if (!(isText(row.coin) && isInt(row.oid) && (row.side === "A" || row.side === "B") && isDecimalText(row.px) && isDecimalText(row.sz))) {
123350
- throw malformed2("a fill lacks coin, oid, side, px or sz");
123608
+ throw malformed3("a fill lacks coin, oid, side, px or sz");
123351
123609
  }
123352
123610
  continue;
123353
123611
  }
123354
123612
  const delta = row.delta;
123355
- if (!isRecord6(delta) || !isText(delta.type)) throw malformed2("a row has no typed delta");
123613
+ if (!isRecord6(delta) || !isText(delta.type)) throw malformed3("a row has no typed delta");
123356
123614
  if (stream === "funding" && !(delta.type === "funding" && isText(delta.coin) && isDecimalText(delta.usdc))) {
123357
- throw malformed2("a funding row lacks coin or usdc");
123615
+ throw malformed3("a funding row lacks coin or usdc");
123358
123616
  }
123359
123617
  }
123360
123618
  return rows;
@@ -130766,7 +131024,7 @@ var init_provider_client = __esm({
130766
131024
  });
130767
131025
 
130768
131026
  // lib/runtime/runtime-prompt-steps.ts
130769
- var buildRuntimePromptParityContext, readRuntimePromptMarketData, invokeRuntimeReviewModel, resolveRuntimePromptKnobs, buildRuntimePromptCandles, requireRuntimePromptTemplates, resolveRuntimeBehaviorMemoryCutoff, buildRuntimeBehaviorStateArtifacts, buildRuntimePromptContextParts, runtimePromptArtifactInput;
131027
+ var buildRuntimePromptParityContext, cycleMarketTicker, readRuntimePromptMarketData, invokeRuntimeReviewModel, resolveRuntimePromptKnobs, buildRuntimePromptCandles, requireRuntimePromptTemplates, resolveRuntimeBehaviorMemoryCutoff, buildRuntimeBehaviorStateArtifacts, buildRuntimePromptContextParts, runtimePromptArtifactInput;
130770
131028
  var init_runtime_prompt_steps = __esm({
130771
131029
  "lib/runtime/runtime-prompt-steps.ts"() {
130772
131030
  "use strict";
@@ -130805,6 +131063,7 @@ var init_runtime_prompt_steps = __esm({
130805
131063
  }
130806
131064
  return parityContext;
130807
131065
  };
131066
+ cycleMarketTicker = (symbol2, candles, loadedTicker) => loadedTicker?.is_fresh === true && toPositiveFinite3(loadedTicker.price) !== null ? loadedTicker : candleCloseTicker(symbol2, candles) ?? loadedTicker;
130808
131067
  readRuntimePromptMarketData = (input) => {
130809
131068
  const marketDataStartedAtMs = Date.now();
130810
131069
  return Promise.all(
@@ -130839,7 +131098,7 @@ var init_runtime_prompt_steps = __esm({
130839
131098
  )
130840
131099
  ]);
130841
131100
  const candles = Object.fromEntries(loadedCandles);
130842
- const ticker = loadedTicker?.is_fresh === true && toPositiveFinite3(loadedTicker.price) !== null ? loadedTicker : candleCloseTicker(marketSymbol, candles) ?? loadedTicker;
131101
+ const ticker = cycleMarketTicker(marketSymbol, candles, loadedTicker);
130843
131102
  if (ticker === null) throw tickerError;
130844
131103
  if (loadedTicker === null) {
130845
131104
  appendRuntimeDebugEvent({
@@ -133056,9 +133315,9 @@ var init_local_analysis = __esm({
133056
133315
  RUNTIME_SOURCE_DEFINITION_VERSION = "runtime-source-v1";
133057
133316
  DECISION_INPUT_DEFINITION_VERSION = "decision-input-v1";
133058
133317
  CONTEXT_ENVELOPE_DEFINITION_VERSION = "context-envelope-v2.1";
133059
- CLIENT_RUNTIME_SOURCE_VERSION = typeof process !== "undefined" && true && "3ff286d7fc6667e818cc519c84b33e40f68d2161".trim() && !["unknown", "unstamped", "development"].includes(
133060
- "3ff286d7fc6667e818cc519c84b33e40f68d2161".trim().toLowerCase()
133061
- ) ? "3ff286d7fc6667e818cc519c84b33e40f68d2161".trim() : null;
133318
+ CLIENT_RUNTIME_SOURCE_VERSION = typeof process !== "undefined" && true && "455c2035586f6d2a0253fb8dabb4418c3f06b04c".trim() && !["unknown", "unstamped", "development"].includes(
133319
+ "455c2035586f6d2a0253fb8dabb4418c3f06b04c".trim().toLowerCase()
133320
+ ) ? "455c2035586f6d2a0253fb8dabb4418c3f06b04c".trim() : null;
133062
133321
  CLIENT_MAIN_PROMPT_RENDERER = "client_runtime.buildLocalRuntimePromptArtifacts:v1";
133063
133322
  CLIENT_REVIEW_PROMPT_RENDERER = "client_runtime.review_prompt_assembly:v1";
133064
133323
  resolveEffectivePromptRuntimeProvenance = (input) => ({
@@ -138288,128 +138547,76 @@ ${copyReviewPromptContext(proposedTrade, input.templates)}`;
138288
138547
  }
138289
138548
  });
138290
138549
 
138291
- // lib/runtime/copy-review-runtime.ts
138292
- var copy_review_runtime_exports = {};
138293
- __export(copy_review_runtime_exports, {
138294
- prepareRuntimeCopyReviewPrimary: () => prepareRuntimeCopyReviewPrimary,
138295
- renderCheckInCopyReviewShadows: () => renderCheckInCopyReviewShadows,
138296
- renderCopyReviewShadows: () => renderCopyReviewShadows,
138297
- renderRuntimeCopyReview: () => renderRuntimeCopyReview,
138298
- shadowBudget: () => shadowBudget,
138299
- shadowPrompts: () => shadowPrompts
138300
- });
138301
- var prepareRuntimeCopyReviewPrimary, renderRuntimeCopyReview, shadowPrompts, SHADOW_RENDER_TIMEOUT_MS, SHADOW_REPORT_TIMEOUT_MS, shadowBudget, renderCopyReviewShadows, renderCheckInCopyReviewShadows;
138302
- var init_copy_review_runtime = __esm({
138303
- "lib/runtime/copy-review-runtime.ts"() {
138550
+ // lib/runtime/copy-review-render-inputs.ts
138551
+ var copyReviewRenderScope, copyReviewAccountSummary, requireCopyReviewAccountEquity, copyReviewWalletAddress, copyReviewParityContext, requireCopyReviewContractReady, copyReviewPrimaryFromInputs, renderCopyReviewFromPrimary, shadowPrompts;
138552
+ var init_copy_review_render_inputs = __esm({
138553
+ "lib/runtime/copy-review-render-inputs.ts"() {
138304
138554
  "use strict";
138305
138555
  init_define_VTX_CLAUDE_CODE_POLICY();
138306
138556
  init_define_VTX_EXO_POLICY();
138307
138557
  init_define_VTX_GROK_POLICY();
138308
138558
  init_define_VTX_PI_MODEL_POLICY();
138309
- init_copy_review();
138310
- init_constants();
138311
- init_runtime_policy_generated2();
138312
138559
  init_ai_settings_helpers();
138313
- init_abort();
138314
138560
  init_client_account_report();
138315
138561
  init_copy_review_prompt();
138316
138562
  init_render();
138317
- init_hyperliquid_account_state_adapter();
138318
138563
  init_local_analysis();
138319
- init_network_debug();
138320
- init_perp_dex_scope();
138321
138564
  init_runtime_error_reason_rules();
138322
138565
  init_runtime_prompt_steps();
138323
- prepareRuntimeCopyReviewPrimary = async (input) => {
138324
- const { config: config2, signal } = input;
138566
+ copyReviewRenderScope = (input) => {
138325
138567
  const settings = sortAiSettings(input.settings || {}) || {};
138326
- const walletAddress = String(settings.hyperliquid_wallet_address || "").trim();
138327
- if (!walletAddress) {
138328
- throw new RuntimeReasonError("The active profile wallet is unavailable. Save a wallet for this profile, then try again.", "profile_wallet_unavailable");
138329
- }
138330
- const { symbols: botSymbols, timeframes } = resolveRuntimeTradingScope(settings, config2);
138331
- const sortedTimeframes = sortTradingTimeframes(timeframes);
138332
- const symbols = input.promptSymbols(botSymbols);
138333
- const activeIndicators = normalizeAiIndicatorFlags(config2.default_ai_indicators, settings.ai_indicators);
138334
- const indicatorCandleCount = Number(config2.indicator_candle_count);
138568
+ const { symbols: botSymbols, timeframes } = resolveRuntimeTradingScope(settings, input.config);
138569
+ const indicatorCandleCount = Number(input.config.indicator_candle_count);
138335
138570
  if (!Number.isSafeInteger(indicatorCandleCount) || indicatorCandleCount < 1) {
138336
138571
  throw new RuntimeReasonError("Missing required client runtime config: indicator_candle_count", "runtime_config_missing");
138337
138572
  }
138338
- const serverBot = input.executionMode === "server";
138339
- const marketDataPromise = settleRuntimeCyclePromise(readRuntimePromptMarketData({
138340
- config: config2,
138341
- symbols,
138342
- sortedTimeframes,
138343
- lookbackSettings: settings.analysis_lookback,
138344
- defaultLookbacks: config2.default_analysis_lookback_fallbacks,
138345
- indicatorCandleCount,
138346
- primarySymbol: symbols[0],
138347
- primaryTimeframe: sortedTimeframes[0],
138348
- signal,
138349
- // A Client bot's candles: the stored ones, and the rest read here (the
138350
- // copied market may be one nothing streams); never a VTX server read of
138351
- // Hyperliquid for it.
138352
- ...serverBot ? {} : {
138353
- candleReadContext: { profileId: input.profileId, deviceConfig: () => config2, priority: input.readPriority }
138354
- }
138355
- }));
138356
- const fillsPromise = settleRuntimeCyclePromise(serverBot ? Promise.resolve(null) : fetchBrowserUserFills({
138357
- publicRequestPriority: input.readPriority,
138358
- config: config2,
138359
- walletAddress,
138360
- symbols,
138361
- forceRefresh: false,
138362
- signal
138363
- }));
138364
- const accountState = await fetchBrowserAccountState2({
138365
- publicRequestPriority: input.readPriority,
138366
- config: config2,
138367
- walletAddress,
138368
- symbol: symbols[0],
138369
- tickerPrice: 0,
138370
- leverage: resolveRuntimeLeveragePreference(settings, config2),
138371
- aggregatePerpDexs: true,
138372
- perpDexScope: perpDexScopeForSymbols(symbols),
138373
- feeSymbols: symbols,
138374
- includeEffectiveTakerRate: true,
138375
- forceRefresh: serverBot,
138376
- serverLoopAccountValue: serverBot,
138377
- sessionId: input.payload.sessionId,
138378
- signal
138379
- });
138380
- const fills = unwrapRuntimeCycleSettledResult(await fillsPromise);
138381
- const accountSummary = {
138382
- ...accountState.accountSummary,
138383
- total_unrealized_pnl: resolveTotalUnrealizedPnl2(
138384
- accountState.accountSummary,
138385
- accountState.positions
138386
- ) ?? accountState.accountSummary.total_unrealized_pnl
138573
+ return {
138574
+ settings,
138575
+ symbols: input.promptSymbols(botSymbols),
138576
+ sortedTimeframes: sortTradingTimeframes(timeframes),
138577
+ indicatorCandleCount
138387
138578
  };
138579
+ };
138580
+ copyReviewAccountSummary = (accountState) => ({
138581
+ ...accountState.accountSummary,
138582
+ total_unrealized_pnl: resolveTotalUnrealizedPnl2(
138583
+ accountState.accountSummary,
138584
+ accountState.positions
138585
+ ) ?? accountState.accountSummary.total_unrealized_pnl
138586
+ });
138587
+ requireCopyReviewAccountEquity = (accountState, serverBot) => {
138388
138588
  const accountEquity = Number(accountState.accountSummary?.account_value) || 0;
138389
138589
  if (accountEquity <= 0 && !serverBot) {
138390
138590
  throw new RuntimeReasonError("Live account equity unavailable for client runtime prompt contract.", "hyperliquid_data_unavailable");
138391
138591
  }
138392
- const parityContext = buildRuntimePromptParityContext({
138592
+ return accountEquity;
138593
+ };
138594
+ copyReviewWalletAddress = (settings) => {
138595
+ const walletAddress = String(settings.hyperliquid_wallet_address || "").trim();
138596
+ if (!walletAddress) {
138597
+ throw new RuntimeReasonError("The active profile wallet is unavailable. Save a wallet for this profile, then try again.", "profile_wallet_unavailable");
138598
+ }
138599
+ return walletAddress;
138600
+ };
138601
+ copyReviewParityContext = (input) => {
138602
+ const { accountState, scope } = input;
138603
+ const accountSummary = copyReviewAccountSummary(accountState);
138604
+ return buildRuntimePromptParityContext({
138393
138605
  account: {
138394
- walletAddress,
138395
- accountEquity,
138606
+ walletAddress: copyReviewWalletAddress(scope.settings),
138607
+ accountEquity: requireCopyReviewAccountEquity(accountState, input.serverBot),
138396
138608
  perpDexAccounts: accountState.accountSummary?.perp_dex_accounts ?? null,
138397
138609
  positions: accountState.positions,
138398
138610
  totalUnrealizedPnl: accountSummary.total_unrealized_pnl ?? null
138399
138611
  },
138400
138612
  deviceCandleSeries: {
138401
- series: symbols.flatMap((marketSymbol) => sortedTimeframes.map((marketTimeframe) => [marketSymbol, marketTimeframe])),
138402
- limit: indicatorCandleCount
138613
+ series: scope.symbols.flatMap((symbol2) => scope.sortedTimeframes.map((timeframe) => [symbol2, timeframe])),
138614
+ limit: scope.indicatorCandleCount
138403
138615
  },
138404
- userFills: fills ? { fills: fills.rawFills, evidence: fills.evidence } : null
138616
+ userFills: input.fills ? { fills: input.fills.rawFills, evidence: input.fills.evidence } : null
138405
138617
  });
138406
- const derived = await fetchCopyReviewPromptContract(input.profileId, {
138407
- ...input.payload,
138408
- isAnalyzing: false,
138409
- isExecuting: false,
138410
- promptParityContext: parityContext,
138411
- copyReviewSymbol: input.copySymbol
138412
- }, { schedulerInstanceId: input.payload.schedulerInstanceId ?? void 0, signal });
138618
+ };
138619
+ requireCopyReviewContractReady = (derived) => {
138413
138620
  if (String(derived.status || "").trim() !== "derived_context_ready") {
138414
138621
  throw new RuntimeReasonError(`Unexpected prompt derived-context status: ${String(derived.status || "unknown")}`, "internal_data_error");
138415
138622
  }
@@ -138418,7 +138625,14 @@ var init_copy_review_runtime = __esm({
138418
138625
  throw new RuntimeReasonError(`Unexpected prompt metadata status: ${String(promptMetadata?.status || "unknown")}`, "internal_data_error");
138419
138626
  }
138420
138627
  assertPromptContractCompatibility(promptMetadata);
138421
- const marketData = unwrapRuntimeCycleSettledResult(await marketDataPromise);
138628
+ return promptMetadata;
138629
+ };
138630
+ copyReviewPrimaryFromInputs = (input) => {
138631
+ const { config: config2, contract: derived, marketData, fills, accountState } = input;
138632
+ const { settings, symbols, sortedTimeframes, indicatorCandleCount } = input.scope;
138633
+ const activeIndicators = normalizeAiIndicatorFlags(config2.default_ai_indicators, settings.ai_indicators);
138634
+ const accountSummary = copyReviewAccountSummary(accountState);
138635
+ const promptMetadata = requireCopyReviewContractReady(derived);
138422
138636
  const tickersBySymbol = Object.fromEntries(marketData.map((entry) => [entry.symbol, entry.ticker]));
138423
138637
  const candlesBySymbol = Object.fromEntries(marketData.map((entry) => [entry.symbol, entry.candles]));
138424
138638
  const derivedContext = asRecord(derived.derived_context);
@@ -138456,7 +138670,7 @@ var init_copy_review_runtime = __esm({
138456
138670
  const { cutoffMs } = resolveRuntimeBehaviorMemoryCutoff(derivedContext, derived.derived_context_generated_at);
138457
138671
  const accountMarginNote = requireRuntimeAccountMarginNote(asRecord(promptInstructions.account));
138458
138672
  const behaviorState = buildRuntimeBehaviorStateArtifacts({
138459
- serverOwnsBehaviorState: serverBot,
138673
+ serverOwnsBehaviorState: input.serverOwnsBehaviorState,
138460
138674
  derivedContext,
138461
138675
  behaviorInstructions: asRecord(promptInstructions.behavior),
138462
138676
  config: config2,
@@ -138521,24 +138735,10 @@ var init_copy_review_runtime = __esm({
138521
138735
  }
138522
138736
  };
138523
138737
  };
138524
- renderRuntimeCopyReview = async (input) => {
138525
- const prepared = await prepareRuntimeCopyReviewPrimary({
138526
- profileId: input.profileId,
138527
- payload: input.payload,
138528
- executionMode: input.executionMode,
138529
- config: input.config,
138530
- settings: input.settings,
138531
- copySymbol: input.event.symbol,
138532
- promptSymbols: (botSymbols) => copyReviewPromptSymbols(input.event.symbol, botSymbols),
138533
- // A copy without a value of its own (no reference price) reviews at the
138534
- // bot's trade size, else the configured default, as the lane serves them.
138535
- promptSize: (sizes) => copyReviewPromptSize(input.event, sizes.profile || null, sizes.default),
138536
- readPriority: input.readPriority,
138537
- signal: input.signal
138538
- });
138738
+ renderCopyReviewFromPrimary = (prepared, copy4) => {
138539
138739
  const prompts = renderCopyReviewPrompts({
138540
- event: input.event,
138541
- source: input.source,
138740
+ event: copy4.event,
138741
+ source: copy4.source,
138542
138742
  templates: prepared.templates,
138543
138743
  primary: prepared.primary,
138544
138744
  review: prepared.review
@@ -138555,6 +138755,125 @@ var init_copy_review_runtime = __esm({
138555
138755
  review_system_prompt: prompts.reviewSystemPrompt,
138556
138756
  review_user_prompt: prompts.reviewUserPrompt
138557
138757
  });
138758
+ }
138759
+ });
138760
+
138761
+ // lib/runtime/copy-review-runtime.ts
138762
+ var copy_review_runtime_exports = {};
138763
+ __export(copy_review_runtime_exports, {
138764
+ prepareRuntimeCopyReviewPrimary: () => prepareRuntimeCopyReviewPrimary,
138765
+ renderCheckInCopyReviewShadows: () => renderCheckInCopyReviewShadows,
138766
+ renderCopyReviewShadows: () => renderCopyReviewShadows,
138767
+ renderRuntimeCopyReview: () => renderRuntimeCopyReview,
138768
+ shadowBudget: () => shadowBudget,
138769
+ shadowPrompts: () => shadowPrompts
138770
+ });
138771
+ var prepareRuntimeCopyReviewPrimary, renderRuntimeCopyReview, SHADOW_RENDER_TIMEOUT_MS, SHADOW_REPORT_TIMEOUT_MS, shadowBudget, renderCopyReviewShadows, renderCheckInCopyReviewShadows;
138772
+ var init_copy_review_runtime = __esm({
138773
+ "lib/runtime/copy-review-runtime.ts"() {
138774
+ "use strict";
138775
+ init_define_VTX_CLAUDE_CODE_POLICY();
138776
+ init_define_VTX_EXO_POLICY();
138777
+ init_define_VTX_GROK_POLICY();
138778
+ init_define_VTX_PI_MODEL_POLICY();
138779
+ init_copy_review();
138780
+ init_constants();
138781
+ init_runtime_policy_generated2();
138782
+ init_abort();
138783
+ init_copy_review_prompt();
138784
+ init_hyperliquid_account_state_adapter();
138785
+ init_local_analysis();
138786
+ init_network_debug();
138787
+ init_perp_dex_scope();
138788
+ init_runtime_error_reason_rules();
138789
+ init_runtime_prompt_steps();
138790
+ init_copy_review_render_inputs();
138791
+ prepareRuntimeCopyReviewPrimary = async (input) => {
138792
+ const { config: config2, signal } = input;
138793
+ const scope = copyReviewRenderScope({ config: config2, settings: input.settings, promptSymbols: input.promptSymbols });
138794
+ const { settings, symbols, sortedTimeframes, indicatorCandleCount } = scope;
138795
+ const walletAddress = copyReviewWalletAddress(settings);
138796
+ const serverBot = input.executionMode === "server";
138797
+ const marketDataPromise = settleRuntimeCyclePromise(readRuntimePromptMarketData({
138798
+ config: config2,
138799
+ symbols,
138800
+ sortedTimeframes,
138801
+ lookbackSettings: settings.analysis_lookback,
138802
+ defaultLookbacks: config2.default_analysis_lookback_fallbacks,
138803
+ indicatorCandleCount,
138804
+ primarySymbol: symbols[0],
138805
+ primaryTimeframe: sortedTimeframes[0],
138806
+ signal,
138807
+ // A Client bot's candles: the stored ones, and the rest read here (the
138808
+ // copied market may be one nothing streams); never a VTX server read of
138809
+ // Hyperliquid for it.
138810
+ ...serverBot ? {} : {
138811
+ candleReadContext: { profileId: input.profileId, deviceConfig: () => config2, priority: input.readPriority }
138812
+ }
138813
+ }));
138814
+ const fillsPromise = settleRuntimeCyclePromise(serverBot ? Promise.resolve(null) : fetchBrowserUserFills({
138815
+ publicRequestPriority: input.readPriority,
138816
+ config: config2,
138817
+ walletAddress,
138818
+ symbols,
138819
+ forceRefresh: false,
138820
+ signal
138821
+ }));
138822
+ const accountState = await fetchBrowserAccountState2({
138823
+ publicRequestPriority: input.readPriority,
138824
+ config: config2,
138825
+ walletAddress,
138826
+ symbol: symbols[0],
138827
+ tickerPrice: 0,
138828
+ leverage: resolveRuntimeLeveragePreference(settings, config2),
138829
+ aggregatePerpDexs: true,
138830
+ perpDexScope: perpDexScopeForSymbols(symbols),
138831
+ feeSymbols: symbols,
138832
+ includeEffectiveTakerRate: true,
138833
+ forceRefresh: serverBot,
138834
+ serverLoopAccountValue: serverBot,
138835
+ sessionId: input.payload.sessionId,
138836
+ signal
138837
+ });
138838
+ const fills = unwrapRuntimeCycleSettledResult(await fillsPromise);
138839
+ const parityContext = copyReviewParityContext({ accountState, fills, serverBot, scope });
138840
+ const derived = await fetchCopyReviewPromptContract(input.profileId, {
138841
+ ...input.payload,
138842
+ isAnalyzing: false,
138843
+ isExecuting: false,
138844
+ promptParityContext: parityContext,
138845
+ copyReviewSymbol: input.copySymbol
138846
+ }, { schedulerInstanceId: input.payload.schedulerInstanceId ?? void 0, signal });
138847
+ requireCopyReviewContractReady(derived);
138848
+ return copyReviewPrimaryFromInputs({
138849
+ config: config2,
138850
+ settings: input.settings,
138851
+ serverOwnsBehaviorState: serverBot,
138852
+ contract: derived,
138853
+ marketData: unwrapRuntimeCycleSettledResult(await marketDataPromise),
138854
+ fills,
138855
+ accountState,
138856
+ scope,
138857
+ promptSize: input.promptSize
138858
+ });
138859
+ };
138860
+ renderRuntimeCopyReview = async (input) => {
138861
+ const prepared = await prepareRuntimeCopyReviewPrimary({
138862
+ profileId: input.profileId,
138863
+ payload: input.payload,
138864
+ executionMode: input.executionMode,
138865
+ config: input.config,
138866
+ settings: input.settings,
138867
+ copySymbol: input.event.symbol,
138868
+ promptSymbols: (botSymbols) => copyReviewPromptSymbols(input.event.symbol, botSymbols),
138869
+ // A copy without a value of its own (no reference price) reviews at the
138870
+ // bot's trade size, else the configured default, as the lane serves them.
138871
+ promptSize: (sizes) => copyReviewPromptSize(input.event, sizes.profile || null, sizes.default),
138872
+ readPriority: input.readPriority,
138873
+ signal: input.signal
138874
+ });
138875
+ return renderCopyReviewFromPrimary(prepared, { event: input.event, source: input.source });
138876
+ };
138558
138877
  SHADOW_RENDER_TIMEOUT_MS = runtime_policy_generated_default2.copy_trading.review_shadow.render_timeout_seconds * MS_PER_SECOND;
138559
138878
  SHADOW_REPORT_TIMEOUT_MS = runtime_policy_generated_default2.copy_trading.review_shadow.report_timeout_seconds * MS_PER_SECOND;
138560
138879
  shadowBudget = (signal, budgetMs) => {